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