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