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