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