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