Switch to ANSI C comments. Removed always true tests on unsigned char. Single buffe...
[freeglut] / freeglut-1.3 / 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       }
509       break;
510
511     case UnmapNotify:
512       /*
513        * A window of ours has been unmapped...
514        */
515       break;
516
517     case Expose:
518       /*
519        * We are too dumb to process partial exposes...
520        */
521       if( event.xexpose.count == 0 )
522           fghRedrawWindowByHandle( event.xexpose.window );
523       break;
524
525     case ConfigureNotify:
526       /*
527        * The window gets resized
528        */
529       fghReshapeWindowByHandle(
530           event.xconfigure.window,
531           event.xconfigure.width,
532           event.xconfigure.height
533       );
534       break;
535
536     case MappingNotify:
537       /*
538        * Have the client's keyboard knowledge updated (xlib.ps,
539        * page 206, says that's a good thing to do)
540        */
541       XRefreshKeyboardMapping( (XMappingEvent *) &event );
542       break;
543
544     case VisibilityNotify:
545       {
546         /*
547          * The window's visiblity might have changed
548          */
549         GETWINDOW( xvisibility );
550
551         /*
552          * Break now if no window status callback has been hooked to that window
553          */
554         if( window->Callbacks.WindowStatus == NULL )
555             break;
556
557         /*
558          * We're going to send a callback to a window. Make it current.
559          */
560         fgSetWindow( window );
561
562         /*
563          * Sending this event, the X server can notify us that the window has just
564          * acquired one of the three possible visibility states: VisibilityUnobscured,
565          * VisibilityPartiallyObscured or VisibilityFullyObscured
566          */
567         switch( event.xvisibility.state )
568         {
569         case VisibilityUnobscured:
570           /*
571            * We are fully visible...
572            */
573           window->Callbacks.WindowStatus( GLUT_FULLY_RETAINED );
574           window->State.Visible = TRUE;
575           break;
576
577         case VisibilityPartiallyObscured:
578           /*
579            * The window is partially visible
580            */
581           window->Callbacks.WindowStatus( GLUT_PARTIALLY_RETAINED );
582           window->State.Visible = TRUE;
583           break;
584
585         case VisibilityFullyObscured:
586           /*
587            * The window is totally obscured
588            */
589           window->Callbacks.WindowStatus( GLUT_FULLY_COVERED );
590           window->State.Visible = FALSE;
591           break;
592         }
593       }
594       break;
595
596     case EnterNotify:
597       {
598         /*
599          * Mouse is over one of our windows
600          */
601         GETWINDOW( xcrossing ); GETMOUSE( xcrossing );
602
603         /*
604          * Is there an entry callback hooked to the window?
605          */
606         if( window->Callbacks.Entry != NULL )
607         {
608           /*
609            * Yeah. Notify the window about having the mouse cursor over
610            */
611           window->Callbacks.Entry( GLUT_ENTERED );
612         }
613       }
614       break;
615
616     case LeaveNotify:
617       {
618         /*
619          * Mouse is no longer over one of our windows
620          */
621         GETWINDOW( xcrossing ); GETMOUSE( xcrossing );
622
623         /*
624          * Is there an entry callback hooked to the window?
625          */
626         if( window->Callbacks.Entry != NULL )
627         {
628           /*
629            * Yeah. Notify the window about having the mouse cursor over
630            */
631           window->Callbacks.Entry( GLUT_LEFT );
632         }
633       }
634       break;
635
636     case MotionNotify:
637       {
638         /*
639          * The mouse cursor was moved...
640          */
641         GETWINDOW( xmotion ); GETMOUSE( xmotion );
642
643         /*
644          * What kind of a movement was it?
645          */
646         if( (event.xmotion.state & Button1Mask) || (event.xmotion.state & Button2Mask) ||
647             (event.xmotion.state & Button3Mask) || (event.xmotion.state & Button4Mask) ||
648             (event.xmotion.state & Button5Mask) )
649         {
650           /*
651            * A mouse button was pressed during the movement...
652            * Is there a motion callback hooked to the window?
653            */
654           if( window->Callbacks.Motion != NULL )
655           {
656             /*
657              * Yup. Have it executed immediately
658              */
659             window->Callbacks.Motion( event.xmotion.x, event.xmotion.y );
660           }
661         }
662         else
663         {
664           /*
665            * Otherwise it was a passive movement...
666            */
667           if( window->Callbacks.Passive != NULL )
668           {
669             /*
670              * That's right, and there is a passive callback, too.
671              */
672             window->Callbacks.Passive( event.xmotion.x, event.xmotion.y );
673           }
674         }
675       }
676       break;
677
678     case ButtonRelease:
679     case ButtonPress:
680       {
681         GLboolean pressed = TRUE ;
682         int button;
683
684         if ( event.type == ButtonRelease ) pressed = FALSE ;
685
686         /*
687          * A mouse button has been pressed or released. Traditionally,
688          * break if the window was found within the freeglut structures.
689          */
690         GETWINDOW( xbutton ); GETMOUSE( xbutton );
691
692         /*
693          * GLUT API assumes that you can't have more than three mouse buttons, so:
694          */
695         switch( event.xbutton.button )
696         {
697         /*
698          * WARNING: this might be wrong, if we only have two mouse buttons,
699          *          Button2 might mean the right button, isn't that right?
700          */
701         case Button1:   button = GLUT_LEFT_BUTTON;   break;
702         case Button2:   button = GLUT_MIDDLE_BUTTON; break;
703         case Button3:   button = GLUT_RIGHT_BUTTON;  break;
704         default:        button = -1;                 break;
705         }
706
707         /*
708          * Skip the unwanted mouse buttons...
709          */
710         if( button == -1 )
711           break;
712
713         /*
714          * Do not execute the application's mouse callback if a menu is hooked to this button.
715          * In that case an appropriate private call should be generated.
716          * Near as I can tell, this is the menu behaviour:
717          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
718          *  - Down-click any button outside the menu, menu active:  deactivate the menu
719          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
720          *  - Up-click the menu button, menu not active:  nothing happens
721          *  - Up-click the menu button outside the menu, menu active:  nothing happens
722          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
723          */
724         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
725         {
726           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
727           {
728             /* Save the current window and menu and set the current window to the window whose menu this is */
729             SFG_Window *save_window = fgStructure.Window ;
730             SFG_Menu *save_menu = fgStructure.Menu ;
731             fgSetWindow ( window ) ;
732             fgStructure.Menu = window->ActiveMenu ;
733
734             /* Execute the menu callback */
735             fgExecuteMenuCallback ( window->ActiveMenu ) ;
736             fgDeactivateMenu ( window ) ;
737
738             /* Restore the current window and menu */
739             fgSetWindow ( save_window ) ;
740             fgStructure.Menu = save_menu ;
741           }
742           else  /* Outside the menu, deactivate the menu if it's a downclick */
743           {
744             if ( pressed == TRUE ) fgDeactivateMenu ( window ) ;
745           }
746
747           /*
748            * Let's make the window redraw as a result of the mouse click and menu activity.
749            */
750           window->State.Redisplay = TRUE ;
751
752           break ;
753         }
754
755         /*
756          * No active menu, let's check whether we need to activate one.
757          */
758         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
759         {
760           /*
761            * Let's make the window redraw as a result of the mouse click.
762            */
763           window->State.Redisplay = TRUE ;
764
765           /*
766            * Activate the appropriate menu structure...
767            */
768           fgActivateMenu( window, button );
769
770           break;
771         }
772
773         /*
774          * Check if there is a mouse callback hooked to the window
775          */
776         if( window->Callbacks.Mouse == NULL )
777           break;
778
779         /*
780          * Set the current window
781          */
782         fgSetWindow( window );
783
784         /*
785          * Remember the current modifiers state
786          */
787         modifiers = 0;
788         if (event.xbutton.state & (ShiftMask|LockMask))
789           modifiers |= GLUT_ACTIVE_SHIFT;
790         if (event.xbutton.state & ControlMask)
791           modifiers |= GLUT_ACTIVE_CTRL;
792         if (event.xbutton.state & Mod1Mask)
793           modifiers |= GLUT_ACTIVE_ALT;
794         window->State.Modifiers = modifiers;
795
796         /*
797          * Finally execute the mouse callback
798          */
799         window->Callbacks.Mouse(
800             button,
801             event.type == ButtonPress ? GLUT_DOWN : GLUT_UP,
802             event.xbutton.x,
803             event.xbutton.y
804         );
805
806         /*
807          * Trash the modifiers state
808          */
809         window->State.Modifiers = 0xffffffff;
810       }
811       break;
812
813     case KeyRelease:
814     case KeyPress:
815       {
816         FGCBkeyboard keyboard_cb;
817         FGCBspecial special_cb;
818
819         /*
820          * A key has been pressed, find the window that had the focus:
821          */
822         GETWINDOW( xkey ); GETMOUSE( xkey );
823
824         if( event.type == KeyPress )
825         {
826           keyboard_cb = window->Callbacks.Keyboard;
827           special_cb = window->Callbacks.Special;
828         }
829         else
830         {
831           keyboard_cb = window->Callbacks.KeyboardUp;
832           special_cb = window->Callbacks.SpecialUp;
833         }
834
835         /*
836          * Is there a keyboard/special callback hooked for this window?
837          */
838         if( (keyboard_cb != NULL) || (special_cb != NULL) )
839         {
840           XComposeStatus composeStatus;
841           char asciiCode[ 32 ];
842           KeySym keySym;
843           int len;
844
845           /*
846            * Check for the ASCII/KeySym codes associated with the event:
847            */
848           len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus );
849
850           /*
851            * Get ready to calling the keyboard/special callbacks
852            */
853           fgSetWindow( window );
854
855           /*
856            * GLUT API tells us to have two separate callbacks...
857            */
858           if( len > 0 )
859           {
860             /*
861              * ...one for the ASCII translateable keypresses...
862              */
863             if( keyboard_cb != NULL )
864             {
865               /*
866                * Remember the current modifiers state
867                */
868               modifiers = 0;
869               if (event.xkey.state & (ShiftMask|LockMask))
870                   modifiers |= GLUT_ACTIVE_SHIFT;
871               if (event.xkey.state & ControlMask)
872                   modifiers |= GLUT_ACTIVE_CTRL;
873               if (event.xkey.state & Mod1Mask)
874                   modifiers |= GLUT_ACTIVE_ALT;
875               window->State.Modifiers = modifiers;
876
877               /*
878                * Execute the callback
879                */
880               keyboard_cb( asciiCode[ 0 ], event.xkey.x, event.xkey.y );
881
882               /*
883                * Trash the modifiers state
884                */
885               window->State.Modifiers = 0xffffffff;
886             }
887           }
888           else
889           {
890             int special = -1;
891
892             /*
893              * ...and one for all the others, which need to be translated to GLUT_KEY_Xs...
894              */
895             switch( keySym )
896             {
897             /*
898              * First the function keys come:
899              */
900             case XK_F1:     special = GLUT_KEY_F1;     break;
901             case XK_F2:     special = GLUT_KEY_F2;     break;
902             case XK_F3:     special = GLUT_KEY_F3;     break;
903             case XK_F4:     special = GLUT_KEY_F4;     break;
904             case XK_F5:     special = GLUT_KEY_F5;     break;
905             case XK_F6:     special = GLUT_KEY_F6;     break;
906             case XK_F7:     special = GLUT_KEY_F7;     break;
907             case XK_F8:     special = GLUT_KEY_F8;     break;
908             case XK_F9:     special = GLUT_KEY_F9;     break;
909             case XK_F10:    special = GLUT_KEY_F10;    break;
910             case XK_F11:    special = GLUT_KEY_F11;    break;
911             case XK_F12:    special = GLUT_KEY_F12;    break;
912
913             /*
914              * Then the arrows and stuff:
915              */
916             case XK_Left:   special = GLUT_KEY_LEFT;   break;
917             case XK_Right:  special = GLUT_KEY_RIGHT;  break;
918             case XK_Up:     special = GLUT_KEY_UP;     break;
919             case XK_Down:   special = GLUT_KEY_DOWN;   break;
920
921             case XK_KP_Prior:
922             case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
923             case XK_KP_Next:
924             case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
925             case XK_KP_Home:
926             case XK_Home:   special = GLUT_KEY_HOME;   break;
927             case XK_KP_End:
928             case XK_End:    special = GLUT_KEY_END;    break;
929             case XK_KP_Insert:
930             case XK_Insert: special = GLUT_KEY_INSERT; break;
931             }
932
933             /*
934              * Execute the callback (if one has been specified),
935              * given that the special code seems to be valid...
936              */
937             if( (special_cb != NULL) && (special != -1) )
938             {
939               /*
940                * Remember the current modifiers state
941                */
942               modifiers = 0;
943               if (event.xkey.state & (ShiftMask|LockMask))
944                 modifiers |= GLUT_ACTIVE_SHIFT;
945               if (event.xkey.state & ControlMask)
946                 modifiers |= GLUT_ACTIVE_CTRL;
947               if (event.xkey.state & Mod1Mask)
948                 modifiers |= GLUT_ACTIVE_ALT;
949               window->State.Modifiers = modifiers;
950
951               special_cb( special, event.xkey.x, event.xkey.y );
952
953               /*
954                * Trash the modifiers state
955                */
956               window->State.Modifiers = 0xffffffff;
957             }
958           }
959         }
960       }
961       break;
962     }
963   }
964   else
965   {
966     /*
967      * Have all the timers checked.
968      */
969     fghCheckTimers();
970
971     /*
972      * Poll the joystick and notify all windows that want to be notified...
973      */
974     fghCheckJoystickPolls();
975
976     /*
977      * No messages in the queue, which means we are idling...
978      */
979     if( fgState.IdleCallback != NULL )
980         fgState.IdleCallback();
981
982     /*
983      * Remember about displaying all the windows that have
984      * been marked for a redisplay (possibly in the idle call):
985      */
986     fghDisplayAll();
987   }
988
989 #elif TARGET_HOST_WIN32
990
991   MSG stMsg;
992
993   /*
994    * The windows processing is considerably smaller
995    */
996   if( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
997   {
998     /*
999      * Grab the message now, checking for WM_QUIT
1000      */
1001     if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1002       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1003
1004     /*
1005      * Translate virtual-key messages and send them to the window...
1006      */
1007     TranslateMessage( &stMsg );
1008     DispatchMessage( &stMsg );
1009   }
1010   else
1011   {
1012     /*
1013      * Have all the timers checked.
1014      */
1015     fghCheckTimers();
1016
1017     /*
1018      * Poll the joystick and notify all windows that want to be notified...
1019      */
1020     fghCheckJoystickPolls();
1021
1022     /*
1023      * No messages in the queue, which means we are idling...
1024      */
1025     if( fgState.IdleCallback != NULL )
1026       fgState.IdleCallback();
1027
1028     /*
1029      * Remember about displaying all the windows that have
1030      * been marked for a redisplay (possibly in the idle call):
1031      */
1032     fghDisplayAll();
1033   }
1034 #endif
1035 }
1036
1037 /*
1038  * Enters the FreeGLUT processing loop. Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1039  */
1040 void FGAPIENTRY glutMainLoop( void )
1041 {
1042 #if TARGET_HOST_WIN32
1043   SFG_Window *window = fgStructure.Windows.First ;
1044 #endif
1045
1046   /*
1047    * Make sure the display has been created etc.
1048    */
1049   freeglut_assert_ready;
1050
1051 #if TARGET_HOST_WIN32
1052   /*
1053    * Processing before the main loop:  If there is a window which is open and which
1054    * has a visibility callback, call it.  I know this is an ugly hack, but I'm not sure
1055    * what else to do about it.  Ideally we should leave something uninitialized in the
1056    * create window code and initialize it in the main loop, and have that initialization
1057    * create a "WM_ACTIVATE" message.  Then we would put the visibility callback code in
1058    * the "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1059    */
1060   while ( window != NULL )
1061   {
1062     if ( window->Callbacks.Visibility != NULL )
1063       window->Callbacks.Visibility ( window->State.Visible ) ;
1064
1065     window = window->Node.Next ;
1066   }
1067 #endif
1068
1069   /*
1070    * Set freeglut to be running
1071    */
1072   fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1073
1074   /*
1075    * Enter the main loop itself.  Inside the loop, process events and check for loop exit.
1076    */
1077   while ( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1078   {
1079     glutMainLoopEvent () ;
1080
1081     /*
1082      * If an event caused a window to be closed, do the actual closing here
1083      */
1084     fgCloseWindows () ;
1085
1086     /*
1087      * If there are no more windows open, stop execution
1088      */
1089     if ( fgStructure.Windows.First == NULL )
1090       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1091   }
1092
1093
1094   /*
1095    * If we got here by the user closing a window or by the application closing down, there may still be windows open.
1096    */
1097   fgCleanUpGlutsMess () ;
1098
1099   /*
1100    * Check whether we return to the calling program or simply exit
1101    */
1102   if ( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1103     exit ( 0 ) ;
1104
1105   /*
1106    * When this loop terminates, destroy the display, state and structure
1107    * of a freeglut session, so that another glutInit() call can happen
1108    */
1109   fgDeinitialize();
1110 }
1111
1112 /*
1113  * Leaves the FreeGLUT processing loop.
1114  */
1115 void FGAPIENTRY glutLeaveMainLoop( void )
1116 {
1117   fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1118 }
1119
1120 /*
1121  * The window procedure for handling Win32 events
1122  */
1123 #if TARGET_HOST_WIN32
1124 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1125 {
1126     SFG_Window* window = fgWindowByHandle( hWnd );
1127     PAINTSTRUCT ps;
1128     LONG lRet = 1;
1129
1130     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1131       return( DefWindowProc( hWnd, uMsg, wParam, lParam ) );
1132
1133 /*    printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0, uMsg, wParam, lParam ) ; */
1134     /*
1135      * Check what type of message are we receiving
1136      */
1137     switch( uMsg )
1138     {
1139     case WM_CREATE:
1140         /*
1141          * The window structure is passed as the creation structure paramter...
1142          */
1143         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1144         assert( window != NULL );
1145
1146         /*
1147          * We can safely store the window's handle now:
1148          */
1149         window->Window.Handle = hWnd;
1150
1151         /*
1152          * Get the window's device context
1153          */
1154         window->Window.Device = GetDC( hWnd );
1155
1156         /*
1157          * Setup the pixel format of our window
1158          */
1159         fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1160
1161         /*
1162          * Create the OpenGL rendering context now
1163          */
1164         window->Window.Context = wglCreateContext( window->Window.Device );
1165
1166         /*
1167          * Still, we'll be needing to explicitly resize the window
1168          */
1169         window->State.NeedToResize = TRUE;
1170
1171         /*
1172          * Finally, have the window's device context released
1173          */
1174         ReleaseDC( window->Window.Handle, window->Window.Device );
1175         break;
1176
1177     case WM_SIZE:
1178         /*
1179          * We got resized... But check if the window has been already added...
1180          */
1181         fghReshapeWindowByHandle( hWnd, LOWORD(lParam), HIWORD(lParam) );
1182         break;
1183 #if 0
1184     case WM_SETFOCUS: 
1185         printf("WM_SETFOCUS: %p\n", window );
1186         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1187         break;
1188
1189     case WM_ACTIVATE: 
1190         if (LOWORD(wParam) != WA_INACTIVE)
1191         {
1192           /* glutSetCursor( fgStructure.Window->State.Cursor ); */
1193                 printf("WM_ACTIVATE: glutSetCursor( %p, %d)\n", window, window->State.Cursor );
1194
1195           glutSetCursor( window->State.Cursor );
1196         }
1197
1198         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1199         break;
1200 #endif
1201
1202     case WM_SETCURSOR: 
1203         /*
1204          * Windows seems to need reminding to erase the cursor for NONE.
1205          */
1206 #if 0
1207         if ((LOWORD(lParam) == HTCLIENT) &&
1208             (fgStructure.Window->State.Cursor == GLUT_CURSOR_NONE))
1209           SetCursor( NULL );
1210 #else
1211         /* Set the cursor AND change it for this window class. */
1212 #       define MAP_CURSOR(a,b) case a: SetCursor( LoadCursor( NULL, b ) ); \
1213         break;
1214         /* Nuke the cursor AND change it for this window class. */
1215 #       define ZAP_CURSOR(a,b) case a: SetCursor( NULL ); \
1216         break;
1217
1218         if (LOWORD(lParam) == HTCLIENT)
1219           switch( window->State.Cursor )
1220           {
1221                 MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, IDC_ARROW     );
1222                 MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  IDC_ARROW     );
1223                 MAP_CURSOR( GLUT_CURSOR_INFO,        IDC_HELP      );
1224                 MAP_CURSOR( GLUT_CURSOR_DESTROY,     IDC_CROSS     );
1225                 MAP_CURSOR( GLUT_CURSOR_HELP,        IDC_HELP      );
1226                 MAP_CURSOR( GLUT_CURSOR_CYCLE,       IDC_SIZEALL   );
1227                 MAP_CURSOR( GLUT_CURSOR_SPRAY,       IDC_CROSS     );
1228                 MAP_CURSOR( GLUT_CURSOR_WAIT,            IDC_WAIT      );
1229                 MAP_CURSOR( GLUT_CURSOR_TEXT,        IDC_UPARROW   );
1230                 MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   IDC_CROSS     );
1231                 /* MAP_CURSOR( GLUT_CURSOR_NONE,        IDC_NO             ); */
1232                 ZAP_CURSOR( GLUT_CURSOR_NONE,        NULL          );
1233
1234                 default:
1235                 MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     IDC_ARROW     );
1236           }
1237 #endif
1238         else
1239           lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1240         break;
1241
1242     case WM_SHOWWINDOW:
1243         /*
1244          * We are now Visible!
1245          */
1246         window->State.Visible = TRUE;
1247         window->State.Redisplay = TRUE;
1248         break;
1249
1250     case WM_PAINT:
1251         /*
1252          * Start the painting job
1253          */
1254
1255         BeginPaint( hWnd, &ps );
1256
1257         /*
1258          * Call the engine's main frame drawing method
1259          */
1260         fghRedrawWindowByHandle( hWnd );
1261
1262         /*
1263          * End the painting job, release the device context
1264          */
1265         EndPaint( hWnd, &ps );
1266         break;
1267
1268     case WM_CLOSE:
1269         /*
1270          * Make sure we don't close a window with current context active
1271          */
1272         if( fgStructure.Window == window )
1273         {
1274             wglMakeCurrent( NULL, NULL );
1275             wglDeleteContext( window->Window.Context );
1276         }
1277
1278         /*
1279          * Put on a linked list of windows to be removed after all the callbacks have returned
1280          */
1281         fgAddToWindowDestroyList ( window, FALSE ) ;
1282
1283         /*
1284          * Proceed with the window destruction
1285          */
1286         DestroyWindow( hWnd );
1287         break;
1288
1289     case WM_DESTROY:
1290         /*
1291          * The window already got destroyed, so don't bother with it.
1292          */
1293         return( 0 );
1294
1295     case WM_MOUSEMOVE:
1296     {
1297         /*
1298          * The mouse cursor has moved. Remember the new mouse cursor's position
1299          */
1300         window->State.MouseX = LOWORD( lParam );
1301         window->State.MouseY = HIWORD( lParam );
1302
1303         /*
1304          * Fallback if there's an active menu hooked to this window
1305          */
1306         if( window->ActiveMenu != NULL )
1307         {
1308             /*
1309              * Let's make the window redraw as a result of the mouse motion.
1310              */
1311             window->State.Redisplay = TRUE ;
1312
1313             break;
1314         }
1315
1316         /*
1317          * Remember the current modifiers state.
1318          */
1319         window->State.Modifiers = 
1320             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1321             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1322             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1323
1324         /*
1325          * Check if any of the mouse buttons is pressed...
1326          */
1327         if( (wParam & MK_LBUTTON) || (wParam & MK_MBUTTON) || (wParam & MK_RBUTTON) )
1328         {
1329             /*
1330              * Yeah, indeed. We need to use the motion callback then:
1331              */
1332             if( window->Callbacks.Motion != NULL )
1333             {
1334                 /*
1335                  * Make sure the current window is set...
1336                  */
1337                 fgSetWindow( window );
1338
1339                 /*
1340                  * Execute the active mouse motion callback now
1341                  */
1342                 window->Callbacks.Motion( window->State.MouseX, window->State.MouseY );
1343             }
1344         }
1345         else
1346         {
1347             /*
1348              * All mouse buttons are up, execute the passive mouse motion callback
1349              */
1350             if( window->Callbacks.Passive != NULL )
1351             {
1352                 /*
1353                  * Make sure the current window is set
1354                  */
1355                 fgSetWindow( window );
1356
1357                 /*
1358                  * Execute the passive mouse motion callback
1359                  */
1360                 window->Callbacks.Passive( window->State.MouseX, window->State.MouseY );
1361             }
1362         }
1363
1364         /*
1365          * Thrash the current modifiers state now
1366          */
1367         window->State.Modifiers = 0xffffffff;
1368     }
1369     break;
1370
1371     case WM_LBUTTONDOWN:
1372     case WM_MBUTTONDOWN:
1373     case WM_RBUTTONDOWN:
1374     case WM_LBUTTONUP:
1375     case WM_MBUTTONUP:
1376     case WM_RBUTTONUP:
1377     {
1378         GLboolean pressed = TRUE;
1379         int button;
1380
1381         /*
1382          * The mouse cursor has moved. Remember the new mouse cursor's position
1383          */
1384         window->State.MouseX = LOWORD( lParam );
1385         window->State.MouseY = HIWORD( lParam );
1386
1387         /*
1388          * We're curious about the GLUT API button name...
1389          */
1390         switch( uMsg )
1391         {
1392         case WM_LBUTTONDOWN: pressed = TRUE;  button = GLUT_LEFT_BUTTON;   break;
1393         case WM_MBUTTONDOWN: pressed = TRUE;  button = GLUT_MIDDLE_BUTTON; break;
1394         case WM_RBUTTONDOWN: pressed = TRUE;  button = GLUT_RIGHT_BUTTON;  break;
1395         case WM_LBUTTONUP:   pressed = FALSE; button = GLUT_LEFT_BUTTON;   break;
1396         case WM_MBUTTONUP:   pressed = FALSE; button = GLUT_MIDDLE_BUTTON; break;
1397         case WM_RBUTTONUP:   pressed = FALSE; button = GLUT_RIGHT_BUTTON;  break;
1398         default:             pressed = FALSE; button = -1;                 break;
1399         }
1400
1401         /*
1402          * The left and right mouse buttons might have been swapped...
1403          */
1404         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1405             if( button == GLUT_LEFT_BUTTON ) button = GLUT_RIGHT_BUTTON;
1406             else if( button == GLUT_RIGHT_BUTTON ) button = GLUT_LEFT_BUTTON;
1407
1408         /*
1409          * Hey, what's up with you?
1410          */
1411         if( button == -1 )
1412             return( DefWindowProc( hWnd, uMsg, lParam, wParam ) );
1413
1414         /*
1415          * Do not execute the application's mouse callback if a menu is hooked to this button.
1416          * In that case an appropriate private call should be generated.
1417          * Near as I can tell, this is the menu behaviour:
1418          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
1419          *  - Down-click any button outside the menu, menu active:  deactivate the menu
1420          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
1421          *  - Up-click the menu button, menu not active:  nothing happens
1422          *  - Up-click the menu button outside the menu, menu active:  nothing happens
1423          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
1424          */
1425         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
1426         {
1427           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
1428           {
1429             /* Save the current window and menu and set the current window to the window whose menu this is */
1430             SFG_Window *save_window = fgStructure.Window ;
1431             SFG_Menu *save_menu = fgStructure.Menu ;
1432             fgSetWindow ( window ) ;
1433             fgStructure.Menu = window->ActiveMenu ;
1434
1435             /* Execute the menu callback */
1436             fgExecuteMenuCallback ( window->ActiveMenu ) ;
1437             fgDeactivateMenu ( window ) ;
1438
1439             /* Restore the current window and menu */
1440             fgSetWindow ( save_window ) ;
1441             fgStructure.Menu = save_menu ;
1442           }
1443           else  /* Outside the menu, deactivate the menu if it's a downclick */
1444           {
1445             if ( pressed == TRUE ) fgDeactivateMenu ( window ) ;
1446           }
1447
1448           /*
1449            * Let's make the window redraw as a result of the mouse click and menu activity.
1450            */
1451           window->State.Redisplay = TRUE ;
1452
1453           break ;
1454         }
1455
1456         /*
1457          * No active menu, let's check whether we need to activate one.
1458          */
1459         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
1460         {
1461             /*
1462              * Let's make the window redraw as a result of the mouse click.
1463              */
1464             window->State.Redisplay = TRUE ;
1465
1466             /*
1467              * Activate the appropriate menu structure...
1468              */
1469             fgActivateMenu( window, button );
1470
1471             break;
1472         }
1473
1474         /*
1475          * Check if there is a mouse callback hooked to the window
1476          */
1477         if( window->Callbacks.Mouse == NULL )
1478             break;
1479
1480         /*
1481          * Set the current window
1482          */
1483         fgSetWindow( window );
1484
1485         /*
1486          * Remember the current modifiers state.
1487          */
1488         window->State.Modifiers = 
1489             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1490             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1491             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1492
1493         /*
1494          * Finally execute the mouse callback
1495          */
1496         window->Callbacks.Mouse(
1497             button,
1498             pressed == TRUE ? GLUT_DOWN : GLUT_UP,
1499             window->State.MouseX,
1500             window->State.MouseY
1501         );
1502
1503         /*
1504          * Trash the modifiers state
1505          */
1506         window->State.Modifiers = 0xffffffff;
1507     }
1508     break;
1509
1510     case WM_SYSKEYDOWN:
1511     case WM_KEYDOWN:
1512     {
1513         int keypress = -1;
1514
1515         /*
1516          * Ignore the automatic key repetition if needed:
1517          */
1518         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1519             break;
1520
1521         /*
1522          * Set the current window
1523          */
1524         fgSetWindow( window );
1525
1526         /*
1527          * Remember the current modifiers state. This is done here in order 
1528          * to make sure the VK_DELETE keyboard callback is executed properly.
1529          */
1530         window->State.Modifiers = 
1531             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1532             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1533             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1534
1535         /*
1536          * Convert the Win32 keystroke codes to GLUTtish way
1537          */
1538 #       define KEY(a,b) case a: keypress = b; break;
1539
1540         switch( wParam )
1541         {
1542             /*
1543              * Most of the special characters can be handled automagically...
1544              */
1545             KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1546             KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1547             KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1548             KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1549             KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1550             KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1551             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1552             KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1553             KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1554             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1555             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1556
1557             /*
1558              * ...yet there is a small exception we need to have handled...
1559              */
1560             case VK_DELETE:
1561                 /*
1562                  * The delete key should be treated as an ASCII keypress:
1563                  */
1564                 if( window->Callbacks.Keyboard != NULL )
1565                     window->Callbacks.Keyboard( 127, window->State.MouseX, window->State.MouseY );
1566         }
1567
1568         /*
1569          * Execute the special callback, if present, given the conversion was a success:
1570          */
1571         if( (keypress != -1) && (window->Callbacks.Special != NULL) )
1572         {
1573             /*
1574              * Have the special callback executed:
1575              */
1576             window->Callbacks.Special( keypress, window->State.MouseX, window->State.MouseY );
1577         }
1578
1579         /*
1580          * Thrash the modifiers register now
1581          */
1582         window->State.Modifiers = 0xffffffff;
1583     }
1584     break;
1585
1586     case WM_SYSKEYUP:
1587     case WM_KEYUP:
1588     {
1589         int keypress = -1;
1590
1591         /*
1592          * Set the current window
1593          */
1594         fgSetWindow( window );
1595
1596         /*
1597          * Remember the current modifiers state. This is done here in order 
1598          * to make sure the VK_DELETE keyboard callback is executed properly.
1599          */
1600         window->State.Modifiers = 
1601             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1602             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1603             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1604
1605         /*
1606          * Convert the Win32 keystroke codes to GLUTtish way.  "KEY(a,b)" was defined under "WM_KEYDOWN"
1607          */
1608
1609         switch( wParam )
1610         {
1611           /*
1612            * Most of the special characters can be handled automagically...
1613            */
1614           KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1615           KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1616           KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1617           KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1618           KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1619           KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1620           KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1621           KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1622           KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1623           KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1624           KEY( VK_INSERT, GLUT_KEY_INSERT    );
1625
1626           /*
1627            * ...yet there is a small exception we need to have handled...
1628            */
1629           case VK_DELETE:
1630             /*
1631              * The delete key should be treated as an ASCII keypress:
1632              */
1633             if( window->Callbacks.KeyboardUp != NULL )
1634                 window->Callbacks.KeyboardUp( 127, window->State.MouseX, window->State.MouseY );
1635           default:
1636             /*
1637              * Call the KeyboardUp callback for a regular character if there is one.
1638              */
1639             if( window->Callbacks.KeyboardUp != NULL )
1640                 window->Callbacks.KeyboardUp( wParam, window->State.MouseX, window->State.MouseY );
1641         }
1642
1643         /*
1644          * Execute the special callback, if present, given the conversion was a success:
1645          */
1646         if( (keypress != -1) && (window->Callbacks.SpecialUp != NULL) )
1647         {
1648             /*
1649              * Have the special callback executed:
1650              */
1651             window->Callbacks.SpecialUp( keypress, window->State.MouseX, window->State.MouseY );
1652         }
1653
1654         /*
1655          * Thrash the modifiers register now
1656          */
1657         window->State.Modifiers = 0xffffffff;
1658     }
1659     break;
1660
1661     case WM_SYSCHAR:
1662     case WM_CHAR:
1663     {
1664         /*
1665          * Ignore the automatic key repetition if needed:
1666          */
1667         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1668             break;
1669
1670         /*
1671          * Clear to go with the keyboard callback, if registered:
1672          */
1673         if( window->Callbacks.Keyboard != NULL )
1674         {
1675             /*
1676              * Remember the current modifiers state
1677              */
1678             window->State.Modifiers = 
1679                 ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1680                 ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1681                 ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1682
1683             /*
1684              * Have the special callback executed:
1685              */
1686             window->Callbacks.Keyboard( wParam, window->State.MouseX, window->State.MouseY );
1687
1688             /*
1689              * Thrash the modifiers register now
1690              */
1691             window->State.Modifiers = 0xffffffff;
1692         }
1693     }
1694     break;
1695
1696     case WM_CAPTURECHANGED :  /* User has finished resizing the window, force a redraw */
1697       if ( window->Callbacks.Display )
1698         window->Callbacks.Display () ;
1699
1700 /*      lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ) ; */
1701       break ;
1702
1703       /*
1704        * Other messages that I have seen and which are not handled already
1705        */
1706     case WM_SETTEXT :  /* 0x000c */
1707       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to set the window text */
1708       break ;
1709
1710     case WM_GETTEXT :  /* 0x000d */
1711       /* Ideally we would copy the title of the window into "lParam" */
1712 /*      strncpy ( (char *)lParam, "Window Title", wParam ) ;
1713       lRet = ( wParam > 12 ) ? 12 : wParam ;  */ /* the number of characters copied */
1714       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1715       break ;
1716
1717     case WM_GETTEXTLENGTH :  /* 0x000e */
1718       /* Ideally we would get the length of the title of the window */
1719       lRet = 12 ;  /* the number of characters in "Window Title\0" (see above) */
1720       break ;
1721
1722     case WM_ERASEBKGND :  /* 0x0014 */
1723       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1724       break ;
1725
1726     case WM_SYNCPAINT :  /* 0x0088 */
1727       /* Another window has moved, need to update this one */
1728       window->State.Redisplay = TRUE ;
1729       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Help screen says this message must be passed to "DefWindowProc" */
1730       break ;
1731
1732     case WM_NCPAINT :  /* 0x0085 */
1733       /* Need to update the border of this window */
1734       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to repaint a standard border */
1735       break ;
1736
1737     default:
1738         /*
1739          * Handle unhandled messages
1740          */
1741         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1742         break;
1743     }
1744
1745     return( lRet );
1746 }
1747 #endif
1748
1749 /*** END OF FILE ***/