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