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