6219980a75460229f5858a52766544cd13afd5a1
[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             fgSetWindow ( window ) ;
797             fgStructure.Menu = window->ActiveMenu ;
798
799             /* Execute the menu callback */
800             fgExecuteMenuCallback ( window->ActiveMenu ) ;
801             fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
802
803             /* Restore the current window and menu */
804             fgSetWindow ( save_window ) ;
805             fgStructure.Menu = save_menu ;
806           }
807           else  /* Outside the menu, deactivate the menu if it's a downclick */
808           {
809             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
810           }
811
812           /*
813            * Let's make the window redraw as a result of the mouse click and menu activity.
814            */
815           window->State.Redisplay = TRUE ;
816
817           break ;
818         }
819
820         /*
821          * No active menu, let's check whether we need to activate one.
822          */
823         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
824         {
825           /*
826            * Let's make the window redraw as a result of the mouse click.
827            */
828           window->State.Redisplay = TRUE ;
829
830           /*
831            * Set the current window
832            */
833           fgSetWindow( window );
834
835           /*
836            * Activate the appropriate menu structure...
837            */
838           fgActivateMenu( window, button );
839
840           break;
841         }
842
843         /*
844          * Check if there is a mouse callback hooked to the window
845          */
846         if( window->Callbacks.Mouse == NULL )
847           break;
848
849         /*
850          * Set the current window
851          */
852         fgSetWindow ( window );
853
854         /*
855          * Remember the current modifiers state
856          */
857         modifiers = 0;
858         if (event.xbutton.state & (ShiftMask|LockMask))
859           modifiers |= GLUT_ACTIVE_SHIFT;
860         if (event.xbutton.state & ControlMask)
861           modifiers |= GLUT_ACTIVE_CTRL;
862         if (event.xbutton.state & Mod1Mask)
863           modifiers |= GLUT_ACTIVE_ALT;
864         fgStructure.Window->State.Modifiers = modifiers;
865
866         /*
867          * Finally execute the mouse callback
868          */
869         fgStructure.Window->Callbacks.Mouse(
870             button,
871             event.type == ButtonPress ? GLUT_DOWN : GLUT_UP,
872             event.xbutton.x,
873             event.xbutton.y
874         );
875
876         /*
877          * Trash the modifiers state
878          */
879         fgStructure.Window->State.Modifiers = 0xffffffff;
880       }
881       break;
882
883     case KeyRelease:
884     case KeyPress:
885       {
886         FGCBkeyboard keyboard_cb;
887         FGCBspecial special_cb;
888
889         /*
890          * A key has been pressed, find the window that had the focus:
891          */
892         GETWINDOW( xkey ); GETMOUSE( xkey );
893
894         if( event.type == KeyPress )
895         {
896           keyboard_cb = window->Callbacks.Keyboard;
897           special_cb = window->Callbacks.Special;
898         }
899         else
900         {
901           keyboard_cb = window->Callbacks.KeyboardUp;
902           special_cb = window->Callbacks.SpecialUp;
903         }
904
905         /*
906          * Is there a keyboard/special callback hooked for this window?
907          */
908         if( (keyboard_cb != NULL) || (special_cb != NULL) )
909         {
910           XComposeStatus composeStatus;
911           char asciiCode[ 32 ];
912           KeySym keySym;
913           int len;
914
915           /*
916            * Check for the ASCII/KeySym codes associated with the event:
917            */
918           len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus );
919
920           /*
921            * GLUT API tells us to have two separate callbacks...
922            */
923           if( len > 0 )
924           {
925             /*
926              * ...one for the ASCII translateable keypresses...
927              */
928             if( keyboard_cb != NULL )
929             {
930               /*
931                * Set the current window
932                */
933               fgSetWindow( window );
934
935               /*
936                * Remember the current modifiers state
937                */
938               modifiers = 0;
939               if (event.xkey.state & (ShiftMask|LockMask))
940                   modifiers |= GLUT_ACTIVE_SHIFT;
941               if (event.xkey.state & ControlMask)
942                   modifiers |= GLUT_ACTIVE_CTRL;
943               if (event.xkey.state & Mod1Mask)
944                   modifiers |= GLUT_ACTIVE_ALT;
945               window->State.Modifiers = modifiers;
946
947               /*
948                * Execute the callback
949                */
950               keyboard_cb( asciiCode[ 0 ], event.xkey.x, event.xkey.y );
951
952               /*
953                * Trash the modifiers state
954                */
955               window->State.Modifiers = 0xffffffff;
956             }
957           }
958           else
959           {
960             int special = -1;
961
962             /*
963              * ...and one for all the others, which need to be translated to GLUT_KEY_Xs...
964              */
965             switch( keySym )
966             {
967             /*
968              * First the function keys come:
969              */
970             case XK_F1:     special = GLUT_KEY_F1;     break;
971             case XK_F2:     special = GLUT_KEY_F2;     break;
972             case XK_F3:     special = GLUT_KEY_F3;     break;
973             case XK_F4:     special = GLUT_KEY_F4;     break;
974             case XK_F5:     special = GLUT_KEY_F5;     break;
975             case XK_F6:     special = GLUT_KEY_F6;     break;
976             case XK_F7:     special = GLUT_KEY_F7;     break;
977             case XK_F8:     special = GLUT_KEY_F8;     break;
978             case XK_F9:     special = GLUT_KEY_F9;     break;
979             case XK_F10:    special = GLUT_KEY_F10;    break;
980             case XK_F11:    special = GLUT_KEY_F11;    break;
981             case XK_F12:    special = GLUT_KEY_F12;    break;
982
983             /*
984              * Then the arrows and stuff:
985              */
986             case XK_Left:   special = GLUT_KEY_LEFT;   break;
987             case XK_Right:  special = GLUT_KEY_RIGHT;  break;
988             case XK_Up:     special = GLUT_KEY_UP;     break;
989             case XK_Down:   special = GLUT_KEY_DOWN;   break;
990
991             case XK_KP_Prior:
992             case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
993             case XK_KP_Next:
994             case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
995             case XK_KP_Home:
996             case XK_Home:   special = GLUT_KEY_HOME;   break;
997             case XK_KP_End:
998             case XK_End:    special = GLUT_KEY_END;    break;
999             case XK_KP_Insert:
1000             case XK_Insert: special = GLUT_KEY_INSERT; break;
1001             }
1002
1003             /*
1004              * Execute the callback (if one has been specified),
1005              * given that the special code seems to be valid...
1006              */
1007             if( (special_cb != NULL) && (special != -1) )
1008             {
1009               /*
1010                * Set the current window
1011                */
1012               fgSetWindow( window );
1013
1014               /*
1015                * Remember the current modifiers state
1016                */
1017               modifiers = 0;
1018               if (event.xkey.state & (ShiftMask|LockMask))
1019                 modifiers |= GLUT_ACTIVE_SHIFT;
1020               if (event.xkey.state & ControlMask)
1021                 modifiers |= GLUT_ACTIVE_CTRL;
1022               if (event.xkey.state & Mod1Mask)
1023                 modifiers |= GLUT_ACTIVE_ALT;
1024               window->State.Modifiers = modifiers;
1025
1026               special_cb( special, event.xkey.x, event.xkey.y );
1027
1028               /*
1029                * Trash the modifiers state
1030                */
1031               window->State.Modifiers = 0xffffffff;
1032             }
1033           }
1034         }
1035       }
1036       break;
1037     }
1038   }
1039   else
1040   {
1041     /*
1042      * Have all the timers checked.
1043      */
1044     fghCheckTimers();
1045
1046     /*
1047      * Poll the joystick and notify all windows that want to be notified...
1048      */
1049     fghCheckJoystickPolls();
1050
1051     /*
1052      * No messages in the queue, which means we are idling...
1053      */
1054     if( fgState.IdleCallback != NULL )
1055         fgState.IdleCallback();
1056
1057     /*
1058      * Remember about displaying all the windows that have
1059      * been marked for a redisplay (possibly in the idle call):
1060      */
1061     fghDisplayAll();
1062   }
1063
1064 #elif TARGET_HOST_WIN32
1065
1066   MSG stMsg;
1067
1068   /*
1069    * The windows processing is considerably smaller
1070    */
1071   if( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
1072   {
1073     /*
1074      * Grab the message now, checking for WM_QUIT
1075      */
1076     if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1077       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1078
1079     /*
1080      * Translate virtual-key messages and send them to the window...
1081      */
1082     TranslateMessage( &stMsg );
1083     DispatchMessage( &stMsg );
1084   }
1085   else
1086   {
1087     /*
1088      * Have all the timers checked.
1089      */
1090     fghCheckTimers();
1091
1092     /*
1093      * Poll the joystick and notify all windows that want to be notified...
1094      */
1095     fghCheckJoystickPolls();
1096
1097     /*
1098      * No messages in the queue, which means we are idling...
1099      */
1100     if( fgState.IdleCallback != NULL )
1101       fgState.IdleCallback();
1102
1103     /*
1104      * Remember about displaying all the windows that have
1105      * been marked for a redisplay (possibly in the idle call):
1106      */
1107     fghDisplayAll();
1108   }
1109 #endif
1110
1111     /* 
1112      * If an event caused a window to be closed, do the actual closing here
1113      */
1114     fgCloseWindows () ;
1115 }
1116
1117 /*
1118  * Enters the freeglut processing loop. Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1119  */
1120 void FGAPIENTRY glutMainLoop( void )
1121 {
1122 #if TARGET_HOST_WIN32
1123   SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1124 #endif
1125
1126   /*
1127    * Make sure the display has been created etc.
1128    */
1129   freeglut_assert_ready;
1130
1131 #if TARGET_HOST_WIN32
1132   /*
1133    * Processing before the main loop:  If there is a window which is open and which
1134    * has a visibility callback, call it.  I know this is an ugly hack, but I'm not sure
1135    * what else to do about it.  Ideally we should leave something uninitialized in the
1136    * create window code and initialize it in the main loop, and have that initialization
1137    * create a "WM_ACTIVATE" message.  Then we would put the visibility callback code in
1138    * the "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1139    */
1140   while ( window != NULL )
1141   {
1142     if ( window->Callbacks.Visibility != NULL )
1143     {
1144       SFG_Window *current_window = fgStructure.Window ;
1145
1146       /*
1147        * Set the current window
1148        */
1149       fgSetWindow( window );
1150
1151       window->Callbacks.Visibility ( window->State.Visible ) ;
1152
1153       /*
1154        * Restore the current window
1155        */
1156       fgSetWindow( current_window );
1157     }
1158
1159     window = (SFG_Window *)window->Node.Next ;
1160   }
1161 #endif
1162
1163   /*
1164    * Set freeglut to be running
1165    */
1166   fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1167
1168   /*
1169    * Enter the main loop itself.  Inside the loop, process events and check for loop exit.
1170    */
1171   while ( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1172   {
1173     glutMainLoopEvent () ;
1174
1175     /*
1176      * If there are no more windows open, stop execution
1177      */
1178     if ( fgStructure.Windows.First == NULL )
1179       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1180   }
1181
1182
1183   /*
1184    * If we got here by the user closing a window or by the application closing down, there may still be windows open.
1185    */
1186   fgCleanUpGlutsMess () ;
1187
1188   /*
1189    * Check whether we return to the calling program or simply exit
1190    */
1191   if ( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1192     exit ( 0 ) ;
1193
1194   /*
1195    * When this loop terminates, destroy the display, state and structure
1196    * of a freeglut session, so that another glutInit() call can happen
1197    */
1198   fgDeinitialize();
1199 }
1200
1201 /*
1202  * Leaves the freeglut processing loop.
1203  */
1204 void FGAPIENTRY glutLeaveMainLoop( void )
1205 {
1206   fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1207 }
1208
1209 /*
1210  * The window procedure for handling Win32 events
1211  */
1212 #if TARGET_HOST_WIN32
1213 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1214 {
1215     SFG_Window* window = fgWindowByHandle( hWnd );
1216     PAINTSTRUCT ps;
1217     LONG lRet = 1;
1218
1219     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1220       return( DefWindowProc( hWnd, uMsg, wParam, lParam ) );
1221
1222 /*    printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0, uMsg, wParam, lParam ) ; */
1223     /*
1224      * Check what type of message are we receiving
1225      */
1226     switch( uMsg )
1227     {
1228     case WM_CREATE:
1229         /*
1230          * The window structure is passed as the creation structure paramter...
1231          */
1232         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1233         assert( window != NULL );
1234
1235         /*
1236          * We can safely store the window's handle now:
1237          */
1238         window->Window.Handle = hWnd;
1239
1240         /*
1241          * Get the window's device context
1242          */
1243         window->Window.Device = GetDC( hWnd );
1244
1245         /*
1246          * Create or get the OpenGL rendering context now
1247          */
1248         if ( fgState.BuildingAMenu )
1249         {
1250           /*
1251            * Setup the pixel format of our window
1252            */
1253           unsigned int current_DisplayMode = fgState.DisplayMode ;
1254           fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ;
1255           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1256           fgState.DisplayMode = current_DisplayMode ;
1257
1258           /*
1259            * If there isn't already an OpenGL rendering context for menu windows, make one
1260            */
1261           if ( !fgStructure.MenuContext )
1262           {
1263             fgStructure.MenuContext = (SFG_MenuContext *)malloc ( sizeof(SFG_MenuContext) ) ;
1264             fgStructure.MenuContext->Context = wglCreateContext( window->Window.Device );
1265           }
1266           else
1267             wglMakeCurrent ( window->Window.Device, fgStructure.MenuContext->Context ) ;
1268
1269 /*          window->Window.Context = wglGetCurrentContext () ;   */
1270           window->Window.Context = wglCreateContext( window->Window.Device );
1271         }
1272         else
1273         {
1274           /*
1275            * Setup the pixel format of our window
1276            */
1277           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1278
1279           if ( fgState.UseCurrentContext == TRUE )
1280           {
1281             window->Window.Context = wglGetCurrentContext();
1282             if ( ! window->Window.Context )
1283               window->Window.Context = wglCreateContext( window->Window.Device );
1284           }
1285           else
1286             window->Window.Context = wglCreateContext( window->Window.Device );
1287         }
1288
1289         /*
1290          * Still, we'll be needing to explicitly resize the window
1291          */
1292         window->State.NeedToResize = TRUE;
1293
1294         /*
1295          * Finally, have the window's device context released
1296          */
1297         ReleaseDC( window->Window.Handle, window->Window.Device );
1298         break;
1299
1300     case WM_SIZE:
1301         /*
1302          * We got resized... But check if the window has been already added...
1303          */
1304         fghReshapeWindowByHandle( hWnd, LOWORD(lParam), HIWORD(lParam) );
1305         break;
1306 #if 0
1307     case WM_SETFOCUS: 
1308         printf("WM_SETFOCUS: %p\n", window );
1309         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1310         break;
1311
1312     case WM_ACTIVATE: 
1313         if (LOWORD(wParam) != WA_INACTIVE)
1314         {
1315           /* glutSetCursor( fgStructure.Window->State.Cursor ); */
1316                 printf("WM_ACTIVATE: glutSetCursor( %p, %d)\n", window, window->State.Cursor );
1317
1318           glutSetCursor( window->State.Cursor );
1319         }
1320
1321         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1322         break;
1323 #endif
1324
1325     case WM_SETCURSOR: 
1326         /*
1327          * Windows seems to need reminding to erase the cursor for NONE.
1328          */
1329 #if 0
1330         if ((LOWORD(lParam) == HTCLIENT) &&
1331             (fgStructure.Window->State.Cursor == GLUT_CURSOR_NONE))
1332           SetCursor( NULL );
1333 #else
1334         /* Set the cursor AND change it for this window class. */
1335 #       define MAP_CURSOR(a,b) case a: SetCursor( LoadCursor( NULL, b ) ); \
1336         break;
1337         /* Nuke the cursor AND change it for this window class. */
1338 #       define ZAP_CURSOR(a,b) case a: SetCursor( NULL ); \
1339         break;
1340
1341         if (LOWORD(lParam) == HTCLIENT)
1342           switch( window->State.Cursor )
1343           {
1344                 MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, IDC_ARROW     );
1345                 MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  IDC_ARROW     );
1346                 MAP_CURSOR( GLUT_CURSOR_INFO,        IDC_HELP      );
1347                 MAP_CURSOR( GLUT_CURSOR_DESTROY,     IDC_CROSS     );
1348                 MAP_CURSOR( GLUT_CURSOR_HELP,        IDC_HELP      );
1349                 MAP_CURSOR( GLUT_CURSOR_CYCLE,       IDC_SIZEALL   );
1350                 MAP_CURSOR( GLUT_CURSOR_SPRAY,       IDC_CROSS     );
1351                 MAP_CURSOR( GLUT_CURSOR_WAIT,            IDC_WAIT      );
1352                 MAP_CURSOR( GLUT_CURSOR_TEXT,        IDC_UPARROW   );
1353                 MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   IDC_CROSS     );
1354                 /* MAP_CURSOR( GLUT_CURSOR_NONE,        IDC_NO             ); */
1355                 ZAP_CURSOR( GLUT_CURSOR_NONE,        NULL          );
1356
1357                 default:
1358                 MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     IDC_ARROW     );
1359           }
1360 #endif
1361         else
1362           lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1363         break;
1364
1365     case WM_SHOWWINDOW:
1366         /*
1367          * We are now Visible!
1368          */
1369         window->State.Visible = TRUE;
1370         window->State.Redisplay = TRUE;
1371         break;
1372
1373     case WM_PAINT:
1374         /*
1375          * Start the painting job
1376          */
1377
1378         BeginPaint( hWnd, &ps );
1379
1380         /*
1381          * Call the engine's main frame drawing method
1382          */
1383         fghRedrawWindowByHandle( hWnd );
1384
1385         /*
1386          * End the painting job, release the device context
1387          */
1388         EndPaint( hWnd, &ps );
1389         break;
1390
1391     case WM_CLOSE:
1392         /*
1393          * Make sure we don't close a window with current context active
1394          */
1395         if( fgStructure.Window == window )
1396         {
1397           int used = FALSE ;
1398           SFG_Window *iter ;
1399
1400             wglMakeCurrent( NULL, NULL );
1401             /* Step through the list of windows.  If the rendering context is notbeing used
1402              * by another window, then we delete it.
1403              */
1404             for ( iter = (SFG_Window *)fgStructure.Windows.First; iter; iter = (SFG_Window *)iter->Node.Next )
1405             {
1406               if ( ( iter->Window.Context == window->Window.Context ) && ( iter != window ) )
1407                 used = TRUE ;
1408             }
1409
1410             if ( used == FALSE ) wglDeleteContext( window->Window.Context );
1411         }
1412
1413         /*
1414          * Put on a linked list of windows to be removed after all the callbacks have returned
1415          */
1416         fgAddToWindowDestroyList ( window, FALSE ) ;
1417
1418         /*
1419          * Proceed with the window destruction
1420          */
1421         DestroyWindow( hWnd );
1422         break;
1423
1424     case WM_DESTROY:
1425         /*
1426          * The window already got destroyed, so don't bother with it.
1427          */
1428         return( 0 );
1429
1430     case WM_MOUSEMOVE:
1431     {
1432         /*
1433          * The mouse cursor has moved. Remember the new mouse cursor's position
1434          */
1435         window->State.MouseX = LOWORD( lParam );
1436         window->State.MouseY = HIWORD( lParam );
1437
1438         /*
1439          * Fallback if there's an active menu hooked to this window
1440          */
1441         if ( window->ActiveMenu != NULL )
1442         {
1443             /*
1444              * Let's make the window redraw as a result of the mouse motion.
1445              */
1446             window->State.Redisplay = TRUE ;
1447
1448             /*
1449              * Since the window is a menu, make the parent window current
1450              */
1451             fgSetWindow ( window->ActiveMenu->ParentWindow ) ;
1452
1453             break;
1454         }
1455
1456         /*
1457          * Remember the current modifiers state.
1458          */
1459         window->State.Modifiers = 
1460             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1461             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1462             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1463
1464         /*
1465          * Check if any of the mouse buttons is pressed...
1466          */
1467         if( (wParam & MK_LBUTTON) || (wParam & MK_MBUTTON) || (wParam & MK_RBUTTON) )
1468         {
1469             /*
1470              * Yeah, indeed. We need to use the motion callback then:
1471              */
1472             if( window->Callbacks.Motion != NULL )
1473             {
1474                 /*
1475                  * Make sure the current window is set...
1476                  */
1477                 fgSetWindow( window );
1478
1479                 /*
1480                  * Execute the active mouse motion callback now
1481                  */
1482                 window->Callbacks.Motion( window->State.MouseX, window->State.MouseY );
1483             }
1484         }
1485         else
1486         {
1487             /*
1488              * All mouse buttons are up, execute the passive mouse motion callback
1489              */
1490             if( window->Callbacks.Passive != NULL )
1491             {
1492                 /*
1493                  * Make sure the current window is set
1494                  */
1495                 fgSetWindow( window );
1496
1497                 /*
1498                  * Execute the passive mouse motion callback
1499                  */
1500                 window->Callbacks.Passive( window->State.MouseX, window->State.MouseY );
1501             }
1502         }
1503
1504         /*
1505          * Thrash the current modifiers state now
1506          */
1507         window->State.Modifiers = 0xffffffff;
1508     }
1509     break;
1510
1511     case WM_LBUTTONDOWN:
1512     case WM_MBUTTONDOWN:
1513     case WM_RBUTTONDOWN:
1514     case WM_LBUTTONUP:
1515     case WM_MBUTTONUP:
1516     case WM_RBUTTONUP:
1517     {
1518         GLboolean pressed = TRUE;
1519         int button;
1520
1521         /*
1522          * The mouse cursor has moved. Remember the new mouse cursor's position
1523          */
1524         window->State.MouseX = LOWORD( lParam );
1525         window->State.MouseY = HIWORD( lParam );
1526
1527         /*
1528          * We're curious about the GLUT API button name...
1529          */
1530         switch( uMsg )
1531         {
1532         case WM_LBUTTONDOWN: pressed = TRUE;  button = GLUT_LEFT_BUTTON;   break;
1533         case WM_MBUTTONDOWN: pressed = TRUE;  button = GLUT_MIDDLE_BUTTON; break;
1534         case WM_RBUTTONDOWN: pressed = TRUE;  button = GLUT_RIGHT_BUTTON;  break;
1535         case WM_LBUTTONUP:   pressed = FALSE; button = GLUT_LEFT_BUTTON;   break;
1536         case WM_MBUTTONUP:   pressed = FALSE; button = GLUT_MIDDLE_BUTTON; break;
1537         case WM_RBUTTONUP:   pressed = FALSE; button = GLUT_RIGHT_BUTTON;  break;
1538         default:             pressed = FALSE; button = -1;                 break;
1539         }
1540
1541         /*
1542          * The left and right mouse buttons might have been swapped...
1543          */
1544         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1545             if( button == GLUT_LEFT_BUTTON ) button = GLUT_RIGHT_BUTTON;
1546             else if( button == GLUT_RIGHT_BUTTON ) button = GLUT_LEFT_BUTTON;
1547
1548         /*
1549          * Hey, what's up with you?
1550          */
1551         if( button == -1 )
1552             return( DefWindowProc( hWnd, uMsg, lParam, wParam ) );
1553
1554         /*
1555          * Do not execute the application's mouse callback if a menu is hooked to this button.
1556          * In that case an appropriate private call should be generated.
1557          * Near as I can tell, this is the menu behaviour:
1558          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
1559          *  - Down-click any button outside the menu, menu active:  deactivate the menu
1560          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
1561          *  - Up-click the menu button, menu not active:  nothing happens
1562          *  - Up-click the menu button outside the menu, menu active:  nothing happens
1563          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
1564          */
1565         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
1566         {
1567           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
1568           {
1569             /* Save the current window and menu and set the current window to the window whose menu this is */
1570             SFG_Window *save_window = fgStructure.Window ;
1571             SFG_Menu *save_menu = fgStructure.Menu ;
1572             fgSetWindow ( window ) ;
1573             fgStructure.Menu = window->ActiveMenu ;
1574
1575             /* Execute the menu callback */
1576             fgExecuteMenuCallback ( window->ActiveMenu ) ;
1577             fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
1578
1579             /* Restore the current window and menu */
1580             fgSetWindow ( save_window ) ;
1581             fgStructure.Menu = save_menu ;
1582           }
1583           else  /* Outside the menu, deactivate the menu if it's a downclick */
1584           {
1585             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
1586           }
1587
1588           /*
1589            * Let's make the window redraw as a result of the mouse click and menu activity.
1590            */
1591           if ( ! window->IsMenu ) window->State.Redisplay = TRUE ;
1592
1593           break ;
1594         }
1595
1596         /*
1597          * No active menu, let's check whether we need to activate one.
1598          */
1599         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
1600         {
1601             /*
1602              * Let's make the window redraw as a result of the mouse click.
1603              */
1604             window->State.Redisplay = TRUE ;
1605
1606             /*
1607              * Set the current window
1608              */
1609             fgSetWindow( window );
1610
1611             /*
1612              * Activate the appropriate menu structure...
1613              */
1614             fgActivateMenu( window, button );
1615
1616             break;
1617         }
1618
1619         /*
1620          * Check if there is a mouse callback hooked to the window
1621          */
1622         if( window->Callbacks.Mouse == NULL )
1623             break;
1624
1625         /*
1626          * Set the current window
1627          */
1628         fgSetWindow ( window );
1629
1630         /*
1631          * Remember the current modifiers state.
1632          */
1633         fgStructure.Window->State.Modifiers = 
1634             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1635             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1636             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1637
1638         /*
1639          * Finally execute the mouse callback
1640          */
1641         window->Callbacks.Mouse(
1642             button,
1643             pressed == TRUE ? GLUT_DOWN : GLUT_UP,
1644             window->State.MouseX,
1645             window->State.MouseY
1646         );
1647
1648         /*
1649          * Trash the modifiers state
1650          */
1651         fgStructure.Window->State.Modifiers = 0xffffffff;
1652     }
1653     break;
1654
1655     case WM_SYSKEYDOWN:
1656     case WM_KEYDOWN:
1657     {
1658         int keypress = -1;
1659         POINT mouse_pos ;
1660
1661         /*
1662          * Ignore the automatic key repetition if needed:
1663          */
1664         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1665             break;
1666
1667         /*
1668          * Remember the current modifiers state. This is done here in order 
1669          * to make sure the VK_DELETE keyboard callback is executed properly.
1670          */
1671         window->State.Modifiers = 
1672             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1673             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1674             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1675
1676         /*
1677          * Set the mouse position
1678          */
1679         GetCursorPos ( &mouse_pos ) ;
1680         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1681
1682         window->State.MouseX = mouse_pos.x ;
1683         window->State.MouseY = mouse_pos.y ;
1684
1685         /*
1686          * Convert the Win32 keystroke codes to GLUTtish way
1687          */
1688 #       define KEY(a,b) case a: keypress = b; break;
1689
1690         switch( wParam )
1691         {
1692             /*
1693              * Most of the special characters can be handled automagically...
1694              */
1695             KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1696             KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1697             KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1698             KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1699             KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1700             KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1701             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1702             KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1703             KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1704             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1705             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1706
1707             /*
1708              * ...yet there is a small exception we need to have handled...
1709              */
1710             case VK_DELETE:
1711                 /*
1712                  * The delete key should be treated as an ASCII keypress:
1713                  */
1714                 if( window->Callbacks.Keyboard != NULL )
1715                 {
1716                     fgSetWindow( window );
1717                     window->Callbacks.Keyboard( 127, window->State.MouseX, window->State.MouseY );
1718                 }
1719         }
1720
1721         /*
1722          * Execute the special callback, if present, given the conversion was a success:
1723          */
1724         if( (keypress != -1) && (window->Callbacks.Special != NULL) )
1725         {
1726             /*
1727              * Set the current window
1728              */
1729             fgSetWindow( window );
1730
1731             /*
1732              * Have the special callback executed:
1733              */
1734             window->Callbacks.Special( keypress, window->State.MouseX, window->State.MouseY );
1735         }
1736
1737         /*
1738          * Thrash the modifiers register now
1739          */
1740         window->State.Modifiers = 0xffffffff;
1741     }
1742     break;
1743
1744     case WM_SYSKEYUP:
1745     case WM_KEYUP:
1746     {
1747         int keypress = -1;
1748         POINT mouse_pos ;
1749
1750         /*
1751          * Remember the current modifiers state. This is done here in order 
1752          * to make sure the VK_DELETE keyboard callback is executed properly.
1753          */
1754         window->State.Modifiers = 
1755             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1756             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1757             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1758
1759         /*
1760          * Set the mouse position
1761          */
1762         GetCursorPos ( &mouse_pos ) ;
1763         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1764
1765         window->State.MouseX = mouse_pos.x ;
1766         window->State.MouseY = mouse_pos.y ;
1767
1768         /*
1769          * Convert the Win32 keystroke codes to GLUTtish way.  "KEY(a,b)" was defined under "WM_KEYDOWN"
1770          */
1771
1772         switch( wParam )
1773         {
1774           /*
1775            * Most of the special characters can be handled automagically...
1776            */
1777           KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1778           KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1779           KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1780           KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1781           KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1782           KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1783           KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1784           KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1785           KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1786           KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1787           KEY( VK_INSERT, GLUT_KEY_INSERT    );
1788
1789           /*
1790            * ...yet there is a small exception we need to have handled...
1791            */
1792           case VK_DELETE:
1793             /*
1794              * The delete key should be treated as an ASCII keypress:
1795              */
1796             if( window->Callbacks.KeyboardUp != NULL )
1797             {
1798                 fgSetWindow ( window ) ;
1799                 window->Callbacks.KeyboardUp( 127, window->State.MouseX, window->State.MouseY );
1800             }
1801
1802             break ;
1803           default:
1804             {
1805               /*
1806                * Call the KeyboardUp callback for a regular character if there is one.
1807                */
1808               BYTE state[ 256 ];
1809               WORD code[ 2 ];
1810
1811               GetKeyboardState(state);
1812
1813               if ( ToAscii( wParam, 0, state, code, 0 ) == 1 )
1814                 wParam=code[ 0 ];
1815
1816               if( window->Callbacks.KeyboardUp != NULL )
1817               {
1818                 /*
1819                  * Set the current window
1820                  */
1821                 fgSetWindow( window );
1822
1823                 window->Callbacks.KeyboardUp( (char)wParam, window->State.MouseX, window->State.MouseY );
1824               }
1825             }
1826         }
1827
1828         /*
1829          * Execute the special callback, if present, given the conversion was a success:
1830          */
1831         if( (keypress != -1) && (window->Callbacks.SpecialUp != NULL) )
1832         {
1833             /*
1834              * Set the current window
1835              */
1836             fgSetWindow( window );
1837
1838             /*
1839              * Have the special callback executed:
1840              */
1841             window->Callbacks.SpecialUp( keypress, window->State.MouseX, window->State.MouseY );
1842         }
1843
1844         /*
1845          * Thrash the modifiers register now
1846          */
1847         window->State.Modifiers = 0xffffffff;
1848     }
1849     break;
1850
1851     case WM_SYSCHAR:
1852     case WM_CHAR:
1853     {
1854         /*
1855          * Ignore the automatic key repetition if needed:
1856          */
1857         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1858             break;
1859
1860         /*
1861          * Clear to go with the keyboard callback, if registered:
1862          */
1863         if( window->Callbacks.Keyboard != NULL )
1864         {
1865             /*
1866              * Set the current window
1867              */
1868             fgSetWindow( window );
1869
1870             /*
1871              * Remember the current modifiers state
1872              */
1873             window->State.Modifiers = 
1874                 ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1875                 ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1876                 ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1877
1878             /*
1879              * Have the special callback executed:
1880              */
1881             window->Callbacks.Keyboard( (char)wParam, window->State.MouseX, window->State.MouseY );
1882
1883             /*
1884              * Thrash the modifiers register now
1885              */
1886             window->State.Modifiers = 0xffffffff;
1887         }
1888     }
1889     break;
1890
1891     case WM_CAPTURECHANGED :  /* User has finished resizing the window, force a redraw */
1892       if ( window->Callbacks.Display )
1893       {
1894         /*
1895          * Set the current window
1896          */
1897         fgSetWindow( window );
1898
1899         window->Callbacks.Display () ;
1900       }
1901
1902 /*      lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ) ; */
1903       break ;
1904
1905       /*
1906        * Other messages that I have seen and which are not handled already
1907        */
1908     case WM_SETTEXT :  /* 0x000c */
1909       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to set the window text */
1910       break ;
1911
1912     case WM_GETTEXT :  /* 0x000d */
1913       /* Ideally we would copy the title of the window into "lParam" */
1914 /*      strncpy ( (char *)lParam, "Window Title", wParam ) ;
1915       lRet = ( wParam > 12 ) ? 12 : wParam ;  */ /* the number of characters copied */
1916       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1917       break ;
1918
1919     case WM_GETTEXTLENGTH :  /* 0x000e */
1920       /* Ideally we would get the length of the title of the window */
1921       lRet = 12 ;  /* the number of characters in "Window Title\0" (see above) */
1922       break ;
1923
1924     case WM_ERASEBKGND :  /* 0x0014 */
1925       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1926       break ;
1927
1928     case WM_SYNCPAINT :  /* 0x0088 */
1929       /* Another window has moved, need to update this one */
1930       window->State.Redisplay = TRUE ;
1931       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Help screen says this message must be passed to "DefWindowProc" */
1932       break ;
1933
1934     case WM_NCPAINT :  /* 0x0085 */
1935       /* Need to update the border of this window */
1936       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to repaint a standard border */
1937       break ;
1938
1939     default:
1940         /*
1941          * Handle unhandled messages
1942          */
1943         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1944         break;
1945     }
1946
1947     return( lRet );
1948 }
1949 #endif
1950
1951 /*** END OF FILE ***/