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