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