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