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