Removing a C++ comment and simplifying the string handling
[freeglut] / src / freeglut_main.c
1 /*
2  * freeglut_main.c
3  *
4  * The windows message processing methods.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Fri Dec 3 1999
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #include <GL/freeglut.h>
29 #include "freeglut_internal.h"
30 #include <errno.h>
31 #include <stdarg.h>
32 #if TARGET_HOST_WIN32
33 #    define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
34 #else
35 #    if HAVE_VPRINTF
36 #        define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
37 #    elif HAVE_DOPRNT
38 #        define VFPRINTF(s,f,a) _doprnt((f),(a),(s))
39 #    else
40 #        define VFPRINTF(s,f,a)
41 #    endif
42 #endif
43
44 #if TARGET_HOST_WINCE
45
46 typedef struct GXDisplayProperties GXDisplayProperties;
47 typedef struct GXKeyList GXKeyList;
48 #include <gx.h>
49
50 typedef struct GXKeyList (*GXGETDEFAULTKEYS)(int);
51 typedef int (*GXOPENINPUT)();
52
53 GXGETDEFAULTKEYS GXGetDefaultKeys_ = NULL;
54 GXOPENINPUT GXOpenInput_ = NULL;
55
56 struct GXKeyList gxKeyList;
57
58 #endif
59
60 /*
61  * Try to get the maximum value allowed for ints, falling back to the minimum
62  * guaranteed by ISO C99 if there is no suitable header.
63  */
64 #if HAVE_LIMITS_H
65 #    include <limits.h>
66 #endif
67 #ifndef INT_MAX
68 #    define INT_MAX 32767
69 #endif
70
71 #ifndef MIN
72 #define MIN(a,b) (((a)<(b)) ? (a) : (b))
73 #endif
74
75
76 /*
77  * TODO BEFORE THE STABLE RELEASE:
78  *
79  * There are some issues concerning window redrawing under X11, and maybe
80  * some events are not handled. The Win32 version lacks some more features,
81  * but seems acceptable for not demanding purposes.
82  *
83  * Need to investigate why the X11 version breaks out with an error when
84  * closing a window (using the window manager, not glutDestroyWindow)...
85  */
86
87 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
88
89 /*
90  * Handle a window configuration change. When no reshape
91  * callback is hooked, the viewport size is updated to
92  * match the new window size.
93  */
94 static void fghReshapeWindow ( SFG_Window *window, int width, int height )
95 {
96     SFG_Window *current_window = fgStructure.CurrentWindow;
97
98     freeglut_return_if_fail( window != NULL );
99
100
101 #if TARGET_HOST_UNIX_X11
102
103     XResizeWindow( fgDisplay.Display, window->Window.Handle,
104                    width, height );
105     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
106
107 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
108
109 #if !TARGET_HOST_WINCE
110     {
111         RECT winRect;
112         int x, y, w, h;
113
114         /*
115          * For windowed mode, get the current position of the
116          * window and resize taking the size of the frame
117          * decorations into account.
118          */
119
120         /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
121         GetWindowRect( window->Window.Handle, &winRect );
122         x = winRect.left;
123         y = winRect.top;
124         w = width;
125         h = height;
126
127         if ( window->Parent == NULL )
128         {
129             if ( ! window->IsMenu && !window->State.IsGameMode )
130             {
131                 w += GetSystemMetrics( SM_CXSIZEFRAME ) * 2;
132                 h += GetSystemMetrics( SM_CYSIZEFRAME ) * 2 +
133                      GetSystemMetrics( SM_CYCAPTION );
134             }
135         }
136         else
137         {
138             RECT parentRect;
139             GetWindowRect( window->Parent->Window.Handle, &parentRect );
140             x -= parentRect.left + GetSystemMetrics( SM_CXSIZEFRAME ) * 2;
141             y -= parentRect.top  + GetSystemMetrics( SM_CYSIZEFRAME ) * 2 +
142                                    GetSystemMetrics( SM_CYCAPTION );
143         }
144
145         /*
146          * SWP_NOACTIVATE      Do not activate the window
147          * SWP_NOOWNERZORDER   Do not change position in z-order
148          * SWP_NOSENDCHANGING  Supress WM_WINDOWPOSCHANGING message
149          * SWP_NOZORDER        Retains the current Z order (ignore 2nd param)
150          */
151
152         SetWindowPos( window->Window.Handle,
153                       HWND_TOP,
154                       x, y, w, h,
155                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
156                       SWP_NOZORDER
157         );
158     }
159 #endif /* TARGET_HOST_WINCE */
160
161     /*
162      * XXX Should update {window->State.OldWidth, window->State.OldHeight}
163      * XXX to keep in lockstep with UNIX_X11 code.
164      */
165     if( FETCH_WCB( *window, Reshape ) )
166         INVOKE_WCB( *window, Reshape, ( width, height ) );
167     else
168     {
169         fgSetWindow( window );
170         glViewport( 0, 0, width, height );
171     }
172
173 #endif
174
175     /*
176      * Force a window redraw.  In Windows at least this is only a partial
177      * solution:  if the window is increasing in size in either dimension,
178      * the already-drawn part does not get drawn again and things look funny.
179      * But without this we get this bad behaviour whenever we resize the
180      * window.
181      */
182     window->State.Redisplay = GL_TRUE;
183
184     if( window->IsMenu )
185         fgSetWindow( current_window );
186 }
187
188 /*
189  * Calls a window's redraw method. This is used when
190  * a redraw is forced by the incoming window messages.
191  */
192 static void fghRedrawWindow ( SFG_Window *window )
193 {
194     SFG_Window *current_window = fgStructure.CurrentWindow;
195
196     freeglut_return_if_fail( window );
197     freeglut_return_if_fail( FETCH_WCB ( *window, Display ) );
198
199     window->State.Redisplay = GL_FALSE;
200
201     freeglut_return_if_fail( window->State.Visible );
202
203     fgSetWindow( window );
204
205     if( window->State.NeedToResize )
206     {
207         fghReshapeWindow(
208             window,
209             window->State.Width,
210             window->State.Height
211         );
212
213         window->State.NeedToResize = GL_FALSE;
214     }
215
216     INVOKE_WCB( *window, Display, ( ) );
217
218     fgSetWindow( current_window );
219 }
220
221 /*
222  * A static helper function to execute display callback for a window
223  */
224 static void fghcbDisplayWindow( SFG_Window *window,
225                                 SFG_Enumerator *enumerator )
226 {
227     if( window->State.Redisplay &&
228         window->State.Visible )
229     {
230         window->State.Redisplay = GL_FALSE;
231
232 #if TARGET_HOST_UNIX_X11
233         fghRedrawWindow ( window ) ;
234 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
235         RedrawWindow(
236             window->Window.Handle, NULL, NULL,
237             RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
238         );
239 #endif
240     }
241
242     fgEnumSubWindows( window, fghcbDisplayWindow, enumerator );
243 }
244
245 /*
246  * Make all windows perform a display call
247  */
248 static void fghDisplayAll( void )
249 {
250     SFG_Enumerator enumerator;
251
252     enumerator.found = GL_FALSE;
253     enumerator.data  =  NULL;
254
255     fgEnumWindows( fghcbDisplayWindow, &enumerator );
256 }
257
258 /*
259  * Window enumerator callback to check for the joystick polling code
260  */
261 static void fghcbCheckJoystickPolls( SFG_Window *window,
262                                      SFG_Enumerator *enumerator )
263 {
264     long int checkTime = fgElapsedTime( );
265
266     if( window->State.JoystickLastPoll + window->State.JoystickPollRate <=
267         checkTime )
268     {
269 #if !TARGET_HOST_WINCE
270         fgJoystickPollWindow( window );
271 #endif /* !TARGET_HOST_WINCE */
272         window->State.JoystickLastPoll = checkTime;
273     }
274
275     fgEnumSubWindows( window, fghcbCheckJoystickPolls, enumerator );
276 }
277
278 /*
279  * Check all windows for joystick polling
280  */
281 static void fghCheckJoystickPolls( void )
282 {
283     SFG_Enumerator enumerator;
284
285     enumerator.found = GL_FALSE;
286     enumerator.data  =  NULL;
287
288     fgEnumWindows( fghcbCheckJoystickPolls, &enumerator );
289 }
290
291 /*
292  * Check the global timers
293  */
294 static void fghCheckTimers( void )
295 {
296     long checkTime = fgElapsedTime( );
297
298     while( fgState.Timers.First )
299     {
300         SFG_Timer *timer = fgState.Timers.First;
301
302         if( timer->TriggerTime > checkTime )
303             break;
304
305         fgListRemove( &fgState.Timers, &timer->Node );
306         fgListAppend( &fgState.FreeTimers, &timer->Node );
307
308         timer->Callback( timer->ID );
309     }
310 }
311
312 /*
313  * Elapsed Time
314  */
315 long fgElapsedTime( void )
316 {
317     if ( fgState.Time.Set )
318     {
319 #if TARGET_HOST_UNIX_X11
320         struct timeval now;
321         long elapsed;
322
323         gettimeofday( &now, NULL );
324
325         elapsed = (now.tv_usec - fgState.Time.Value.tv_usec) / 1000;
326         elapsed += (now.tv_sec - fgState.Time.Value.tv_sec) * 1000;
327
328         return elapsed;
329 #elif TARGET_HOST_WIN32
330         return timeGetTime() - fgState.Time.Value;
331 #elif TARGET_HOST_WINCE
332         return GetTickCount() - fgState.Time.Value;
333 #endif
334     }
335     else
336     {
337 #if TARGET_HOST_UNIX_X11
338         gettimeofday( &fgState.Time.Value, NULL );
339 #elif TARGET_HOST_WIN32
340         fgState.Time.Value = timeGetTime ();
341 #elif TARGET_HOST_WINCE
342         fgState.Time.Value = GetTickCount();
343 #endif
344         fgState.Time.Set = GL_TRUE ;
345
346         return 0 ;
347     }
348 }
349
350 /*
351  * Error Messages.
352  */
353 void fgError( const char *fmt, ... )
354 {
355     va_list ap;
356
357     va_start( ap, fmt );
358
359     fprintf( stderr, "freeglut ");
360     if( fgState.ProgramName )
361         fprintf( stderr, "(%s): ", fgState.ProgramName );
362     VFPRINTF( stderr, fmt, ap );
363     fprintf( stderr, "\n" );
364
365     va_end( ap );
366
367     if ( fgState.Initialised )
368         fgDeinitialize ();
369
370     exit( 1 );
371 }
372
373 void fgWarning( const char *fmt, ... )
374 {
375     va_list ap;
376
377     va_start( ap, fmt );
378
379     fprintf( stderr, "freeglut ");
380     if( fgState.ProgramName )
381         fprintf( stderr, "(%s): ", fgState.ProgramName );
382     VFPRINTF( stderr, fmt, ap );
383     fprintf( stderr, "\n" );
384
385     va_end( ap );
386 }
387
388 /*
389  * Indicates whether Joystick events are being used by ANY window.
390  *
391  * The current mechanism is to walk all of the windows and ask if
392  * there is a joystick callback.  We have a short-circuit early
393  * return if we find any joystick handler registered.
394  *
395  * The real way to do this is to make use of the glutTimer() API
396  * to more cleanly re-implement the joystick API.  Then, this code
397  * and all other "joystick timer" code can be yanked.
398  *
399  */
400 static void fghCheckJoystickCallback( SFG_Window* w, SFG_Enumerator* e)
401 {
402     if( FETCH_WCB( *w, Joystick ) )
403     {
404         e->found = GL_TRUE;
405         e->data = w;
406     }
407     fgEnumSubWindows( w, fghCheckJoystickCallback, e );
408 }
409 static int fghHaveJoystick( void )
410 {
411     SFG_Enumerator enumerator;
412
413     enumerator.found = GL_FALSE;
414     enumerator.data = NULL;
415     fgEnumWindows( fghCheckJoystickCallback, &enumerator );
416     return !!enumerator.data;
417 }
418 static void fghHavePendingRedisplaysCallback( SFG_Window* w, SFG_Enumerator* e)
419 {
420     if( w->State.Redisplay )
421     {
422         e->found = GL_TRUE;
423         e->data = w;
424     }
425     fgEnumSubWindows( w, fghHavePendingRedisplaysCallback, e );
426 }
427 static int fghHavePendingRedisplays (void)
428 {
429     SFG_Enumerator enumerator;
430
431     enumerator.found = GL_FALSE;
432     enumerator.data = NULL;
433     fgEnumWindows( fghHavePendingRedisplaysCallback, &enumerator );
434     return !!enumerator.data;
435 }
436 /*
437  * Returns the number of GLUT ticks (milliseconds) till the next timer event.
438  */
439 static long fghNextTimer( void )
440 {
441     long ret = INT_MAX;
442     SFG_Timer *timer = fgState.Timers.First;
443
444     if( timer )
445         ret = timer->TriggerTime - fgElapsedTime();
446     if( ret < 0 )
447         ret = 0;
448
449     return ret;
450 }
451 /*
452  * Does the magic required to relinquish the CPU until something interesting
453  * happens.
454  */
455 static void fghSleepForEvents( void )
456 {
457     long msec;
458
459     if( fgState.IdleCallback || fghHavePendingRedisplays( ) )
460         return;
461
462     msec = fghNextTimer( );
463     /* XXX Use GLUT timers for joysticks... */
464     /* XXX Dumb; forces granularity to .01sec */
465     if( fghHaveJoystick( ) && ( msec < 10 ) )     
466         msec = 10;
467
468 #if TARGET_HOST_UNIX_X11
469     /*
470      * Possibly due to aggressive use of XFlush() and friends,
471      * it is possible to have our socket drained but still have
472      * unprocessed events.  (Or, this may just be normal with
473      * X, anyway?)  We do non-trivial processing of X events
474      * after the event-reading loop, in any case, so we
475      * need to allow that we may have an empty socket but non-
476      * empty event queue.
477      */
478     if( ! XPending( fgDisplay.Display ) )
479     {
480         fd_set fdset;
481         int err;
482         int socket;
483         struct timeval wait;
484
485         socket = ConnectionNumber( fgDisplay.Display );
486         FD_ZERO( &fdset );
487         FD_SET( socket, &fdset );
488         wait.tv_sec = msec / 1000;
489         wait.tv_usec = (msec % 1000) * 1000;
490         err = select( socket+1, &fdset, NULL, NULL, &wait );
491
492         if( ( -1 == err ) && ( errno != EINTR ) )
493             fgWarning ( "freeglut select() error: %d", errno );
494     }
495 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
496     MsgWaitForMultipleObjects( 0, NULL, FALSE, msec, QS_ALLEVENTS );
497 #endif
498 }
499
500 #if TARGET_HOST_UNIX_X11
501 /*
502  * Returns GLUT modifier mask for an XEvent.
503  */
504 static int fghGetXModifiers( XEvent *event )
505 {
506     int ret = 0;
507
508     if( event->xkey.state & ( ShiftMask | LockMask ) )
509         ret |= GLUT_ACTIVE_SHIFT;
510     if( event->xkey.state & ControlMask )
511         ret |= GLUT_ACTIVE_CTRL;
512     if( event->xkey.state & Mod1Mask )
513         ret |= GLUT_ACTIVE_ALT;
514
515     return ret;
516 }
517 #endif
518
519
520 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
521
522 /*
523  * Executes a single iteration in the freeglut processing loop.
524  */
525 void FGAPIENTRY glutMainLoopEvent( void )
526 {
527 #if TARGET_HOST_UNIX_X11
528     SFG_Window* window;
529     XEvent event;
530
531     /* This code was repeated constantly, so here it goes into a definition: */
532 #define GETWINDOW(a)                             \
533     window = fgWindowByHandle( event.a.window ); \
534     if( window == NULL )                         \
535         break;
536
537 #define GETMOUSE(a)                              \
538     window->State.MouseX = event.a.x;            \
539     window->State.MouseY = event.a.y;
540
541     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
542
543     while( XPending( fgDisplay.Display ) )
544     {
545         XNextEvent( fgDisplay.Display, &event );
546
547         switch( event.type )
548         {
549         case ClientMessage:
550             /* Destroy the window when the WM_DELETE_WINDOW message arrives */
551             if( (Atom) event.xclient.data.l[ 0 ] == fgDisplay.DeleteWindow )
552             {
553                 GETWINDOW( xclient );
554
555                 fgDestroyWindow ( window );
556
557                 if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
558                 {
559                     fgDeinitialize( );
560                     exit( 0 );
561                 }
562                 else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
563                     fgState.ExecState = GLUT_EXEC_STATE_STOP;
564
565                 return;
566             }
567             break;
568
569             /*
570              * CreateNotify causes a configure-event so that sub-windows are
571              * handled compatibly with GLUT.  Otherwise, your sub-windows
572              * (in freeglut only) will not get an initial reshape event,
573              * which can break things.
574              *
575              * GLUT presumably does this because it generally tries to treat
576              * sub-windows the same as windows.
577              *
578              * XXX Technically, GETWINDOW( xconfigure ) and
579              * XXX {event.xconfigure} may not be legit ways to get at
580              * XXX data for CreateNotify events.  In practice, the data
581              * XXX is in a union which is laid out much the same either
582              * XXX way.  But if you want to split hairs, this isn't legit,
583              * XXX and we should instead duplicate some code.
584              */
585         case CreateNotify:
586         case ConfigureNotify:
587             GETWINDOW( xconfigure );
588             {
589                 int width = event.xconfigure.width;
590                 int height = event.xconfigure.height;
591
592                 if( ( width != window->State.OldWidth ) ||
593                     ( height != window->State.OldHeight ) )
594                 {
595                     SFG_Window *current_window = fgStructure.CurrentWindow;
596
597                     window->State.OldWidth = width;
598                     window->State.OldHeight = height;
599                     if( FETCH_WCB( *window, Reshape ) )
600                         INVOKE_WCB( *window, Reshape, ( width, height ) );
601                     else
602                     {
603                         fgSetWindow( window );
604                         glViewport( 0, 0, width, height );
605                     }
606                     glutPostRedisplay( );
607                     if( window->IsMenu )
608                         fgSetWindow( current_window );
609                 }
610             }
611             break;
612
613         case DestroyNotify:
614             /*
615              * This is sent to confirm the XDestroyWindow call.
616              *
617              * XXX WHY is this commented out?  Should we re-enable it?
618              */
619             /* fgAddToWindowDestroyList ( window ); */
620             break;
621
622         case Expose:
623             /*
624              * We are too dumb to process partial exposes...
625              *
626              * XXX Well, we could do it.  However, it seems to only
627              * XXX be potentially useful for single-buffered (since
628              * XXX double-buffered does not respect viewport when we
629              * XXX do a buffer-swap).
630              *
631              */
632             if( event.xexpose.count == 0 )
633             {
634                 GETWINDOW( xexpose );
635                 window->State.Redisplay = GL_TRUE;
636             }
637             break;
638
639         case MapNotify:
640         case UnmapNotify:
641             /*
642              * If we never do anything with this, can we just not ask to
643              * get these messages?
644              */
645             break;
646
647         case MappingNotify:
648             /*
649              * Have the client's keyboard knowledge updated (xlib.ps,
650              * page 206, says that's a good thing to do)
651              */
652             XRefreshKeyboardMapping( (XMappingEvent *) &event );
653             break;
654
655         case VisibilityNotify:
656         {
657             GETWINDOW( xvisibility );
658             /*
659              * XXX INVOKE_WCB() does this check for us.
660              */
661             if( ! FETCH_WCB( *window, WindowStatus ) )
662                 break;
663             fgSetWindow( window );
664
665             /*
666              * Sending this event, the X server can notify us that the window
667              * has just acquired one of the three possible visibility states:
668              * VisibilityUnobscured, VisibilityPartiallyObscured or
669              * VisibilityFullyObscured
670              */
671             switch( event.xvisibility.state )
672             {
673             case VisibilityUnobscured:
674                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_RETAINED ) );
675                 window->State.Visible = GL_TRUE;
676                 break;
677
678             case VisibilityPartiallyObscured:
679                 INVOKE_WCB( *window, WindowStatus,
680                             ( GLUT_PARTIALLY_RETAINED ) );
681                 window->State.Visible = GL_TRUE;
682                 break;
683
684             case VisibilityFullyObscured:
685                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_COVERED ) );
686                 window->State.Visible = GL_FALSE;
687                 break;
688
689             default:
690                 fgWarning( "Unknown X visibility state: %d",
691                            event.xvisibility.state );
692                 break;
693             }
694         }
695         break;
696
697         case EnterNotify:
698         case LeaveNotify:
699             GETWINDOW( xcrossing );
700             GETMOUSE( xcrossing );
701             if( ( event.type == LeaveNotify ) && window->IsMenu &&
702                 window->ActiveMenu && window->ActiveMenu->IsActive )
703                 fgUpdateMenuHighlight( window->ActiveMenu );
704
705             INVOKE_WCB( *window, Entry, ( ( EnterNotify == event.type ) ?
706                                           GLUT_ENTERED :
707                                           GLUT_LEFT ) );
708             break;
709
710         case MotionNotify:
711         {
712             GETWINDOW( xmotion );
713             GETMOUSE( xmotion );
714
715             if( window->ActiveMenu )
716             {
717                 if( window == window->ActiveMenu->ParentWindow )
718                 {
719                     window->ActiveMenu->Window->State.MouseX =
720                         event.xmotion.x_root - window->ActiveMenu->X;
721                     window->ActiveMenu->Window->State.MouseY =
722                         event.xmotion.y_root - window->ActiveMenu->Y;
723                 }
724
725                 fgUpdateMenuHighlight( window->ActiveMenu );
726
727                 break;
728             }
729
730             /*
731              * XXX For more than 5 buttons, just check {event.xmotion.state},
732              * XXX rather than a host of bit-masks?  Or maybe we need to
733              * XXX track ButtonPress/ButtonRelease events in our own
734              * XXX bit-mask?
735              */
736 #define BUTTON_MASK \
737   ( Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask )
738             if ( event.xmotion.state & BUTTON_MASK )
739                 INVOKE_WCB( *window, Motion, ( event.xmotion.x,
740                                                event.xmotion.y ) );
741             else
742                 INVOKE_WCB( *window, Passive, ( event.xmotion.x,
743                                                 event.xmotion.y ) );
744         }
745         break;
746
747         case ButtonRelease:
748         case ButtonPress:
749         {
750             GLboolean pressed = GL_TRUE;
751             int button;
752
753             if( event.type == ButtonRelease )
754                 pressed = GL_FALSE ;
755
756             /*
757              * A mouse button has been pressed or released. Traditionally,
758              * break if the window was found within the freeglut structures.
759              */
760             GETWINDOW( xbutton );
761             GETMOUSE( xbutton );
762
763             /*
764              * An X button (at least in XFree86) is numbered from 1.
765              * A GLUT button is numbered from 0.
766              * Old GLUT passed through buttons other than just the first
767              * three, though it only gave symbolic names and official
768              * support to the first three.
769              */
770             button = event.xbutton.button - 1;
771
772             /*
773              * Do not execute the application's mouse callback if a menu
774              * is hooked to this button.  In that case an appropriate
775              * private call should be generated.
776              */
777             if( fgCheckActiveMenu( window, button, pressed,
778                                    event.xbutton.x_root, event.xbutton.y_root ) )
779                 break;
780
781             /*
782              * Check if there is a mouse or mouse wheel callback hooked to the
783              * window
784              */
785             if( ! FETCH_WCB( *window, Mouse ) &&
786                 ! FETCH_WCB( *window, MouseWheel ) )
787                 break;
788
789             fgState.Modifiers = fghGetXModifiers( &event );
790
791             /* Finally execute the mouse or mouse wheel callback */
792             if( ( button < glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS ) ) || ( ! FETCH_WCB( *window, MouseWheel ) ) )
793                 INVOKE_WCB( *window, Mouse, ( button,
794                                               pressed ? GLUT_DOWN : GLUT_UP,
795                                               event.xbutton.x,
796                                               event.xbutton.y )
797                 );
798             else
799             {
800                 /*
801                  * Map 4 and 5 to wheel zero; EVEN to +1, ODD to -1
802                  *  "  6 and 7 "    "   one; ...
803                  *
804                  * XXX This *should* be behind some variables/macros,
805                  * XXX since the order and numbering isn't certain
806                  * XXX See XFree86 configuration docs (even back in the
807                  * XXX 3.x days, and especially with 4.x).
808                  *
809                  * XXX Note that {button} has already been decremeted
810                  * XXX in mapping from X button numbering to GLUT.
811                  */
812                 int wheel_number = (button - glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS )) / 2;
813                 int direction = -1;
814                 if( button % 2 )
815                     direction = 1;
816
817                 if( pressed )
818                     INVOKE_WCB( *window, MouseWheel, ( wheel_number,
819                                                        direction,
820                                                        event.xbutton.x,
821                                                        event.xbutton.y )
822                     );
823             }
824
825             /* Trash the modifiers state */
826             fgState.Modifiers = 0xffffffff;
827         }
828         break;
829
830         case KeyRelease:
831         case KeyPress:
832         {
833             FGCBKeyboard keyboard_cb;
834             FGCBSpecial special_cb;
835
836             GETWINDOW( xkey );
837             GETMOUSE( xkey );
838
839             /* Detect auto repeated keys, if configured globally or per-window */
840
841             if ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE )
842             {
843                 if (event.type==KeyRelease)
844                 {
845                     /*
846                      * Look at X11 keystate to detect repeat mode.
847                      * While X11 says the key is actually held down, we'll ignore KeyRelease/KeyPress pairs.
848                      */
849
850                     char keys[32];
851                     XQueryKeymap( fgDisplay.Display, keys ); /* Look at X11 keystate to detect repeat mode */
852
853                     if ( event.xkey.keycode<256 )            /* XQueryKeymap is limited to 256 keycodes    */
854                     {
855                         if ( keys[event.xkey.keycode>>3] & (1<<(event.xkey.keycode%8)) )
856                             window->State.KeyRepeating = GL_TRUE;
857                         else
858                             window->State.KeyRepeating = GL_FALSE;
859                     }
860                 }
861             }
862             else
863                 window->State.KeyRepeating = GL_FALSE;
864
865             /* Cease processing this event if it is auto repeated */
866
867             if (window->State.KeyRepeating)
868                 break;
869
870             if( event.type == KeyPress )
871             {
872                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, Keyboard ));
873                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, Special  ));
874             }
875             else
876             {
877                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, KeyboardUp ));
878                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, SpecialUp  ));
879             }
880
881             /* Is there a keyboard/special callback hooked for this window? */
882             if( keyboard_cb || special_cb )
883             {
884                 XComposeStatus composeStatus;
885                 char asciiCode[ 32 ];
886                 KeySym keySym;
887                 int len;
888
889                 /* Check for the ASCII/KeySym codes associated with the event: */
890                 len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode),
891                                      &keySym, &composeStatus
892                 );
893
894                 /* GLUT API tells us to have two separate callbacks... */
895                 if( len > 0 )
896                 {
897                     /* ...one for the ASCII translateable keypresses... */
898                     if( keyboard_cb )
899                     {
900                         fgSetWindow( window );
901                         fgState.Modifiers = fghGetXModifiers( &event );
902                         keyboard_cb( asciiCode[ 0 ],
903                                      event.xkey.x, event.xkey.y
904                         );
905                         fgState.Modifiers = 0xffffffff;
906                     }
907                 }
908                 else
909                 {
910                     int special = -1;
911
912                     /*
913                      * ...and one for all the others, which need to be
914                      * translated to GLUT_KEY_Xs...
915                      */
916                     switch( keySym )
917                     {
918                     case XK_F1:     special = GLUT_KEY_F1;     break;
919                     case XK_F2:     special = GLUT_KEY_F2;     break;
920                     case XK_F3:     special = GLUT_KEY_F3;     break;
921                     case XK_F4:     special = GLUT_KEY_F4;     break;
922                     case XK_F5:     special = GLUT_KEY_F5;     break;
923                     case XK_F6:     special = GLUT_KEY_F6;     break;
924                     case XK_F7:     special = GLUT_KEY_F7;     break;
925                     case XK_F8:     special = GLUT_KEY_F8;     break;
926                     case XK_F9:     special = GLUT_KEY_F9;     break;
927                     case XK_F10:    special = GLUT_KEY_F10;    break;
928                     case XK_F11:    special = GLUT_KEY_F11;    break;
929                     case XK_F12:    special = GLUT_KEY_F12;    break;
930
931                     case XK_Left:   special = GLUT_KEY_LEFT;   break;
932                     case XK_Right:  special = GLUT_KEY_RIGHT;  break;
933                     case XK_Up:     special = GLUT_KEY_UP;     break;
934                     case XK_Down:   special = GLUT_KEY_DOWN;   break;
935
936                     case XK_KP_Prior:
937                     case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
938                     case XK_KP_Next:
939                     case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
940                     case XK_KP_Home:
941                     case XK_Home:   special = GLUT_KEY_HOME;   break;
942                     case XK_KP_End:
943                     case XK_End:    special = GLUT_KEY_END;    break;
944                     case XK_KP_Insert:
945                     case XK_Insert: special = GLUT_KEY_INSERT; break;
946                     }
947
948                     /*
949                      * Execute the callback (if one has been specified),
950                      * given that the special code seems to be valid...
951                      */
952                     if( special_cb && (special != -1) )
953                     {
954                         fgSetWindow( window );
955                         fgState.Modifiers = fghGetXModifiers( &event );
956                         special_cb( special, event.xkey.x, event.xkey.y );
957                         fgState.Modifiers = 0xffffffff;
958                     }
959                 }
960             }
961         }
962         break;
963
964         case ReparentNotify:
965             break; /* XXX Should disable this event */
966
967         default:
968             fgWarning ("Unknown X event type: %d", event.type);
969             break;
970         }
971     }
972
973 #elif TARGET_HOST_WIN32 || TARGET_HOST_WINCE
974
975     MSG stMsg;
976
977     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
978
979     while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
980     {
981         if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
982         {
983             if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
984             {
985                 fgDeinitialize( );
986                 exit( 0 );
987             }
988             else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
989                 fgState.ExecState = GLUT_EXEC_STATE_STOP;
990
991             return;
992         }
993
994         TranslateMessage( &stMsg );
995         DispatchMessage( &stMsg );
996     }
997 #endif
998
999     if( fgState.Timers.First )
1000         fghCheckTimers( );
1001     fghCheckJoystickPolls( );
1002     fghDisplayAll( );
1003
1004     fgCloseWindows( );
1005 }
1006
1007 /*
1008  * Enters the freeglut processing loop.
1009  * Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1010  */
1011 void FGAPIENTRY glutMainLoop( void )
1012 {
1013     int action;
1014
1015 #if TARGET_HOST_WIN32 || TARGET_HOST_WINCE
1016     SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1017 #endif
1018
1019     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoop" );
1020
1021 #if TARGET_HOST_WIN32 || TARGET_HOST_WINCE
1022     /*
1023      * Processing before the main loop:  If there is a window which is open and
1024      * which has a visibility callback, call it.  I know this is an ugly hack,
1025      * but I'm not sure what else to do about it.  Ideally we should leave
1026      * something uninitialized in the create window code and initialize it in
1027      * the main loop, and have that initialization create a "WM_ACTIVATE"
1028      * message.  Then we would put the visibility callback code in the
1029      * "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1030      */
1031     while( window )
1032     {
1033         if ( FETCH_WCB( *window, Visibility ) )
1034         {
1035             SFG_Window *current_window = fgStructure.CurrentWindow ;
1036
1037             INVOKE_WCB( *window, Visibility, ( window->State.Visible ) );
1038             fgSetWindow( current_window );
1039         }
1040
1041         window = (SFG_Window *)window->Node.Next ;
1042     }
1043 #endif
1044
1045     fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1046     while( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1047     {
1048         SFG_Window *window;
1049
1050         glutMainLoopEvent( );
1051         /*
1052          * Step through the list of windows, seeing if there are any
1053          * that are not menus
1054          */
1055         for( window = ( SFG_Window * )fgStructure.Windows.First;
1056              window;
1057              window = ( SFG_Window * )window->Node.Next )
1058             if ( ! ( window->IsMenu ) )
1059                 break;
1060
1061         if( ! window )
1062             fgState.ExecState = GLUT_EXEC_STATE_STOP;
1063         else
1064         {
1065             if( fgState.IdleCallback )
1066             {
1067                 if( fgStructure.CurrentWindow &&
1068                     fgStructure.CurrentWindow->IsMenu )
1069                     /* fail safe */
1070                     fgSetWindow( window );
1071                 fgState.IdleCallback( );
1072             }
1073
1074             fghSleepForEvents( );
1075         }
1076     }
1077
1078     /*
1079      * When this loop terminates, destroy the display, state and structure
1080      * of a freeglut session, so that another glutInit() call can happen
1081      *
1082      * Save the "ActionOnWindowClose" because "fgDeinitialize" resets it.
1083      */
1084     action = fgState.ActionOnWindowClose;
1085     fgDeinitialize( );
1086     if( action == GLUT_ACTION_EXIT )
1087         exit( 0 );
1088 }
1089
1090 /*
1091  * Leaves the freeglut processing loop.
1092  */
1093 void FGAPIENTRY glutLeaveMainLoop( void )
1094 {
1095     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveMainLoop" );
1096     fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1097 }
1098
1099
1100 #if TARGET_HOST_WIN32 || TARGET_HOST_WINCE
1101 /*
1102  * Determine a GLUT modifer mask based on MS-WINDOWS system info.
1103  */
1104 static int fghGetWin32Modifiers (void)
1105 {
1106     return
1107         ( ( ( GetKeyState( VK_LSHIFT   ) < 0 ) ||
1108             ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1109         ( ( ( GetKeyState( VK_LCONTROL ) < 0 ) ||
1110             ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1111         ( ( ( GetKeyState( VK_LMENU    ) < 0 ) ||
1112             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1113 }
1114
1115 /*
1116  * The window procedure for handling Win32 events
1117  */
1118 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam,
1119                                LPARAM lParam )
1120 {
1121     SFG_Window* window;
1122     PAINTSTRUCT ps;
1123     LONG lRet = 1;
1124
1125     FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED ( "Event Handler" ) ;
1126
1127     window = fgWindowByHandle( hWnd );
1128
1129     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1130       return DefWindowProc( hWnd, uMsg, wParam, lParam );
1131
1132     /* printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0,
1133              uMsg, wParam, lParam ); */
1134     switch( uMsg )
1135     {
1136     case WM_CREATE:
1137         /* The window structure is passed as the creation structure paramter... */
1138         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1139         FREEGLUT_INTERNAL_ERROR_EXIT ( ( window != NULL ), "Cannot create window",
1140                                        "fgWindowProc" );
1141
1142         window->Window.Handle = hWnd;
1143         window->Window.Device = GetDC( hWnd );
1144         if( window->IsMenu )
1145         {
1146             unsigned int current_DisplayMode = fgState.DisplayMode;
1147             fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH;
1148 #if !TARGET_HOST_WINCE
1149             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1150 #endif
1151             fgState.DisplayMode = current_DisplayMode;
1152
1153             if( fgStructure.MenuContext )
1154                 wglMakeCurrent( window->Window.Device,
1155                                 fgStructure.MenuContext->Context
1156                 );
1157             else
1158             {
1159                 fgStructure.MenuContext =
1160                     (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
1161                 fgStructure.MenuContext->Context =
1162                     wglCreateContext( window->Window.Device );
1163             }
1164
1165             /* window->Window.Context = wglGetCurrentContext ();   */
1166             window->Window.Context = wglCreateContext( window->Window.Device );
1167         }
1168         else
1169         {
1170 #if !TARGET_HOST_WINCE
1171             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1172 #endif
1173
1174             if( ! fgState.UseCurrentContext )
1175                 window->Window.Context =
1176                     wglCreateContext( window->Window.Device );
1177             else
1178             {
1179                 window->Window.Context = wglGetCurrentContext( );
1180                 if( ! window->Window.Context )
1181                     window->Window.Context =
1182                         wglCreateContext( window->Window.Device );
1183             }
1184         }
1185
1186         window->State.NeedToResize = GL_TRUE;
1187         window->State.Width  = fgState.Size.X;
1188         window->State.Height = fgState.Size.Y;
1189
1190         ReleaseDC( window->Window.Handle, window->Window.Device );
1191
1192 #if TARGET_HOST_WINCE
1193         /* Take over button handling */
1194         {
1195             HINSTANCE dxDllLib=LoadLibrary(_T("gx.dll"));
1196             if (dxDllLib)
1197             {
1198                 GXGetDefaultKeys_=(GXGETDEFAULTKEYS)GetProcAddress(dxDllLib, _T("?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z"));
1199                 GXOpenInput_=(GXOPENINPUT)GetProcAddress(dxDllLib, _T("?GXOpenInput@@YAHXZ"));
1200             }
1201
1202             if(GXOpenInput_)
1203                 (*GXOpenInput_)();
1204             if(GXGetDefaultKeys_)
1205                 gxKeyList = (*GXGetDefaultKeys_)(GX_LANDSCAPEKEYS);
1206         }
1207
1208 #endif /* TARGET_HOST_WINCE */
1209         break;
1210
1211     case WM_SIZE:
1212         /*
1213          * If the window is visible, then it is the user manually resizing it.
1214          * If it is not, then it is the system sending us a dummy resize with
1215          * zero dimensions on a "glutIconifyWindow" call.
1216          */
1217         if( window->State.Visible )
1218         {
1219             window->State.NeedToResize = GL_TRUE;
1220 #if TARGET_HOST_WINCE
1221             window->State.Width  = HIWORD(lParam);
1222             window->State.Height = LOWORD(lParam);
1223 #else
1224             window->State.Width  = LOWORD(lParam);
1225             window->State.Height = HIWORD(lParam);
1226 #endif /* TARGET_HOST_WINCE */
1227         }
1228
1229         break;
1230 #if 0
1231     case WM_SETFOCUS:
1232 /*        printf("WM_SETFOCUS: %p\n", window ); */
1233         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1234         break;
1235
1236     case WM_ACTIVATE:
1237         if (LOWORD(wParam) != WA_INACTIVE)
1238         {
1239 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
1240                    window->State.Cursor ); */
1241             fgSetCursor( window, window->State.Cursor );
1242         }
1243
1244         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1245         break;
1246 #endif
1247
1248     case WM_SETCURSOR:
1249 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
1250         if( LOWORD( lParam ) == HTCLIENT )
1251             fgSetCursor ( window, window->State.Cursor ) ;
1252         else
1253             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1254         break;
1255
1256     case WM_SHOWWINDOW:
1257         window->State.Visible = GL_TRUE;
1258         window->State.Redisplay = GL_TRUE;
1259         break;
1260
1261     case WM_PAINT:
1262         /* Turn on the visibility in case it was turned off somehow */
1263         window->State.Visible = GL_TRUE;
1264         BeginPaint( hWnd, &ps );
1265         fghRedrawWindow( window );
1266         EndPaint( hWnd, &ps );
1267         break;
1268
1269     case WM_CLOSE:
1270         fgDestroyWindow ( window );
1271         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
1272             PostQuitMessage(0);
1273         break;
1274
1275     case WM_DESTROY:
1276         /*
1277          * The window already got destroyed, so don't bother with it.
1278          */
1279         return 0;
1280
1281     /* XXX For a future patch:  we need a mouse entry event.  Unfortunately Windows
1282      * XXX doesn't give us one, so we will probably need a "MouseInWindow" flag in
1283      * XXX the SFG_Window structure.  Set it to true to begin with and then have the
1284      * XXX WM_MOUSELEAVE code set it to false.  Then when we get a WM_MOUSEMOVE event,
1285      * XXX if the flag is false we invoke the Entry callback and set the flag to true.
1286      */
1287     case 0x02a2:  /* This is the message we get when the mouse is leaving the window */
1288         if( window->IsMenu &&
1289             window->ActiveMenu && window->ActiveMenu->IsActive )
1290             fgUpdateMenuHighlight( window->ActiveMenu );
1291
1292         INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
1293         break ;
1294
1295     case WM_MOUSEMOVE:
1296     {
1297 #if TARGET_HOST_WINCE
1298         window->State.MouseX = 320-HIWORD( lParam );
1299         window->State.MouseY = LOWORD( lParam );
1300 #else
1301         window->State.MouseX = LOWORD( lParam );
1302         window->State.MouseY = HIWORD( lParam );
1303 #endif /* TARGET_HOST_WINCE */
1304         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1305         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1306         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1307         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1308
1309         if ( window->ActiveMenu )
1310         {
1311             fgUpdateMenuHighlight( window->ActiveMenu );
1312             break;
1313         }
1314
1315         fgState.Modifiers = fghGetWin32Modifiers( );
1316
1317         if( ( wParam & MK_LBUTTON ) ||
1318             ( wParam & MK_MBUTTON ) ||
1319             ( wParam & MK_RBUTTON ) )
1320             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
1321                                            window->State.MouseY ) );
1322         else
1323             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
1324                                             window->State.MouseY ) );
1325
1326         fgState.Modifiers = 0xffffffff;
1327     }
1328     break;
1329
1330     case WM_LBUTTONDOWN:
1331     case WM_MBUTTONDOWN:
1332     case WM_RBUTTONDOWN:
1333     case WM_LBUTTONUP:
1334     case WM_MBUTTONUP:
1335     case WM_RBUTTONUP:
1336     {
1337         GLboolean pressed = GL_TRUE;
1338         int button;
1339
1340 #if TARGET_HOST_WINCE
1341         window->State.MouseX = 320-HIWORD( lParam );
1342         window->State.MouseY = LOWORD( lParam );
1343 #else
1344         window->State.MouseX = LOWORD( lParam );
1345         window->State.MouseY = HIWORD( lParam );
1346 #endif /* TARGET_HOST_WINCE */
1347
1348         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1349         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1350         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1351         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1352
1353         switch( uMsg )
1354         {
1355         case WM_LBUTTONDOWN:
1356             pressed = GL_TRUE;
1357             button = GLUT_LEFT_BUTTON;
1358             break;
1359         case WM_MBUTTONDOWN:
1360             pressed = GL_TRUE;
1361             button = GLUT_MIDDLE_BUTTON;
1362             break;
1363         case WM_RBUTTONDOWN:
1364             pressed = GL_TRUE;
1365             button = GLUT_RIGHT_BUTTON;
1366             break;
1367         case WM_LBUTTONUP:
1368             pressed = GL_FALSE;
1369             button = GLUT_LEFT_BUTTON;
1370             break;
1371         case WM_MBUTTONUP:
1372             pressed = GL_FALSE;
1373             button = GLUT_MIDDLE_BUTTON;
1374             break;
1375         case WM_RBUTTONUP:
1376             pressed = GL_FALSE;
1377             button = GLUT_RIGHT_BUTTON;
1378             break;
1379         default:
1380             pressed = GL_FALSE;
1381             button = -1;
1382             break;
1383         }
1384
1385 #if !TARGET_HOST_WINCE
1386         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1387         {
1388             if( button == GLUT_LEFT_BUTTON )
1389                 button = GLUT_RIGHT_BUTTON;
1390             else
1391                 if( button == GLUT_RIGHT_BUTTON )
1392                     button = GLUT_LEFT_BUTTON;
1393         }
1394 #endif /* !TARGET_HOST_WINCE */
1395
1396         if( button == -1 )
1397             return DefWindowProc( hWnd, uMsg, lParam, wParam );
1398
1399         /*
1400          * Do not execute the application's mouse callback if a menu
1401          * is hooked to this button.  In that case an appropriate
1402          * private call should be generated.
1403          */
1404         if( fgCheckActiveMenu( window, button, pressed,
1405                                window->State.MouseX, window->State.MouseY ) )
1406             break;
1407
1408         /* Set capture so that the window captures all the mouse messages */
1409         /*
1410          * XXX - Multiple button support:  Under X11, the mouse is not released
1411          * XXX - from the window until all buttons have been released, even if the
1412          * XXX - user presses a button in another window.  This will take more
1413          * XXX - code changes than I am up to at the moment (10/5/04).  The present
1414          * XXX - is a 90 percent solution.
1415          */
1416         if ( pressed == GL_TRUE )
1417           SetCapture ( window->Window.Handle ) ;
1418         else
1419           ReleaseCapture () ;
1420
1421         if( ! FETCH_WCB( *window, Mouse ) )
1422             break;
1423
1424         fgSetWindow( window );
1425         fgState.Modifiers = fghGetWin32Modifiers( );
1426
1427         INVOKE_WCB(
1428             *window, Mouse,
1429             ( button,
1430               pressed ? GLUT_DOWN : GLUT_UP,
1431               window->State.MouseX,
1432               window->State.MouseY
1433             )
1434         );
1435
1436         fgState.Modifiers = 0xffffffff;
1437     }
1438     break;
1439
1440     case 0x020a:
1441         /* Should be WM_MOUSEWHEEL but my compiler doesn't recognize it */
1442     {
1443         /*
1444          * XXX THIS IS SPECULATIVE -- John Fay, 10/2/03
1445          * XXX Should use WHEEL_DELTA instead of 120
1446          */
1447         int wheel_number = LOWORD( wParam );
1448         short ticks = ( short )HIWORD( wParam ) / 120;
1449         int direction = 1;
1450
1451         if( ticks < 0 )
1452         {
1453             direction = -1;
1454             ticks = -ticks;
1455         }
1456
1457         /*
1458          * The mouse cursor has moved. Remember the new mouse cursor's position
1459          */
1460         /*        window->State.MouseX = LOWORD( lParam ); */
1461         /* Need to adjust by window position, */
1462         /*        window->State.MouseY = HIWORD( lParam ); */
1463         /* change "lParam" to other parameter */
1464
1465         if( ! FETCH_WCB( *window, MouseWheel ) &&
1466             ! FETCH_WCB( *window, Mouse ) )
1467             break;
1468
1469         fgSetWindow( window );
1470         fgState.Modifiers = fghGetWin32Modifiers( );
1471
1472         while( ticks-- )
1473             if( FETCH_WCB( *window, MouseWheel ) )
1474                 INVOKE_WCB( *window, MouseWheel,
1475                             ( wheel_number,
1476                               direction,
1477                               window->State.MouseX,
1478                               window->State.MouseY
1479                             )
1480                 );
1481             else  /* No mouse wheel, call the mouse button callback twice */
1482             {
1483                 /*
1484                  * XXX The below assumes that you have no more than 3 mouse
1485                  * XXX buttons.  Sorry.
1486                  */
1487                 int button = wheel_number*2 + 4;
1488                 if( direction > 0 )
1489                     ++button;
1490                 INVOKE_WCB( *window, Mouse,
1491                             ( button, GLUT_DOWN,
1492                               window->State.MouseX, window->State.MouseY )
1493                 );
1494                 INVOKE_WCB( *window, Mouse,
1495                             ( button, GLUT_UP,
1496                               window->State.MouseX, window->State.MouseX )
1497                 );
1498             }
1499
1500         fgState.Modifiers = 0xffffffff;
1501     }
1502     break ;
1503
1504     case WM_SYSKEYDOWN:
1505     case WM_KEYDOWN:
1506     {
1507         int keypress = -1;
1508         POINT mouse_pos ;
1509
1510         if( ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
1511             break;
1512
1513         /*
1514          * Remember the current modifiers state. This is done here in order
1515          * to make sure the VK_DELETE keyboard callback is executed properly.
1516          */
1517         fgState.Modifiers = fghGetWin32Modifiers( );
1518
1519         GetCursorPos( &mouse_pos );
1520         ScreenToClient( window->Window.Handle, &mouse_pos );
1521
1522         window->State.MouseX = mouse_pos.x;
1523         window->State.MouseY = mouse_pos.y;
1524
1525         /* Convert the Win32 keystroke codes to GLUTtish way */
1526 #       define KEY(a,b) case a: keypress = b; break;
1527
1528         switch( wParam )
1529         {
1530             KEY( VK_F1,     GLUT_KEY_F1        );
1531             KEY( VK_F2,     GLUT_KEY_F2        );
1532             KEY( VK_F3,     GLUT_KEY_F3        );
1533             KEY( VK_F4,     GLUT_KEY_F4        );
1534             KEY( VK_F5,     GLUT_KEY_F5        );
1535             KEY( VK_F6,     GLUT_KEY_F6        );
1536             KEY( VK_F7,     GLUT_KEY_F7        );
1537             KEY( VK_F8,     GLUT_KEY_F8        );
1538             KEY( VK_F9,     GLUT_KEY_F9        );
1539             KEY( VK_F10,    GLUT_KEY_F10       );
1540             KEY( VK_F11,    GLUT_KEY_F11       );
1541             KEY( VK_F12,    GLUT_KEY_F12       );
1542             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
1543             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1544             KEY( VK_HOME,   GLUT_KEY_HOME      );
1545             KEY( VK_END,    GLUT_KEY_END       );
1546             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
1547             KEY( VK_UP,     GLUT_KEY_UP        );
1548             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
1549             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1550             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1551
1552         case VK_DELETE:
1553             /* The delete key should be treated as an ASCII keypress: */
1554             INVOKE_WCB( *window, Keyboard,
1555                         ( 127, window->State.MouseX, window->State.MouseY )
1556             );
1557         }
1558
1559 #if TARGET_HOST_WINCE
1560         if(!(lParam & 0x40000000)) /* Prevent auto-repeat */
1561         {
1562             if(wParam==(unsigned)gxKeyList.vkRight)
1563                 keypress = GLUT_KEY_RIGHT;
1564             else if(wParam==(unsigned)gxKeyList.vkLeft)
1565                 keypress = GLUT_KEY_LEFT;
1566             else if(wParam==(unsigned)gxKeyList.vkUp)
1567                 keypress = GLUT_KEY_UP;
1568             else if(wParam==(unsigned)gxKeyList.vkDown)
1569                 keypress = GLUT_KEY_DOWN;
1570             else if(wParam==(unsigned)gxKeyList.vkA)
1571                 keypress = GLUT_KEY_F1;
1572             else if(wParam==(unsigned)gxKeyList.vkB)
1573                 keypress = GLUT_KEY_F2;
1574             else if(wParam==(unsigned)gxKeyList.vkC)
1575                 keypress = GLUT_KEY_F3;
1576             else if(wParam==(unsigned)gxKeyList.vkStart)
1577                 keypress = GLUT_KEY_F4;
1578         }
1579 #endif
1580
1581         if( keypress != -1 )
1582             INVOKE_WCB( *window, Special,
1583                         ( keypress,
1584                           window->State.MouseX, window->State.MouseY )
1585             );
1586
1587         fgState.Modifiers = 0xffffffff;
1588     }
1589     break;
1590
1591     case WM_SYSKEYUP:
1592     case WM_KEYUP:
1593     {
1594         int keypress = -1;
1595         POINT mouse_pos;
1596
1597         /*
1598          * Remember the current modifiers state. This is done here in order
1599          * to make sure the VK_DELETE keyboard callback is executed properly.
1600          */
1601         fgState.Modifiers = fghGetWin32Modifiers( );
1602
1603         GetCursorPos( &mouse_pos );
1604         ScreenToClient( window->Window.Handle, &mouse_pos );
1605
1606         window->State.MouseX = mouse_pos.x;
1607         window->State.MouseY = mouse_pos.y;
1608
1609         /*
1610          * Convert the Win32 keystroke codes to GLUTtish way.
1611          * "KEY(a,b)" was defined under "WM_KEYDOWN"
1612          */
1613
1614         switch( wParam )
1615         {
1616             KEY( VK_F1,     GLUT_KEY_F1        );
1617             KEY( VK_F2,     GLUT_KEY_F2        );
1618             KEY( VK_F3,     GLUT_KEY_F3        );
1619             KEY( VK_F4,     GLUT_KEY_F4        );
1620             KEY( VK_F5,     GLUT_KEY_F5        );
1621             KEY( VK_F6,     GLUT_KEY_F6        );
1622             KEY( VK_F7,     GLUT_KEY_F7        );
1623             KEY( VK_F8,     GLUT_KEY_F8        );
1624             KEY( VK_F9,     GLUT_KEY_F9        );
1625             KEY( VK_F10,    GLUT_KEY_F10       );
1626             KEY( VK_F11,    GLUT_KEY_F11       );
1627             KEY( VK_F12,    GLUT_KEY_F12       );
1628             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
1629             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1630             KEY( VK_HOME,   GLUT_KEY_HOME      );
1631             KEY( VK_END,    GLUT_KEY_END       );
1632             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
1633             KEY( VK_UP,     GLUT_KEY_UP        );
1634             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
1635             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1636             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1637
1638           case VK_DELETE:
1639               /* The delete key should be treated as an ASCII keypress: */
1640               INVOKE_WCB( *window, KeyboardUp,
1641                           ( 127, window->State.MouseX, window->State.MouseY )
1642               );
1643               break;
1644
1645         default:
1646         {
1647 #if !TARGET_HOST_WINCE
1648             BYTE state[ 256 ];
1649             WORD code[ 2 ];
1650
1651             GetKeyboardState( state );
1652
1653             if( ToAscii( wParam, 0, state, code, 0 ) == 1 )
1654                 wParam=code[ 0 ];
1655
1656             INVOKE_WCB( *window, KeyboardUp,
1657                         ( (char)wParam,
1658                           window->State.MouseX, window->State.MouseY )
1659             );
1660 #endif /* !TARGET_HOST_WINCE */
1661         }
1662         }
1663
1664         if( keypress != -1 )
1665             INVOKE_WCB( *window, SpecialUp,
1666                         ( keypress,
1667                           window->State.MouseX, window->State.MouseY )
1668             );
1669
1670         fgState.Modifiers = 0xffffffff;
1671     }
1672     break;
1673
1674     case WM_SYSCHAR:
1675     case WM_CHAR:
1676     {
1677       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
1678             break;
1679
1680         fgState.Modifiers = fghGetWin32Modifiers( );
1681         INVOKE_WCB( *window, Keyboard,
1682                     ( (char)wParam,
1683                       window->State.MouseX, window->State.MouseY )
1684         );
1685         fgState.Modifiers = 0xffffffff;
1686     }
1687     break;
1688
1689     case WM_CAPTURECHANGED:
1690         /* User has finished resizing the window, force a redraw */
1691         INVOKE_WCB( *window, Display, ( ) );
1692
1693         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
1694         break;
1695
1696         /* Other messages that I have seen and which are not handled already */
1697     case WM_SETTEXT:  /* 0x000c */
1698         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1699         /* Pass it on to "DefWindowProc" to set the window text */
1700         break;
1701
1702     case WM_GETTEXT:  /* 0x000d */
1703         /* Ideally we would copy the title of the window into "lParam" */
1704         /* strncpy ( (char *)lParam, "Window Title", wParam );
1705            lRet = ( wParam > 12 ) ? 12 : wParam;  */
1706         /* the number of characters copied */
1707         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1708         break;
1709
1710     case WM_GETTEXTLENGTH:  /* 0x000e */
1711         /* Ideally we would get the length of the title of the window */
1712         lRet = 12;
1713         /* the number of characters in "Window Title\0" (see above) */
1714         break;
1715
1716     case WM_ERASEBKGND:  /* 0x0014 */
1717         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1718         break;
1719
1720 #if !TARGET_HOST_WINCE
1721     case WM_SYNCPAINT:  /* 0x0088 */
1722         /* Another window has moved, need to update this one */
1723         window->State.Redisplay = GL_TRUE;
1724         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1725         /* Help screen says this message must be passed to "DefWindowProc" */
1726         break;
1727
1728     case WM_NCPAINT:  /* 0x0085 */
1729       /* Need to update the border of this window */
1730         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1731         /* Pass it on to "DefWindowProc" to repaint a standard border */
1732         break;
1733
1734     case WM_SYSCOMMAND :  /* 0x0112 */
1735         {
1736           /*
1737            * We have received a system command message.  Try to act on it.
1738            * The commands are passed in through the "wParam" parameter:
1739            * The least significant digit seems to be which edge of the window
1740            * is being used for a resize event:
1741            *     4  3  5
1742            *     1     2
1743            *     7  6  8
1744            * Congratulations and thanks to Richard Rauch for figuring this out..
1745            */
1746             switch ( wParam & 0xfff0 )
1747             {
1748             case SC_SIZE       :
1749                 break ;
1750
1751             case SC_MOVE       :
1752                 break ;
1753
1754             case SC_MINIMIZE   :
1755                 /* User has clicked on the "-" to minimize the window */
1756                 /* Turn off the visibility */
1757                 window->State.Visible = GL_FALSE ;
1758
1759                 break ;
1760
1761             case SC_MAXIMIZE   :
1762                 break ;
1763
1764             case SC_NEXTWINDOW :
1765                 break ;
1766
1767             case SC_PREVWINDOW :
1768                 break ;
1769
1770             case SC_CLOSE      :
1771                 /* Followed very closely by a WM_CLOSE message */
1772                 break ;
1773
1774             case SC_VSCROLL    :
1775                 break ;
1776
1777             case SC_HSCROLL    :
1778                 break ;
1779
1780             case SC_MOUSEMENU  :
1781                 break ;
1782
1783             case SC_KEYMENU    :
1784                 break ;
1785
1786             case SC_ARRANGE    :
1787                 break ;
1788
1789             case SC_RESTORE    :
1790                 break ;
1791
1792             case SC_TASKLIST   :
1793                 break ;
1794
1795             case SC_SCREENSAVE :
1796                 break ;
1797
1798             case SC_HOTKEY     :
1799                 break ;
1800
1801             default:
1802 #if _DEBUG
1803                 fgWarning( "Unknown wParam type 0x%x", wParam );
1804 #endif
1805                 break;
1806             }
1807         }
1808 #endif /* !TARGET_HOST_WINCE */
1809
1810         /* We need to pass the message on to the operating system as well */
1811         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1812         break;
1813
1814     default:
1815         /* Handle unhandled messages */
1816         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1817         break;
1818     }
1819
1820     return lRet;
1821 }
1822 #endif
1823
1824 /*** END OF FILE ***/