Menus should deallocate better now - John Fay
[freeglut] / src / freeglut_main.c
1 /*
2  * freeglut_main.c
3  *
4  * The windows message processing methods.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Fri Dec 3 1999
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #define  G_LOG_DOMAIN  "freeglut-main"
33
34 #include "../include/GL/freeglut.h"
35 #include "freeglut_internal.h"
36
37 /*
38  * TODO BEFORE THE STABLE RELEASE:
39  *
40  * There are some issues concerning window redrawing under X11, and maybe
41  * some events are not handled. The Win32 version lacks some more features,
42  * but seems acceptable for not demanding purposes.
43  *
44  * Need to investigate why the X11 version breaks out with an error when
45  * closing a window (using the window manager, not glutDestroyWindow)...
46  */
47
48 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
49
50 /*
51  * Calls a window's redraw method. This is used when
52  * a redraw is forced by the incoming window messages.
53  */
54
55 static void fghRedrawWindowByHandle
56 #if TARGET_HOST_UNIX_X11
57     ( Window handle )
58 #elif TARGET_HOST_WIN32
59     ( HWND handle )
60 #endif
61 {
62     /*
63      * Find the window we have to redraw...
64      */
65     SFG_Window* window = fgWindowByHandle( handle );
66     freeglut_return_if_fail( window != NULL );
67
68     /*
69      * Check if there is a display callback hooked to it
70      */
71     freeglut_return_if_fail( window->Callbacks.Display != NULL );
72
73     /*
74      * Return if the window is not visible
75      */
76     freeglut_return_if_fail( window->State.Visible == TRUE );
77
78     /*
79      * Set the window as the current one.
80      */
81     fgSetWindow( window );
82
83     /*
84      * Do not exagerate with the redisplaying
85      */
86     window->State.Redisplay = FALSE;
87
88     /*
89      * Have the callback executed now. The buffers should
90      * be swapped by the glutSwapBuffers() execution inside
91      * the callback itself.
92      */
93
94     window->Callbacks.Display();
95 }
96
97 /*
98  * Handle a window configuration change. When no reshape
99  * callback is hooked, the viewport size is updated to
100  * match the new window size.
101  */
102 static void fghReshapeWindowByHandle
103 #if TARGET_HOST_UNIX_X11
104     ( Window handle, int width, int height )
105 #elif TARGET_HOST_WIN32
106     ( HWND handle, int width, int height )
107 #endif
108 {
109   SFG_Window *current_window = fgStructure.Window ;
110
111     /*
112      * Find the window that received the reshape event
113      */
114     SFG_Window* window = fgWindowByHandle( handle );
115     freeglut_return_if_fail( window != NULL );
116
117     /*
118      * Remember about setting the current window...
119      */
120     fgSetWindow( window );
121
122     /*
123      * Check if there is a reshape callback hooked
124      */
125     if( window->Callbacks.Reshape != NULL )
126     {
127         /*
128          * OKi, have it called immediately
129          */
130         window->Callbacks.Reshape( width, height );
131     }
132     else
133     {
134         /*
135          * Otherwise just resize the viewport
136          */
137         glViewport( 0, 0, width, height );
138     }
139
140     /*
141      * Force a window redraw.  In Windows at least this is only a partial solution:  if the
142      * window is increasing in size in either dimension, the already-drawn part does not get
143      * drawn again and things look funny.  But without this we get this bad behaviour whenever
144      * we resize the window.
145      */
146     window->State.Redisplay = TRUE ;
147
148     /*
149      * If this is a menu, restore the active window
150      */
151     if ( window->IsMenu )
152       fgSetWindow ( current_window ) ;
153 }
154
155 /*
156  * A static helper function to execute display callback for a window
157  */
158 static void fghcbDisplayWindow( SFG_Window *window, SFG_Enumerator *enumerator )
159 {
160 #if TARGET_HOST_UNIX_X11
161     /*
162      * Check if there is an idle callback hooked
163      */
164     if( (window->Callbacks.Display != NULL) &&
165         (window->State.Redisplay == TRUE) &&
166         (window->State.Visible == TRUE) )
167     {
168         SFG_Window *current_window = fgStructure.Window ;
169
170         /*
171          * OKi, this is the case: have the window set as the current one
172          */
173         fgSetWindow( window );
174
175         /*
176          * Do not exagerate with the redisplaying
177          */
178         window->State.Redisplay = FALSE;
179
180         /*
181          * And execute the display callback immediately after
182          */
183         window->Callbacks.Display();
184
185         fgSetWindow ( current_window ) ;
186     }
187
188 #elif TARGET_HOST_WIN32
189
190     /*
191      * Do we need to explicitly resize the window?
192      */
193     if( window->State.NeedToResize )
194     {
195         SFG_Window *current_window = fgStructure.Window ;
196
197         fgSetWindow( window );
198
199         fghReshapeWindowByHandle( 
200             window->Window.Handle,
201             glutGet( GLUT_WINDOW_WIDTH ),
202             glutGet( GLUT_WINDOW_HEIGHT )
203         );
204
205         /*
206          * Never ever do that again:
207          */
208         window->State.NeedToResize = FALSE;
209
210         fgSetWindow ( current_window ) ;
211     }
212
213     /*
214      * This is done in a bit different way under Windows
215      */
216     if( (window->Callbacks.Display != NULL) &&
217         (window->State.Redisplay == TRUE) &&
218         (window->State.Visible == TRUE) )
219     {
220       /*
221        * Do not exagerate with the redisplaying
222        */
223       window->State.Redisplay = FALSE;
224
225       RedrawWindow( 
226         window->Window.Handle, NULL, NULL, 
227         RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
228         );
229     }
230
231 #endif
232
233     /*
234      * Process this window's children (if any)
235      */
236     fgEnumSubWindows( window, fghcbDisplayWindow, enumerator );
237 }
238
239 /*
240  * Make all windows perform a display call
241  */
242 static void fghDisplayAll( void )
243 {
244     SFG_Enumerator enumerator;
245
246     /*
247      * Uses a method very similiar for fgWindowByHandle...
248      */
249     enumerator.found = FALSE;
250     enumerator.data  =  NULL;
251
252     /*
253      * Start the enumeration now:
254      */
255     fgEnumWindows( fghcbDisplayWindow, &enumerator );
256 }
257
258 /*
259  * Window enumerator callback to check for the joystick polling code
260  */
261 static void fghcbCheckJoystickPolls( SFG_Window *window, SFG_Enumerator *enumerator )
262 {
263     long int checkTime = fgElapsedTime();
264
265     /*
266      * Check if actually need to do the poll for the currently enumerated window:
267      */
268     if( window->State.JoystickLastPoll + window->State.JoystickPollRate >= checkTime )
269     {
270         /*
271          * Yeah, that's it. Poll the joystick...
272          */
273         fgJoystickPollWindow( window );
274
275         /*
276          * ...and reset the polling counters:
277          */
278         window->State.JoystickLastPoll = checkTime;
279     }
280
281     /*
282      * Process this window's children (if any)
283      */
284     fgEnumSubWindows( window, fghcbCheckJoystickPolls, enumerator );
285 }
286
287 /*
288  * Check all windows for joystick polling
289  */
290 static void fghCheckJoystickPolls( void )
291 {
292     SFG_Enumerator enumerator;
293
294     /*
295      * Uses a method very similiar for fgWindowByHandle...
296      */
297     enumerator.found = FALSE;
298     enumerator.data  =  NULL;
299
300     /*
301      * Start the enumeration now:
302      */
303     fgEnumWindows( fghcbCheckJoystickPolls, &enumerator );
304 }
305
306 /*
307  * Check the global timers
308  */
309 static void fghCheckTimers( void )
310 {
311     long checkTime = fgElapsedTime();
312     SFG_Timer *timer, *next;
313     SFG_List timedOut;
314
315     fgListInit(&timedOut);
316
317     /*
318      * For every timer that is waiting for triggering
319      */
320     for( timer = (SFG_Timer *)fgState.Timers.First; timer; timer = (SFG_Timer *)next )
321     {
322               next = (SFG_Timer *)timer->Node.Next;
323
324         /*
325          * Check for the timeout:
326          */
327         if( timer->TriggerTime <= checkTime )
328         {
329             /*
330              * Add the timer to the timed out timers list
331              */
332                   fgListRemove( &fgState.Timers, &timer->Node );
333             fgListAppend( &timedOut, &timer->Node );
334         }
335     }
336
337     /*
338      * Now feel free to execute all the hooked and timed out timer callbacks
339      * And delete the timed out timers...
340      */
341     while ( (timer = (SFG_Timer *)timedOut.First) )
342     {
343         if( timer->Callback != NULL )
344             timer->Callback( timer->ID );
345         fgListRemove( &timedOut, &timer->Node );
346         free( timer );
347     }
348 }
349
350
351 /*
352  * Elapsed Time
353  */
354 long fgElapsedTime( void )
355 {
356 #if TARGET_HOST_UNIX_X11
357         struct timeval now;
358         long elapsed;
359
360         gettimeofday( &now, NULL );
361
362         elapsed = (now.tv_usec - fgState.Time.Value.tv_usec) / 1000;
363         elapsed += (now.tv_sec - fgState.Time.Value.tv_sec) * 1000;
364
365         return( elapsed );
366 #elif TARGET_HOST_WIN32
367   return (timeGetTime() - fgState.Time.Value);
368 #endif
369 }
370
371 /*
372  * Error Messages.
373  */
374 void fgError( const char *fmt, ... )
375 {
376     va_list ap;
377
378     va_start( ap, fmt );
379
380     fprintf( stderr, "freeglut: ");
381     vfprintf( stderr, fmt, ap );
382     fprintf( stderr, "\n" );
383
384     va_end( ap );
385
386     exit( 1 );
387 }
388
389 void fgWarning( const char *fmt, ... )
390 {
391     va_list ap;
392
393     va_start( ap, fmt );
394
395     fprintf( stderr, "freeglut: ");
396     vfprintf( stderr, fmt, ap );
397     fprintf( stderr, "\n" );
398
399     va_end( ap );
400 }
401
402 /*
403  * Clean up on exit
404  */
405 static void fgCleanUpGlutsMess( void ) 
406 {
407   int i;
408
409   i = 0;
410
411   if ( fgStructure.Windows.First != NULL ) 
412   {
413     SFG_Window *win = (SFG_Window *)fgStructure.Windows.First ;
414     glEnd();
415     glFinish();
416     glFlush();
417     while ( win != NULL )
418     {
419       SFG_Window *temp_win = (SFG_Window *)win->Node.Next ;
420       fgDestroyWindow ( win, FALSE ) ;
421       win = temp_win ;
422     }
423   }
424
425 #if 0
426   /* these are pointers to external handles */
427
428   __glutWindowListSize    = 0;
429   __glutStaleWindowList   = NULL;
430   __glutWindowList        = NULL;
431   __glutCurrentWindow     = NULL;
432
433   /* make sure we no longer have a GL context */
434
435   if ( wglGetCurrentContext() != NULL ) 
436   {
437     wglDeleteContext( wglGetCurrentContext() );
438   }
439
440   hInstance = GetModuleHandle(NULL);
441   UnregisterClass( classname, hInstance );
442
443   /* clean up allocated timer memory */
444
445   tList = __glutTimerList;
446   i = 0;
447
448   while ( __glutTimerList ) 
449   {
450     i++;
451     tList = __glutTimerList;
452     
453     if ( __glutTimerList )
454       __glutTimerList = __glutTimerList->next;
455
456     if ( tList )
457       free( tList );
458   }
459 #endif
460 }
461
462
463 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
464
465 /*
466  * Executes a single iteration in the freeglut processing loop.
467  */
468 void FGAPIENTRY glutMainLoopEvent( void )
469 {
470 #if TARGET_HOST_UNIX_X11
471   SFG_Window* window;
472   XEvent event;
473   int modifiers;
474
475   /*
476    * This code was repeated constantly, so here it goes into a definition:
477    */
478 # define GETWINDOW(a) window = fgWindowByHandle( event.a.window );if( window == NULL ) break;
479 # define GETMOUSE(a) window->State.MouseX = event.a.x; window->State.MouseY = event.a.y;
480
481   /*
482    * Make sure the display has been created etc.
483    */
484   freeglut_assert_ready;
485
486   /*
487    * Do we have any event messages pending?
488    */
489   if( XPending( fgDisplay.Display ) )
490   {
491     /*
492      * Grab the next event to be processed...
493      */
494     XNextEvent( fgDisplay.Display, &event );
495
496     /*
497      * Check the event's type
498      */
499     switch( event.type )
500     {
501     case CreateNotify:
502       /*
503        * The window creation confirmation
504        */
505       break;
506
507     case DestroyNotify:
508       /*
509        * This is sent to confirm the XDestroyWindow call.
510        */
511       /*
512        * Call the window closure callback, remove from the structure, etc.
513        */
514 /*      fgAddToWindowDestroyList ( window, FALSE ); */
515
516       break;
517
518     case ClientMessage:
519       /*
520        * Destroy the window when the WM_DELETE_WINDOW message arrives
521        */
522       if( (Atom) event.xclient.data.l[ 0 ] == fgDisplay.DeleteWindow )
523       {
524         GETWINDOW( xclient ); 
525
526         /*
527          * Call the XWindows functions to close the window
528          */
529         fgCloseWindow ( window ) ;
530
531         /*
532          * Call the window closure callback, remove from the structure, etc.
533          */
534         fgAddToWindowDestroyList ( window, FALSE );
535       }
536       break;
537
538     case UnmapNotify:
539       /*
540        * A window of ours has been unmapped...
541        */
542       break;
543
544     case Expose:
545       /*
546        * We are too dumb to process partial exposes...
547        */
548       if( event.xexpose.count == 0 )
549           fghRedrawWindowByHandle( event.xexpose.window );
550       break;
551
552     case ConfigureNotify:
553       /*
554        * The window gets resized
555        */
556       fghReshapeWindowByHandle(
557           event.xconfigure.window,
558           event.xconfigure.width,
559           event.xconfigure.height
560       );
561       break;
562
563     case MappingNotify:
564       /*
565        * Have the client's keyboard knowledge updated (xlib.ps,
566        * page 206, says that's a good thing to do)
567        */
568       XRefreshKeyboardMapping( (XMappingEvent *) &event );
569       break;
570
571     case VisibilityNotify:
572       {
573         /*
574          * The window's visiblity might have changed
575          */
576         GETWINDOW( xvisibility ); 
577
578         /*
579          * Break now if no window status callback has been hooked to that window
580          */
581         if( window->Callbacks.WindowStatus == NULL )
582             break;
583
584         /*
585          * We're going to send a callback to a window. Make it current.
586          */
587         fgSetWindow( window );
588
589         /*
590          * Sending this event, the X server can notify us that the window has just
591          * acquired one of the three possible visibility states: VisibilityUnobscured,
592          * VisibilityPartiallyObscured or VisibilityFullyObscured
593          */
594         switch( event.xvisibility.state )
595         {
596         case VisibilityUnobscured:
597           /*
598            * We are fully visible...
599            */
600           window->Callbacks.WindowStatus( GLUT_FULLY_RETAINED );
601           window->State.Visible = TRUE;
602           break;
603
604         case VisibilityPartiallyObscured:
605           /*
606            * The window is partially visible
607            */
608           window->Callbacks.WindowStatus( GLUT_PARTIALLY_RETAINED );
609           window->State.Visible = TRUE;
610           break;
611
612         case VisibilityFullyObscured:
613           /*
614            * The window is totally obscured
615            */
616           window->Callbacks.WindowStatus( GLUT_FULLY_COVERED );
617           window->State.Visible = FALSE;
618           break;
619         }
620       }
621       break;
622
623     case EnterNotify:
624       {
625         /*
626          * Mouse is over one of our windows
627          */
628         GETWINDOW( xcrossing ); GETMOUSE( xcrossing );
629
630         /*
631          * Is there an entry callback hooked to the window?
632          */
633         if( window->Callbacks.Entry != NULL )
634         {
635           /*
636            * Set the current window
637            */
638           fgSetWindow ( window ) ;
639
640           /*
641            * Yeah. Notify the window about having the mouse cursor over
642            */
643           window->Callbacks.Entry( GLUT_ENTERED );
644         }
645       }
646       break;
647
648     case LeaveNotify:
649       {
650         /*
651          * Mouse is no longer over one of our windows
652          */
653         GETWINDOW( xcrossing ); GETMOUSE( xcrossing );
654
655         /*
656          * Is there an entry callback hooked to the window?
657          */
658         if( window->Callbacks.Entry != NULL )
659         {
660           /*
661            * Set the current window
662            */
663           fgSetWindow ( window ) ;
664
665           /*
666            * Yeah. Notify the window about having the mouse cursor over
667            */
668           window->Callbacks.Entry( GLUT_LEFT );
669         }
670       }
671       break;
672
673     case MotionNotify:
674       {
675         /*
676          * The mouse cursor was moved...
677          */
678         GETWINDOW( xmotion ); GETMOUSE( xmotion );
679
680         /*
681          * Fallback if there's an active menu hooked to this window
682          */
683         if( window->ActiveMenu != NULL )
684         {
685             /*
686              * Let's make the window redraw as a result of the mouse motion.
687              */
688             window->State.Redisplay = TRUE ;
689
690             /*
691              * Since the window is a menu, make the parent window current
692              */
693             fgSetWindow ( window->ActiveMenu->ParentWindow ) ;
694
695             break;
696         }
697
698         /*
699          * What kind of a movement was it?
700          */
701         if( (event.xmotion.state & Button1Mask) || (event.xmotion.state & Button2Mask) ||
702             (event.xmotion.state & Button3Mask) || (event.xmotion.state & Button4Mask) ||
703             (event.xmotion.state & Button5Mask) )
704         {
705           /*
706            * A mouse button was pressed during the movement...
707            * Is there a motion callback hooked to the window?
708            */
709           if( window->Callbacks.Motion != NULL )
710           {
711             /*
712              * Set the current window
713              */
714             fgSetWindow ( window ) ;
715
716             /*
717              * Yup. Have it executed immediately
718              */
719             window->Callbacks.Motion( event.xmotion.x, event.xmotion.y );
720           }
721         }
722         else
723         {
724           /*
725            * Otherwise it was a passive movement...
726            */
727           if( window->Callbacks.Passive != NULL )
728           {
729             /*
730              * Set the current window
731              */
732             fgSetWindow ( window ) ;
733
734             /*
735              * That's right, and there is a passive callback, too.
736              */
737             window->Callbacks.Passive( event.xmotion.x, event.xmotion.y );
738           }
739         }
740       }
741       break;
742
743     case ButtonRelease:
744     case ButtonPress:
745       {
746         GLboolean pressed = TRUE ;
747         int button;
748
749         if ( event.type == ButtonRelease ) pressed = FALSE ;
750
751         /*
752          * A mouse button has been pressed or released. Traditionally,
753          * break if the window was found within the freeglut structures.
754          */
755         GETWINDOW( xbutton ); GETMOUSE( xbutton );
756
757         /*
758          * GLUT API assumes that you can't have more than three mouse buttons, so:
759          */
760         switch( event.xbutton.button )
761         {
762         /*
763          * WARNING: this might be wrong, if we only have two mouse buttons,
764          *          Button2 might mean the right button, isn't that right?
765          */
766         case Button1:   button = GLUT_LEFT_BUTTON;   break;
767         case Button2:   button = GLUT_MIDDLE_BUTTON; break;
768         case Button3:   button = GLUT_RIGHT_BUTTON;  break;
769         default:        button = -1;                 break;
770         }
771
772         /*
773          * Skip the unwanted mouse buttons...
774          */
775         if( button == -1 )
776           break;
777
778         /*
779          * Do not execute the application's mouse callback if a menu is hooked to this button.
780          * In that case an appropriate private call should be generated.
781          * Near as I can tell, this is the menu behaviour:
782          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
783          *  - Down-click any button outside the menu, menu active:  deactivate the menu
784          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
785          *  - Up-click the menu button, menu not active:  nothing happens
786          *  - Up-click the menu button outside the menu, menu active:  nothing happens
787          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
788          */
789         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
790         {
791           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
792           {
793             /* Save the current window and menu and set the current window to the window whose menu this is */
794             SFG_Window *save_window = fgStructure.Window ;
795             SFG_Menu *save_menu = fgStructure.Menu ;
796             SFG_Window *parent_window = window->ActiveMenu->ParentWindow ;
797             fgSetWindow ( window ) ;
798             fgStructure.Menu = window->ActiveMenu ;
799
800             /* Execute the menu callback */
801             fgExecuteMenuCallback ( window->ActiveMenu ) ;
802             fgDeactivateMenu ( parent_window ) ;
803
804             /* Restore the current window and menu */
805             fgSetWindow ( save_window ) ;
806             fgStructure.Menu = save_menu ;
807           }
808           else  /* Outside the menu, deactivate the menu if it's a downclick */
809           {
810             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
811           }
812
813           /*
814            * Let's make the window redraw as a result of the mouse click and menu activity.
815            */
816           window->State.Redisplay = TRUE ;
817
818           break ;
819         }
820
821         /*
822          * No active menu, let's check whether we need to activate one.
823          */
824         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
825         {
826           /*
827            * Let's make the window redraw as a result of the mouse click.
828            */
829           window->State.Redisplay = TRUE ;
830
831           /*
832            * Set the current window
833            */
834           fgSetWindow( window );
835
836           /*
837            * Activate the appropriate menu structure...
838            */
839           fgActivateMenu( window, button );
840
841           break;
842         }
843
844         /*
845          * Check if there is a mouse callback hooked to the window
846          */
847         if( window->Callbacks.Mouse == NULL )
848           break;
849
850         /*
851          * Set the current window
852          */
853         fgSetWindow ( window );
854
855         /*
856          * Remember the current modifiers state
857          */
858         modifiers = 0;
859         if (event.xbutton.state & (ShiftMask|LockMask))
860           modifiers |= GLUT_ACTIVE_SHIFT;
861         if (event.xbutton.state & ControlMask)
862           modifiers |= GLUT_ACTIVE_CTRL;
863         if (event.xbutton.state & Mod1Mask)
864           modifiers |= GLUT_ACTIVE_ALT;
865         fgStructure.Window->State.Modifiers = modifiers;
866
867         /*
868          * Finally execute the mouse callback
869          */
870         fgStructure.Window->Callbacks.Mouse(
871             button,
872             event.type == ButtonPress ? GLUT_DOWN : GLUT_UP,
873             event.xbutton.x,
874             event.xbutton.y
875         );
876
877         /*
878          * Trash the modifiers state
879          */
880         fgStructure.Window->State.Modifiers = 0xffffffff;
881       }
882       break;
883
884     case KeyRelease:
885     case KeyPress:
886       {
887         FGCBkeyboard keyboard_cb;
888         FGCBspecial special_cb;
889
890         /*
891          * A key has been pressed, find the window that had the focus:
892          */
893         GETWINDOW( xkey ); GETMOUSE( xkey );
894
895         if( event.type == KeyPress )
896         {
897           keyboard_cb = window->Callbacks.Keyboard;
898           special_cb = window->Callbacks.Special;
899         }
900         else
901         {
902           keyboard_cb = window->Callbacks.KeyboardUp;
903           special_cb = window->Callbacks.SpecialUp;
904         }
905
906         /*
907          * Is there a keyboard/special callback hooked for this window?
908          */
909         if( (keyboard_cb != NULL) || (special_cb != NULL) )
910         {
911           XComposeStatus composeStatus;
912           char asciiCode[ 32 ];
913           KeySym keySym;
914           int len;
915
916           /*
917            * Check for the ASCII/KeySym codes associated with the event:
918            */
919           len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus );
920
921           /*
922            * GLUT API tells us to have two separate callbacks...
923            */
924           if( len > 0 )
925           {
926             /*
927              * ...one for the ASCII translateable keypresses...
928              */
929             if( keyboard_cb != NULL )
930             {
931               /*
932                * Set the current window
933                */
934               fgSetWindow( window );
935
936               /*
937                * Remember the current modifiers state
938                */
939               modifiers = 0;
940               if (event.xkey.state & (ShiftMask|LockMask))
941                   modifiers |= GLUT_ACTIVE_SHIFT;
942               if (event.xkey.state & ControlMask)
943                   modifiers |= GLUT_ACTIVE_CTRL;
944               if (event.xkey.state & Mod1Mask)
945                   modifiers |= GLUT_ACTIVE_ALT;
946               window->State.Modifiers = modifiers;
947
948               /*
949                * Execute the callback
950                */
951               keyboard_cb( asciiCode[ 0 ], event.xkey.x, event.xkey.y );
952
953               /*
954                * Trash the modifiers state
955                */
956               window->State.Modifiers = 0xffffffff;
957             }
958           }
959           else
960           {
961             int special = -1;
962
963             /*
964              * ...and one for all the others, which need to be translated to GLUT_KEY_Xs...
965              */
966             switch( keySym )
967             {
968             /*
969              * First the function keys come:
970              */
971             case XK_F1:     special = GLUT_KEY_F1;     break;
972             case XK_F2:     special = GLUT_KEY_F2;     break;
973             case XK_F3:     special = GLUT_KEY_F3;     break;
974             case XK_F4:     special = GLUT_KEY_F4;     break;
975             case XK_F5:     special = GLUT_KEY_F5;     break;
976             case XK_F6:     special = GLUT_KEY_F6;     break;
977             case XK_F7:     special = GLUT_KEY_F7;     break;
978             case XK_F8:     special = GLUT_KEY_F8;     break;
979             case XK_F9:     special = GLUT_KEY_F9;     break;
980             case XK_F10:    special = GLUT_KEY_F10;    break;
981             case XK_F11:    special = GLUT_KEY_F11;    break;
982             case XK_F12:    special = GLUT_KEY_F12;    break;
983
984             /*
985              * Then the arrows and stuff:
986              */
987             case XK_Left:   special = GLUT_KEY_LEFT;   break;
988             case XK_Right:  special = GLUT_KEY_RIGHT;  break;
989             case XK_Up:     special = GLUT_KEY_UP;     break;
990             case XK_Down:   special = GLUT_KEY_DOWN;   break;
991
992             case XK_KP_Prior:
993             case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
994             case XK_KP_Next:
995             case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
996             case XK_KP_Home:
997             case XK_Home:   special = GLUT_KEY_HOME;   break;
998             case XK_KP_End:
999             case XK_End:    special = GLUT_KEY_END;    break;
1000             case XK_KP_Insert:
1001             case XK_Insert: special = GLUT_KEY_INSERT; break;
1002             }
1003
1004             /*
1005              * Execute the callback (if one has been specified),
1006              * given that the special code seems to be valid...
1007              */
1008             if( (special_cb != NULL) && (special != -1) )
1009             {
1010               /*
1011                * Set the current window
1012                */
1013               fgSetWindow( window );
1014
1015               /*
1016                * Remember the current modifiers state
1017                */
1018               modifiers = 0;
1019               if (event.xkey.state & (ShiftMask|LockMask))
1020                 modifiers |= GLUT_ACTIVE_SHIFT;
1021               if (event.xkey.state & ControlMask)
1022                 modifiers |= GLUT_ACTIVE_CTRL;
1023               if (event.xkey.state & Mod1Mask)
1024                 modifiers |= GLUT_ACTIVE_ALT;
1025               window->State.Modifiers = modifiers;
1026
1027               special_cb( special, event.xkey.x, event.xkey.y );
1028
1029               /*
1030                * Trash the modifiers state
1031                */
1032               window->State.Modifiers = 0xffffffff;
1033             }
1034           }
1035         }
1036       }
1037       break;
1038     }
1039   }
1040   else
1041   {
1042     /*
1043      * Have all the timers checked.
1044      */
1045     fghCheckTimers();
1046
1047     /*
1048      * Poll the joystick and notify all windows that want to be notified...
1049      */
1050     fghCheckJoystickPolls();
1051
1052     /*
1053      * No messages in the queue, which means we are idling...
1054      */
1055     if( fgState.IdleCallback != NULL )
1056         fgState.IdleCallback();
1057
1058     /*
1059      * Remember about displaying all the windows that have
1060      * been marked for a redisplay (possibly in the idle call):
1061      */
1062     fghDisplayAll();
1063   }
1064
1065 #elif TARGET_HOST_WIN32
1066
1067   MSG stMsg;
1068
1069   /*
1070    * The windows processing is considerably smaller
1071    */
1072   if( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
1073   {
1074     /*
1075      * Grab the message now, checking for WM_QUIT
1076      */
1077     if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1078       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1079
1080     /*
1081      * Translate virtual-key messages and send them to the window...
1082      */
1083     TranslateMessage( &stMsg );
1084     DispatchMessage( &stMsg );
1085   }
1086   else
1087   {
1088     /*
1089      * Have all the timers checked.
1090      */
1091     fghCheckTimers();
1092
1093     /*
1094      * Poll the joystick and notify all windows that want to be notified...
1095      */
1096     fghCheckJoystickPolls();
1097
1098     /*
1099      * No messages in the queue, which means we are idling...
1100      */
1101     if( fgState.IdleCallback != NULL )
1102       fgState.IdleCallback();
1103
1104     /*
1105      * Remember about displaying all the windows that have
1106      * been marked for a redisplay (possibly in the idle call):
1107      */
1108     fghDisplayAll();
1109   }
1110 #endif
1111
1112     /* 
1113      * If an event caused a window to be closed, do the actual closing here
1114      */
1115     fgCloseWindows () ;
1116 }
1117
1118 /*
1119  * Enters the freeglut processing loop. Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1120  */
1121 void FGAPIENTRY glutMainLoop( void )
1122 {
1123 #if TARGET_HOST_WIN32
1124   SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1125 #endif
1126
1127   /*
1128    * Make sure the display has been created etc.
1129    */
1130   freeglut_assert_ready;
1131
1132 #if TARGET_HOST_WIN32
1133   /*
1134    * Processing before the main loop:  If there is a window which is open and which
1135    * has a visibility callback, call it.  I know this is an ugly hack, but I'm not sure
1136    * what else to do about it.  Ideally we should leave something uninitialized in the
1137    * create window code and initialize it in the main loop, and have that initialization
1138    * create a "WM_ACTIVATE" message.  Then we would put the visibility callback code in
1139    * the "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1140    */
1141   while ( window != NULL )
1142   {
1143     if ( window->Callbacks.Visibility != NULL )
1144     {
1145       SFG_Window *current_window = fgStructure.Window ;
1146
1147       /*
1148        * Set the current window
1149        */
1150       fgSetWindow( window );
1151
1152       window->Callbacks.Visibility ( window->State.Visible ) ;
1153
1154       /*
1155        * Restore the current window
1156        */
1157       fgSetWindow( current_window );
1158     }
1159
1160     window = (SFG_Window *)window->Node.Next ;
1161   }
1162 #endif
1163
1164   /*
1165    * Set freeglut to be running
1166    */
1167   fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1168
1169   /*
1170    * Enter the main loop itself.  Inside the loop, process events and check for loop exit.
1171    */
1172   while ( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1173   {
1174     glutMainLoopEvent () ;
1175
1176     /*
1177      * If there are no more windows open, stop execution
1178      */
1179     if ( fgStructure.Windows.First == NULL )
1180       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1181   }
1182
1183
1184   /*
1185    * If we got here by the user closing a window or by the application closing down, there may still be windows open.
1186    */
1187   fgCleanUpGlutsMess () ;
1188
1189   /*
1190    * Check whether we return to the calling program or simply exit
1191    */
1192   if ( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1193     exit ( 0 ) ;
1194
1195   /*
1196    * When this loop terminates, destroy the display, state and structure
1197    * of a freeglut session, so that another glutInit() call can happen
1198    */
1199   fgDeinitialize();
1200 }
1201
1202 /*
1203  * Leaves the freeglut processing loop.
1204  */
1205 void FGAPIENTRY glutLeaveMainLoop( void )
1206 {
1207   fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1208 }
1209
1210 /*
1211  * The window procedure for handling Win32 events
1212  */
1213 #if TARGET_HOST_WIN32
1214 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1215 {
1216     SFG_Window* window = fgWindowByHandle( hWnd );
1217     PAINTSTRUCT ps;
1218     LONG lRet = 1;
1219
1220     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1221       return( DefWindowProc( hWnd, uMsg, wParam, lParam ) );
1222
1223 /*    printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0, uMsg, wParam, lParam ) ; */
1224     /*
1225      * Check what type of message are we receiving
1226      */
1227     switch( uMsg )
1228     {
1229     case WM_CREATE:
1230         /*
1231          * The window structure is passed as the creation structure paramter...
1232          */
1233         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1234         assert( window != NULL );
1235
1236         /*
1237          * We can safely store the window's handle now:
1238          */
1239         window->Window.Handle = hWnd;
1240
1241         /*
1242          * Get the window's device context
1243          */
1244         window->Window.Device = GetDC( hWnd );
1245
1246         /*
1247          * Create or get the OpenGL rendering context now
1248          */
1249         if ( fgState.BuildingAMenu )
1250         {
1251           /*
1252            * Setup the pixel format of our window
1253            */
1254           unsigned int current_DisplayMode = fgState.DisplayMode ;
1255           fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ;
1256           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1257           fgState.DisplayMode = current_DisplayMode ;
1258
1259           /*
1260            * If there isn't already an OpenGL rendering context for menu windows, make one
1261            */
1262           if ( !fgStructure.MenuContext )
1263           {
1264             fgStructure.MenuContext = (SFG_MenuContext *)malloc ( sizeof(SFG_MenuContext) ) ;
1265             fgStructure.MenuContext->Context = wglCreateContext( window->Window.Device );
1266           }
1267           else
1268             wglMakeCurrent ( window->Window.Device, fgStructure.MenuContext->Context ) ;
1269
1270 /*          window->Window.Context = wglGetCurrentContext () ;   */
1271           window->Window.Context = wglCreateContext( window->Window.Device );
1272         }
1273         else
1274         {
1275           /*
1276            * Setup the pixel format of our window
1277            */
1278           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1279
1280           if ( fgState.UseCurrentContext == TRUE )
1281           {
1282             window->Window.Context = wglGetCurrentContext();
1283             if ( ! window->Window.Context )
1284               window->Window.Context = wglCreateContext( window->Window.Device );
1285           }
1286           else
1287             window->Window.Context = wglCreateContext( window->Window.Device );
1288         }
1289
1290         /*
1291          * Still, we'll be needing to explicitly resize the window
1292          */
1293         window->State.NeedToResize = TRUE;
1294
1295         /*
1296          * Finally, have the window's device context released
1297          */
1298         ReleaseDC( window->Window.Handle, window->Window.Device );
1299         break;
1300
1301     case WM_SIZE:
1302         /*
1303          * We got resized... But check if the window has been already added...
1304          */
1305         fghReshapeWindowByHandle( hWnd, LOWORD(lParam), HIWORD(lParam) );
1306         break;
1307 #if 0
1308     case WM_SETFOCUS: 
1309         printf("WM_SETFOCUS: %p\n", window );
1310         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1311         break;
1312
1313     case WM_ACTIVATE: 
1314         if (LOWORD(wParam) != WA_INACTIVE)
1315         {
1316           /* glutSetCursor( fgStructure.Window->State.Cursor ); */
1317                 printf("WM_ACTIVATE: glutSetCursor( %p, %d)\n", window, window->State.Cursor );
1318
1319           glutSetCursor( window->State.Cursor );
1320         }
1321
1322         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1323         break;
1324 #endif
1325
1326     case WM_SETCURSOR: 
1327         /*
1328          * Windows seems to need reminding to erase the cursor for NONE.
1329          */
1330 #if 0
1331         if ((LOWORD(lParam) == HTCLIENT) &&
1332             (fgStructure.Window->State.Cursor == GLUT_CURSOR_NONE))
1333           SetCursor( NULL );
1334 #else
1335         /* Set the cursor AND change it for this window class. */
1336 #       define MAP_CURSOR(a,b) case a: SetCursor( LoadCursor( NULL, b ) ); \
1337         break;
1338         /* Nuke the cursor AND change it for this window class. */
1339 #       define ZAP_CURSOR(a,b) case a: SetCursor( NULL ); \
1340         break;
1341
1342         if (LOWORD(lParam) == HTCLIENT)
1343           switch( window->State.Cursor )
1344           {
1345                 MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, IDC_ARROW     );
1346                 MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  IDC_ARROW     );
1347                 MAP_CURSOR( GLUT_CURSOR_INFO,        IDC_HELP      );
1348                 MAP_CURSOR( GLUT_CURSOR_DESTROY,     IDC_CROSS     );
1349                 MAP_CURSOR( GLUT_CURSOR_HELP,        IDC_HELP      );
1350                 MAP_CURSOR( GLUT_CURSOR_CYCLE,       IDC_SIZEALL   );
1351                 MAP_CURSOR( GLUT_CURSOR_SPRAY,       IDC_CROSS     );
1352                 MAP_CURSOR( GLUT_CURSOR_WAIT,            IDC_WAIT      );
1353                 MAP_CURSOR( GLUT_CURSOR_TEXT,        IDC_UPARROW   );
1354                 MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   IDC_CROSS     );
1355                 /* MAP_CURSOR( GLUT_CURSOR_NONE,        IDC_NO             ); */
1356                 ZAP_CURSOR( GLUT_CURSOR_NONE,        NULL          );
1357
1358                 default:
1359                 MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     IDC_ARROW     );
1360           }
1361 #endif
1362         else
1363           lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1364         break;
1365
1366     case WM_SHOWWINDOW:
1367         /*
1368          * We are now Visible!
1369          */
1370         window->State.Visible = TRUE;
1371         window->State.Redisplay = TRUE;
1372         break;
1373
1374     case WM_PAINT:
1375         /*
1376          * Start the painting job
1377          */
1378
1379         BeginPaint( hWnd, &ps );
1380
1381         /*
1382          * Call the engine's main frame drawing method
1383          */
1384         fghRedrawWindowByHandle( hWnd );
1385
1386         /*
1387          * End the painting job, release the device context
1388          */
1389         EndPaint( hWnd, &ps );
1390         break;
1391
1392     case WM_CLOSE:
1393         /*
1394          * Make sure we don't close a window with current context active
1395          */
1396         if( fgStructure.Window == window )
1397         {
1398           int used = FALSE ;
1399           SFG_Window *iter ;
1400
1401             wglMakeCurrent( NULL, NULL );
1402             /* Step through the list of windows.  If the rendering context is notbeing used
1403              * by another window, then we delete it.
1404              */
1405             for ( iter = (SFG_Window *)fgStructure.Windows.First; iter; iter = (SFG_Window *)iter->Node.Next )
1406             {
1407               if ( ( iter->Window.Context == window->Window.Context ) && ( iter != window ) )
1408                 used = TRUE ;
1409             }
1410
1411             if ( used == FALSE ) wglDeleteContext( window->Window.Context );
1412         }
1413
1414         /*
1415          * Put on a linked list of windows to be removed after all the callbacks have returned
1416          */
1417         fgAddToWindowDestroyList ( window, FALSE ) ;
1418
1419         /*
1420          * Proceed with the window destruction
1421          */
1422         DestroyWindow( hWnd );
1423         break;
1424
1425     case WM_DESTROY:
1426         /*
1427          * The window already got destroyed, so don't bother with it.
1428          */
1429         return( 0 );
1430
1431     case WM_MOUSEMOVE:
1432     {
1433         /*
1434          * The mouse cursor has moved. Remember the new mouse cursor's position
1435          */
1436         window->State.MouseX = LOWORD( lParam );
1437         window->State.MouseY = HIWORD( lParam );
1438
1439         /*
1440          * Fallback if there's an active menu hooked to this window
1441          */
1442         if ( window->ActiveMenu != NULL )
1443         {
1444             /*
1445              * Let's make the window redraw as a result of the mouse motion.
1446              */
1447             window->State.Redisplay = TRUE ;
1448
1449             /*
1450              * Since the window is a menu, make the parent window current
1451              */
1452             fgSetWindow ( window->ActiveMenu->ParentWindow ) ;
1453
1454             break;
1455         }
1456
1457         /*
1458          * Remember the current modifiers state.
1459          */
1460         window->State.Modifiers = 
1461             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1462             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1463             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1464
1465         /*
1466          * Check if any of the mouse buttons is pressed...
1467          */
1468         if( (wParam & MK_LBUTTON) || (wParam & MK_MBUTTON) || (wParam & MK_RBUTTON) )
1469         {
1470             /*
1471              * Yeah, indeed. We need to use the motion callback then:
1472              */
1473             if( window->Callbacks.Motion != NULL )
1474             {
1475                 /*
1476                  * Make sure the current window is set...
1477                  */
1478                 fgSetWindow( window );
1479
1480                 /*
1481                  * Execute the active mouse motion callback now
1482                  */
1483                 window->Callbacks.Motion( window->State.MouseX, window->State.MouseY );
1484             }
1485         }
1486         else
1487         {
1488             /*
1489              * All mouse buttons are up, execute the passive mouse motion callback
1490              */
1491             if( window->Callbacks.Passive != NULL )
1492             {
1493                 /*
1494                  * Make sure the current window is set
1495                  */
1496                 fgSetWindow( window );
1497
1498                 /*
1499                  * Execute the passive mouse motion callback
1500                  */
1501                 window->Callbacks.Passive( window->State.MouseX, window->State.MouseY );
1502             }
1503         }
1504
1505         /*
1506          * Thrash the current modifiers state now
1507          */
1508         window->State.Modifiers = 0xffffffff;
1509     }
1510     break;
1511
1512     case WM_LBUTTONDOWN:
1513     case WM_MBUTTONDOWN:
1514     case WM_RBUTTONDOWN:
1515     case WM_LBUTTONUP:
1516     case WM_MBUTTONUP:
1517     case WM_RBUTTONUP:
1518     {
1519         GLboolean pressed = TRUE;
1520         int button;
1521
1522         /*
1523          * The mouse cursor has moved. Remember the new mouse cursor's position
1524          */
1525         window->State.MouseX = LOWORD( lParam );
1526         window->State.MouseY = HIWORD( lParam );
1527
1528         /*
1529          * We're curious about the GLUT API button name...
1530          */
1531         switch( uMsg )
1532         {
1533         case WM_LBUTTONDOWN: pressed = TRUE;  button = GLUT_LEFT_BUTTON;   break;
1534         case WM_MBUTTONDOWN: pressed = TRUE;  button = GLUT_MIDDLE_BUTTON; break;
1535         case WM_RBUTTONDOWN: pressed = TRUE;  button = GLUT_RIGHT_BUTTON;  break;
1536         case WM_LBUTTONUP:   pressed = FALSE; button = GLUT_LEFT_BUTTON;   break;
1537         case WM_MBUTTONUP:   pressed = FALSE; button = GLUT_MIDDLE_BUTTON; break;
1538         case WM_RBUTTONUP:   pressed = FALSE; button = GLUT_RIGHT_BUTTON;  break;
1539         default:             pressed = FALSE; button = -1;                 break;
1540         }
1541
1542         /*
1543          * The left and right mouse buttons might have been swapped...
1544          */
1545         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1546             if( button == GLUT_LEFT_BUTTON ) button = GLUT_RIGHT_BUTTON;
1547             else if( button == GLUT_RIGHT_BUTTON ) button = GLUT_LEFT_BUTTON;
1548
1549         /*
1550          * Hey, what's up with you?
1551          */
1552         if( button == -1 )
1553             return( DefWindowProc( hWnd, uMsg, lParam, wParam ) );
1554
1555         /*
1556          * Do not execute the application's mouse callback if a menu is hooked to this button.
1557          * In that case an appropriate private call should be generated.
1558          * Near as I can tell, this is the menu behaviour:
1559          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
1560          *  - Down-click any button outside the menu, menu active:  deactivate the menu
1561          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
1562          *  - Up-click the menu button, menu not active:  nothing happens
1563          *  - Up-click the menu button outside the menu, menu active:  nothing happens
1564          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
1565          */
1566         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
1567         {
1568           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
1569           {
1570             /* Save the current window and menu and set the current window to the window whose menu this is */
1571             SFG_Window *save_window = fgStructure.Window ;
1572             SFG_Menu *save_menu = fgStructure.Menu ;
1573             fgSetWindow ( window ) ;
1574             fgStructure.Menu = window->ActiveMenu ;
1575
1576             /* Execute the menu callback */
1577             fgExecuteMenuCallback ( window->ActiveMenu ) ;
1578             fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
1579
1580             /* Restore the current window and menu */
1581             fgSetWindow ( save_window ) ;
1582             fgStructure.Menu = save_menu ;
1583           }
1584           else  /* Outside the menu, deactivate the menu if it's a downclick */
1585           {
1586             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
1587           }
1588
1589           /*
1590            * Let's make the window redraw as a result of the mouse click and menu activity.
1591            */
1592           if ( ! window->IsMenu ) window->State.Redisplay = TRUE ;
1593
1594           break ;
1595         }
1596
1597         /*
1598          * No active menu, let's check whether we need to activate one.
1599          */
1600         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
1601         {
1602             /*
1603              * Let's make the window redraw as a result of the mouse click.
1604              */
1605             window->State.Redisplay = TRUE ;
1606
1607             /*
1608              * Set the current window
1609              */
1610             fgSetWindow( window );
1611
1612             /*
1613              * Activate the appropriate menu structure...
1614              */
1615             fgActivateMenu( window, button );
1616
1617             break;
1618         }
1619
1620         /*
1621          * Check if there is a mouse callback hooked to the window
1622          */
1623         if( window->Callbacks.Mouse == NULL )
1624             break;
1625
1626         /*
1627          * Set the current window
1628          */
1629         fgSetWindow ( window );
1630
1631         /*
1632          * Remember the current modifiers state.
1633          */
1634         fgStructure.Window->State.Modifiers = 
1635             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1636             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1637             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1638
1639         /*
1640          * Finally execute the mouse callback
1641          */
1642         window->Callbacks.Mouse(
1643             button,
1644             pressed == TRUE ? GLUT_DOWN : GLUT_UP,
1645             window->State.MouseX,
1646             window->State.MouseY
1647         );
1648
1649         /*
1650          * Trash the modifiers state
1651          */
1652         fgStructure.Window->State.Modifiers = 0xffffffff;
1653     }
1654     break;
1655
1656     case WM_SYSKEYDOWN:
1657     case WM_KEYDOWN:
1658     {
1659         int keypress = -1;
1660         POINT mouse_pos ;
1661
1662         /*
1663          * Ignore the automatic key repetition if needed:
1664          */
1665         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1666             break;
1667
1668         /*
1669          * Remember the current modifiers state. This is done here in order 
1670          * to make sure the VK_DELETE keyboard callback is executed properly.
1671          */
1672         window->State.Modifiers = 
1673             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1674             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1675             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1676
1677         /*
1678          * Set the mouse position
1679          */
1680         GetCursorPos ( &mouse_pos ) ;
1681         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1682
1683         window->State.MouseX = mouse_pos.x ;
1684         window->State.MouseY = mouse_pos.y ;
1685
1686         /*
1687          * Convert the Win32 keystroke codes to GLUTtish way
1688          */
1689 #       define KEY(a,b) case a: keypress = b; break;
1690
1691         switch( wParam )
1692         {
1693             /*
1694              * Most of the special characters can be handled automagically...
1695              */
1696             KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1697             KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1698             KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1699             KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1700             KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1701             KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1702             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1703             KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1704             KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1705             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1706             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1707
1708             /*
1709              * ...yet there is a small exception we need to have handled...
1710              */
1711             case VK_DELETE:
1712                 /*
1713                  * The delete key should be treated as an ASCII keypress:
1714                  */
1715                 if( window->Callbacks.Keyboard != NULL )
1716                 {
1717                     fgSetWindow( window );
1718                     window->Callbacks.Keyboard( 127, window->State.MouseX, window->State.MouseY );
1719                 }
1720         }
1721
1722         /*
1723          * Execute the special callback, if present, given the conversion was a success:
1724          */
1725         if( (keypress != -1) && (window->Callbacks.Special != NULL) )
1726         {
1727             /*
1728              * Set the current window
1729              */
1730             fgSetWindow( window );
1731
1732             /*
1733              * Have the special callback executed:
1734              */
1735             window->Callbacks.Special( keypress, window->State.MouseX, window->State.MouseY );
1736         }
1737
1738         /*
1739          * Thrash the modifiers register now
1740          */
1741         window->State.Modifiers = 0xffffffff;
1742     }
1743     break;
1744
1745     case WM_SYSKEYUP:
1746     case WM_KEYUP:
1747     {
1748         int keypress = -1;
1749         POINT mouse_pos ;
1750
1751         /*
1752          * Remember the current modifiers state. This is done here in order 
1753          * to make sure the VK_DELETE keyboard callback is executed properly.
1754          */
1755         window->State.Modifiers = 
1756             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1757             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1758             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1759
1760         /*
1761          * Set the mouse position
1762          */
1763         GetCursorPos ( &mouse_pos ) ;
1764         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1765
1766         window->State.MouseX = mouse_pos.x ;
1767         window->State.MouseY = mouse_pos.y ;
1768
1769         /*
1770          * Convert the Win32 keystroke codes to GLUTtish way.  "KEY(a,b)" was defined under "WM_KEYDOWN"
1771          */
1772
1773         switch( wParam )
1774         {
1775           /*
1776            * Most of the special characters can be handled automagically...
1777            */
1778           KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1779           KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1780           KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1781           KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1782           KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1783           KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1784           KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1785           KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1786           KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1787           KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1788           KEY( VK_INSERT, GLUT_KEY_INSERT    );
1789
1790           /*
1791            * ...yet there is a small exception we need to have handled...
1792            */
1793           case VK_DELETE:
1794             /*
1795              * The delete key should be treated as an ASCII keypress:
1796              */
1797             if( window->Callbacks.KeyboardUp != NULL )
1798             {
1799                 fgSetWindow ( window ) ;
1800                 window->Callbacks.KeyboardUp( 127, window->State.MouseX, window->State.MouseY );
1801             }
1802
1803             break ;
1804           default:
1805             {
1806               /*
1807                * Call the KeyboardUp callback for a regular character if there is one.
1808                */
1809               BYTE state[ 256 ];
1810               WORD code[ 2 ];
1811
1812               GetKeyboardState(state);
1813
1814               if ( ToAscii( wParam, 0, state, code, 0 ) == 1 )
1815                 wParam=code[ 0 ];
1816
1817               if( window->Callbacks.KeyboardUp != NULL )
1818               {
1819                 /*
1820                  * Set the current window
1821                  */
1822                 fgSetWindow( window );
1823
1824                 window->Callbacks.KeyboardUp( (char)wParam, window->State.MouseX, window->State.MouseY );
1825               }
1826             }
1827         }
1828
1829         /*
1830          * Execute the special callback, if present, given the conversion was a success:
1831          */
1832         if( (keypress != -1) && (window->Callbacks.SpecialUp != NULL) )
1833         {
1834             /*
1835              * Set the current window
1836              */
1837             fgSetWindow( window );
1838
1839             /*
1840              * Have the special callback executed:
1841              */
1842             window->Callbacks.SpecialUp( keypress, window->State.MouseX, window->State.MouseY );
1843         }
1844
1845         /*
1846          * Thrash the modifiers register now
1847          */
1848         window->State.Modifiers = 0xffffffff;
1849     }
1850     break;
1851
1852     case WM_SYSCHAR:
1853     case WM_CHAR:
1854     {
1855         /*
1856          * Ignore the automatic key repetition if needed:
1857          */
1858         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1859             break;
1860
1861         /*
1862          * Clear to go with the keyboard callback, if registered:
1863          */
1864         if( window->Callbacks.Keyboard != NULL )
1865         {
1866             /*
1867              * Set the current window
1868              */
1869             fgSetWindow( window );
1870
1871             /*
1872              * Remember the current modifiers state
1873              */
1874             window->State.Modifiers = 
1875                 ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1876                 ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1877                 ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1878
1879             /*
1880              * Have the special callback executed:
1881              */
1882             window->Callbacks.Keyboard( (char)wParam, window->State.MouseX, window->State.MouseY );
1883
1884             /*
1885              * Thrash the modifiers register now
1886              */
1887             window->State.Modifiers = 0xffffffff;
1888         }
1889     }
1890     break;
1891
1892     case WM_CAPTURECHANGED :  /* User has finished resizing the window, force a redraw */
1893       if ( window->Callbacks.Display )
1894       {
1895         /*
1896          * Set the current window
1897          */
1898         fgSetWindow( window );
1899
1900         window->Callbacks.Display () ;
1901       }
1902
1903 /*      lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ) ; */
1904       break ;
1905
1906       /*
1907        * Other messages that I have seen and which are not handled already
1908        */
1909     case WM_SETTEXT :  /* 0x000c */
1910       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to set the window text */
1911       break ;
1912
1913     case WM_GETTEXT :  /* 0x000d */
1914       /* Ideally we would copy the title of the window into "lParam" */
1915 /*      strncpy ( (char *)lParam, "Window Title", wParam ) ;
1916       lRet = ( wParam > 12 ) ? 12 : wParam ;  */ /* the number of characters copied */
1917       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1918       break ;
1919
1920     case WM_GETTEXTLENGTH :  /* 0x000e */
1921       /* Ideally we would get the length of the title of the window */
1922       lRet = 12 ;  /* the number of characters in "Window Title\0" (see above) */
1923       break ;
1924
1925     case WM_ERASEBKGND :  /* 0x0014 */
1926       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1927       break ;
1928
1929     case WM_SYNCPAINT :  /* 0x0088 */
1930       /* Another window has moved, need to update this one */
1931       window->State.Redisplay = TRUE ;
1932       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Help screen says this message must be passed to "DefWindowProc" */
1933       break ;
1934
1935     case WM_NCPAINT :  /* 0x0085 */
1936       /* Need to update the border of this window */
1937       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to repaint a standard border */
1938       break ;
1939
1940     default:
1941         /*
1942          * Handle unhandled messages
1943          */
1944         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1945         break;
1946     }
1947
1948     return( lRet );
1949 }
1950 #endif
1951
1952 /*** END OF FILE ***/