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