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