Added support for more arbitrary number of mouse buttons (though only the
[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          * An X button (at least in XFree86) is numbered from 1.
829          * A GLUT button is numbered from 0.
830          * Old GLUT passed through buttons other than just the first
831          * three, though it only gave symbolic names and official
832          * support to the first three.
833          *
834          */
835         button = event.xbutton.button - 1;
836
837         /*
838          * Do not execute the application's mouse callback if a menu is hooked to this button.
839          * In that case an appropriate private call should be generated.
840          * Near as I can tell, this is the menu behaviour:
841          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
842          *  - Down-click any button outside the menu, menu active:  deactivate the menu
843          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
844          *  - Up-click the menu button, menu not active:  nothing happens
845          *  - Up-click the menu button outside the menu, menu active:  nothing happens
846          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
847          */
848         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
849         {
850           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
851           {
852             /* Save the current window and menu and set the current window to the window whose menu this is */
853             SFG_Window *save_window = fgStructure.Window ;
854             SFG_Menu *save_menu = fgStructure.Menu ;
855             SFG_Window *parent_window = window->ActiveMenu->ParentWindow ;
856             fgSetWindow ( window ) ;
857             fgStructure.Menu = window->ActiveMenu ;
858
859             /* Execute the menu callback */
860             fgExecuteMenuCallback ( window->ActiveMenu ) ;
861             fgDeactivateMenu ( parent_window ) ;
862
863             /* Restore the current window and menu */
864             fgSetWindow ( save_window ) ;
865             fgStructure.Menu = save_menu ;
866           }
867           else  /* Outside the menu, deactivate the menu if it's a downclick */
868           {
869             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
870           }
871
872           /*
873            * Let's make the window redraw as a result of the mouse click and menu activity.
874            */
875           window->State.Redisplay = TRUE ;
876
877           break ;
878         }
879
880         /*
881          * No active menu, let's check whether we need to activate one.
882          */
883         if (( 0 <= button ) && ( 2 >= button ) &&
884             ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
885         {
886           /*
887            * Let's make the window redraw as a result of the mouse click.
888            */
889           window->State.Redisplay = TRUE ;
890
891           /*
892            * Set the current window
893            */
894           fgSetWindow( window );
895
896           /*
897            * Activate the appropriate menu structure...
898            */
899           fgActivateMenu( window, button );
900
901           break;
902         }
903
904         /*
905          * Check if there is a mouse callback hooked to the window
906          */
907         if( window->Callbacks.Mouse == NULL )
908           break;
909
910         /*
911          * Set the current window
912          */
913         fgSetWindow ( window );
914
915         /*
916          * Remember the current modifiers state
917          */
918         modifiers = 0;
919         if (event.xbutton.state & (ShiftMask|LockMask))
920           modifiers |= GLUT_ACTIVE_SHIFT;
921         if (event.xbutton.state & ControlMask)
922           modifiers |= GLUT_ACTIVE_CTRL;
923         if (event.xbutton.state & Mod1Mask)
924           modifiers |= GLUT_ACTIVE_ALT;
925         fgStructure.Window->State.Modifiers = modifiers;
926
927         /*
928          * Finally execute the mouse callback
929          */
930         fgStructure.Window->Callbacks.Mouse(
931             button,
932             event.type == ButtonPress ? GLUT_DOWN : GLUT_UP,
933             event.xbutton.x,
934             event.xbutton.y
935         );
936
937         /*
938          * Trash the modifiers state
939          */
940         fgStructure.Window->State.Modifiers = 0xffffffff;
941       }
942       break;
943
944     case KeyRelease:
945     case KeyPress:
946       {
947         FGCBkeyboard keyboard_cb;
948         FGCBspecial special_cb;
949
950         /*
951          * A key has been pressed, find the window that had the focus:
952          */
953         GETWINDOW( xkey ); GETMOUSE( xkey );
954
955         if( event.type == KeyPress )
956         {
957           keyboard_cb = window->Callbacks.Keyboard;
958           special_cb = window->Callbacks.Special;
959         }
960         else
961         {
962           keyboard_cb = window->Callbacks.KeyboardUp;
963           special_cb = window->Callbacks.SpecialUp;
964         }
965
966         /*
967          * Is there a keyboard/special callback hooked for this window?
968          */
969         if( (keyboard_cb != NULL) || (special_cb != NULL) )
970         {
971           XComposeStatus composeStatus;
972           char asciiCode[ 32 ];
973           KeySym keySym;
974           int len;
975
976           /*
977            * Check for the ASCII/KeySym codes associated with the event:
978            */
979           len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode), &keySym, &composeStatus );
980
981           /*
982            * GLUT API tells us to have two separate callbacks...
983            */
984           if( len > 0 )
985           {
986             /*
987              * ...one for the ASCII translateable keypresses...
988              */
989             if( keyboard_cb != NULL )
990             {
991               /*
992                * Set the current window
993                */
994               fgSetWindow( window );
995
996               /*
997                * Remember the current modifiers state
998                */
999               modifiers = 0;
1000               if (event.xkey.state & (ShiftMask|LockMask))
1001                   modifiers |= GLUT_ACTIVE_SHIFT;
1002               if (event.xkey.state & ControlMask)
1003                   modifiers |= GLUT_ACTIVE_CTRL;
1004               if (event.xkey.state & Mod1Mask)
1005                   modifiers |= GLUT_ACTIVE_ALT;
1006               window->State.Modifiers = modifiers;
1007
1008               /*
1009                * Execute the callback
1010                */
1011               keyboard_cb( asciiCode[ 0 ], event.xkey.x, event.xkey.y );
1012
1013               /*
1014                * Trash the modifiers state
1015                */
1016               window->State.Modifiers = 0xffffffff;
1017             }
1018           }
1019           else
1020           {
1021             int special = -1;
1022
1023             /*
1024              * ...and one for all the others, which need to be translated to GLUT_KEY_Xs...
1025              */
1026             switch( keySym )
1027             {
1028             /*
1029              * First the function keys come:
1030              */
1031             case XK_F1:     special = GLUT_KEY_F1;     break;
1032             case XK_F2:     special = GLUT_KEY_F2;     break;
1033             case XK_F3:     special = GLUT_KEY_F3;     break;
1034             case XK_F4:     special = GLUT_KEY_F4;     break;
1035             case XK_F5:     special = GLUT_KEY_F5;     break;
1036             case XK_F6:     special = GLUT_KEY_F6;     break;
1037             case XK_F7:     special = GLUT_KEY_F7;     break;
1038             case XK_F8:     special = GLUT_KEY_F8;     break;
1039             case XK_F9:     special = GLUT_KEY_F9;     break;
1040             case XK_F10:    special = GLUT_KEY_F10;    break;
1041             case XK_F11:    special = GLUT_KEY_F11;    break;
1042             case XK_F12:    special = GLUT_KEY_F12;    break;
1043
1044             /*
1045              * Then the arrows and stuff:
1046              */
1047             case XK_Left:   special = GLUT_KEY_LEFT;   break;
1048             case XK_Right:  special = GLUT_KEY_RIGHT;  break;
1049             case XK_Up:     special = GLUT_KEY_UP;     break;
1050             case XK_Down:   special = GLUT_KEY_DOWN;   break;
1051
1052             case XK_KP_Prior:
1053             case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
1054             case XK_KP_Next:
1055             case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
1056             case XK_KP_Home:
1057             case XK_Home:   special = GLUT_KEY_HOME;   break;
1058             case XK_KP_End:
1059             case XK_End:    special = GLUT_KEY_END;    break;
1060             case XK_KP_Insert:
1061             case XK_Insert: special = GLUT_KEY_INSERT; break;
1062             }
1063
1064             /*
1065              * Execute the callback (if one has been specified),
1066              * given that the special code seems to be valid...
1067              */
1068             if( (special_cb != NULL) && (special != -1) )
1069             {
1070               /*
1071                * Set the current window
1072                */
1073               fgSetWindow( window );
1074
1075               /*
1076                * Remember the current modifiers state
1077                */
1078               modifiers = 0;
1079               if (event.xkey.state & (ShiftMask|LockMask))
1080                 modifiers |= GLUT_ACTIVE_SHIFT;
1081               if (event.xkey.state & ControlMask)
1082                 modifiers |= GLUT_ACTIVE_CTRL;
1083               if (event.xkey.state & Mod1Mask)
1084                 modifiers |= GLUT_ACTIVE_ALT;
1085               window->State.Modifiers = modifiers;
1086
1087               special_cb( special, event.xkey.x, event.xkey.y );
1088
1089               /*
1090                * Trash the modifiers state
1091                */
1092               window->State.Modifiers = 0xffffffff;
1093             }
1094           }
1095         }
1096       }
1097       break;
1098     }
1099   }
1100
1101   {
1102     /*
1103      * Have all the timers checked.
1104      */
1105     fghCheckTimers();
1106
1107     /*
1108      * Poll the joystick and notify all windows that want to be notified...
1109      */
1110     fghCheckJoystickPolls();
1111
1112     /*
1113      * No messages in the queue, which means we are idling...
1114      */
1115     if( fgState.IdleCallback != NULL )
1116         fgState.IdleCallback();
1117
1118     /*
1119      * Remember about displaying all the windows that have
1120      * been marked for a redisplay (possibly in the idle call):
1121      */
1122     fghDisplayAll();
1123   }
1124
1125 #elif TARGET_HOST_WIN32
1126
1127   MSG stMsg;
1128
1129   /*
1130    * The windows processing is considerably smaller
1131    */
1132   while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
1133   {
1134     /*
1135      * Grab the message now, checking for WM_QUIT
1136      */
1137     if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1138       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1139
1140     /*
1141      * Translate virtual-key messages and send them to the window...
1142      */
1143     TranslateMessage( &stMsg );
1144     DispatchMessage( &stMsg );
1145   }
1146
1147   {
1148     /*
1149      * Have all the timers checked.
1150      */
1151     fghCheckTimers();
1152
1153     /*
1154      * Poll the joystick and notify all windows that want to be notified...
1155      */
1156     fghCheckJoystickPolls();
1157
1158     /*
1159      * No messages in the queue, which means we are idling...
1160      */
1161     if( fgState.IdleCallback != NULL )
1162       fgState.IdleCallback();
1163
1164     /*
1165      * Remember about displaying all the windows that have
1166      * been marked for a redisplay (possibly in the idle call):
1167      */
1168     fghDisplayAll();
1169   }
1170 #endif
1171
1172     /* 
1173      * If an event caused a window to be closed, do the actual closing here
1174      */
1175     fgCloseWindows () ;
1176 }
1177
1178 /*
1179  * Enters the freeglut processing loop. Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1180  */
1181 void FGAPIENTRY glutMainLoop( void )
1182 {
1183 #if TARGET_HOST_WIN32
1184   SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1185 #endif
1186
1187   /*
1188    * Make sure the display has been created etc.
1189    */
1190   freeglut_assert_ready;
1191
1192 #if TARGET_HOST_WIN32
1193   /*
1194    * Processing before the main loop:  If there is a window which is open and which
1195    * has a visibility callback, call it.  I know this is an ugly hack, but I'm not sure
1196    * what else to do about it.  Ideally we should leave something uninitialized in the
1197    * create window code and initialize it in the main loop, and have that initialization
1198    * create a "WM_ACTIVATE" message.  Then we would put the visibility callback code in
1199    * the "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1200    */
1201   while ( window != NULL )
1202   {
1203     if ( window->Callbacks.Visibility != NULL )
1204     {
1205       SFG_Window *current_window = fgStructure.Window ;
1206
1207       /*
1208        * Set the current window
1209        */
1210       fgSetWindow( window );
1211
1212       window->Callbacks.Visibility ( window->State.Visible ) ;
1213
1214       /*
1215        * Restore the current window
1216        */
1217       fgSetWindow( current_window );
1218     }
1219
1220     window = (SFG_Window *)window->Node.Next ;
1221   }
1222 #endif
1223
1224   /*
1225    * Set freeglut to be running
1226    */
1227   fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1228
1229   /*
1230    * Enter the main loop itself.  Inside the loop, process events and check for loop exit.
1231    */
1232   while ( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1233   {
1234     glutMainLoopEvent () ;
1235
1236     /*
1237      * If there are no more windows open, stop execution
1238      */
1239     if ( fgStructure.Windows.First == NULL )
1240       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1241     else
1242       fgSleepForEvents();
1243   }
1244
1245   {
1246     fgExecutionState execState = fgState.ActionOnWindowClose;
1247
1248     /*
1249      * When this loop terminates, destroy the display, state and structure
1250      * of a freeglut session, so that another glutInit() call can happen
1251      */
1252     fgDeinitialize();
1253
1254     /*
1255      * Check whether we return to the calling program or simply exit
1256      */
1257     if ( execState == GLUT_ACTION_EXIT )
1258       exit ( 0 ) ;
1259   }
1260 }
1261
1262 /*
1263  * Leaves the freeglut processing loop.
1264  */
1265 void FGAPIENTRY glutLeaveMainLoop( void )
1266 {
1267   fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1268 }
1269
1270 /*
1271  * The window procedure for handling Win32 events
1272  */
1273 #if TARGET_HOST_WIN32
1274 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
1275 {
1276     SFG_Window* window = fgWindowByHandle( hWnd );
1277     PAINTSTRUCT ps;
1278     LONG lRet = 1;
1279
1280     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1281       return( DefWindowProc( hWnd, uMsg, wParam, lParam ) );
1282
1283 /*    printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0, uMsg, wParam, lParam ) ; */
1284     /*
1285      * Check what type of message are we receiving
1286      */
1287     switch( uMsg )
1288     {
1289     case WM_CREATE:
1290         /*
1291          * The window structure is passed as the creation structure paramter...
1292          */
1293         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1294         assert( window != NULL );
1295
1296         /*
1297          * We can safely store the window's handle now:
1298          */
1299         window->Window.Handle = hWnd;
1300
1301         /*
1302          * Get the window's device context
1303          */
1304         window->Window.Device = GetDC( hWnd );
1305
1306         /*
1307          * Create or get the OpenGL rendering context now
1308          */
1309         if ( fgState.BuildingAMenu )
1310         {
1311           /*
1312            * Setup the pixel format of our window
1313            */
1314           unsigned int current_DisplayMode = fgState.DisplayMode ;
1315           fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ;
1316           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1317           fgState.DisplayMode = current_DisplayMode ;
1318
1319           /*
1320            * If there isn't already an OpenGL rendering context for menu windows, make one
1321            */
1322           if ( !fgStructure.MenuContext )
1323           {
1324             fgStructure.MenuContext = (SFG_MenuContext *)malloc ( sizeof(SFG_MenuContext) ) ;
1325             fgStructure.MenuContext->Context = wglCreateContext( window->Window.Device );
1326           }
1327           else
1328             wglMakeCurrent ( window->Window.Device, fgStructure.MenuContext->Context ) ;
1329
1330 /*          window->Window.Context = wglGetCurrentContext () ;   */
1331           window->Window.Context = wglCreateContext( window->Window.Device );
1332         }
1333         else
1334         {
1335           /*
1336            * Setup the pixel format of our window
1337            */
1338           fgSetupPixelFormat( window, FALSE, PFD_MAIN_PLANE );
1339
1340           if ( fgState.UseCurrentContext == TRUE )
1341           {
1342             window->Window.Context = wglGetCurrentContext();
1343             if ( ! window->Window.Context )
1344               window->Window.Context = wglCreateContext( window->Window.Device );
1345           }
1346           else
1347             window->Window.Context = wglCreateContext( window->Window.Device );
1348         }
1349
1350         /*
1351          * Still, we'll be needing to explicitly resize the window
1352          */
1353         window->State.NeedToResize = TRUE;
1354
1355         /*
1356          * Finally, have the window's device context released
1357          */
1358         ReleaseDC( window->Window.Handle, window->Window.Device );
1359         break;
1360
1361     case WM_SIZE:
1362         /*
1363          * We got resized... But check if the window has been already added...
1364          */
1365         fghReshapeWindowByHandle( hWnd, LOWORD(lParam), HIWORD(lParam) );
1366         break;
1367 #if 0
1368     case WM_SETFOCUS: 
1369         printf("WM_SETFOCUS: %p\n", window );
1370         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1371         break;
1372
1373     case WM_ACTIVATE: 
1374         if (LOWORD(wParam) != WA_INACTIVE)
1375         {
1376           /* glutSetCursor( fgStructure.Window->State.Cursor ); */
1377                 printf("WM_ACTIVATE: glutSetCursor( %p, %d)\n", window, window->State.Cursor );
1378
1379           glutSetCursor( window->State.Cursor );
1380         }
1381
1382         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1383         break;
1384 #endif
1385
1386     case WM_SETCURSOR: 
1387         /*
1388          * Windows seems to need reminding to erase the cursor for NONE.
1389          */
1390 #if 0
1391         if ((LOWORD(lParam) == HTCLIENT) &&
1392             (fgStructure.Window->State.Cursor == GLUT_CURSOR_NONE))
1393           SetCursor( NULL );
1394 #else
1395         /* Set the cursor AND change it for this window class. */
1396 #       define MAP_CURSOR(a,b) case a: SetCursor( LoadCursor( NULL, b ) ); \
1397         break;
1398         /* Nuke the cursor AND change it for this window class. */
1399 #       define ZAP_CURSOR(a,b) case a: SetCursor( NULL ); \
1400         break;
1401
1402         if (LOWORD(lParam) == HTCLIENT)
1403           switch( window->State.Cursor )
1404           {
1405                 MAP_CURSOR( GLUT_CURSOR_RIGHT_ARROW, IDC_ARROW     );
1406                 MAP_CURSOR( GLUT_CURSOR_LEFT_ARROW,  IDC_ARROW     );
1407                 MAP_CURSOR( GLUT_CURSOR_INFO,        IDC_HELP      );
1408                 MAP_CURSOR( GLUT_CURSOR_DESTROY,     IDC_CROSS     );
1409                 MAP_CURSOR( GLUT_CURSOR_HELP,        IDC_HELP      );
1410                 MAP_CURSOR( GLUT_CURSOR_CYCLE,       IDC_SIZEALL   );
1411                 MAP_CURSOR( GLUT_CURSOR_SPRAY,       IDC_CROSS     );
1412                 MAP_CURSOR( GLUT_CURSOR_WAIT,            IDC_WAIT      );
1413                 MAP_CURSOR( GLUT_CURSOR_TEXT,        IDC_UPARROW   );
1414                 MAP_CURSOR( GLUT_CURSOR_CROSSHAIR,   IDC_CROSS     );
1415                 /* MAP_CURSOR( GLUT_CURSOR_NONE,        IDC_NO             ); */
1416                 ZAP_CURSOR( GLUT_CURSOR_NONE,        NULL          );
1417
1418                 default:
1419                 MAP_CURSOR( GLUT_CURSOR_UP_DOWN,     IDC_ARROW     );
1420           }
1421 #endif
1422         else
1423           lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1424         break;
1425
1426     case WM_SHOWWINDOW:
1427         /*
1428          * We are now Visible!
1429          */
1430         window->State.Visible = TRUE;
1431         window->State.Redisplay = TRUE;
1432         break;
1433
1434     case WM_PAINT:
1435         /*
1436          * Start the painting job
1437          */
1438
1439         BeginPaint( hWnd, &ps );
1440
1441         /*
1442          * Call the engine's main frame drawing method
1443          */
1444         fghRedrawWindowByHandle( hWnd );
1445
1446         /*
1447          * End the painting job, release the device context
1448          */
1449         EndPaint( hWnd, &ps );
1450         break;
1451
1452     case WM_CLOSE:
1453         /*
1454          * Make sure we don't close a window with current context active
1455          */
1456         if( fgStructure.Window == window )
1457         {
1458           int used = FALSE ;
1459           SFG_Window *iter ;
1460
1461             wglMakeCurrent( NULL, NULL );
1462             /* Step through the list of windows.  If the rendering context is notbeing used
1463              * by another window, then we delete it.
1464              */
1465             for ( iter = (SFG_Window *)fgStructure.Windows.First; iter; iter = (SFG_Window *)iter->Node.Next )
1466             {
1467               if ( ( iter->Window.Context == window->Window.Context ) && ( iter != window ) )
1468                 used = TRUE ;
1469             }
1470
1471             if ( used == FALSE ) wglDeleteContext( window->Window.Context );
1472         }
1473
1474         /*
1475          * Put on a linked list of windows to be removed after all the callbacks have returned
1476          */
1477         fgAddToWindowDestroyList ( window, FALSE ) ;
1478
1479         /*
1480          * Proceed with the window destruction
1481          */
1482         DestroyWindow( hWnd );
1483         break;
1484
1485     case WM_DESTROY:
1486         /*
1487          * The window already got destroyed, so don't bother with it.
1488          */
1489         return( 0 );
1490
1491     case WM_MOUSEMOVE:
1492     {
1493         /*
1494          * The mouse cursor has moved. Remember the new mouse cursor's position
1495          */
1496         window->State.MouseX = LOWORD( lParam );
1497         window->State.MouseY = HIWORD( lParam );
1498
1499         /*
1500          * Fallback if there's an active menu hooked to this window
1501          */
1502         if ( window->ActiveMenu != NULL )
1503         {
1504             /*
1505              * Let's make the window redraw as a result of the mouse motion.
1506              */
1507             window->State.Redisplay = TRUE ;
1508
1509             /*
1510              * Since the window is a menu, make the parent window current
1511              */
1512             fgSetWindow ( window->ActiveMenu->ParentWindow ) ;
1513
1514             break;
1515         }
1516
1517         /*
1518          * Remember the current modifiers state.
1519          */
1520         window->State.Modifiers = 
1521             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1522             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1523             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1524
1525         /*
1526          * Check if any of the mouse buttons is pressed...
1527          */
1528         if( (wParam & MK_LBUTTON) || (wParam & MK_MBUTTON) || (wParam & MK_RBUTTON) )
1529         {
1530             /*
1531              * Yeah, indeed. We need to use the motion callback then:
1532              */
1533             if( window->Callbacks.Motion != NULL )
1534             {
1535                 /*
1536                  * Make sure the current window is set...
1537                  */
1538                 fgSetWindow( window );
1539
1540                 /*
1541                  * Execute the active mouse motion callback now
1542                  */
1543                 window->Callbacks.Motion( window->State.MouseX, window->State.MouseY );
1544             }
1545         }
1546         else
1547         {
1548             /*
1549              * All mouse buttons are up, execute the passive mouse motion callback
1550              */
1551             if( window->Callbacks.Passive != NULL )
1552             {
1553                 /*
1554                  * Make sure the current window is set
1555                  */
1556                 fgSetWindow( window );
1557
1558                 /*
1559                  * Execute the passive mouse motion callback
1560                  */
1561                 window->Callbacks.Passive( window->State.MouseX, window->State.MouseY );
1562             }
1563         }
1564
1565         /*
1566          * Thrash the current modifiers state now
1567          */
1568         window->State.Modifiers = 0xffffffff;
1569     }
1570     break;
1571
1572     case WM_LBUTTONDOWN:
1573     case WM_MBUTTONDOWN:
1574     case WM_RBUTTONDOWN:
1575     case WM_LBUTTONUP:
1576     case WM_MBUTTONUP:
1577     case WM_RBUTTONUP:
1578     {
1579         GLboolean pressed = TRUE;
1580         int button;
1581
1582         /*
1583          * The mouse cursor has moved. Remember the new mouse cursor's position
1584          */
1585         window->State.MouseX = LOWORD( lParam );
1586         window->State.MouseY = HIWORD( lParam );
1587
1588         /*
1589          * We're curious about the GLUT API button name...
1590          */
1591         switch( uMsg )
1592         {
1593         case WM_LBUTTONDOWN: pressed = TRUE;  button = GLUT_LEFT_BUTTON;   break;
1594         case WM_MBUTTONDOWN: pressed = TRUE;  button = GLUT_MIDDLE_BUTTON; break;
1595         case WM_RBUTTONDOWN: pressed = TRUE;  button = GLUT_RIGHT_BUTTON;  break;
1596         case WM_LBUTTONUP:   pressed = FALSE; button = GLUT_LEFT_BUTTON;   break;
1597         case WM_MBUTTONUP:   pressed = FALSE; button = GLUT_MIDDLE_BUTTON; break;
1598         case WM_RBUTTONUP:   pressed = FALSE; button = GLUT_RIGHT_BUTTON;  break;
1599         default:             pressed = FALSE; button = -1;                 break;
1600         }
1601
1602         /*
1603          * The left and right mouse buttons might have been swapped...
1604          */
1605         if( GetSystemMetrics( SM_SWAPBUTTON ) )
1606             if( button == GLUT_LEFT_BUTTON ) button = GLUT_RIGHT_BUTTON;
1607             else if( button == GLUT_RIGHT_BUTTON ) button = GLUT_LEFT_BUTTON;
1608
1609         /*
1610          * Hey, what's up with you?
1611          */
1612         if( button == -1 )
1613             return( DefWindowProc( hWnd, uMsg, lParam, wParam ) );
1614
1615         /*
1616          * Do not execute the application's mouse callback if a menu is hooked to this button.
1617          * In that case an appropriate private call should be generated.
1618          * Near as I can tell, this is the menu behaviour:
1619          *  - Down-click the menu button, menu not active:  activate the menu with its upper left-hand corner at the mouse location.
1620          *  - Down-click any button outside the menu, menu active:  deactivate the menu
1621          *  - Down-click any button inside the menu, menu active:  select the menu entry and deactivate the menu
1622          *  - Up-click the menu button, menu not active:  nothing happens
1623          *  - Up-click the menu button outside the menu, menu active:  nothing happens
1624          *  - Up-click the menu button inside the menu, menu active:  select the menu entry and deactivate the menu
1625          */
1626         if ( window->ActiveMenu != NULL )  /* Window has an active menu, it absorbs any mouse click */
1627         {
1628           if ( fgCheckActiveMenu ( window, window->ActiveMenu ) == TRUE )  /* Inside the menu, invoke the callback and deactivate the menu*/
1629           {
1630             /* Save the current window and menu and set the current window to the window whose menu this is */
1631             SFG_Window *save_window = fgStructure.Window ;
1632             SFG_Menu *save_menu = fgStructure.Menu ;
1633             SFG_Window *parent_window = window->ActiveMenu->ParentWindow ;
1634             fgSetWindow ( window ) ;
1635             fgStructure.Menu = window->ActiveMenu ;
1636
1637             /* Execute the menu callback */
1638             fgExecuteMenuCallback ( window->ActiveMenu ) ;
1639             fgDeactivateMenu ( parent_window ) ;
1640
1641             /* Restore the current window and menu */
1642             fgSetWindow ( save_window ) ;
1643             fgStructure.Menu = save_menu ;
1644           }
1645           else  /* Outside the menu, deactivate the menu if it's a downclick */
1646           {
1647             if ( pressed == TRUE ) fgDeactivateMenu ( window->ActiveMenu->ParentWindow ) ;
1648           }
1649
1650           /*
1651            * Let's make the window redraw as a result of the mouse click and menu activity.
1652            */
1653           if ( ! window->IsMenu ) window->State.Redisplay = TRUE ;
1654
1655           break ;
1656         }
1657
1658         /*
1659          * No active menu, let's check whether we need to activate one.
1660          */
1661         if ( ( window->Menu[ button ] != NULL ) && ( pressed == TRUE ) )
1662         {
1663             /*
1664              * Let's make the window redraw as a result of the mouse click.
1665              */
1666             window->State.Redisplay = TRUE ;
1667
1668             /*
1669              * Set the current window
1670              */
1671             fgSetWindow( window );
1672
1673             /*
1674              * Activate the appropriate menu structure...
1675              */
1676             fgActivateMenu( window, button );
1677
1678             break;
1679         }
1680
1681         /*
1682          * Check if there is a mouse callback hooked to the window
1683          */
1684         if( window->Callbacks.Mouse == NULL )
1685             break;
1686
1687         /*
1688          * Set the current window
1689          */
1690         fgSetWindow ( window );
1691
1692         /*
1693          * Remember the current modifiers state.
1694          */
1695         fgStructure.Window->State.Modifiers = 
1696             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1697             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1698             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1699
1700         /*
1701          * Finally execute the mouse callback
1702          */
1703         window->Callbacks.Mouse(
1704             button,
1705             pressed == TRUE ? GLUT_DOWN : GLUT_UP,
1706             window->State.MouseX,
1707             window->State.MouseY
1708         );
1709
1710         /*
1711          * Trash the modifiers state
1712          */
1713         fgStructure.Window->State.Modifiers = 0xffffffff;
1714     }
1715     break;
1716
1717     case WM_SYSKEYDOWN:
1718     case WM_KEYDOWN:
1719     {
1720         int keypress = -1;
1721         POINT mouse_pos ;
1722
1723         /*
1724          * Ignore the automatic key repetition if needed:
1725          */
1726         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1727             break;
1728
1729         /*
1730          * Remember the current modifiers state. This is done here in order 
1731          * to make sure the VK_DELETE keyboard callback is executed properly.
1732          */
1733         window->State.Modifiers = 
1734             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1735             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1736             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1737
1738         /*
1739          * Set the mouse position
1740          */
1741         GetCursorPos ( &mouse_pos ) ;
1742         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1743
1744         window->State.MouseX = mouse_pos.x ;
1745         window->State.MouseY = mouse_pos.y ;
1746
1747         /*
1748          * Convert the Win32 keystroke codes to GLUTtish way
1749          */
1750 #       define KEY(a,b) case a: keypress = b; break;
1751
1752         switch( wParam )
1753         {
1754             /*
1755              * Most of the special characters can be handled automagically...
1756              */
1757             KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1758             KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1759             KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1760             KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1761             KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1762             KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1763             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1764             KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1765             KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1766             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1767             KEY( VK_INSERT, GLUT_KEY_INSERT    );
1768
1769             /*
1770              * ...yet there is a small exception we need to have handled...
1771              */
1772             case VK_DELETE:
1773                 /*
1774                  * The delete key should be treated as an ASCII keypress:
1775                  */
1776                 if( window->Callbacks.Keyboard != NULL )
1777                 {
1778                     fgSetWindow( window );
1779                     window->Callbacks.Keyboard( 127, window->State.MouseX, window->State.MouseY );
1780                 }
1781         }
1782
1783         /*
1784          * Execute the special callback, if present, given the conversion was a success:
1785          */
1786         if( (keypress != -1) && (window->Callbacks.Special != NULL) )
1787         {
1788             /*
1789              * Set the current window
1790              */
1791             fgSetWindow( window );
1792
1793             /*
1794              * Have the special callback executed:
1795              */
1796             window->Callbacks.Special( keypress, window->State.MouseX, window->State.MouseY );
1797         }
1798
1799         /*
1800          * Thrash the modifiers register now
1801          */
1802         window->State.Modifiers = 0xffffffff;
1803     }
1804     break;
1805
1806     case WM_SYSKEYUP:
1807     case WM_KEYUP:
1808     {
1809         int keypress = -1;
1810         POINT mouse_pos ;
1811
1812         /*
1813          * Remember the current modifiers state. This is done here in order 
1814          * to make sure the VK_DELETE keyboard callback is executed properly.
1815          */
1816         window->State.Modifiers = 
1817             ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1818             ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1819             ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1820
1821         /*
1822          * Set the mouse position
1823          */
1824         GetCursorPos ( &mouse_pos ) ;
1825         ScreenToClient ( window->Window.Handle, &mouse_pos ) ;
1826
1827         window->State.MouseX = mouse_pos.x ;
1828         window->State.MouseY = mouse_pos.y ;
1829
1830         /*
1831          * Convert the Win32 keystroke codes to GLUTtish way.  "KEY(a,b)" was defined under "WM_KEYDOWN"
1832          */
1833
1834         switch( wParam )
1835         {
1836           /*
1837            * Most of the special characters can be handled automagically...
1838            */
1839           KEY( VK_F1,     GLUT_KEY_F1        ); KEY( VK_F2,     GLUT_KEY_F2        );
1840           KEY( VK_F3,     GLUT_KEY_F3        ); KEY( VK_F4,     GLUT_KEY_F4        );
1841           KEY( VK_F5,     GLUT_KEY_F5        ); KEY( VK_F6,     GLUT_KEY_F6        );
1842           KEY( VK_F7,     GLUT_KEY_F7        ); KEY( VK_F8,     GLUT_KEY_F8        );
1843           KEY( VK_F9,     GLUT_KEY_F9        ); KEY( VK_F10,    GLUT_KEY_F10       );
1844           KEY( VK_F11,    GLUT_KEY_F11       ); KEY( VK_F12,    GLUT_KEY_F12       );
1845           KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   ); KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
1846           KEY( VK_HOME,   GLUT_KEY_HOME      ); KEY( VK_END,    GLUT_KEY_END       );
1847           KEY( VK_LEFT,   GLUT_KEY_LEFT      ); KEY( VK_UP,     GLUT_KEY_UP        );
1848           KEY( VK_RIGHT,  GLUT_KEY_RIGHT     ); KEY( VK_DOWN,   GLUT_KEY_DOWN      );
1849           KEY( VK_INSERT, GLUT_KEY_INSERT    );
1850
1851           /*
1852            * ...yet there is a small exception we need to have handled...
1853            */
1854           case VK_DELETE:
1855             /*
1856              * The delete key should be treated as an ASCII keypress:
1857              */
1858             if( window->Callbacks.KeyboardUp != NULL )
1859             {
1860                 fgSetWindow ( window ) ;
1861                 window->Callbacks.KeyboardUp( 127, window->State.MouseX, window->State.MouseY );
1862             }
1863
1864             break ;
1865           default:
1866             {
1867               /*
1868                * Call the KeyboardUp callback for a regular character if there is one.
1869                */
1870               BYTE state[ 256 ];
1871               WORD code[ 2 ];
1872
1873               GetKeyboardState(state);
1874
1875               if ( ToAscii( wParam, 0, state, code, 0 ) == 1 )
1876                 wParam=code[ 0 ];
1877
1878               if( window->Callbacks.KeyboardUp != NULL )
1879               {
1880                 /*
1881                  * Set the current window
1882                  */
1883                 fgSetWindow( window );
1884
1885                 window->Callbacks.KeyboardUp( (char)wParam, window->State.MouseX, window->State.MouseY );
1886               }
1887             }
1888         }
1889
1890         /*
1891          * Execute the special callback, if present, given the conversion was a success:
1892          */
1893         if( (keypress != -1) && (window->Callbacks.SpecialUp != NULL) )
1894         {
1895             /*
1896              * Set the current window
1897              */
1898             fgSetWindow( window );
1899
1900             /*
1901              * Have the special callback executed:
1902              */
1903             window->Callbacks.SpecialUp( keypress, window->State.MouseX, window->State.MouseY );
1904         }
1905
1906         /*
1907          * Thrash the modifiers register now
1908          */
1909         window->State.Modifiers = 0xffffffff;
1910     }
1911     break;
1912
1913     case WM_SYSCHAR:
1914     case WM_CHAR:
1915     {
1916         /*
1917          * Ignore the automatic key repetition if needed:
1918          */
1919         if( fgState.IgnoreKeyRepeat && (lParam & KF_REPEAT) )
1920             break;
1921
1922         /*
1923          * Clear to go with the keyboard callback, if registered:
1924          */
1925         if( window->Callbacks.Keyboard != NULL )
1926         {
1927             /*
1928              * Set the current window
1929              */
1930             fgSetWindow( window );
1931
1932             /*
1933              * Remember the current modifiers state
1934              */
1935             window->State.Modifiers = 
1936                 ( ( (GetKeyState( VK_LSHIFT   ) < 0 ) || ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1937                 ( ( (GetKeyState( VK_LCONTROL ) < 0 ) || ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1938                 ( ( (GetKeyState( VK_LMENU    ) < 0 ) || ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1939
1940             /*
1941              * Have the special callback executed:
1942              */
1943             window->Callbacks.Keyboard( (char)wParam, window->State.MouseX, window->State.MouseY );
1944
1945             /*
1946              * Thrash the modifiers register now
1947              */
1948             window->State.Modifiers = 0xffffffff;
1949         }
1950     }
1951     break;
1952
1953     case WM_CAPTURECHANGED :  /* User has finished resizing the window, force a redraw */
1954       if ( window->Callbacks.Display )
1955       {
1956         /*
1957          * Set the current window
1958          */
1959         fgSetWindow( window );
1960
1961         window->Callbacks.Display () ;
1962       }
1963
1964 /*      lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ) ; */
1965       break ;
1966
1967       /*
1968        * Other messages that I have seen and which are not handled already
1969        */
1970     case WM_SETTEXT :  /* 0x000c */
1971       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to set the window text */
1972       break ;
1973
1974     case WM_GETTEXT :  /* 0x000d */
1975       /* Ideally we would copy the title of the window into "lParam" */
1976 /*      strncpy ( (char *)lParam, "Window Title", wParam ) ;
1977       lRet = ( wParam > 12 ) ? 12 : wParam ;  */ /* the number of characters copied */
1978       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1979       break ;
1980
1981     case WM_GETTEXTLENGTH :  /* 0x000e */
1982       /* Ideally we would get the length of the title of the window */
1983       lRet = 12 ;  /* the number of characters in "Window Title\0" (see above) */
1984       break ;
1985
1986     case WM_ERASEBKGND :  /* 0x0014 */
1987       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1988       break ;
1989
1990     case WM_SYNCPAINT :  /* 0x0088 */
1991       /* Another window has moved, need to update this one */
1992       window->State.Redisplay = TRUE ;
1993       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Help screen says this message must be passed to "DefWindowProc" */
1994       break ;
1995
1996     case WM_NCPAINT :  /* 0x0085 */
1997       /* Need to update the border of this window */
1998       lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );  /* Pass it on to "DefWindowProc" to repaint a standard border */
1999       break ;
2000
2001     default:
2002         /*
2003          * Handle unhandled messages
2004          */
2005         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2006         break;
2007     }
2008
2009     return( lRet );
2010 }
2011 #endif
2012
2013 /*** END OF FILE ***/