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