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