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