aec6a1d33c27e02fd88a3918358801bb7b65040e
[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 #ifdef HAVE_ERRNO_H
31 #    include <errno.h>
32 #endif
33 #include <stdarg.h>
34 #ifdef  HAVE_VFPRINTF
35 #    define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
36 #elif defined(HAVE__DOPRNT)
37 #    define VFPRINTF(s,f,a) _doprnt((f),(a),(s))
38 #else
39 #    define VFPRINTF(s,f,a)
40 #endif
41
42 #ifdef _WIN32_WCE
43
44 typedef struct GXDisplayProperties GXDisplayProperties;
45 typedef struct GXKeyList GXKeyList;
46 #include <gx.h>
47
48 typedef struct GXKeyList (*GXGETDEFAULTKEYS)(int);
49 typedef int (*GXOPENINPUT)();
50
51 GXGETDEFAULTKEYS GXGetDefaultKeys_ = NULL;
52 GXOPENINPUT GXOpenInput_ = NULL;
53
54 struct GXKeyList gxKeyList;
55
56 #endif /* _WIN32_WCE */
57
58 /*
59  * Try to get the maximum value allowed for ints, falling back to the minimum
60  * guaranteed by ISO C99 if there is no suitable header.
61  */
62 #ifdef HAVE_LIMITS_H
63 #    include <limits.h>
64 #endif
65 #ifndef INT_MAX
66 #    define INT_MAX 32767
67 #endif
68
69 #ifndef MIN
70 #    define MIN(a,b) (((a)<(b)) ? (a) : (b))
71 #endif
72
73
74 /*
75  * TODO BEFORE THE STABLE RELEASE:
76  *
77  * There are some issues concerning window redrawing under X11, and maybe
78  * some events are not handled. The Win32 version lacks some more features,
79  * but seems acceptable for not demanding purposes.
80  *
81  * Need to investigate why the X11 version breaks out with an error when
82  * closing a window (using the window manager, not glutDestroyWindow)...
83  */
84
85 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
86
87 /*
88  * Handle a window configuration change. When no reshape
89  * callback is hooked, the viewport size is updated to
90  * match the new window size.
91  */
92 static void fghReshapeWindow ( SFG_Window *window, int width, int height )
93 {
94     SFG_Window *current_window = fgStructure.CurrentWindow;
95
96     freeglut_return_if_fail( window != NULL );
97
98
99 #if TARGET_HOST_POSIX_X11
100
101     XResizeWindow( fgDisplay.Display, window->Window.Handle,
102                    width, height );
103     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
104
105 #elif TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE)
106     {
107         RECT winRect;
108         int x, y, w, h;
109
110         /*
111          * For windowed mode, get the current position of the
112          * window and resize taking the size of the frame
113          * decorations into account.
114          */
115
116         /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
117         GetWindowRect( window->Window.Handle, &winRect );
118         x = winRect.left;
119         y = winRect.top;
120         w = width;
121         h = height;
122
123         if ( window->Parent == NULL )
124         {
125             if ( ! window->IsMenu && (window != fgStructure.GameModeWindow) )
126             {
127                 w += GetSystemMetrics( SM_CXSIZEFRAME ) * 2;
128                 h += GetSystemMetrics( SM_CYSIZEFRAME ) * 2 +
129                      GetSystemMetrics( SM_CYCAPTION );
130             }
131         }
132         else
133         {
134             RECT parentRect;
135             GetWindowRect( window->Parent->Window.Handle, &parentRect );
136             x -= parentRect.left + GetSystemMetrics( SM_CXSIZEFRAME ) * 2;
137             y -= parentRect.top  + GetSystemMetrics( SM_CYSIZEFRAME ) * 2 +
138                                    GetSystemMetrics( SM_CYCAPTION );
139         }
140
141         /*
142          * SWP_NOACTIVATE      Do not activate the window
143          * SWP_NOOWNERZORDER   Do not change position in z-order
144          * SWP_NOSENDCHANGING  Supress WM_WINDOWPOSCHANGING message
145          * SWP_NOZORDER        Retains the current Z order (ignore 2nd param)
146          */
147
148         SetWindowPos( window->Window.Handle,
149                       HWND_TOP,
150                       x, y, w, h,
151                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
152                       SWP_NOZORDER
153         );
154     }
155 #endif
156
157     /*
158      * XXX Should update {window->State.OldWidth, window->State.OldHeight}
159      * XXX to keep in lockstep with POSIX_X11 code.
160      */
161     if( FETCH_WCB( *window, Reshape ) )
162         INVOKE_WCB( *window, Reshape, ( width, height ) );
163     else
164     {
165         fgSetWindow( window );
166         glViewport( 0, 0, width, height );
167     }
168
169     /*
170      * Force a window redraw.  In Windows at least this is only a partial
171      * solution:  if the window is increasing in size in either dimension,
172      * the already-drawn part does not get drawn again and things look funny.
173      * But without this we get this bad behaviour whenever we resize the
174      * window.
175      */
176     window->State.Redisplay = GL_TRUE;
177
178     if( window->IsMenu )
179         fgSetWindow( current_window );
180 }
181
182 /*
183  * Calls a window's redraw method. This is used when
184  * a redraw is forced by the incoming window messages.
185  */
186 static void fghRedrawWindow ( SFG_Window *window )
187 {
188     SFG_Window *current_window = fgStructure.CurrentWindow;
189
190     freeglut_return_if_fail( window );
191     freeglut_return_if_fail( FETCH_WCB ( *window, Display ) );
192
193     window->State.Redisplay = GL_FALSE;
194
195     freeglut_return_if_fail( window->State.Visible );
196
197     fgSetWindow( window );
198
199     if( window->State.NeedToResize )
200     {
201         fghReshapeWindow(
202             window,
203             window->State.Width,
204             window->State.Height
205         );
206
207         window->State.NeedToResize = GL_FALSE;
208     }
209
210     INVOKE_WCB( *window, Display, ( ) );
211
212     fgSetWindow( current_window );
213 }
214
215 /*
216  * A static helper function to execute display callback for a window
217  */
218 static void fghcbDisplayWindow( SFG_Window *window,
219                                 SFG_Enumerator *enumerator )
220 {
221     if( window->State.Redisplay &&
222         window->State.Visible )
223     {
224         window->State.Redisplay = GL_FALSE;
225
226 #if TARGET_HOST_POSIX_X11
227         fghRedrawWindow ( window ) ;
228 #elif TARGET_HOST_MS_WINDOWS
229         RedrawWindow(
230             window->Window.Handle, NULL, NULL,
231             RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
232         );
233 #endif
234     }
235
236     fgEnumSubWindows( window, fghcbDisplayWindow, enumerator );
237 }
238
239 /*
240  * Make all windows perform a display call
241  */
242 static void fghDisplayAll( void )
243 {
244     SFG_Enumerator enumerator;
245
246     enumerator.found = GL_FALSE;
247     enumerator.data  =  NULL;
248
249     fgEnumWindows( fghcbDisplayWindow, &enumerator );
250 }
251
252 /*
253  * Window enumerator callback to check for the joystick polling code
254  */
255 static void fghcbCheckJoystickPolls( SFG_Window *window,
256                                      SFG_Enumerator *enumerator )
257 {
258     long int checkTime = fgElapsedTime( );
259
260     if( window->State.JoystickLastPoll + window->State.JoystickPollRate <=
261         checkTime )
262     {
263 #if !defined(_WIN32_WCE)
264         fgJoystickPollWindow( window );
265 #endif /* !defined(_WIN32_WCE) */
266         window->State.JoystickLastPoll = checkTime;
267     }
268
269     fgEnumSubWindows( window, fghcbCheckJoystickPolls, enumerator );
270 }
271
272 /*
273  * Check all windows for joystick polling
274  */
275 static void fghCheckJoystickPolls( void )
276 {
277     SFG_Enumerator enumerator;
278
279     enumerator.found = GL_FALSE;
280     enumerator.data  =  NULL;
281
282     fgEnumWindows( fghcbCheckJoystickPolls, &enumerator );
283 }
284
285 /*
286  * Check the global timers
287  */
288 static void fghCheckTimers( void )
289 {
290     long checkTime = fgElapsedTime( );
291
292     while( fgState.Timers.First )
293     {
294         SFG_Timer *timer = fgState.Timers.First;
295
296         if( timer->TriggerTime > checkTime )
297             break;
298
299         fgListRemove( &fgState.Timers, &timer->Node );
300         fgListAppend( &fgState.FreeTimers, &timer->Node );
301
302         timer->Callback( timer->ID );
303     }
304 }
305
306  
307 /* Platform-dependent time in milliseconds, as an unsigned 32-bit integer.
308  * This value wraps every 49.7 days, but integer overflows cancel
309  * when subtracting an initial start time, unless the total time exceeds
310  * 32-bit, where the GLUT API return value is also overflowed.
311  */  
312 unsigned long fgSystemTime(void) {
313 #if TARGET_HOST_SOLARIS || HAVE_GETTIMEOFDAY
314     struct timeval now;
315     gettimeofday( &now, NULL );
316     return now.tv_usec/1000 + now.tv_sec*1000;
317 #elif TARGET_HOST_MS_WINDOWS
318 #    if defined(_WIN32_WCE)
319     return GetTickCount();
320 #    else
321     return timeGetTime();
322 #    endif
323 #endif
324 }
325   
326 /*
327  * Elapsed Time
328  */
329 long fgElapsedTime( void )
330 {
331     return (long) (fgSystemTime() - fgState.Time);
332 }
333
334 /*
335  * Error Messages.
336  */
337 void fgError( const char *fmt, ... )
338 {
339     va_list ap;
340
341     va_start( ap, fmt );
342
343     fprintf( stderr, "freeglut ");
344     if( fgState.ProgramName )
345         fprintf( stderr, "(%s): ", fgState.ProgramName );
346     VFPRINTF( stderr, fmt, ap );
347     fprintf( stderr, "\n" );
348
349     va_end( ap );
350
351     if ( fgState.Initialised )
352         fgDeinitialize ();
353
354     exit( 1 );
355 }
356
357 void fgWarning( const char *fmt, ... )
358 {
359     va_list ap;
360
361     va_start( ap, fmt );
362
363     fprintf( stderr, "freeglut ");
364     if( fgState.ProgramName )
365         fprintf( stderr, "(%s): ", fgState.ProgramName );
366     VFPRINTF( stderr, fmt, ap );
367     fprintf( stderr, "\n" );
368
369     va_end( ap );
370 }
371
372 /*
373  * Indicates whether Joystick events are being used by ANY window.
374  *
375  * The current mechanism is to walk all of the windows and ask if
376  * there is a joystick callback.  We have a short-circuit early
377  * return if we find any joystick handler registered.
378  *
379  * The real way to do this is to make use of the glutTimer() API
380  * to more cleanly re-implement the joystick API.  Then, this code
381  * and all other "joystick timer" code can be yanked.
382  *
383  */
384 static void fghCheckJoystickCallback( SFG_Window* w, SFG_Enumerator* e)
385 {
386     if( FETCH_WCB( *w, Joystick ) )
387     {
388         e->found = GL_TRUE;
389         e->data = w;
390     }
391     fgEnumSubWindows( w, fghCheckJoystickCallback, e );
392 }
393 static int fghHaveJoystick( void )
394 {
395     SFG_Enumerator enumerator;
396
397     enumerator.found = GL_FALSE;
398     enumerator.data = NULL;
399     fgEnumWindows( fghCheckJoystickCallback, &enumerator );
400     return !!enumerator.data;
401 }
402 static void fghHavePendingRedisplaysCallback( SFG_Window* w, SFG_Enumerator* e)
403 {
404     if( w->State.Redisplay && w->State.Visible )
405     {
406         e->found = GL_TRUE;
407         e->data = w;
408     }
409     fgEnumSubWindows( w, fghHavePendingRedisplaysCallback, e );
410 }
411 static int fghHavePendingRedisplays (void)
412 {
413     SFG_Enumerator enumerator;
414
415     enumerator.found = GL_FALSE;
416     enumerator.data = NULL;
417     fgEnumWindows( fghHavePendingRedisplaysCallback, &enumerator );
418     return !!enumerator.data;
419 }
420 /*
421  * Returns the number of GLUT ticks (milliseconds) till the next timer event.
422  */
423 static long fghNextTimer( void )
424 {
425     long ret = INT_MAX;
426     SFG_Timer *timer = fgState.Timers.First;
427
428     if( timer )
429         ret = timer->TriggerTime - fgElapsedTime();
430     if( ret < 0 )
431         ret = 0;
432
433     return ret;
434 }
435 /*
436  * Does the magic required to relinquish the CPU until something interesting
437  * happens.
438  */
439 static void fghSleepForEvents( void )
440 {
441     long msec;
442
443     if( fgState.IdleCallback || fghHavePendingRedisplays( ) )
444         return;
445
446     msec = fghNextTimer( );
447     /* XXX Use GLUT timers for joysticks... */
448     /* XXX Dumb; forces granularity to .01sec */
449     if( fghHaveJoystick( ) && ( msec > 10 ) )     
450         msec = 10;
451
452 #if TARGET_HOST_POSIX_X11
453     /*
454      * Possibly due to aggressive use of XFlush() and friends,
455      * it is possible to have our socket drained but still have
456      * unprocessed events.  (Or, this may just be normal with
457      * X, anyway?)  We do non-trivial processing of X events
458      * after the event-reading loop, in any case, so we
459      * need to allow that we may have an empty socket but non-
460      * empty event queue.
461      */
462     if( ! XPending( fgDisplay.Display ) )
463     {
464         fd_set fdset;
465         int err;
466         int socket;
467         struct timeval wait;
468
469         socket = ConnectionNumber( fgDisplay.Display );
470         FD_ZERO( &fdset );
471         FD_SET( socket, &fdset );
472         wait.tv_sec = msec / 1000;
473         wait.tv_usec = (msec % 1000) * 1000;
474         err = select( socket+1, &fdset, NULL, NULL, &wait );
475
476 #ifdef HAVE_ERRNO_H
477         if( ( -1 == err ) && ( errno != EINTR ) )
478             fgWarning ( "freeglut select() error: %d", errno );
479 #endif
480     }
481 #elif TARGET_HOST_MS_WINDOWS
482     MsgWaitForMultipleObjects( 0, NULL, FALSE, msec, QS_ALLINPUT );
483 #endif
484 }
485
486 #if TARGET_HOST_POSIX_X11
487 /*
488  * Returns GLUT modifier mask for the state field of an X11 event.
489  */
490 static int fghGetXModifiers( int state )
491 {
492     int ret = 0;
493
494     if( state & ( ShiftMask | LockMask ) )
495         ret |= GLUT_ACTIVE_SHIFT;
496     if( state & ControlMask )
497         ret |= GLUT_ACTIVE_CTRL;
498     if( state & Mod1Mask )
499         ret |= GLUT_ACTIVE_ALT;
500
501     return ret;
502 }
503 #endif
504
505
506 #if TARGET_HOST_POSIX_X11 && _DEBUG
507
508 static const char* fghTypeToString( int type )
509 {
510     switch( type ) {
511     case KeyPress: return "KeyPress";
512     case KeyRelease: return "KeyRelease";
513     case ButtonPress: return "ButtonPress";
514     case ButtonRelease: return "ButtonRelease";
515     case MotionNotify: return "MotionNotify";
516     case EnterNotify: return "EnterNotify";
517     case LeaveNotify: return "LeaveNotify";
518     case FocusIn: return "FocusIn";
519     case FocusOut: return "FocusOut";
520     case KeymapNotify: return "KeymapNotify";
521     case Expose: return "Expose";
522     case GraphicsExpose: return "GraphicsExpose";
523     case NoExpose: return "NoExpose";
524     case VisibilityNotify: return "VisibilityNotify";
525     case CreateNotify: return "CreateNotify";
526     case DestroyNotify: return "DestroyNotify";
527     case UnmapNotify: return "UnmapNotify";
528     case MapNotify: return "MapNotify";
529     case MapRequest: return "MapRequest";
530     case ReparentNotify: return "ReparentNotify";
531     case ConfigureNotify: return "ConfigureNotify";
532     case ConfigureRequest: return "ConfigureRequest";
533     case GravityNotify: return "GravityNotify";
534     case ResizeRequest: return "ResizeRequest";
535     case CirculateNotify: return "CirculateNotify";
536     case CirculateRequest: return "CirculateRequest";
537     case PropertyNotify: return "PropertyNotify";
538     case SelectionClear: return "SelectionClear";
539     case SelectionRequest: return "SelectionRequest";
540     case SelectionNotify: return "SelectionNotify";
541     case ColormapNotify: return "ColormapNotify";
542     case ClientMessage: return "ClientMessage";
543     case MappingNotify: return "MappingNotify";
544     default: return "UNKNOWN";
545     }
546 }
547
548 static const char* fghBoolToString( Bool b )
549 {
550     return b == False ? "False" : "True";
551 }
552
553 static const char* fghNotifyHintToString( char is_hint )
554 {
555     switch( is_hint ) {
556     case NotifyNormal: return "NotifyNormal";
557     case NotifyHint: return "NotifyHint";
558     default: return "UNKNOWN";
559     }
560 }
561
562 static const char* fghNotifyModeToString( int mode )
563 {
564     switch( mode ) {
565     case NotifyNormal: return "NotifyNormal";
566     case NotifyGrab: return "NotifyGrab";
567     case NotifyUngrab: return "NotifyUngrab";
568     case NotifyWhileGrabbed: return "NotifyWhileGrabbed";
569     default: return "UNKNOWN";
570     }
571 }
572
573 static const char* fghNotifyDetailToString( int detail )
574 {
575     switch( detail ) {
576     case NotifyAncestor: return "NotifyAncestor";
577     case NotifyVirtual: return "NotifyVirtual";
578     case NotifyInferior: return "NotifyInferior";
579     case NotifyNonlinear: return "NotifyNonlinear";
580     case NotifyNonlinearVirtual: return "NotifyNonlinearVirtual";
581     case NotifyPointer: return "NotifyPointer";
582     case NotifyPointerRoot: return "NotifyPointerRoot";
583     case NotifyDetailNone: return "NotifyDetailNone";
584     default: return "UNKNOWN";
585     }
586 }
587
588 static const char* fghVisibilityToString( int state ) {
589     switch( state ) {
590     case VisibilityUnobscured: return "VisibilityUnobscured";
591     case VisibilityPartiallyObscured: return "VisibilityPartiallyObscured";
592     case VisibilityFullyObscured: return "VisibilityFullyObscured";
593     default: return "UNKNOWN";
594     }
595 }
596
597 static const char* fghConfigureDetailToString( int detail )
598 {
599     switch( detail ) {
600     case Above: return "Above";
601     case Below: return "Below";
602     case TopIf: return "TopIf";
603     case BottomIf: return "BottomIf";
604     case Opposite: return "Opposite";
605     default: return "UNKNOWN";
606     }
607 }
608
609 static const char* fghPlaceToString( int place )
610 {
611     switch( place ) {
612     case PlaceOnTop: return "PlaceOnTop";
613     case PlaceOnBottom: return "PlaceOnBottom";
614     default: return "UNKNOWN";
615     }
616 }
617
618 static const char* fghMappingRequestToString( int request )
619 {
620     switch( request ) {
621     case MappingModifier: return "MappingModifier";
622     case MappingKeyboard: return "MappingKeyboard";
623     case MappingPointer: return "MappingPointer";
624     default: return "UNKNOWN";
625     }
626 }
627
628 static const char* fghPropertyStateToString( int state )
629 {
630     switch( state ) {
631     case PropertyNewValue: return "PropertyNewValue";
632     case PropertyDelete: return "PropertyDelete";
633     default: return "UNKNOWN";
634     }
635 }
636
637 static const char* fghColormapStateToString( int state )
638 {
639     switch( state ) {
640     case ColormapUninstalled: return "ColormapUninstalled";
641     case ColormapInstalled: return "ColormapInstalled";
642     default: return "UNKNOWN";
643     }
644 }
645
646 static void fghPrintEvent( XEvent *event )
647 {
648     switch( event->type ) {
649
650     case KeyPress:
651     case KeyRelease: {
652         XKeyEvent *e = &event->xkey;
653         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
654                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
655                    "keycode=%u, same_screen=%s", fghTypeToString( e->type ),
656                    e->window, e->root, e->subwindow, (unsigned long)e->time,
657                    e->x, e->y, e->x_root, e->y_root, e->state, e->keycode,
658                    fghBoolToString( e->same_screen ) );
659         break;
660     }
661
662     case ButtonPress:
663     case ButtonRelease: {
664         XButtonEvent *e = &event->xbutton;
665         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
666                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
667                    "button=%u, same_screen=%d", fghTypeToString( e->type ),
668                    e->window, e->root, e->subwindow, (unsigned long)e->time,
669                    e->x, e->y, e->x_root, e->y_root, e->state, e->button,
670                    fghBoolToString( e->same_screen ) );
671         break;
672     }
673
674     case MotionNotify: {
675         XMotionEvent *e = &event->xmotion;
676         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
677                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
678                    "is_hint=%s, same_screen=%d", fghTypeToString( e->type ),
679                    e->window, e->root, e->subwindow, (unsigned long)e->time,
680                    e->x, e->y, e->x_root, e->y_root, e->state,
681                    fghNotifyHintToString( e->is_hint ),
682                    fghBoolToString( e->same_screen ) );
683         break;
684     }
685
686     case EnterNotify:
687     case LeaveNotify: {
688         XCrossingEvent *e = &event->xcrossing;
689         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
690                    "(x,y)=(%d,%d), mode=%s, detail=%s, same_screen=%d, "
691                    "focus=%d, state=0x%x", fghTypeToString( e->type ),
692                    e->window, e->root, e->subwindow, (unsigned long)e->time,
693                    e->x, e->y, fghNotifyModeToString( e->mode ),
694                    fghNotifyDetailToString( e->detail ), (int)e->same_screen,
695                    (int)e->focus, e->state );
696         break;
697     }
698
699     case FocusIn:
700     case FocusOut: {
701         XFocusChangeEvent *e = &event->xfocus;
702         fgWarning( "%s: window=0x%x, mode=%s, detail=%s",
703                    fghTypeToString( e->type ), e->window,
704                    fghNotifyModeToString( e->mode ),
705                    fghNotifyDetailToString( e->detail ) );
706         break;
707     }
708
709     case KeymapNotify: {
710         XKeymapEvent *e = &event->xkeymap;
711         char buf[32 * 2 + 1];
712         int i;
713         for ( i = 0; i < 32; i++ ) {
714             snprintf( &buf[ i * 2 ], sizeof( buf ) - i * 2,
715                       "%02x", e->key_vector[ i ] );
716         }
717         buf[ i ] = '\0';
718         fgWarning( "%s: window=0x%x, %s", fghTypeToString( e->type ), e->window,
719                    buf );
720         break;
721     }
722
723     case Expose: {
724         XExposeEvent *e = &event->xexpose;
725         fgWarning( "%s: window=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
726                    "count=%d", fghTypeToString( e->type ), e->window, e->x,
727                    e->y, e->width, e->height, e->count );
728         break;
729     }
730
731     case GraphicsExpose: {
732         XGraphicsExposeEvent *e = &event->xgraphicsexpose;
733         fgWarning( "%s: drawable=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
734                    "count=%d, (major_code,minor_code)=(%d,%d)",
735                    fghTypeToString( e->type ), e->drawable, e->x, e->y,
736                    e->width, e->height, e->count, e->major_code,
737                    e->minor_code );
738         break;
739     }
740
741     case NoExpose: {
742         XNoExposeEvent *e = &event->xnoexpose;
743         fgWarning( "%s: drawable=0x%x, (major_code,minor_code)=(%d,%d)",
744                    fghTypeToString( e->type ), e->drawable, e->major_code,
745                    e->minor_code );
746         break;
747     }
748
749     case VisibilityNotify: {
750         XVisibilityEvent *e = &event->xvisibility;
751         fgWarning( "%s: window=0x%x, state=%s", fghTypeToString( e->type ),
752                    e->window, fghVisibilityToString( e->state) );
753         break;
754     }
755
756     case CreateNotify: {
757         XCreateWindowEvent *e = &event->xcreatewindow;
758         fgWarning( "%s: (x,y)=(%d,%d), (width,height)=(%d,%d), border_width=%d, "
759                    "window=0x%x, override_redirect=%s",
760                    fghTypeToString( e->type ), e->x, e->y, e->width, e->height,
761                    e->border_width, e->window,
762                    fghBoolToString( e->override_redirect ) );
763         break;
764     }
765
766     case DestroyNotify: {
767         XDestroyWindowEvent *e = &event->xdestroywindow;
768         fgWarning( "%s: event=0x%x, window=0x%x",
769                    fghTypeToString( e->type ), e->event, e->window );
770         break;
771     }
772
773     case UnmapNotify: {
774         XUnmapEvent *e = &event->xunmap;
775         fgWarning( "%s: event=0x%x, window=0x%x, from_configure=%s",
776                    fghTypeToString( e->type ), e->event, e->window,
777                    fghBoolToString( e->from_configure ) );
778         break;
779     }
780
781     case MapNotify: {
782         XMapEvent *e = &event->xmap;
783         fgWarning( "%s: event=0x%x, window=0x%x, override_redirect=%s",
784                    fghTypeToString( e->type ), e->event, e->window,
785                    fghBoolToString( e->override_redirect ) );
786         break;
787     }
788
789     case MapRequest: {
790         XMapRequestEvent *e = &event->xmaprequest;
791         fgWarning( "%s: parent=0x%x, window=0x%x",
792                    fghTypeToString( event->type ), e->parent, e->window );
793         break;
794     }
795
796     case ReparentNotify: {
797         XReparentEvent *e = &event->xreparent;
798         fgWarning( "%s: event=0x%x, window=0x%x, parent=0x%x, (x,y)=(%d,%d), "
799                    "override_redirect=%s", fghTypeToString( e->type ),
800                    e->event, e->window, e->parent, e->x, e->y,
801                    fghBoolToString( e->override_redirect ) );
802         break;
803     }
804
805     case ConfigureNotify: {
806         XConfigureEvent *e = &event->xconfigure;
807         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d), "
808                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
809                    "override_redirect=%s", fghTypeToString( e->type ), e->event,
810                    e->window, e->x, e->y, e->width, e->height, e->border_width,
811                    e->above, fghBoolToString( e->override_redirect ) );
812         break;
813     }
814
815     case ConfigureRequest: {
816         XConfigureRequestEvent *e = &event->xconfigurerequest;
817         fgWarning( "%s: parent=0x%x, window=0x%x, (x,y)=(%d,%d), "
818                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
819                    "detail=%s, value_mask=%lx", fghTypeToString( e->type ),
820                    e->parent, e->window, e->x, e->y, e->width, e->height,
821                    e->border_width, e->above,
822                    fghConfigureDetailToString( e->detail ), e->value_mask );
823         break;
824     }
825
826     case GravityNotify: {
827         XGravityEvent *e = &event->xgravity;
828         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d)",
829                    fghTypeToString( e->type ), e->event, e->window, e->x, e->y );
830         break;
831     }
832
833     case ResizeRequest: {
834         XResizeRequestEvent *e = &event->xresizerequest;
835         fgWarning( "%s: window=0x%x, (width,height)=(%d,%d)",
836                    fghTypeToString( e->type ), e->window, e->width, e->height );
837         break;
838     }
839
840     case CirculateNotify: {
841         XCirculateEvent *e = &event->xcirculate;
842         fgWarning( "%s: event=0x%x, window=0x%x, place=%s",
843                    fghTypeToString( e->type ), e->event, e->window,
844                    fghPlaceToString( e->place ) );
845         break;
846     }
847
848     case CirculateRequest: {
849         XCirculateRequestEvent *e = &event->xcirculaterequest;
850         fgWarning( "%s: parent=0x%x, window=0x%x, place=%s",
851                    fghTypeToString( e->type ), e->parent, e->window,
852                    fghPlaceToString( e->place ) );
853         break;
854     }
855
856     case PropertyNotify: {
857         XPropertyEvent *e = &event->xproperty;
858         fgWarning( "%s: window=0x%x, atom=%lu, time=%lu, state=%s",
859                    fghTypeToString( e->type ), e->window,
860                    (unsigned long)e->atom, (unsigned long)e->time,
861                    fghPropertyStateToString( e->state ) );
862         break;
863     }
864
865     case SelectionClear: {
866         XSelectionClearEvent *e = &event->xselectionclear;
867         fgWarning( "%s: window=0x%x, selection=%lu, time=%lu",
868                    fghTypeToString( e->type ), e->window,
869                    (unsigned long)e->selection, (unsigned long)e->time );
870         break;
871     }
872
873     case SelectionRequest: {
874         XSelectionRequestEvent *e = &event->xselectionrequest;
875         fgWarning( "%s: owner=0x%x, requestor=0x%x, selection=0x%x, "
876                    "target=0x%x, property=%lu, time=%lu",
877                    fghTypeToString( e->type ), e->owner, e->requestor,
878                    (unsigned long)e->selection, (unsigned long)e->target,
879                    (unsigned long)e->property, (unsigned long)e->time );
880         break;
881     }
882
883     case SelectionNotify: {
884         XSelectionEvent *e = &event->xselection;
885         fgWarning( "%s: requestor=0x%x, selection=0x%x, target=0x%x, "
886                    "property=%lu, time=%lu", fghTypeToString( e->type ),
887                    e->requestor, (unsigned long)e->selection,
888                    (unsigned long)e->target, (unsigned long)e->property,
889                    (unsigned long)e->time );
890         break;
891     }
892
893     case ColormapNotify: {
894         XColormapEvent *e = &event->xcolormap;
895         fgWarning( "%s: window=0x%x, colormap=%lu, new=%s, state=%s",
896                    fghTypeToString( e->type ), e->window,
897                    (unsigned long)e->colormap, fghBoolToString( e->new ),
898                    fghColormapStateToString( e->state ) );
899         break;
900     }
901
902     case ClientMessage: {
903         XClientMessageEvent *e = &event->xclient;
904         char buf[ 61 ];
905         char* p = buf;
906         char* end = buf + sizeof( buf );
907         int i;
908         switch( e->format ) {
909         case 8:
910           for ( i = 0; i < 20; i++, p += 3 ) {
911                 snprintf( p, end - p, " %02x", e->data.b[ i ] );
912             }
913             break;
914         case 16:
915             for ( i = 0; i < 10; i++, p += 5 ) {
916                 snprintf( p, end - p, " %04x", e->data.s[ i ] );
917             }
918             break;
919         case 32:
920             for ( i = 0; i < 5; i++, p += 9 ) {
921                 snprintf( p, end - p, " %08lx", e->data.l[ i ] );
922             }
923             break;
924         }
925         *p = '\0';
926         fgWarning( "%s: window=0x%x, message_type=%lu, format=%d, data=(%s )",
927                    fghTypeToString( e->type ), e->window,
928                    (unsigned long)e->message_type, e->format, buf );
929         break;
930     }
931
932     case MappingNotify: {
933         XMappingEvent *e = &event->xmapping;
934         fgWarning( "%s: window=0x%x, request=%s, first_keycode=%d, count=%d",
935                    fghTypeToString( e->type ), e->window,
936                    fghMappingRequestToString( e->request ), e->first_keycode,
937                    e->count );
938         break;
939     }
940
941     default: {
942         fgWarning( "%s", fghTypeToString( event->type ) );
943         break;
944     }
945     }
946 }
947
948 #endif
949
950 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
951
952 /*
953  * Executes a single iteration in the freeglut processing loop.
954  */
955 void FGAPIENTRY glutMainLoopEvent( void )
956 {
957 #if TARGET_HOST_POSIX_X11
958     SFG_Window* window;
959     XEvent event;
960
961     /* This code was repeated constantly, so here it goes into a definition: */
962 #define GETWINDOW(a)                             \
963     window = fgWindowByHandle( event.a.window ); \
964     if( window == NULL )                         \
965         break;
966
967 #define GETMOUSE(a)                              \
968     window->State.MouseX = event.a.x;            \
969     window->State.MouseY = event.a.y;
970
971     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
972
973     while( XPending( fgDisplay.Display ) )
974     {
975         XNextEvent( fgDisplay.Display, &event );
976 #if _DEBUG
977         fghPrintEvent( &event );
978 #endif
979
980         switch( event.type )
981         {
982         case ClientMessage:
983             if(fgIsSpaceballXEvent(&event)) {
984                 fgSpaceballHandleXEvent(&event);
985                 break;
986             }
987             /* Destroy the window when the WM_DELETE_WINDOW message arrives */
988             if( (Atom) event.xclient.data.l[ 0 ] == fgDisplay.DeleteWindow )
989             {
990                 GETWINDOW( xclient );
991
992                 fgDestroyWindow ( window );
993
994                 if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
995                 {
996                     fgDeinitialize( );
997                     exit( 0 );
998                 }
999                 else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
1000                     fgState.ExecState = GLUT_EXEC_STATE_STOP;
1001
1002                 return;
1003             }
1004             break;
1005
1006             /*
1007              * CreateNotify causes a configure-event so that sub-windows are
1008              * handled compatibly with GLUT.  Otherwise, your sub-windows
1009              * (in freeglut only) will not get an initial reshape event,
1010              * which can break things.
1011              *
1012              * GLUT presumably does this because it generally tries to treat
1013              * sub-windows the same as windows.
1014              */
1015         case CreateNotify:
1016         case ConfigureNotify:
1017             {
1018                 int width, height;
1019                 if( event.type == CreateNotify ) {
1020                     GETWINDOW( xcreatewindow );
1021                     width = event.xcreatewindow.width;
1022                     height = event.xcreatewindow.height;
1023                 } else {
1024                     GETWINDOW( xconfigure );
1025                     width = event.xconfigure.width;
1026                     height = event.xconfigure.height;
1027                 }
1028
1029                 if( ( width != window->State.OldWidth ) ||
1030                     ( height != window->State.OldHeight ) )
1031                 {
1032                     SFG_Window *current_window = fgStructure.CurrentWindow;
1033
1034                     window->State.OldWidth = width;
1035                     window->State.OldHeight = height;
1036                     if( FETCH_WCB( *window, Reshape ) )
1037                         INVOKE_WCB( *window, Reshape, ( width, height ) );
1038                     else
1039                     {
1040                         fgSetWindow( window );
1041                         glViewport( 0, 0, width, height );
1042                     }
1043                     glutPostRedisplay( );
1044                     if( window->IsMenu )
1045                         fgSetWindow( current_window );
1046                 }
1047             }
1048             break;
1049
1050         case DestroyNotify:
1051             /*
1052              * This is sent to confirm the XDestroyWindow call.
1053              *
1054              * XXX WHY is this commented out?  Should we re-enable it?
1055              */
1056             /* fgAddToWindowDestroyList ( window ); */
1057             break;
1058
1059         case Expose:
1060             /*
1061              * We are too dumb to process partial exposes...
1062              *
1063              * XXX Well, we could do it.  However, it seems to only
1064              * XXX be potentially useful for single-buffered (since
1065              * XXX double-buffered does not respect viewport when we
1066              * XXX do a buffer-swap).
1067              *
1068              */
1069             if( event.xexpose.count == 0 )
1070             {
1071                 GETWINDOW( xexpose );
1072                 window->State.Redisplay = GL_TRUE;
1073             }
1074             break;
1075
1076         case MapNotify:
1077             break;
1078
1079         case UnmapNotify:
1080             /* We get this when iconifying a window. */ 
1081             GETWINDOW( xunmap );
1082             INVOKE_WCB( *window, WindowStatus, ( GLUT_HIDDEN ) );
1083             window->State.Visible = GL_FALSE;
1084             break;
1085
1086         case MappingNotify:
1087             /*
1088              * Have the client's keyboard knowledge updated (xlib.ps,
1089              * page 206, says that's a good thing to do)
1090              */
1091             XRefreshKeyboardMapping( (XMappingEvent *) &event );
1092             break;
1093
1094         case VisibilityNotify:
1095         {
1096             /*
1097              * Sending this event, the X server can notify us that the window
1098              * has just acquired one of the three possible visibility states:
1099              * VisibilityUnobscured, VisibilityPartiallyObscured or
1100              * VisibilityFullyObscured. Note that we DO NOT receive a
1101              * VisibilityNotify event when iconifying a window, we only get an
1102              * UnmapNotify then.
1103              */
1104             GETWINDOW( xvisibility );
1105             switch( event.xvisibility.state )
1106             {
1107             case VisibilityUnobscured:
1108                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_RETAINED ) );
1109                 window->State.Visible = GL_TRUE;
1110                 break;
1111
1112             case VisibilityPartiallyObscured:
1113                 INVOKE_WCB( *window, WindowStatus,
1114                             ( GLUT_PARTIALLY_RETAINED ) );
1115                 window->State.Visible = GL_TRUE;
1116                 break;
1117
1118             case VisibilityFullyObscured:
1119                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_COVERED ) );
1120                 window->State.Visible = GL_FALSE;
1121                 break;
1122
1123             default:
1124                 fgWarning( "Unknown X visibility state: %d",
1125                            event.xvisibility.state );
1126                 break;
1127             }
1128         }
1129         break;
1130
1131         case EnterNotify:
1132         case LeaveNotify:
1133             GETWINDOW( xcrossing );
1134             GETMOUSE( xcrossing );
1135             if( ( event.type == LeaveNotify ) && window->IsMenu &&
1136                 window->ActiveMenu && window->ActiveMenu->IsActive )
1137                 fgUpdateMenuHighlight( window->ActiveMenu );
1138
1139             INVOKE_WCB( *window, Entry, ( ( EnterNotify == event.type ) ?
1140                                           GLUT_ENTERED :
1141                                           GLUT_LEFT ) );
1142             break;
1143
1144         case MotionNotify:
1145         {
1146             GETWINDOW( xmotion );
1147             GETMOUSE( xmotion );
1148
1149             if( window->ActiveMenu )
1150             {
1151                 if( window == window->ActiveMenu->ParentWindow )
1152                 {
1153                     window->ActiveMenu->Window->State.MouseX =
1154                         event.xmotion.x_root - window->ActiveMenu->X;
1155                     window->ActiveMenu->Window->State.MouseY =
1156                         event.xmotion.y_root - window->ActiveMenu->Y;
1157                 }
1158
1159                 fgUpdateMenuHighlight( window->ActiveMenu );
1160
1161                 break;
1162             }
1163
1164             /*
1165              * XXX For more than 5 buttons, just check {event.xmotion.state},
1166              * XXX rather than a host of bit-masks?  Or maybe we need to
1167              * XXX track ButtonPress/ButtonRelease events in our own
1168              * XXX bit-mask?
1169              */
1170             fgState.Modifiers = fghGetXModifiers( event.xmotion.state );
1171             if ( event.xmotion.state & ( Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask ) ) {
1172                 INVOKE_WCB( *window, Motion, ( event.xmotion.x,
1173                                                event.xmotion.y ) );
1174             } else {
1175                 INVOKE_WCB( *window, Passive, ( event.xmotion.x,
1176                                                 event.xmotion.y ) );
1177             }
1178             fgState.Modifiers = INVALID_MODIFIERS;
1179         }
1180         break;
1181
1182         case ButtonRelease:
1183         case ButtonPress:
1184         {
1185             GLboolean pressed = GL_TRUE;
1186             int button;
1187
1188             if( event.type == ButtonRelease )
1189                 pressed = GL_FALSE ;
1190
1191             /*
1192              * A mouse button has been pressed or released. Traditionally,
1193              * break if the window was found within the freeglut structures.
1194              */
1195             GETWINDOW( xbutton );
1196             GETMOUSE( xbutton );
1197
1198             /*
1199              * An X button (at least in XFree86) is numbered from 1.
1200              * A GLUT button is numbered from 0.
1201              * Old GLUT passed through buttons other than just the first
1202              * three, though it only gave symbolic names and official
1203              * support to the first three.
1204              */
1205             button = event.xbutton.button - 1;
1206
1207             /*
1208              * Do not execute the application's mouse callback if a menu
1209              * is hooked to this button.  In that case an appropriate
1210              * private call should be generated.
1211              */
1212             if( fgCheckActiveMenu( window, button, pressed,
1213                                    event.xbutton.x_root, event.xbutton.y_root ) )
1214                 break;
1215
1216             /*
1217              * Check if there is a mouse or mouse wheel callback hooked to the
1218              * window
1219              */
1220             if( ! FETCH_WCB( *window, Mouse ) &&
1221                 ! FETCH_WCB( *window, MouseWheel ) )
1222                 break;
1223
1224             fgState.Modifiers = fghGetXModifiers( event.xbutton.state );
1225
1226             /* Finally execute the mouse or mouse wheel callback */
1227             if( ( button < glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS ) ) || ( ! FETCH_WCB( *window, MouseWheel ) ) )
1228                 INVOKE_WCB( *window, Mouse, ( button,
1229                                               pressed ? GLUT_DOWN : GLUT_UP,
1230                                               event.xbutton.x,
1231                                               event.xbutton.y )
1232                 );
1233             else
1234             {
1235                 /*
1236                  * Map 4 and 5 to wheel zero; EVEN to +1, ODD to -1
1237                  *  "  6 and 7 "    "   one; ...
1238                  *
1239                  * XXX This *should* be behind some variables/macros,
1240                  * XXX since the order and numbering isn't certain
1241                  * XXX See XFree86 configuration docs (even back in the
1242                  * XXX 3.x days, and especially with 4.x).
1243                  *
1244                  * XXX Note that {button} has already been decremeted
1245                  * XXX in mapping from X button numbering to GLUT.
1246                  */
1247                 int wheel_number = (button - glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS )) / 2;
1248                 int direction = -1;
1249                 if( button % 2 )
1250                     direction = 1;
1251
1252                 if( pressed )
1253                     INVOKE_WCB( *window, MouseWheel, ( wheel_number,
1254                                                        direction,
1255                                                        event.xbutton.x,
1256                                                        event.xbutton.y )
1257                     );
1258             }
1259             fgState.Modifiers = INVALID_MODIFIERS;
1260         }
1261         break;
1262
1263         case KeyRelease:
1264         case KeyPress:
1265         {
1266             FGCBKeyboard keyboard_cb;
1267             FGCBSpecial special_cb;
1268
1269             GETWINDOW( xkey );
1270             GETMOUSE( xkey );
1271
1272             /* Detect auto repeated keys, if configured globally or per-window */
1273
1274             if ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE )
1275             {
1276                 if (event.type==KeyRelease)
1277                 {
1278                     /*
1279                      * Look at X11 keystate to detect repeat mode.
1280                      * While X11 says the key is actually held down, we'll ignore KeyRelease/KeyPress pairs.
1281                      */
1282
1283                     char keys[32];
1284                     XQueryKeymap( fgDisplay.Display, keys ); /* Look at X11 keystate to detect repeat mode */
1285
1286                     if ( event.xkey.keycode<256 )            /* XQueryKeymap is limited to 256 keycodes    */
1287                     {
1288                         if ( keys[event.xkey.keycode>>3] & (1<<(event.xkey.keycode%8)) )
1289                             window->State.KeyRepeating = GL_TRUE;
1290                         else
1291                             window->State.KeyRepeating = GL_FALSE;
1292                     }
1293                 }
1294             }
1295             else
1296                 window->State.KeyRepeating = GL_FALSE;
1297
1298             /* Cease processing this event if it is auto repeated */
1299
1300             if (window->State.KeyRepeating)
1301             {
1302                 if (event.type == KeyPress) window->State.KeyRepeating = GL_FALSE;
1303                 break;
1304             }
1305
1306             if( event.type == KeyPress )
1307             {
1308                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, Keyboard ));
1309                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, Special  ));
1310             }
1311             else
1312             {
1313                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, KeyboardUp ));
1314                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, SpecialUp  ));
1315             }
1316
1317             /* Is there a keyboard/special callback hooked for this window? */
1318             if( keyboard_cb || special_cb )
1319             {
1320                 XComposeStatus composeStatus;
1321                 char asciiCode[ 32 ];
1322                 KeySym keySym;
1323                 int len;
1324
1325                 /* Check for the ASCII/KeySym codes associated with the event: */
1326                 len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode),
1327                                      &keySym, &composeStatus
1328                 );
1329
1330                 /* GLUT API tells us to have two separate callbacks... */
1331                 if( len > 0 )
1332                 {
1333                     /* ...one for the ASCII translateable keypresses... */
1334                     if( keyboard_cb )
1335                     {
1336                         fgSetWindow( window );
1337                         fgState.Modifiers = fghGetXModifiers( event.xkey.state );
1338                         keyboard_cb( asciiCode[ 0 ],
1339                                      event.xkey.x, event.xkey.y
1340                         );
1341                         fgState.Modifiers = INVALID_MODIFIERS;
1342                     }
1343                 }
1344                 else
1345                 {
1346                     int special = -1;
1347
1348                     /*
1349                      * ...and one for all the others, which need to be
1350                      * translated to GLUT_KEY_Xs...
1351                      */
1352                     switch( keySym )
1353                     {
1354                     case XK_F1:     special = GLUT_KEY_F1;     break;
1355                     case XK_F2:     special = GLUT_KEY_F2;     break;
1356                     case XK_F3:     special = GLUT_KEY_F3;     break;
1357                     case XK_F4:     special = GLUT_KEY_F4;     break;
1358                     case XK_F5:     special = GLUT_KEY_F5;     break;
1359                     case XK_F6:     special = GLUT_KEY_F6;     break;
1360                     case XK_F7:     special = GLUT_KEY_F7;     break;
1361                     case XK_F8:     special = GLUT_KEY_F8;     break;
1362                     case XK_F9:     special = GLUT_KEY_F9;     break;
1363                     case XK_F10:    special = GLUT_KEY_F10;    break;
1364                     case XK_F11:    special = GLUT_KEY_F11;    break;
1365                     case XK_F12:    special = GLUT_KEY_F12;    break;
1366
1367                     case XK_KP_Left:
1368                     case XK_Left:   special = GLUT_KEY_LEFT;   break;
1369                     case XK_KP_Right:
1370                     case XK_Right:  special = GLUT_KEY_RIGHT;  break;
1371                     case XK_KP_Up:
1372                     case XK_Up:     special = GLUT_KEY_UP;     break;
1373                     case XK_KP_Down:
1374                     case XK_Down:   special = GLUT_KEY_DOWN;   break;
1375
1376                     case XK_KP_Prior:
1377                     case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
1378                     case XK_KP_Next:
1379                     case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
1380                     case XK_KP_Home:
1381                     case XK_Home:   special = GLUT_KEY_HOME;   break;
1382                     case XK_KP_End:
1383                     case XK_End:    special = GLUT_KEY_END;    break;
1384                     case XK_KP_Insert:
1385                     case XK_Insert: special = GLUT_KEY_INSERT; break;
1386
1387                     case XK_Num_Lock :  special = GLUT_KEY_NUM_LOCK;  break;
1388                     case XK_KP_Begin :  special = GLUT_KEY_BEGIN;     break;
1389                     case XK_KP_Delete:  special = GLUT_KEY_DELETE;    break;
1390
1391                     case XK_Shift_L:   special = GLUT_KEY_SHIFT_L;    break;
1392                     case XK_Shift_R:   special = GLUT_KEY_SHIFT_R;    break;
1393                     case XK_Control_L: special = GLUT_KEY_CTRL_L;     break;
1394                     case XK_Control_R: special = GLUT_KEY_CTRL_R;     break;
1395                     case XK_Alt_L:     special = GLUT_KEY_ALT_L;      break;
1396                     case XK_Alt_R:     special = GLUT_KEY_ALT_R;      break;
1397                     }
1398
1399                     /*
1400                      * Execute the callback (if one has been specified),
1401                      * given that the special code seems to be valid...
1402                      */
1403                     if( special_cb && (special != -1) )
1404                     {
1405                         fgSetWindow( window );
1406                         fgState.Modifiers = fghGetXModifiers( event.xkey.state );
1407                         special_cb( special, event.xkey.x, event.xkey.y );
1408                         fgState.Modifiers = INVALID_MODIFIERS;
1409                     }
1410                 }
1411             }
1412         }
1413         break;
1414
1415         case ReparentNotify:
1416             break; /* XXX Should disable this event */
1417
1418         /* Not handled */
1419         case GravityNotify:
1420             break;
1421
1422         default:
1423             fgWarning ("Unknown X event type: %d\n", event.type);
1424             break;
1425         }
1426     }
1427
1428 #elif TARGET_HOST_MS_WINDOWS
1429
1430     MSG stMsg;
1431
1432     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
1433
1434     while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
1435     {
1436         if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1437         {
1438             if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1439             {
1440                 fgDeinitialize( );
1441                 exit( 0 );
1442             }
1443             else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
1444                 fgState.ExecState = GLUT_EXEC_STATE_STOP;
1445
1446             return;
1447         }
1448
1449         TranslateMessage( &stMsg );
1450         DispatchMessage( &stMsg );
1451     }
1452 #endif
1453
1454     if( fgState.Timers.First )
1455         fghCheckTimers( );
1456     fghCheckJoystickPolls( );
1457     fghDisplayAll( );
1458
1459     fgCloseWindows( );
1460 }
1461
1462 /*
1463  * Enters the freeglut processing loop.
1464  * Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1465  */
1466 void FGAPIENTRY glutMainLoop( void )
1467 {
1468     int action;
1469
1470 #if TARGET_HOST_MS_WINDOWS
1471     SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1472 #endif
1473
1474     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoop" );
1475
1476 #if TARGET_HOST_MS_WINDOWS
1477     /*
1478      * Processing before the main loop:  If there is a window which is open and
1479      * which has a visibility callback, call it.  I know this is an ugly hack,
1480      * but I'm not sure what else to do about it.  Ideally we should leave
1481      * something uninitialized in the create window code and initialize it in
1482      * the main loop, and have that initialization create a "WM_ACTIVATE"
1483      * message.  Then we would put the visibility callback code in the
1484      * "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1485      */
1486     while( window )
1487     {
1488         if ( FETCH_WCB( *window, Visibility ) )
1489         {
1490             SFG_Window *current_window = fgStructure.CurrentWindow ;
1491
1492             INVOKE_WCB( *window, Visibility, ( window->State.Visible ) );
1493             fgSetWindow( current_window );
1494         }
1495
1496         window = (SFG_Window *)window->Node.Next ;
1497     }
1498 #endif
1499
1500     fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1501     while( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1502     {
1503         SFG_Window *window;
1504
1505         glutMainLoopEvent( );
1506         /*
1507          * Step through the list of windows, seeing if there are any
1508          * that are not menus
1509          */
1510         for( window = ( SFG_Window * )fgStructure.Windows.First;
1511              window;
1512              window = ( SFG_Window * )window->Node.Next )
1513             if ( ! ( window->IsMenu ) )
1514                 break;
1515
1516         if( ! window )
1517             fgState.ExecState = GLUT_EXEC_STATE_STOP;
1518         else
1519         {
1520             if( fgState.IdleCallback )
1521             {
1522                 if( fgStructure.CurrentWindow &&
1523                     fgStructure.CurrentWindow->IsMenu )
1524                     /* fail safe */
1525                     fgSetWindow( window );
1526                 fgState.IdleCallback( );
1527             }
1528
1529             fghSleepForEvents( );
1530         }
1531     }
1532
1533     /*
1534      * When this loop terminates, destroy the display, state and structure
1535      * of a freeglut session, so that another glutInit() call can happen
1536      *
1537      * Save the "ActionOnWindowClose" because "fgDeinitialize" resets it.
1538      */
1539     action = fgState.ActionOnWindowClose;
1540     fgDeinitialize( );
1541     if( action == GLUT_ACTION_EXIT )
1542         exit( 0 );
1543 }
1544
1545 /*
1546  * Leaves the freeglut processing loop.
1547  */
1548 void FGAPIENTRY glutLeaveMainLoop( void )
1549 {
1550     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveMainLoop" );
1551     fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1552 }
1553
1554
1555 #if TARGET_HOST_MS_WINDOWS
1556 /*
1557  * Determine a GLUT modifer mask based on MS-WINDOWS system info.
1558  */
1559 static int fghGetWin32Modifiers (void)
1560 {
1561     return
1562         ( ( ( GetKeyState( VK_LSHIFT   ) < 0 ) ||
1563             ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1564         ( ( ( GetKeyState( VK_LCONTROL ) < 0 ) ||
1565             ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1566         ( ( ( GetKeyState( VK_LMENU    ) < 0 ) ||
1567             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1568 }
1569
1570 /*
1571  * The window procedure for handling Win32 events
1572  */
1573 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam,
1574                                LPARAM lParam )
1575 {
1576     static unsigned char lControl = 0, rControl = 0, lShift = 0,
1577                          rShift = 0, lAlt = 0, rAlt = 0;
1578
1579     SFG_Window* window;
1580     PAINTSTRUCT ps;
1581     LRESULT lRet = 1;
1582
1583     FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED ( "Event Handler" ) ;
1584
1585     window = fgWindowByHandle( hWnd );
1586
1587     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1588       return DefWindowProc( hWnd, uMsg, wParam, lParam );
1589
1590     /* printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0,
1591              uMsg, wParam, lParam ); */
1592
1593     if ( window )
1594     {
1595       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Down! */
1596       if ( !lControl && GetAsyncKeyState ( VK_LCONTROL ) )
1597       {
1598           INVOKE_WCB    ( *window, Special,
1599                         ( GLUT_KEY_CTRL_L, window->State.MouseX, window->State.MouseY )
1600                       );
1601
1602           lControl = 1;
1603       }
1604
1605       if ( !rControl && GetAsyncKeyState ( VK_RCONTROL ) )
1606       {
1607           INVOKE_WCB ( *window, Special,
1608                        ( GLUT_KEY_CTRL_R, window->State.MouseX, window->State.MouseY )
1609                      );
1610
1611           rControl = 1;
1612       }
1613
1614       if ( !lShift && GetAsyncKeyState ( VK_LSHIFT ) )
1615       {
1616           INVOKE_WCB ( *window, Special,
1617                        ( GLUT_KEY_SHIFT_L, window->State.MouseX, window->State.MouseY )
1618                      );
1619
1620           lShift = 1;
1621       }
1622
1623       if ( !rShift && GetAsyncKeyState ( VK_RSHIFT ) )
1624       {
1625           INVOKE_WCB ( *window, Special,
1626                        ( GLUT_KEY_SHIFT_R, window->State.MouseX, window->State.MouseY )
1627                      );
1628
1629           rShift = 1;
1630       }
1631
1632       if ( !lAlt && GetAsyncKeyState ( VK_LMENU ) )
1633       {
1634           INVOKE_WCB ( *window, Special,
1635                        ( GLUT_KEY_ALT_L, window->State.MouseX, window->State.MouseY )
1636                      );
1637
1638           lAlt = 1;
1639       }
1640
1641       if ( !rAlt && GetAsyncKeyState ( VK_RMENU ) )
1642       {
1643           INVOKE_WCB ( *window, Special,
1644                        ( GLUT_KEY_ALT_R, window->State.MouseX, window->State.MouseY )
1645                      );
1646
1647           rAlt = 1;
1648       }
1649
1650       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Up! */
1651       if ( lControl && !GetAsyncKeyState ( VK_LCONTROL ) )
1652       {
1653           INVOKE_WCB ( *window, SpecialUp,
1654                        ( GLUT_KEY_CTRL_L, window->State.MouseX, window->State.MouseY )
1655                      );
1656
1657           lControl = 0;
1658       }
1659
1660       if ( rControl && !GetAsyncKeyState ( VK_RCONTROL ) )
1661       {
1662           INVOKE_WCB ( *window, SpecialUp,
1663                        ( GLUT_KEY_CTRL_R, window->State.MouseX, window->State.MouseY )
1664                      );
1665
1666           rControl = 0;
1667       }
1668
1669       if ( lShift && !GetAsyncKeyState ( VK_LSHIFT ) )
1670       {
1671           INVOKE_WCB ( *window, SpecialUp,
1672                        ( GLUT_KEY_SHIFT_L, window->State.MouseX, window->State.MouseY )
1673                      );
1674
1675           lShift = 0;
1676       }
1677
1678       if ( rShift && !GetAsyncKeyState ( VK_RSHIFT ) )
1679       {
1680           INVOKE_WCB ( *window, SpecialUp,
1681                        ( GLUT_KEY_SHIFT_R, window->State.MouseX, window->State.MouseY )
1682                      );
1683
1684           rShift = 0;
1685       }
1686
1687       if ( lAlt && !GetAsyncKeyState ( VK_LMENU ) )
1688       {
1689           INVOKE_WCB ( *window, SpecialUp,
1690                        ( GLUT_KEY_ALT_L, window->State.MouseX, window->State.MouseY )
1691                      );
1692
1693           lAlt = 0;
1694       }
1695
1696       if ( rAlt && !GetAsyncKeyState ( VK_RMENU ) )
1697       {
1698           INVOKE_WCB ( *window, SpecialUp,
1699                        ( GLUT_KEY_ALT_R, window->State.MouseX, window->State.MouseY )
1700                      );
1701
1702           rAlt = 0;
1703       }
1704     }
1705
1706     switch( uMsg )
1707     {
1708     case WM_CREATE:
1709         /* The window structure is passed as the creation structure paramter... */
1710         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1711         FREEGLUT_INTERNAL_ERROR_EXIT ( ( window != NULL ), "Cannot create window",
1712                                        "fgWindowProc" );
1713
1714         window->Window.Handle = hWnd;
1715         window->Window.Device = GetDC( hWnd );
1716         if( window->IsMenu )
1717         {
1718             unsigned int current_DisplayMode = fgState.DisplayMode;
1719             fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH;
1720 #if !defined(_WIN32_WCE)
1721             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1722 #endif
1723             fgState.DisplayMode = current_DisplayMode;
1724
1725             if( fgStructure.MenuContext )
1726                 wglMakeCurrent( window->Window.Device,
1727                                 fgStructure.MenuContext->MContext
1728                 );
1729             else
1730             {
1731                 fgStructure.MenuContext =
1732                     (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
1733                 fgStructure.MenuContext->MContext =
1734                     wglCreateContext( window->Window.Device );
1735             }
1736
1737             /* window->Window.Context = wglGetCurrentContext ();   */
1738             window->Window.Context = wglCreateContext( window->Window.Device );
1739         }
1740         else
1741         {
1742 #if !defined(_WIN32_WCE)
1743             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1744 #endif
1745
1746             if( ! fgState.UseCurrentContext )
1747                 window->Window.Context =
1748                     wglCreateContext( window->Window.Device );
1749             else
1750             {
1751                 window->Window.Context = wglGetCurrentContext( );
1752                 if( ! window->Window.Context )
1753                     window->Window.Context =
1754                         wglCreateContext( window->Window.Device );
1755             }
1756
1757 #if !defined(_WIN32_WCE)
1758             fgNewWGLCreateContext( window );
1759 #endif
1760         }
1761
1762         window->State.NeedToResize = GL_TRUE;
1763         if( ( window->State.Width < 0 ) || ( window->State.Height < 0 ) )
1764         {
1765             SFG_Window *current_window = fgStructure.CurrentWindow;
1766
1767             fgSetWindow( window );
1768             window->State.Width = glutGet( GLUT_WINDOW_WIDTH );
1769             window->State.Height = glutGet( GLUT_WINDOW_HEIGHT );
1770             fgSetWindow( current_window );
1771         }
1772
1773         ReleaseDC( window->Window.Handle, window->Window.Device );
1774
1775 #if defined(_WIN32_WCE)
1776         /* Take over button handling */
1777         {
1778             HINSTANCE dxDllLib=LoadLibrary(_T("gx.dll"));
1779             if (dxDllLib)
1780             {
1781                 GXGetDefaultKeys_=(GXGETDEFAULTKEYS)GetProcAddress(dxDllLib, _T("?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z"));
1782                 GXOpenInput_=(GXOPENINPUT)GetProcAddress(dxDllLib, _T("?GXOpenInput@@YAHXZ"));
1783             }
1784
1785             if(GXOpenInput_)
1786                 (*GXOpenInput_)();
1787             if(GXGetDefaultKeys_)
1788                 gxKeyList = (*GXGetDefaultKeys_)(GX_LANDSCAPEKEYS);
1789         }
1790
1791 #endif /* defined(_WIN32_WCE) */
1792         break;
1793
1794     case WM_SIZE:
1795         /*
1796          * If the window is visible, then it is the user manually resizing it.
1797          * If it is not, then it is the system sending us a dummy resize with
1798          * zero dimensions on a "glutIconifyWindow" call.
1799          */
1800         if( window->State.Visible )
1801         {
1802             window->State.NeedToResize = GL_TRUE;
1803 #if defined(_WIN32_WCE)
1804             window->State.Width  = HIWORD(lParam);
1805             window->State.Height = LOWORD(lParam);
1806 #else
1807             window->State.Width  = LOWORD(lParam);
1808             window->State.Height = HIWORD(lParam);
1809 #endif /* defined(_WIN32_WCE) */
1810         }
1811
1812         break;
1813
1814     case WM_SETFOCUS:
1815 /*        printf("WM_SETFOCUS: %p\n", window ); */
1816         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1817         INVOKE_WCB( *window, Entry, ( GLUT_ENTERED ) );
1818         break;
1819
1820     case WM_KILLFOCUS:
1821 /*        printf("WM_KILLFOCUS: %p\n", window ); */
1822         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1823         INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
1824
1825         if( window->IsMenu &&
1826             window->ActiveMenu && window->ActiveMenu->IsActive )
1827             fgUpdateMenuHighlight( window->ActiveMenu );
1828
1829         break;
1830
1831 #if 0
1832     case WM_ACTIVATE:
1833         if (LOWORD(wParam) != WA_INACTIVE)
1834         {
1835 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
1836                    window->State.Cursor ); */
1837             fgSetCursor( window, window->State.Cursor );
1838         }
1839
1840         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1841         break;
1842 #endif
1843
1844     case WM_SETCURSOR:
1845 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
1846         if( LOWORD( lParam ) == HTCLIENT )
1847             fgSetCursor ( window, window->State.Cursor ) ;
1848         else
1849             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1850         break;
1851
1852     case WM_SHOWWINDOW:
1853         window->State.Visible = GL_TRUE;
1854         window->State.Redisplay = GL_TRUE;
1855         break;
1856
1857     case WM_PAINT:
1858         /* Turn on the visibility in case it was turned off somehow */
1859         window->State.Visible = GL_TRUE;
1860         BeginPaint( hWnd, &ps );
1861         fghRedrawWindow( window );
1862         EndPaint( hWnd, &ps );
1863         break;
1864
1865     case WM_CLOSE:
1866         fgDestroyWindow ( window );
1867         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
1868             PostQuitMessage(0);
1869         break;
1870
1871     case WM_DESTROY:
1872         /*
1873          * The window already got destroyed, so don't bother with it.
1874          */
1875         return 0;
1876
1877     case WM_MOUSEMOVE:
1878     {
1879 #if defined(_WIN32_WCE)
1880         window->State.MouseX = 320-HIWORD( lParam );
1881         window->State.MouseY = LOWORD( lParam );
1882 #else
1883         window->State.MouseX = LOWORD( lParam );
1884         window->State.MouseY = HIWORD( lParam );
1885 #endif /* defined(_WIN32_WCE) */
1886         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1887         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1888         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1889         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1890
1891         if ( window->ActiveMenu )
1892         {
1893             fgUpdateMenuHighlight( window->ActiveMenu );
1894             break;
1895         }
1896
1897         fgState.Modifiers = fghGetWin32Modifiers( );
1898
1899         if( ( wParam & MK_LBUTTON ) ||
1900             ( wParam & MK_MBUTTON ) ||
1901             ( wParam & MK_RBUTTON ) )
1902             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
1903                                            window->State.MouseY ) );
1904         else
1905             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
1906                                             window->State.MouseY ) );
1907
1908         fgState.Modifiers = INVALID_MODIFIERS;
1909     }
1910     break;
1911
1912     case WM_LBUTTONDOWN:
1913     case WM_MBUTTONDOWN:
1914     case WM_RBUTTONDOWN:
1915     case WM_LBUTTONUP:
1916     case WM_MBUTTONUP:
1917     case WM_RBUTTONUP:
1918     {
1919         GLboolean pressed = GL_TRUE;
1920         int button;
1921
1922 #if defined(_WIN32_WCE)
1923         window->State.MouseX = 320-HIWORD( lParam );
1924         window->State.MouseY = LOWORD( lParam );
1925 #else
1926         window->State.MouseX = LOWORD( lParam );
1927         window->State.MouseY = HIWORD( lParam );
1928 #endif /* defined(_WIN32_WCE) */
1929
1930         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1931         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1932         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1933         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1934
1935         switch( uMsg )
1936         {
1937         case WM_LBUTTONDOWN:
1938             pressed = GL_TRUE;
1939             button = GLUT_LEFT_BUTTON;
1940             break;
1941         case WM_MBUTTONDOWN:
1942             pressed = GL_TRUE;
1943             button = GLUT_MIDDLE_BUTTON;
1944             break;
1945         case WM_RBUTTONDOWN:
1946             pressed = GL_TRUE;
1947             button = GLUT_RIGHT_BUTTON;
1948             break;
1949         case WM_LBUTTONUP:
1950             pressed = GL_FALSE;
1951             button = GLUT_LEFT_BUTTON;
1952             break;
1953         case WM_MBUTTONUP:
1954             pressed = GL_FALSE;
1955             button = GLUT_MIDDLE_BUTTON;
1956             break;
1957         case WM_RBUTTONUP:
1958             pressed = GL_FALSE;
1959             button = GLUT_RIGHT_BUTTON;
1960             break;
1961         default:
1962             pressed = GL_FALSE;
1963             button = -1;
1964             break;
1965         }
1966
1967 #if !defined(_WIN32_WCE)
1968         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1969         {
1970             if( button == GLUT_LEFT_BUTTON )
1971                 button = GLUT_RIGHT_BUTTON;
1972             else
1973                 if( button == GLUT_RIGHT_BUTTON )
1974                     button = GLUT_LEFT_BUTTON;
1975         }
1976 #endif /* !defined(_WIN32_WCE) */
1977
1978         if( button == -1 )
1979             return DefWindowProc( hWnd, uMsg, lParam, wParam );
1980
1981         /*
1982          * Do not execute the application's mouse callback if a menu
1983          * is hooked to this button.  In that case an appropriate
1984          * private call should be generated.
1985          */
1986         if( fgCheckActiveMenu( window, button, pressed,
1987                                window->State.MouseX, window->State.MouseY ) )
1988             break;
1989
1990         /* Set capture so that the window captures all the mouse messages */
1991         /*
1992          * XXX - Multiple button support:  Under X11, the mouse is not released
1993          * XXX - from the window until all buttons have been released, even if the
1994          * XXX - user presses a button in another window.  This will take more
1995          * XXX - code changes than I am up to at the moment (10/5/04).  The present
1996          * XXX - is a 90 percent solution.
1997          */
1998         if ( pressed == GL_TRUE )
1999           SetCapture ( window->Window.Handle ) ;
2000         else
2001           ReleaseCapture () ;
2002
2003         if( ! FETCH_WCB( *window, Mouse ) )
2004             break;
2005
2006         fgSetWindow( window );
2007         fgState.Modifiers = fghGetWin32Modifiers( );
2008
2009         INVOKE_WCB(
2010             *window, Mouse,
2011             ( button,
2012               pressed ? GLUT_DOWN : GLUT_UP,
2013               window->State.MouseX,
2014               window->State.MouseY
2015             )
2016         );
2017
2018         fgState.Modifiers = INVALID_MODIFIERS;
2019     }
2020     break;
2021
2022     case 0x020a:
2023         /* Should be WM_MOUSEWHEEL but my compiler doesn't recognize it */
2024     {
2025         /*
2026          * XXX THIS IS SPECULATIVE -- John Fay, 10/2/03
2027          * XXX Should use WHEEL_DELTA instead of 120
2028          */
2029         int wheel_number = LOWORD( wParam );
2030         short ticks = ( short )HIWORD( wParam ) / 120;
2031         int direction = 1;
2032
2033         if( ticks < 0 )
2034         {
2035             direction = -1;
2036             ticks = -ticks;
2037         }
2038
2039         /*
2040          * The mouse cursor has moved. Remember the new mouse cursor's position
2041          */
2042         /*        window->State.MouseX = LOWORD( lParam ); */
2043         /* Need to adjust by window position, */
2044         /*        window->State.MouseY = HIWORD( lParam ); */
2045         /* change "lParam" to other parameter */
2046
2047         if( ! FETCH_WCB( *window, MouseWheel ) &&
2048             ! FETCH_WCB( *window, Mouse ) )
2049             break;
2050
2051         fgSetWindow( window );
2052         fgState.Modifiers = fghGetWin32Modifiers( );
2053
2054         while( ticks-- )
2055             if( FETCH_WCB( *window, MouseWheel ) )
2056                 INVOKE_WCB( *window, MouseWheel,
2057                             ( wheel_number,
2058                               direction,
2059                               window->State.MouseX,
2060                               window->State.MouseY
2061                             )
2062                 );
2063             else  /* No mouse wheel, call the mouse button callback twice */
2064             {
2065                 /*
2066                  * Map wheel zero to button 3 and 4; +1 to 3, -1 to 4
2067                  *  "    "   one                     +1 to 5, -1 to 6, ...
2068                  *
2069                  * XXX The below assumes that you have no more than 3 mouse
2070                  * XXX buttons.  Sorry.
2071                  */
2072                 int button = wheel_number * 2 + 3;
2073                 if( direction < 0 )
2074                     ++button;
2075                 INVOKE_WCB( *window, Mouse,
2076                             ( button, GLUT_DOWN,
2077                               window->State.MouseX, window->State.MouseY )
2078                 );
2079                 INVOKE_WCB( *window, Mouse,
2080                             ( button, GLUT_UP,
2081                               window->State.MouseX, window->State.MouseY )
2082                 );
2083             }
2084
2085         fgState.Modifiers = INVALID_MODIFIERS;
2086     }
2087     break ;
2088
2089     case WM_SYSKEYDOWN:
2090     case WM_KEYDOWN:
2091     {
2092         int keypress = -1;
2093         POINT mouse_pos ;
2094
2095         if( ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
2096             break;
2097
2098         /*
2099          * Remember the current modifiers state. This is done here in order
2100          * to make sure the VK_DELETE keyboard callback is executed properly.
2101          */
2102         fgState.Modifiers = fghGetWin32Modifiers( );
2103
2104         GetCursorPos( &mouse_pos );
2105         ScreenToClient( window->Window.Handle, &mouse_pos );
2106
2107         window->State.MouseX = mouse_pos.x;
2108         window->State.MouseY = mouse_pos.y;
2109
2110         /* Convert the Win32 keystroke codes to GLUTtish way */
2111 #       define KEY(a,b) case a: keypress = b; break;
2112
2113         switch( wParam )
2114         {
2115             KEY( VK_F1,     GLUT_KEY_F1        );
2116             KEY( VK_F2,     GLUT_KEY_F2        );
2117             KEY( VK_F3,     GLUT_KEY_F3        );
2118             KEY( VK_F4,     GLUT_KEY_F4        );
2119             KEY( VK_F5,     GLUT_KEY_F5        );
2120             KEY( VK_F6,     GLUT_KEY_F6        );
2121             KEY( VK_F7,     GLUT_KEY_F7        );
2122             KEY( VK_F8,     GLUT_KEY_F8        );
2123             KEY( VK_F9,     GLUT_KEY_F9        );
2124             KEY( VK_F10,    GLUT_KEY_F10       );
2125             KEY( VK_F11,    GLUT_KEY_F11       );
2126             KEY( VK_F12,    GLUT_KEY_F12       );
2127             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
2128             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
2129             KEY( VK_HOME,   GLUT_KEY_HOME      );
2130             KEY( VK_END,    GLUT_KEY_END       );
2131             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
2132             KEY( VK_UP,     GLUT_KEY_UP        );
2133             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
2134             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
2135             KEY( VK_INSERT, GLUT_KEY_INSERT    );
2136             KEY( VK_LCONTROL, GLUT_KEY_CTRL_L  );
2137             KEY( VK_RCONTROL, GLUT_KEY_CTRL_R  );
2138             KEY( VK_LSHIFT, GLUT_KEY_SHIFT_L   );
2139             KEY( VK_RSHIFT, GLUT_KEY_SHIFT_R   );
2140             KEY( VK_LMENU,  GLUT_KEY_ALT_L     );
2141             KEY( VK_RMENU,  GLUT_KEY_ALT_R     );
2142
2143         case VK_DELETE:
2144             /* The delete key should be treated as an ASCII keypress: */
2145             INVOKE_WCB( *window, Keyboard,
2146                         ( 127, window->State.MouseX, window->State.MouseY )
2147             );
2148         }
2149
2150 #if defined(_WIN32_WCE)
2151         if(!(lParam & 0x40000000)) /* Prevent auto-repeat */
2152         {
2153             if(wParam==(unsigned)gxKeyList.vkRight)
2154                 keypress = GLUT_KEY_RIGHT;
2155             else if(wParam==(unsigned)gxKeyList.vkLeft)
2156                 keypress = GLUT_KEY_LEFT;
2157             else if(wParam==(unsigned)gxKeyList.vkUp)
2158                 keypress = GLUT_KEY_UP;
2159             else if(wParam==(unsigned)gxKeyList.vkDown)
2160                 keypress = GLUT_KEY_DOWN;
2161             else if(wParam==(unsigned)gxKeyList.vkA)
2162                 keypress = GLUT_KEY_F1;
2163             else if(wParam==(unsigned)gxKeyList.vkB)
2164                 keypress = GLUT_KEY_F2;
2165             else if(wParam==(unsigned)gxKeyList.vkC)
2166                 keypress = GLUT_KEY_F3;
2167             else if(wParam==(unsigned)gxKeyList.vkStart)
2168                 keypress = GLUT_KEY_F4;
2169         }
2170 #endif
2171
2172         if( keypress != -1 )
2173             INVOKE_WCB( *window, Special,
2174                         ( keypress,
2175                           window->State.MouseX, window->State.MouseY )
2176             );
2177
2178         fgState.Modifiers = INVALID_MODIFIERS;
2179     }
2180     break;
2181
2182     case WM_SYSKEYUP:
2183     case WM_KEYUP:
2184     {
2185         int keypress = -1;
2186         POINT mouse_pos;
2187
2188         /*
2189          * Remember the current modifiers state. This is done here in order
2190          * to make sure the VK_DELETE keyboard callback is executed properly.
2191          */
2192         fgState.Modifiers = fghGetWin32Modifiers( );
2193
2194         GetCursorPos( &mouse_pos );
2195         ScreenToClient( window->Window.Handle, &mouse_pos );
2196
2197         window->State.MouseX = mouse_pos.x;
2198         window->State.MouseY = mouse_pos.y;
2199
2200         /*
2201          * Convert the Win32 keystroke codes to GLUTtish way.
2202          * "KEY(a,b)" was defined under "WM_KEYDOWN"
2203          */
2204
2205         switch( wParam )
2206         {
2207             KEY( VK_F1,     GLUT_KEY_F1        );
2208             KEY( VK_F2,     GLUT_KEY_F2        );
2209             KEY( VK_F3,     GLUT_KEY_F3        );
2210             KEY( VK_F4,     GLUT_KEY_F4        );
2211             KEY( VK_F5,     GLUT_KEY_F5        );
2212             KEY( VK_F6,     GLUT_KEY_F6        );
2213             KEY( VK_F7,     GLUT_KEY_F7        );
2214             KEY( VK_F8,     GLUT_KEY_F8        );
2215             KEY( VK_F9,     GLUT_KEY_F9        );
2216             KEY( VK_F10,    GLUT_KEY_F10       );
2217             KEY( VK_F11,    GLUT_KEY_F11       );
2218             KEY( VK_F12,    GLUT_KEY_F12       );
2219             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
2220             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
2221             KEY( VK_HOME,   GLUT_KEY_HOME      );
2222             KEY( VK_END,    GLUT_KEY_END       );
2223             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
2224             KEY( VK_UP,     GLUT_KEY_UP        );
2225             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
2226             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
2227             KEY( VK_INSERT, GLUT_KEY_INSERT    );
2228             KEY( VK_LCONTROL, GLUT_KEY_CTRL_L  );
2229             KEY( VK_RCONTROL, GLUT_KEY_CTRL_R  );
2230             KEY( VK_LSHIFT, GLUT_KEY_SHIFT_L   );
2231             KEY( VK_RSHIFT, GLUT_KEY_SHIFT_R   );
2232             KEY( VK_LMENU,  GLUT_KEY_ALT_L     );
2233             KEY( VK_RMENU,  GLUT_KEY_ALT_R     );
2234
2235           case VK_DELETE:
2236               /* The delete key should be treated as an ASCII keypress: */
2237               INVOKE_WCB( *window, KeyboardUp,
2238                           ( 127, window->State.MouseX, window->State.MouseY )
2239               );
2240               break;
2241
2242         default:
2243         {
2244 #if !defined(_WIN32_WCE)
2245             BYTE state[ 256 ];
2246             WORD code[ 2 ];
2247
2248             GetKeyboardState( state );
2249
2250             if( ToAscii( (UINT)wParam, 0, state, code, 0 ) == 1 )
2251                 wParam=code[ 0 ];
2252
2253             INVOKE_WCB( *window, KeyboardUp,
2254                         ( (char)wParam,
2255                           window->State.MouseX, window->State.MouseY )
2256             );
2257 #endif /* !defined(_WIN32_WCE) */
2258         }
2259         }
2260
2261         if( keypress != -1 )
2262             INVOKE_WCB( *window, SpecialUp,
2263                         ( keypress,
2264                           window->State.MouseX, window->State.MouseY )
2265             );
2266
2267         fgState.Modifiers = INVALID_MODIFIERS;
2268     }
2269     break;
2270
2271     case WM_SYSCHAR:
2272     case WM_CHAR:
2273     {
2274       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
2275             break;
2276
2277         fgState.Modifiers = fghGetWin32Modifiers( );
2278         INVOKE_WCB( *window, Keyboard,
2279                     ( (char)wParam,
2280                       window->State.MouseX, window->State.MouseY )
2281         );
2282         fgState.Modifiers = INVALID_MODIFIERS;
2283     }
2284     break;
2285
2286     case WM_CAPTURECHANGED:
2287         /* User has finished resizing the window, force a redraw */
2288         INVOKE_WCB( *window, Display, ( ) );
2289
2290         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
2291         break;
2292
2293         /* Other messages that I have seen and which are not handled already */
2294     case WM_SETTEXT:  /* 0x000c */
2295         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2296         /* Pass it on to "DefWindowProc" to set the window text */
2297         break;
2298
2299     case WM_GETTEXT:  /* 0x000d */
2300         /* Ideally we would copy the title of the window into "lParam" */
2301         /* strncpy ( (char *)lParam, "Window Title", wParam );
2302            lRet = ( wParam > 12 ) ? 12 : wParam;  */
2303         /* the number of characters copied */
2304         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2305         break;
2306
2307     case WM_GETTEXTLENGTH:  /* 0x000e */
2308         /* Ideally we would get the length of the title of the window */
2309         lRet = 12;
2310         /* the number of characters in "Window Title\0" (see above) */
2311         break;
2312
2313     case WM_ERASEBKGND:  /* 0x0014 */
2314         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2315         break;
2316
2317 #if !defined(_WIN32_WCE)
2318     case WM_SYNCPAINT:  /* 0x0088 */
2319         /* Another window has moved, need to update this one */
2320         window->State.Redisplay = GL_TRUE;
2321         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2322         /* Help screen says this message must be passed to "DefWindowProc" */
2323         break;
2324
2325     case WM_NCPAINT:  /* 0x0085 */
2326       /* Need to update the border of this window */
2327         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2328         /* Pass it on to "DefWindowProc" to repaint a standard border */
2329         break;
2330
2331     case WM_SYSCOMMAND :  /* 0x0112 */
2332         {
2333           /*
2334            * We have received a system command message.  Try to act on it.
2335            * The commands are passed in through the "wParam" parameter:
2336            * The least significant digit seems to be which edge of the window
2337            * is being used for a resize event:
2338            *     4  3  5
2339            *     1     2
2340            *     7  6  8
2341            * Congratulations and thanks to Richard Rauch for figuring this out..
2342            */
2343             switch ( wParam & 0xfff0 )
2344             {
2345             case SC_SIZE       :
2346                 break ;
2347
2348             case SC_MOVE       :
2349                 break ;
2350
2351             case SC_MINIMIZE   :
2352                 /* User has clicked on the "-" to minimize the window */
2353                 /* Turn off the visibility */
2354                 window->State.Visible = GL_FALSE ;
2355
2356                 break ;
2357
2358             case SC_MAXIMIZE   :
2359                 break ;
2360
2361             case SC_NEXTWINDOW :
2362                 break ;
2363
2364             case SC_PREVWINDOW :
2365                 break ;
2366
2367             case SC_CLOSE      :
2368                 /* Followed very closely by a WM_CLOSE message */
2369                 break ;
2370
2371             case SC_VSCROLL    :
2372                 break ;
2373
2374             case SC_HSCROLL    :
2375                 break ;
2376
2377             case SC_MOUSEMENU  :
2378                 break ;
2379
2380             case SC_KEYMENU    :
2381                 break ;
2382
2383             case SC_ARRANGE    :
2384                 break ;
2385
2386             case SC_RESTORE    :
2387                 break ;
2388
2389             case SC_TASKLIST   :
2390                 break ;
2391
2392             case SC_SCREENSAVE :
2393                 break ;
2394
2395             case SC_HOTKEY     :
2396                 break ;
2397
2398 #if(WINVER >= 0x0400)
2399             case SC_DEFAULT    :
2400                 break ;
2401
2402             case SC_MONITORPOWER    :
2403                 break ;
2404
2405             case SC_CONTEXTHELP    :
2406                 break ;
2407 #endif /* WINVER >= 0x0400 */
2408
2409             default:
2410 #if _DEBUG
2411                 fgWarning( "Unknown wParam type 0x%x", wParam );
2412 #endif
2413                 break;
2414             }
2415         }
2416 #endif /* !defined(_WIN32_WCE) */
2417
2418         /* We need to pass the message on to the operating system as well */
2419         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2420         break;
2421
2422     default:
2423         /* Handle unhandled messages */
2424         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2425         break;
2426     }
2427
2428     return lRet;
2429 }
2430 #endif
2431
2432 /*** END OF FILE ***/