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