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