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