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