resetting manifest requested domain to floor
[platform/upstream/freeglut.git] / 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 #ifdef HAVE_ERRNO_H
31 #    include <errno.h>
32 #endif
33 #include <stdarg.h>
34 #ifdef  HAVE_VFPRINTF
35 #    define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
36 #elif defined(HAVE__DOPRNT)
37 #    define VFPRINTF(s,f,a) _doprnt((f),(a),(s))
38 #else
39 #    define VFPRINTF(s,f,a)
40 #endif
41
42 #ifdef _WIN32_WCE
43
44 typedef struct GXDisplayProperties GXDisplayProperties;
45 typedef struct GXKeyList GXKeyList;
46 #include <gx.h>
47
48 typedef struct GXKeyList (*GXGETDEFAULTKEYS)(int);
49 typedef int (*GXOPENINPUT)();
50
51 GXGETDEFAULTKEYS GXGetDefaultKeys_ = NULL;
52 GXOPENINPUT GXOpenInput_ = NULL;
53
54 struct GXKeyList gxKeyList;
55
56 #endif /* _WIN32_WCE */
57
58 /*
59  * Try to get the maximum value allowed for ints, falling back to the minimum
60  * guaranteed by ISO C99 if there is no suitable header.
61  */
62 #ifdef HAVE_LIMITS_H
63 #    include <limits.h>
64 #endif
65 #ifndef INT_MAX
66 #    define INT_MAX 32767
67 #endif
68
69 #ifndef MIN
70 #    define MIN(a,b) (((a)<(b)) ? (a) : (b))
71 #endif
72
73 #ifdef WM_TOUCH
74     typedef BOOL (WINAPI *pGetTouchInputInfo)(HTOUCHINPUT,UINT,PTOUCHINPUT,int);
75     typedef BOOL (WINAPI *pCloseTouchInputHandle)(HTOUCHINPUT);
76         static pGetTouchInputInfo fghGetTouchInputInfo = (pGetTouchInputInfo)0xDEADBEEF;
77         static pCloseTouchInputHandle fghCloseTouchInputHandle = (pCloseTouchInputHandle)0xDEADBEEF;
78 #endif
79
80 /*
81  * TODO BEFORE THE STABLE RELEASE:
82  *
83  * There are some issues concerning window redrawing under X11, and maybe
84  * some events are not handled. The Win32 version lacks some more features,
85  * but seems acceptable for not demanding purposes.
86  *
87  * Need to investigate why the X11 version breaks out with an error when
88  * closing a window (using the window manager, not glutDestroyWindow)...
89  */
90
91 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
92
93 /*
94  * Handle a window configuration change. When no reshape
95  * callback is hooked, the viewport size is updated to
96  * match the new window size.
97  */
98 static void fghReshapeWindow ( SFG_Window *window, int width, int height )
99 {
100     SFG_Window *current_window = fgStructure.CurrentWindow;
101
102     freeglut_return_if_fail( window != NULL );
103
104 #if TARGET_HOST_POSIX_X11
105
106     XResizeWindow( fgDisplay.Display, window->Window.Handle,
107                    width, height );
108     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
109
110 #elif TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE)
111     {
112         RECT windowRect;
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, &windowRect );
122
123         /* Create rect in FreeGLUT format, (X,Y) topleft outside window, WxH of client area */
124         windowRect.right    = windowRect.left+width;
125         windowRect.bottom   = windowRect.top+height;
126
127         if (window->Parent == NULL)
128             /* get the window rect from this to feed to SetWindowPos, correct for window decorations */
129             fghComputeWindowRectFromClientArea_QueryWindow(window,&windowRect,TRUE);
130         else
131         {
132             /* correct rect for position client area of parent window
133              * (SetWindowPos input for child windows is in coordinates
134              * relative to the parent's client area).
135              * Child windows don't have decoration, so no need to correct
136              * for them.
137              */
138             RECT parentRect;
139             parentRect = fghGetClientArea( window->Parent, FALSE );
140             windowRect.left   -= parentRect.left;
141             windowRect.right  -= parentRect.left;
142             windowRect.top    -= parentRect.top;
143             windowRect.bottom -= parentRect.top;
144         }
145         
146         /* Do the actual resizing */
147         SetWindowPos( window->Window.Handle,
148                       HWND_TOP,
149                       windowRect.left, windowRect.top,
150                       windowRect.right - windowRect.left,
151                       windowRect.bottom- windowRect.top,
152                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
153                       SWP_NOZORDER
154         );
155     }
156 #endif
157
158     if( FETCH_WCB( *window, Reshape ) )
159         INVOKE_WCB( *window, Reshape, ( width, height ) );
160     else
161     {
162         fgSetWindow( window );
163         glViewport( 0, 0, width, height );
164     }
165
166     /*
167      * Force a window redraw.  In Windows at least this is only a partial
168      * solution:  if the window is increasing in size in either dimension,
169      * the already-drawn part does not get drawn again and things look funny.
170      * But without this we get this bad behaviour whenever we resize the
171      * window.
172      */
173     window->State.Redisplay = GL_TRUE;
174
175     if( window->IsMenu )
176         fgSetWindow( current_window );
177 }
178
179 /*
180  * Calls a window's redraw method. This is used when
181  * a redraw is forced by the incoming window messages.
182  */
183 static void fghRedrawWindow ( SFG_Window *window )
184 {
185     SFG_Window *current_window = fgStructure.CurrentWindow;
186
187     freeglut_return_if_fail( window );
188     freeglut_return_if_fail( FETCH_WCB ( *window, Display ) );
189
190     window->State.Redisplay = GL_FALSE;
191
192     freeglut_return_if_fail( window->State.Visible );
193
194     fgSetWindow( window );
195
196     if( window->State.NeedToResize )
197     {
198         fghReshapeWindow(
199             window,
200             window->State.Width,
201             window->State.Height
202         );
203
204         window->State.NeedToResize = GL_FALSE;
205     }
206
207     INVOKE_WCB( *window, Display, ( ) );
208
209     fgSetWindow( current_window );
210 }
211
212 /*
213  * A static helper function to execute display callback for a window
214  */
215 static void fghcbDisplayWindow( SFG_Window *window,
216                                 SFG_Enumerator *enumerator )
217 {
218     if( window->State.Redisplay &&
219         window->State.Visible )
220     {
221         window->State.Redisplay = GL_FALSE;
222
223 #if TARGET_HOST_POSIX_X11
224         fghRedrawWindow ( window ) ;
225 #elif TARGET_HOST_MS_WINDOWS
226
227         RedrawWindow(
228             window->Window.Handle, NULL, NULL,
229             RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
230         );
231 #endif
232     }
233
234     fgEnumSubWindows( window, fghcbDisplayWindow, enumerator );
235 }
236
237 /*
238  * Make all windows perform a display call
239  */
240 static void fghDisplayAll( void )
241 {
242     SFG_Enumerator enumerator;
243
244     enumerator.found = GL_FALSE;
245     enumerator.data  =  NULL;
246
247     fgEnumWindows( fghcbDisplayWindow, &enumerator );
248 }
249
250 /*
251  * Window enumerator callback to check for the joystick polling code
252  */
253 static void fghcbCheckJoystickPolls( SFG_Window *window,
254                                      SFG_Enumerator *enumerator )
255 {
256     long int checkTime = fgElapsedTime( );
257
258     if( window->State.JoystickLastPoll + window->State.JoystickPollRate <=
259         checkTime )
260     {
261 #if !defined(_WIN32_WCE)
262         fgJoystickPollWindow( window );
263 #endif /* !defined(_WIN32_WCE) */
264         window->State.JoystickLastPoll = checkTime;
265     }
266
267     fgEnumSubWindows( window, fghcbCheckJoystickPolls, enumerator );
268 }
269
270 /*
271  * Check all windows for joystick polling
272  */
273 static void fghCheckJoystickPolls( void )
274 {
275     SFG_Enumerator enumerator;
276
277     enumerator.found = GL_FALSE;
278     enumerator.data  =  NULL;
279
280     fgEnumWindows( fghcbCheckJoystickPolls, &enumerator );
281 }
282
283 /*
284  * Check the global timers
285  */
286 static void fghCheckTimers( void )
287 {
288     long checkTime = fgElapsedTime( );
289
290     while( fgState.Timers.First )
291     {
292         SFG_Timer *timer = fgState.Timers.First;
293
294         if( timer->TriggerTime > checkTime )
295             break;
296
297         fgListRemove( &fgState.Timers, &timer->Node );
298         fgListAppend( &fgState.FreeTimers, &timer->Node );
299
300         timer->Callback( timer->ID );
301     }
302 }
303
304  
305 /* Platform-dependent time in milliseconds, as an unsigned 32-bit integer.
306  * This value wraps every 49.7 days, but integer overflows cancel
307  * when subtracting an initial start time, unless the total time exceeds
308  * 32-bit, where the GLUT API return value is also overflowed.
309  */  
310 unsigned long fgSystemTime(void) {
311 #if TARGET_HOST_SOLARIS || HAVE_GETTIMEOFDAY
312     struct timeval now;
313     gettimeofday( &now, NULL );
314     return now.tv_usec/1000 + now.tv_sec*1000;
315 #elif TARGET_HOST_MS_WINDOWS
316 #    if defined(_WIN32_WCE)
317     return GetTickCount();
318 #    else
319     return timeGetTime();
320 #    endif
321 #endif
322 }
323   
324 /*
325  * Elapsed Time
326  */
327 long fgElapsedTime( void )
328 {
329     return (long) (fgSystemTime() - fgState.Time);
330 }
331
332 /*
333  * Error Messages.
334  */
335 void fgError( const char *fmt, ... )
336 {
337     va_list ap;
338
339     if (fgState.ErrorFunc) {
340
341         va_start( ap, fmt );
342
343         /* call user set error handler here */
344         fgState.ErrorFunc(fmt, ap);
345
346         va_end( ap );
347
348     } else {
349
350         va_start( ap, fmt );
351
352         fprintf( stderr, "freeglut ");
353         if( fgState.ProgramName )
354             fprintf( stderr, "(%s): ", fgState.ProgramName );
355         VFPRINTF( stderr, fmt, ap );
356         fprintf( stderr, "\n" );
357
358         va_end( ap );
359
360         if ( fgState.Initialised )
361             fgDeinitialize ();
362
363         exit( 1 );
364     }
365 }
366
367 void fgWarning( const char *fmt, ... )
368 {
369     va_list ap;
370
371     if (fgState.WarningFunc) {
372
373         va_start( ap, fmt );
374
375         /* call user set warning handler here */
376         fgState.WarningFunc(fmt, ap);
377
378         va_end( ap );
379
380     } else {
381
382         va_start( ap, fmt );
383
384         fprintf( stderr, "freeglut ");
385         if( fgState.ProgramName )
386             fprintf( stderr, "(%s): ", fgState.ProgramName );
387         VFPRINTF( stderr, fmt, ap );
388         fprintf( stderr, "\n" );
389
390         va_end( ap );
391     }
392 }
393
394
395 /*
396  * Indicates whether Joystick events are being used by ANY window.
397  *
398  * The current mechanism is to walk all of the windows and ask if
399  * there is a joystick callback.  We have a short-circuit early
400  * return if we find any joystick handler registered.
401  *
402  * The real way to do this is to make use of the glutTimer() API
403  * to more cleanly re-implement the joystick API.  Then, this code
404  * and all other "joystick timer" code can be yanked.
405  *
406  */
407 static void fghCheckJoystickCallback( SFG_Window* w, SFG_Enumerator* e)
408 {
409     if( FETCH_WCB( *w, Joystick ) )
410     {
411         e->found = GL_TRUE;
412         e->data = w;
413     }
414     fgEnumSubWindows( w, fghCheckJoystickCallback, e );
415 }
416 static int fghHaveJoystick( void )
417 {
418     SFG_Enumerator enumerator;
419
420     enumerator.found = GL_FALSE;
421     enumerator.data = NULL;
422     fgEnumWindows( fghCheckJoystickCallback, &enumerator );
423     return !!enumerator.data;
424 }
425 static void fghHavePendingRedisplaysCallback( SFG_Window* w, SFG_Enumerator* e)
426 {
427     if( w->State.Redisplay && w->State.Visible )
428     {
429         e->found = GL_TRUE;
430         e->data = w;
431     }
432     fgEnumSubWindows( w, fghHavePendingRedisplaysCallback, e );
433 }
434 static int fghHavePendingRedisplays (void)
435 {
436     SFG_Enumerator enumerator;
437
438     enumerator.found = GL_FALSE;
439     enumerator.data = NULL;
440     fgEnumWindows( fghHavePendingRedisplaysCallback, &enumerator );
441     return !!enumerator.data;
442 }
443 /*
444  * Returns the number of GLUT ticks (milliseconds) till the next timer event.
445  */
446 static long fghNextTimer( void )
447 {
448     long ret = INT_MAX;
449     SFG_Timer *timer = fgState.Timers.First;
450
451     if( timer )
452         ret = timer->TriggerTime - fgElapsedTime();
453     if( ret < 0 )
454         ret = 0;
455
456     return ret;
457 }
458 /*
459  * Does the magic required to relinquish the CPU until something interesting
460  * happens.
461  */
462 static void fghSleepForEvents( void )
463 {
464     long msec;
465
466     if( fgState.IdleCallback || fghHavePendingRedisplays( ) )
467         return;
468
469     msec = fghNextTimer( );
470     /* XXX Use GLUT timers for joysticks... */
471     /* XXX Dumb; forces granularity to .01sec */
472     if( fghHaveJoystick( ) && ( msec > 10 ) )     
473         msec = 10;
474
475 #if TARGET_HOST_POSIX_X11
476     /*
477      * Possibly due to aggressive use of XFlush() and friends,
478      * it is possible to have our socket drained but still have
479      * unprocessed events.  (Or, this may just be normal with
480      * X, anyway?)  We do non-trivial processing of X events
481      * after the event-reading loop, in any case, so we
482      * need to allow that we may have an empty socket but non-
483      * empty event queue.
484      */
485     if( ! XPending( fgDisplay.Display ) )
486     {
487         fd_set fdset;
488         int err;
489         int socket;
490         struct timeval wait;
491
492         socket = ConnectionNumber( fgDisplay.Display );
493         FD_ZERO( &fdset );
494         FD_SET( socket, &fdset );
495         wait.tv_sec = msec / 1000;
496         wait.tv_usec = (msec % 1000) * 1000;
497         err = select( socket+1, &fdset, NULL, NULL, &wait );
498
499 #ifdef HAVE_ERRNO_H
500         if( ( -1 == err ) && ( errno != EINTR ) )
501             fgWarning ( "freeglut select() error: %d", errno );
502 #endif
503     }
504 #elif TARGET_HOST_MS_WINDOWS
505     MsgWaitForMultipleObjects( 0, NULL, FALSE, msec, QS_ALLINPUT );
506 #endif
507 }
508
509 #if TARGET_HOST_POSIX_X11
510 /*
511  * Returns GLUT modifier mask for the state field of an X11 event.
512  */
513 int fghGetXModifiers( int state )
514 {
515     int ret = 0;
516
517     if( state & ( ShiftMask | LockMask ) )
518         ret |= GLUT_ACTIVE_SHIFT;
519     if( state & ControlMask )
520         ret |= GLUT_ACTIVE_CTRL;
521     if( state & Mod1Mask )
522         ret |= GLUT_ACTIVE_ALT;
523
524     return ret;
525 }
526 #endif
527
528
529 #if TARGET_HOST_POSIX_X11 && _DEBUG
530
531 static const char* fghTypeToString( int type )
532 {
533     switch( type ) {
534     case KeyPress: return "KeyPress";
535     case KeyRelease: return "KeyRelease";
536     case ButtonPress: return "ButtonPress";
537     case ButtonRelease: return "ButtonRelease";
538     case MotionNotify: return "MotionNotify";
539     case EnterNotify: return "EnterNotify";
540     case LeaveNotify: return "LeaveNotify";
541     case FocusIn: return "FocusIn";
542     case FocusOut: return "FocusOut";
543     case KeymapNotify: return "KeymapNotify";
544     case Expose: return "Expose";
545     case GraphicsExpose: return "GraphicsExpose";
546     case NoExpose: return "NoExpose";
547     case VisibilityNotify: return "VisibilityNotify";
548     case CreateNotify: return "CreateNotify";
549     case DestroyNotify: return "DestroyNotify";
550     case UnmapNotify: return "UnmapNotify";
551     case MapNotify: return "MapNotify";
552     case MapRequest: return "MapRequest";
553     case ReparentNotify: return "ReparentNotify";
554     case ConfigureNotify: return "ConfigureNotify";
555     case ConfigureRequest: return "ConfigureRequest";
556     case GravityNotify: return "GravityNotify";
557     case ResizeRequest: return "ResizeRequest";
558     case CirculateNotify: return "CirculateNotify";
559     case CirculateRequest: return "CirculateRequest";
560     case PropertyNotify: return "PropertyNotify";
561     case SelectionClear: return "SelectionClear";
562     case SelectionRequest: return "SelectionRequest";
563     case SelectionNotify: return "SelectionNotify";
564     case ColormapNotify: return "ColormapNotify";
565     case ClientMessage: return "ClientMessage";
566     case MappingNotify: return "MappingNotify";
567     default: return "UNKNOWN";
568     }
569 }
570
571 static const char* fghBoolToString( Bool b )
572 {
573     return b == False ? "False" : "True";
574 }
575
576 static const char* fghNotifyHintToString( char is_hint )
577 {
578     switch( is_hint ) {
579     case NotifyNormal: return "NotifyNormal";
580     case NotifyHint: return "NotifyHint";
581     default: return "UNKNOWN";
582     }
583 }
584
585 static const char* fghNotifyModeToString( int mode )
586 {
587     switch( mode ) {
588     case NotifyNormal: return "NotifyNormal";
589     case NotifyGrab: return "NotifyGrab";
590     case NotifyUngrab: return "NotifyUngrab";
591     case NotifyWhileGrabbed: return "NotifyWhileGrabbed";
592     default: return "UNKNOWN";
593     }
594 }
595
596 static const char* fghNotifyDetailToString( int detail )
597 {
598     switch( detail ) {
599     case NotifyAncestor: return "NotifyAncestor";
600     case NotifyVirtual: return "NotifyVirtual";
601     case NotifyInferior: return "NotifyInferior";
602     case NotifyNonlinear: return "NotifyNonlinear";
603     case NotifyNonlinearVirtual: return "NotifyNonlinearVirtual";
604     case NotifyPointer: return "NotifyPointer";
605     case NotifyPointerRoot: return "NotifyPointerRoot";
606     case NotifyDetailNone: return "NotifyDetailNone";
607     default: return "UNKNOWN";
608     }
609 }
610
611 static const char* fghVisibilityToString( int state ) {
612     switch( state ) {
613     case VisibilityUnobscured: return "VisibilityUnobscured";
614     case VisibilityPartiallyObscured: return "VisibilityPartiallyObscured";
615     case VisibilityFullyObscured: return "VisibilityFullyObscured";
616     default: return "UNKNOWN";
617     }
618 }
619
620 static const char* fghConfigureDetailToString( int detail )
621 {
622     switch( detail ) {
623     case Above: return "Above";
624     case Below: return "Below";
625     case TopIf: return "TopIf";
626     case BottomIf: return "BottomIf";
627     case Opposite: return "Opposite";
628     default: return "UNKNOWN";
629     }
630 }
631
632 static const char* fghPlaceToString( int place )
633 {
634     switch( place ) {
635     case PlaceOnTop: return "PlaceOnTop";
636     case PlaceOnBottom: return "PlaceOnBottom";
637     default: return "UNKNOWN";
638     }
639 }
640
641 static const char* fghMappingRequestToString( int request )
642 {
643     switch( request ) {
644     case MappingModifier: return "MappingModifier";
645     case MappingKeyboard: return "MappingKeyboard";
646     case MappingPointer: return "MappingPointer";
647     default: return "UNKNOWN";
648     }
649 }
650
651 static const char* fghPropertyStateToString( int state )
652 {
653     switch( state ) {
654     case PropertyNewValue: return "PropertyNewValue";
655     case PropertyDelete: return "PropertyDelete";
656     default: return "UNKNOWN";
657     }
658 }
659
660 static const char* fghColormapStateToString( int state )
661 {
662     switch( state ) {
663     case ColormapUninstalled: return "ColormapUninstalled";
664     case ColormapInstalled: return "ColormapInstalled";
665     default: return "UNKNOWN";
666     }
667 }
668
669 static void fghPrintEvent( XEvent *event )
670 {
671     switch( event->type ) {
672
673     case KeyPress:
674     case KeyRelease: {
675         XKeyEvent *e = &event->xkey;
676         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
677                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
678                    "keycode=%u, same_screen=%s", fghTypeToString( e->type ),
679                    e->window, e->root, e->subwindow, (unsigned long)e->time,
680                    e->x, e->y, e->x_root, e->y_root, e->state, e->keycode,
681                    fghBoolToString( e->same_screen ) );
682         break;
683     }
684
685     case ButtonPress:
686     case ButtonRelease: {
687         XButtonEvent *e = &event->xbutton;
688         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
689                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
690                    "button=%u, same_screen=%d", fghTypeToString( e->type ),
691                    e->window, e->root, e->subwindow, (unsigned long)e->time,
692                    e->x, e->y, e->x_root, e->y_root, e->state, e->button,
693                    fghBoolToString( e->same_screen ) );
694         break;
695     }
696
697     case MotionNotify: {
698         XMotionEvent *e = &event->xmotion;
699         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
700                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
701                    "is_hint=%s, same_screen=%d", fghTypeToString( e->type ),
702                    e->window, e->root, e->subwindow, (unsigned long)e->time,
703                    e->x, e->y, e->x_root, e->y_root, e->state,
704                    fghNotifyHintToString( e->is_hint ),
705                    fghBoolToString( e->same_screen ) );
706         break;
707     }
708
709     case EnterNotify:
710     case LeaveNotify: {
711         XCrossingEvent *e = &event->xcrossing;
712         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
713                    "(x,y)=(%d,%d), mode=%s, detail=%s, same_screen=%d, "
714                    "focus=%d, state=0x%x", fghTypeToString( e->type ),
715                    e->window, e->root, e->subwindow, (unsigned long)e->time,
716                    e->x, e->y, fghNotifyModeToString( e->mode ),
717                    fghNotifyDetailToString( e->detail ), (int)e->same_screen,
718                    (int)e->focus, e->state );
719         break;
720     }
721
722     case FocusIn:
723     case FocusOut: {
724         XFocusChangeEvent *e = &event->xfocus;
725         fgWarning( "%s: window=0x%x, mode=%s, detail=%s",
726                    fghTypeToString( e->type ), e->window,
727                    fghNotifyModeToString( e->mode ),
728                    fghNotifyDetailToString( e->detail ) );
729         break;
730     }
731
732     case KeymapNotify: {
733         XKeymapEvent *e = &event->xkeymap;
734         char buf[32 * 2 + 1];
735         int i;
736         for ( i = 0; i < 32; i++ ) {
737             snprintf( &buf[ i * 2 ], sizeof( buf ) - i * 2,
738                       "%02x", e->key_vector[ i ] );
739         }
740         buf[ i ] = '\0';
741         fgWarning( "%s: window=0x%x, %s", fghTypeToString( e->type ), e->window,
742                    buf );
743         break;
744     }
745
746     case Expose: {
747         XExposeEvent *e = &event->xexpose;
748         fgWarning( "%s: window=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
749                    "count=%d", fghTypeToString( e->type ), e->window, e->x,
750                    e->y, e->width, e->height, e->count );
751         break;
752     }
753
754     case GraphicsExpose: {
755         XGraphicsExposeEvent *e = &event->xgraphicsexpose;
756         fgWarning( "%s: drawable=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
757                    "count=%d, (major_code,minor_code)=(%d,%d)",
758                    fghTypeToString( e->type ), e->drawable, e->x, e->y,
759                    e->width, e->height, e->count, e->major_code,
760                    e->minor_code );
761         break;
762     }
763
764     case NoExpose: {
765         XNoExposeEvent *e = &event->xnoexpose;
766         fgWarning( "%s: drawable=0x%x, (major_code,minor_code)=(%d,%d)",
767                    fghTypeToString( e->type ), e->drawable, e->major_code,
768                    e->minor_code );
769         break;
770     }
771
772     case VisibilityNotify: {
773         XVisibilityEvent *e = &event->xvisibility;
774         fgWarning( "%s: window=0x%x, state=%s", fghTypeToString( e->type ),
775                    e->window, fghVisibilityToString( e->state) );
776         break;
777     }
778
779     case CreateNotify: {
780         XCreateWindowEvent *e = &event->xcreatewindow;
781         fgWarning( "%s: (x,y)=(%d,%d), (width,height)=(%d,%d), border_width=%d, "
782                    "window=0x%x, override_redirect=%s",
783                    fghTypeToString( e->type ), e->x, e->y, e->width, e->height,
784                    e->border_width, e->window,
785                    fghBoolToString( e->override_redirect ) );
786         break;
787     }
788
789     case DestroyNotify: {
790         XDestroyWindowEvent *e = &event->xdestroywindow;
791         fgWarning( "%s: event=0x%x, window=0x%x",
792                    fghTypeToString( e->type ), e->event, e->window );
793         break;
794     }
795
796     case UnmapNotify: {
797         XUnmapEvent *e = &event->xunmap;
798         fgWarning( "%s: event=0x%x, window=0x%x, from_configure=%s",
799                    fghTypeToString( e->type ), e->event, e->window,
800                    fghBoolToString( e->from_configure ) );
801         break;
802     }
803
804     case MapNotify: {
805         XMapEvent *e = &event->xmap;
806         fgWarning( "%s: event=0x%x, window=0x%x, override_redirect=%s",
807                    fghTypeToString( e->type ), e->event, e->window,
808                    fghBoolToString( e->override_redirect ) );
809         break;
810     }
811
812     case MapRequest: {
813         XMapRequestEvent *e = &event->xmaprequest;
814         fgWarning( "%s: parent=0x%x, window=0x%x",
815                    fghTypeToString( event->type ), e->parent, e->window );
816         break;
817     }
818
819     case ReparentNotify: {
820         XReparentEvent *e = &event->xreparent;
821         fgWarning( "%s: event=0x%x, window=0x%x, parent=0x%x, (x,y)=(%d,%d), "
822                    "override_redirect=%s", fghTypeToString( e->type ),
823                    e->event, e->window, e->parent, e->x, e->y,
824                    fghBoolToString( e->override_redirect ) );
825         break;
826     }
827
828     case ConfigureNotify: {
829         XConfigureEvent *e = &event->xconfigure;
830         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d), "
831                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
832                    "override_redirect=%s", fghTypeToString( e->type ), e->event,
833                    e->window, e->x, e->y, e->width, e->height, e->border_width,
834                    e->above, fghBoolToString( e->override_redirect ) );
835         break;
836     }
837
838     case ConfigureRequest: {
839         XConfigureRequestEvent *e = &event->xconfigurerequest;
840         fgWarning( "%s: parent=0x%x, window=0x%x, (x,y)=(%d,%d), "
841                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
842                    "detail=%s, value_mask=%lx", fghTypeToString( e->type ),
843                    e->parent, e->window, e->x, e->y, e->width, e->height,
844                    e->border_width, e->above,
845                    fghConfigureDetailToString( e->detail ), e->value_mask );
846         break;
847     }
848
849     case GravityNotify: {
850         XGravityEvent *e = &event->xgravity;
851         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d)",
852                    fghTypeToString( e->type ), e->event, e->window, e->x, e->y );
853         break;
854     }
855
856     case ResizeRequest: {
857         XResizeRequestEvent *e = &event->xresizerequest;
858         fgWarning( "%s: window=0x%x, (width,height)=(%d,%d)",
859                    fghTypeToString( e->type ), e->window, e->width, e->height );
860         break;
861     }
862
863     case CirculateNotify: {
864         XCirculateEvent *e = &event->xcirculate;
865         fgWarning( "%s: event=0x%x, window=0x%x, place=%s",
866                    fghTypeToString( e->type ), e->event, e->window,
867                    fghPlaceToString( e->place ) );
868         break;
869     }
870
871     case CirculateRequest: {
872         XCirculateRequestEvent *e = &event->xcirculaterequest;
873         fgWarning( "%s: parent=0x%x, window=0x%x, place=%s",
874                    fghTypeToString( e->type ), e->parent, e->window,
875                    fghPlaceToString( e->place ) );
876         break;
877     }
878
879     case PropertyNotify: {
880         XPropertyEvent *e = &event->xproperty;
881         fgWarning( "%s: window=0x%x, atom=%lu, time=%lu, state=%s",
882                    fghTypeToString( e->type ), e->window,
883                    (unsigned long)e->atom, (unsigned long)e->time,
884                    fghPropertyStateToString( e->state ) );
885         break;
886     }
887
888     case SelectionClear: {
889         XSelectionClearEvent *e = &event->xselectionclear;
890         fgWarning( "%s: window=0x%x, selection=%lu, time=%lu",
891                    fghTypeToString( e->type ), e->window,
892                    (unsigned long)e->selection, (unsigned long)e->time );
893         break;
894     }
895
896     case SelectionRequest: {
897         XSelectionRequestEvent *e = &event->xselectionrequest;
898         fgWarning( "%s: owner=0x%x, requestor=0x%x, selection=0x%x, "
899                    "target=0x%x, property=%lu, time=%lu",
900                    fghTypeToString( e->type ), e->owner, e->requestor,
901                    (unsigned long)e->selection, (unsigned long)e->target,
902                    (unsigned long)e->property, (unsigned long)e->time );
903         break;
904     }
905
906     case SelectionNotify: {
907         XSelectionEvent *e = &event->xselection;
908         fgWarning( "%s: requestor=0x%x, selection=0x%x, target=0x%x, "
909                    "property=%lu, time=%lu", fghTypeToString( e->type ),
910                    e->requestor, (unsigned long)e->selection,
911                    (unsigned long)e->target, (unsigned long)e->property,
912                    (unsigned long)e->time );
913         break;
914     }
915
916     case ColormapNotify: {
917         XColormapEvent *e = &event->xcolormap;
918         fgWarning( "%s: window=0x%x, colormap=%lu, new=%s, state=%s",
919                    fghTypeToString( e->type ), e->window,
920                    (unsigned long)e->colormap, fghBoolToString( e->new ),
921                    fghColormapStateToString( e->state ) );
922         break;
923     }
924
925     case ClientMessage: {
926         XClientMessageEvent *e = &event->xclient;
927         char buf[ 61 ];
928         char* p = buf;
929         char* end = buf + sizeof( buf );
930         int i;
931         switch( e->format ) {
932         case 8:
933           for ( i = 0; i < 20; i++, p += 3 ) {
934                 snprintf( p, end - p, " %02x", e->data.b[ i ] );
935             }
936             break;
937         case 16:
938             for ( i = 0; i < 10; i++, p += 5 ) {
939                 snprintf( p, end - p, " %04x", e->data.s[ i ] );
940             }
941             break;
942         case 32:
943             for ( i = 0; i < 5; i++, p += 9 ) {
944                 snprintf( p, end - p, " %08lx", e->data.l[ i ] );
945             }
946             break;
947         }
948         *p = '\0';
949         fgWarning( "%s: window=0x%x, message_type=%lu, format=%d, data=(%s )",
950                    fghTypeToString( e->type ), e->window,
951                    (unsigned long)e->message_type, e->format, buf );
952         break;
953     }
954
955     case MappingNotify: {
956         XMappingEvent *e = &event->xmapping;
957         fgWarning( "%s: window=0x%x, request=%s, first_keycode=%d, count=%d",
958                    fghTypeToString( e->type ), e->window,
959                    fghMappingRequestToString( e->request ), e->first_keycode,
960                    e->count );
961         break;
962     }
963
964     default: {
965         fgWarning( "%s", fghTypeToString( event->type ) );
966         break;
967     }
968     }
969 }
970
971 #endif
972
973 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
974
975 /*
976  * Executes a single iteration in the freeglut processing loop.
977  */
978 void FGAPIENTRY glutMainLoopEvent( void )
979 {
980 #if TARGET_HOST_POSIX_X11
981     SFG_Window* window;
982     XEvent event;
983
984     /* This code was repeated constantly, so here it goes into a definition: */
985 #define GETWINDOW(a)                             \
986     window = fgWindowByHandle( event.a.window ); \
987     if( window == NULL )                         \
988         break;
989
990 #define GETMOUSE(a)                              \
991     window->State.MouseX = event.a.x;            \
992     window->State.MouseY = event.a.y;
993
994     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
995
996     while( XPending( fgDisplay.Display ) )
997     {
998         XNextEvent( fgDisplay.Display, &event );
999 #if _DEBUG
1000         fghPrintEvent( &event );
1001 #endif
1002
1003         switch( event.type )
1004         {
1005         case ClientMessage:
1006             if(fgIsSpaceballXEvent(&event)) {
1007                 fgSpaceballHandleXEvent(&event);
1008                 break;
1009             }
1010             /* Destroy the window when the WM_DELETE_WINDOW message arrives */
1011             if( (Atom) event.xclient.data.l[ 0 ] == fgDisplay.DeleteWindow )
1012             {
1013                 GETWINDOW( xclient );
1014
1015                 fgDestroyWindow ( window );
1016
1017                 if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1018                 {
1019                     fgDeinitialize( );
1020                     exit( 0 );
1021                 }
1022                 else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
1023                     fgState.ExecState = GLUT_EXEC_STATE_STOP;
1024
1025                 return;
1026             }
1027             break;
1028
1029             /*
1030              * CreateNotify causes a configure-event so that sub-windows are
1031              * handled compatibly with GLUT.  Otherwise, your sub-windows
1032              * (in freeglut only) will not get an initial reshape event,
1033              * which can break things.
1034              *
1035              * GLUT presumably does this because it generally tries to treat
1036              * sub-windows the same as windows.
1037              */
1038         case CreateNotify:
1039         case ConfigureNotify:
1040             {
1041                 int width, height;
1042                 if( event.type == CreateNotify ) {
1043                     GETWINDOW( xcreatewindow );
1044                     width = event.xcreatewindow.width;
1045                     height = event.xcreatewindow.height;
1046                 } else {
1047                     GETWINDOW( xconfigure );
1048                     width = event.xconfigure.width;
1049                     height = event.xconfigure.height;
1050                 }
1051
1052                 if( ( width != window->State.OldWidth ) ||
1053                     ( height != window->State.OldHeight ) )
1054                 {
1055                     SFG_Window *current_window = fgStructure.CurrentWindow;
1056
1057                     window->State.OldWidth = width;
1058                     window->State.OldHeight = height;
1059                     if( FETCH_WCB( *window, Reshape ) )
1060                         INVOKE_WCB( *window, Reshape, ( width, height ) );
1061                     else
1062                     {
1063                         fgSetWindow( window );
1064                         glViewport( 0, 0, width, height );
1065                     }
1066                     glutPostRedisplay( );
1067                     if( window->IsMenu )
1068                         fgSetWindow( current_window );
1069                 }
1070             }
1071             break;
1072
1073         case DestroyNotify:
1074             /*
1075              * This is sent to confirm the XDestroyWindow call.
1076              *
1077              * XXX WHY is this commented out?  Should we re-enable it?
1078              */
1079             /* fgAddToWindowDestroyList ( window ); */
1080             break;
1081
1082         case Expose:
1083             /*
1084              * We are too dumb to process partial exposes...
1085              *
1086              * XXX Well, we could do it.  However, it seems to only
1087              * XXX be potentially useful for single-buffered (since
1088              * XXX double-buffered does not respect viewport when we
1089              * XXX do a buffer-swap).
1090              *
1091              */
1092             if( event.xexpose.count == 0 )
1093             {
1094                 GETWINDOW( xexpose );
1095                 window->State.Redisplay = GL_TRUE;
1096             }
1097             break;
1098
1099         case MapNotify:
1100             break;
1101
1102         case UnmapNotify:
1103             /* We get this when iconifying a window. */ 
1104             GETWINDOW( xunmap );
1105             INVOKE_WCB( *window, WindowStatus, ( GLUT_HIDDEN ) );
1106             window->State.Visible = GL_FALSE;
1107             break;
1108
1109         case MappingNotify:
1110             /*
1111              * Have the client's keyboard knowledge updated (xlib.ps,
1112              * page 206, says that's a good thing to do)
1113              */
1114             XRefreshKeyboardMapping( (XMappingEvent *) &event );
1115             break;
1116
1117         case VisibilityNotify:
1118         {
1119             /*
1120              * Sending this event, the X server can notify us that the window
1121              * has just acquired one of the three possible visibility states:
1122              * VisibilityUnobscured, VisibilityPartiallyObscured or
1123              * VisibilityFullyObscured. Note that we DO NOT receive a
1124              * VisibilityNotify event when iconifying a window, we only get an
1125              * UnmapNotify then.
1126              */
1127             GETWINDOW( xvisibility );
1128             switch( event.xvisibility.state )
1129             {
1130             case VisibilityUnobscured:
1131                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_RETAINED ) );
1132                 window->State.Visible = GL_TRUE;
1133                 break;
1134
1135             case VisibilityPartiallyObscured:
1136                 INVOKE_WCB( *window, WindowStatus,
1137                             ( GLUT_PARTIALLY_RETAINED ) );
1138                 window->State.Visible = GL_TRUE;
1139                 break;
1140
1141             case VisibilityFullyObscured:
1142                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_COVERED ) );
1143                 window->State.Visible = GL_FALSE;
1144                 break;
1145
1146             default:
1147                 fgWarning( "Unknown X visibility state: %d",
1148                            event.xvisibility.state );
1149                 break;
1150             }
1151         }
1152         break;
1153
1154         case EnterNotify:
1155         case LeaveNotify:
1156             GETWINDOW( xcrossing );
1157             GETMOUSE( xcrossing );
1158             if( ( event.type == LeaveNotify ) && window->IsMenu &&
1159                 window->ActiveMenu && window->ActiveMenu->IsActive )
1160                 fgUpdateMenuHighlight( window->ActiveMenu );
1161
1162             INVOKE_WCB( *window, Entry, ( ( EnterNotify == event.type ) ?
1163                                           GLUT_ENTERED :
1164                                           GLUT_LEFT ) );
1165             break;
1166
1167         case MotionNotify:
1168         {
1169             GETWINDOW( xmotion );
1170             GETMOUSE( xmotion );
1171
1172             if( window->ActiveMenu )
1173             {
1174                 if( window == window->ActiveMenu->ParentWindow )
1175                 {
1176                     window->ActiveMenu->Window->State.MouseX =
1177                         event.xmotion.x_root - window->ActiveMenu->X;
1178                     window->ActiveMenu->Window->State.MouseY =
1179                         event.xmotion.y_root - window->ActiveMenu->Y;
1180                 }
1181
1182                 fgUpdateMenuHighlight( window->ActiveMenu );
1183
1184                 break;
1185             }
1186
1187             /*
1188              * XXX For more than 5 buttons, just check {event.xmotion.state},
1189              * XXX rather than a host of bit-masks?  Or maybe we need to
1190              * XXX track ButtonPress/ButtonRelease events in our own
1191              * XXX bit-mask?
1192              */
1193             fgState.Modifiers = fghGetXModifiers( event.xmotion.state );
1194             if ( event.xmotion.state & ( Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask ) ) {
1195                 INVOKE_WCB( *window, Motion, ( event.xmotion.x,
1196                                                event.xmotion.y ) );
1197             } else {
1198                 INVOKE_WCB( *window, Passive, ( event.xmotion.x,
1199                                                 event.xmotion.y ) );
1200             }
1201             fgState.Modifiers = INVALID_MODIFIERS;
1202         }
1203         break;
1204
1205         case ButtonRelease:
1206         case ButtonPress:
1207         {
1208             GLboolean pressed = GL_TRUE;
1209             int button;
1210
1211             if( event.type == ButtonRelease )
1212                 pressed = GL_FALSE ;
1213
1214             /*
1215              * A mouse button has been pressed or released. Traditionally,
1216              * break if the window was found within the freeglut structures.
1217              */
1218             GETWINDOW( xbutton );
1219             GETMOUSE( xbutton );
1220
1221             /*
1222              * An X button (at least in XFree86) is numbered from 1.
1223              * A GLUT button is numbered from 0.
1224              * Old GLUT passed through buttons other than just the first
1225              * three, though it only gave symbolic names and official
1226              * support to the first three.
1227              */
1228             button = event.xbutton.button - 1;
1229
1230             /*
1231              * Do not execute the application's mouse callback if a menu
1232              * is hooked to this button.  In that case an appropriate
1233              * private call should be generated.
1234              */
1235             if( fgCheckActiveMenu( window, button, pressed,
1236                                    event.xbutton.x_root, event.xbutton.y_root ) )
1237                 break;
1238
1239             /*
1240              * Check if there is a mouse or mouse wheel callback hooked to the
1241              * window
1242              */
1243             if( ! FETCH_WCB( *window, Mouse ) &&
1244                 ! FETCH_WCB( *window, MouseWheel ) )
1245                 break;
1246
1247             fgState.Modifiers = fghGetXModifiers( event.xbutton.state );
1248
1249             /* Finally execute the mouse or mouse wheel callback */
1250             if( ( button < glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS ) ) || ( ! FETCH_WCB( *window, MouseWheel ) ) )
1251                 INVOKE_WCB( *window, Mouse, ( button,
1252                                               pressed ? GLUT_DOWN : GLUT_UP,
1253                                               event.xbutton.x,
1254                                               event.xbutton.y )
1255                 );
1256             else
1257             {
1258                 /*
1259                  * Map 4 and 5 to wheel zero; EVEN to +1, ODD to -1
1260                  *  "  6 and 7 "    "   one; ...
1261                  *
1262                  * XXX This *should* be behind some variables/macros,
1263                  * XXX since the order and numbering isn't certain
1264                  * XXX See XFree86 configuration docs (even back in the
1265                  * XXX 3.x days, and especially with 4.x).
1266                  *
1267                  * XXX Note that {button} has already been decremented
1268                  * XXX in mapping from X button numbering to GLUT.
1269                                  *
1270                                  * XXX Should add support for partial wheel turns as Windows does -- 5/27/11
1271                  */
1272                 int wheel_number = (button - glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS )) / 2;
1273                 int direction = -1;
1274                 if( button % 2 )
1275                     direction = 1;
1276
1277                 if( pressed )
1278                     INVOKE_WCB( *window, MouseWheel, ( wheel_number,
1279                                                        direction,
1280                                                        event.xbutton.x,
1281                                                        event.xbutton.y )
1282                     );
1283             }
1284             fgState.Modifiers = INVALID_MODIFIERS;
1285         }
1286         break;
1287
1288         case KeyRelease:
1289         case KeyPress:
1290         {
1291             FGCBKeyboard keyboard_cb;
1292             FGCBSpecial special_cb;
1293
1294             GETWINDOW( xkey );
1295             GETMOUSE( xkey );
1296
1297             /* Detect auto repeated keys, if configured globally or per-window */
1298
1299             if ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE )
1300             {
1301                 if (event.type==KeyRelease)
1302                 {
1303                     /*
1304                      * Look at X11 keystate to detect repeat mode.
1305                      * While X11 says the key is actually held down, we'll ignore KeyRelease/KeyPress pairs.
1306                      */
1307
1308                     char keys[32];
1309                     XQueryKeymap( fgDisplay.Display, keys ); /* Look at X11 keystate to detect repeat mode */
1310
1311                     if ( event.xkey.keycode<256 )            /* XQueryKeymap is limited to 256 keycodes    */
1312                     {
1313                         if ( keys[event.xkey.keycode>>3] & (1<<(event.xkey.keycode%8)) )
1314                             window->State.KeyRepeating = GL_TRUE;
1315                         else
1316                             window->State.KeyRepeating = GL_FALSE;
1317                     }
1318                 }
1319             }
1320             else
1321                 window->State.KeyRepeating = GL_FALSE;
1322
1323             /* Cease processing this event if it is auto repeated */
1324
1325             if (window->State.KeyRepeating)
1326             {
1327                 if (event.type == KeyPress) window->State.KeyRepeating = GL_FALSE;
1328                 break;
1329             }
1330
1331             if( event.type == KeyPress )
1332             {
1333                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, Keyboard ));
1334                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, Special  ));
1335             }
1336             else
1337             {
1338                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, KeyboardUp ));
1339                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, SpecialUp  ));
1340             }
1341
1342             /* Is there a keyboard/special callback hooked for this window? */
1343             if( keyboard_cb || special_cb )
1344             {
1345                 XComposeStatus composeStatus;
1346                 char asciiCode[ 32 ];
1347                 KeySym keySym;
1348                 int len;
1349
1350                 /* Check for the ASCII/KeySym codes associated with the event: */
1351                 len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode),
1352                                      &keySym, &composeStatus
1353                 );
1354
1355                 /* GLUT API tells us to have two separate callbacks... */
1356                 if( len > 0 )
1357                 {
1358                     /* ...one for the ASCII translateable keypresses... */
1359                     if( keyboard_cb )
1360                     {
1361                         fgSetWindow( window );
1362                         fgState.Modifiers = fghGetXModifiers( event.xkey.state );
1363                         keyboard_cb( asciiCode[ 0 ],
1364                                      event.xkey.x, event.xkey.y
1365                         );
1366                         fgState.Modifiers = INVALID_MODIFIERS;
1367                     }
1368                 }
1369                 else
1370                 {
1371                     int special = -1;
1372
1373                     /*
1374                      * ...and one for all the others, which need to be
1375                      * translated to GLUT_KEY_Xs...
1376                      */
1377                     switch( keySym )
1378                     {
1379                     case XK_F1:     special = GLUT_KEY_F1;     break;
1380                     case XK_F2:     special = GLUT_KEY_F2;     break;
1381                     case XK_F3:     special = GLUT_KEY_F3;     break;
1382                     case XK_F4:     special = GLUT_KEY_F4;     break;
1383                     case XK_F5:     special = GLUT_KEY_F5;     break;
1384                     case XK_F6:     special = GLUT_KEY_F6;     break;
1385                     case XK_F7:     special = GLUT_KEY_F7;     break;
1386                     case XK_F8:     special = GLUT_KEY_F8;     break;
1387                     case XK_F9:     special = GLUT_KEY_F9;     break;
1388                     case XK_F10:    special = GLUT_KEY_F10;    break;
1389                     case XK_F11:    special = GLUT_KEY_F11;    break;
1390                     case XK_F12:    special = GLUT_KEY_F12;    break;
1391
1392                     case XK_KP_Left:
1393                     case XK_Left:   special = GLUT_KEY_LEFT;   break;
1394                     case XK_KP_Right:
1395                     case XK_Right:  special = GLUT_KEY_RIGHT;  break;
1396                     case XK_KP_Up:
1397                     case XK_Up:     special = GLUT_KEY_UP;     break;
1398                     case XK_KP_Down:
1399                     case XK_Down:   special = GLUT_KEY_DOWN;   break;
1400
1401                     case XK_KP_Prior:
1402                     case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
1403                     case XK_KP_Next:
1404                     case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
1405                     case XK_KP_Home:
1406                     case XK_Home:   special = GLUT_KEY_HOME;   break;
1407                     case XK_KP_End:
1408                     case XK_End:    special = GLUT_KEY_END;    break;
1409                     case XK_KP_Insert:
1410                     case XK_Insert: special = GLUT_KEY_INSERT; break;
1411
1412                     case XK_Num_Lock :  special = GLUT_KEY_NUM_LOCK;  break;
1413                     case XK_KP_Begin :  special = GLUT_KEY_BEGIN;     break;
1414                     case XK_KP_Delete:  special = GLUT_KEY_DELETE;    break;
1415
1416                     case XK_Shift_L:   special = GLUT_KEY_SHIFT_L;    break;
1417                     case XK_Shift_R:   special = GLUT_KEY_SHIFT_R;    break;
1418                     case XK_Control_L: special = GLUT_KEY_CTRL_L;     break;
1419                     case XK_Control_R: special = GLUT_KEY_CTRL_R;     break;
1420                     case XK_Alt_L:     special = GLUT_KEY_ALT_L;      break;
1421                     case XK_Alt_R:     special = GLUT_KEY_ALT_R;      break;
1422                     }
1423
1424                     /*
1425                      * Execute the callback (if one has been specified),
1426                      * given that the special code seems to be valid...
1427                      */
1428                     if( special_cb && (special != -1) )
1429                     {
1430                         fgSetWindow( window );
1431                         fgState.Modifiers = fghGetXModifiers( event.xkey.state );
1432                         special_cb( special, event.xkey.x, event.xkey.y );
1433                         fgState.Modifiers = INVALID_MODIFIERS;
1434                     }
1435                 }
1436             }
1437         }
1438         break;
1439
1440         case ReparentNotify:
1441             break; /* XXX Should disable this event */
1442
1443         /* Not handled */
1444         case GravityNotify:
1445             break;
1446
1447         default:
1448             /* enter handling of Extension Events here */
1449             #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1450                 fgHandleExtensionEvents( &event );
1451             #endif
1452             break;
1453         }
1454     }
1455
1456 #elif TARGET_HOST_MS_WINDOWS
1457
1458     MSG stMsg;
1459
1460     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
1461
1462     while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
1463     {
1464         if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
1465         {
1466             if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
1467             {
1468                 fgDeinitialize( );
1469                 exit( 0 );
1470             }
1471             else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
1472                 fgState.ExecState = GLUT_EXEC_STATE_STOP;
1473
1474             return;
1475         }
1476
1477         TranslateMessage( &stMsg );
1478         DispatchMessage( &stMsg );
1479     }
1480 #endif
1481
1482     if( fgState.Timers.First )
1483         fghCheckTimers( );
1484     fghCheckJoystickPolls( );
1485     fghDisplayAll( );
1486
1487     fgCloseWindows( );
1488 }
1489
1490 /*
1491  * Enters the freeglut processing loop.
1492  * Stays until the "ExecState" changes to "GLUT_EXEC_STATE_STOP".
1493  */
1494 void FGAPIENTRY glutMainLoop( void )
1495 {
1496     int action;
1497
1498 #if TARGET_HOST_MS_WINDOWS
1499     SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
1500 #endif
1501
1502     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoop" );
1503
1504 #if TARGET_HOST_MS_WINDOWS
1505     /*
1506      * Processing before the main loop:  If there is a window which is open and
1507      * which has a visibility callback, call it.  I know this is an ugly hack,
1508      * but I'm not sure what else to do about it.  Ideally we should leave
1509      * something uninitialized in the create window code and initialize it in
1510      * the main loop, and have that initialization create a "WM_ACTIVATE"
1511      * message.  Then we would put the visibility callback code in the
1512      * "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
1513      */
1514     while( window )
1515     {
1516         if ( FETCH_WCB( *window, Visibility ) )
1517         {
1518             SFG_Window *current_window = fgStructure.CurrentWindow ;
1519
1520             INVOKE_WCB( *window, Visibility, ( window->State.Visible ) );
1521             fgSetWindow( current_window );
1522         }
1523
1524         window = (SFG_Window *)window->Node.Next ;
1525     }
1526 #endif
1527
1528     fgState.ExecState = GLUT_EXEC_STATE_RUNNING ;
1529     while( fgState.ExecState == GLUT_EXEC_STATE_RUNNING )
1530     {
1531         SFG_Window *window;
1532
1533         glutMainLoopEvent( );
1534         /*
1535          * Step through the list of windows, seeing if there are any
1536          * that are not menus
1537          */
1538         for( window = ( SFG_Window * )fgStructure.Windows.First;
1539              window;
1540              window = ( SFG_Window * )window->Node.Next )
1541             if ( ! ( window->IsMenu ) )
1542                 break;
1543
1544         if( ! window )
1545             fgState.ExecState = GLUT_EXEC_STATE_STOP;
1546         else
1547         {
1548             if( fgState.IdleCallback )
1549             {
1550                 if( fgStructure.CurrentWindow &&
1551                     fgStructure.CurrentWindow->IsMenu )
1552                     /* fail safe */
1553                     fgSetWindow( window );
1554                 fgState.IdleCallback( );
1555             }
1556
1557             fghSleepForEvents( );
1558         }
1559     }
1560
1561     /*
1562      * When this loop terminates, destroy the display, state and structure
1563      * of a freeglut session, so that another glutInit() call can happen
1564      *
1565      * Save the "ActionOnWindowClose" because "fgDeinitialize" resets it.
1566      */
1567     action = fgState.ActionOnWindowClose;
1568     fgDeinitialize( );
1569     if( action == GLUT_ACTION_EXIT )
1570         exit( 0 );
1571 }
1572
1573 /*
1574  * Leaves the freeglut processing loop.
1575  */
1576 void FGAPIENTRY glutLeaveMainLoop( void )
1577 {
1578     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutLeaveMainLoop" );
1579     fgState.ExecState = GLUT_EXEC_STATE_STOP ;
1580 }
1581
1582
1583 #if TARGET_HOST_MS_WINDOWS
1584 /*
1585  * Determine a GLUT modifer mask based on MS-WINDOWS system info.
1586  */
1587 static int fghGetWin32Modifiers (void)
1588 {
1589     return
1590         ( ( ( GetKeyState( VK_LSHIFT   ) < 0 ) ||
1591             ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
1592         ( ( ( GetKeyState( VK_LCONTROL ) < 0 ) ||
1593             ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
1594         ( ( ( GetKeyState( VK_LMENU    ) < 0 ) ||
1595             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
1596 }
1597
1598 /*
1599  * The window procedure for handling Win32 events
1600  */
1601 LRESULT CALLBACK fgWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam,
1602                                LPARAM lParam )
1603 {
1604     static unsigned char lControl = 0, rControl = 0, lShift = 0,
1605                          rShift = 0, lAlt = 0, rAlt = 0;
1606
1607     SFG_Window* window;
1608     PAINTSTRUCT ps;
1609     LRESULT lRet = 1;
1610
1611     FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED ( "Event Handler" ) ;
1612
1613     window = fgWindowByHandle( hWnd );
1614
1615     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
1616       return DefWindowProc( hWnd, uMsg, wParam, lParam );
1617
1618     /* printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0,
1619              uMsg, wParam, lParam ); */
1620
1621     if ( window )
1622     {
1623       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Down! */
1624       if ( !lControl && GetAsyncKeyState ( VK_LCONTROL ) )
1625       {
1626           INVOKE_WCB    ( *window, Special,
1627                         ( GLUT_KEY_CTRL_L, window->State.MouseX, window->State.MouseY )
1628                       );
1629
1630           lControl = 1;
1631       }
1632
1633       if ( !rControl && GetAsyncKeyState ( VK_RCONTROL ) )
1634       {
1635           INVOKE_WCB ( *window, Special,
1636                        ( GLUT_KEY_CTRL_R, window->State.MouseX, window->State.MouseY )
1637                      );
1638
1639           rControl = 1;
1640       }
1641
1642       if ( !lShift && GetAsyncKeyState ( VK_LSHIFT ) )
1643       {
1644           INVOKE_WCB ( *window, Special,
1645                        ( GLUT_KEY_SHIFT_L, window->State.MouseX, window->State.MouseY )
1646                      );
1647
1648           lShift = 1;
1649       }
1650
1651       if ( !rShift && GetAsyncKeyState ( VK_RSHIFT ) )
1652       {
1653           INVOKE_WCB ( *window, Special,
1654                        ( GLUT_KEY_SHIFT_R, window->State.MouseX, window->State.MouseY )
1655                      );
1656
1657           rShift = 1;
1658       }
1659
1660       if ( !lAlt && GetAsyncKeyState ( VK_LMENU ) )
1661       {
1662           INVOKE_WCB ( *window, Special,
1663                        ( GLUT_KEY_ALT_L, window->State.MouseX, window->State.MouseY )
1664                      );
1665
1666           lAlt = 1;
1667       }
1668
1669       if ( !rAlt && GetAsyncKeyState ( VK_RMENU ) )
1670       {
1671           INVOKE_WCB ( *window, Special,
1672                        ( GLUT_KEY_ALT_R, window->State.MouseX, window->State.MouseY )
1673                      );
1674
1675           rAlt = 1;
1676       }
1677
1678       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Up! */
1679       if ( lControl && !GetAsyncKeyState ( VK_LCONTROL ) )
1680       {
1681           INVOKE_WCB ( *window, SpecialUp,
1682                        ( GLUT_KEY_CTRL_L, window->State.MouseX, window->State.MouseY )
1683                      );
1684
1685           lControl = 0;
1686       }
1687
1688       if ( rControl && !GetAsyncKeyState ( VK_RCONTROL ) )
1689       {
1690           INVOKE_WCB ( *window, SpecialUp,
1691                        ( GLUT_KEY_CTRL_R, window->State.MouseX, window->State.MouseY )
1692                      );
1693
1694           rControl = 0;
1695       }
1696
1697       if ( lShift && !GetAsyncKeyState ( VK_LSHIFT ) )
1698       {
1699           INVOKE_WCB ( *window, SpecialUp,
1700                        ( GLUT_KEY_SHIFT_L, window->State.MouseX, window->State.MouseY )
1701                      );
1702
1703           lShift = 0;
1704       }
1705
1706       if ( rShift && !GetAsyncKeyState ( VK_RSHIFT ) )
1707       {
1708           INVOKE_WCB ( *window, SpecialUp,
1709                        ( GLUT_KEY_SHIFT_R, window->State.MouseX, window->State.MouseY )
1710                      );
1711
1712           rShift = 0;
1713       }
1714
1715       if ( lAlt && !GetAsyncKeyState ( VK_LMENU ) )
1716       {
1717           INVOKE_WCB ( *window, SpecialUp,
1718                        ( GLUT_KEY_ALT_L, window->State.MouseX, window->State.MouseY )
1719                      );
1720
1721           lAlt = 0;
1722       }
1723
1724       if ( rAlt && !GetAsyncKeyState ( VK_RMENU ) )
1725       {
1726           INVOKE_WCB ( *window, SpecialUp,
1727                        ( GLUT_KEY_ALT_R, window->State.MouseX, window->State.MouseY )
1728                      );
1729
1730           rAlt = 0;
1731       }
1732     }
1733
1734     switch( uMsg )
1735     {
1736     case WM_CREATE:
1737         /* The window structure is passed as the creation structure parameter... */
1738         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
1739         FREEGLUT_INTERNAL_ERROR_EXIT ( ( window != NULL ), "Cannot create window",
1740                                        "fgWindowProc" );
1741
1742         window->Window.Handle = hWnd;
1743         window->Window.Device = GetDC( hWnd );
1744         if( window->IsMenu )
1745         {
1746             unsigned int current_DisplayMode = fgState.DisplayMode;
1747             fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH;
1748 #if !defined(_WIN32_WCE)
1749             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1750 #endif
1751             fgState.DisplayMode = current_DisplayMode;
1752
1753             if( fgStructure.MenuContext )
1754                 wglMakeCurrent( window->Window.Device,
1755                                 fgStructure.MenuContext->MContext
1756                 );
1757             else
1758             {
1759                 fgStructure.MenuContext =
1760                     (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
1761                 fgStructure.MenuContext->MContext =
1762                     wglCreateContext( window->Window.Device );
1763             }
1764
1765             /* window->Window.Context = wglGetCurrentContext ();   */
1766             window->Window.Context = wglCreateContext( window->Window.Device );
1767         }
1768         else
1769         {
1770 #if !defined(_WIN32_WCE)
1771             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
1772 #endif
1773
1774             if( ! fgState.UseCurrentContext )
1775                 window->Window.Context =
1776                     wglCreateContext( window->Window.Device );
1777             else
1778             {
1779                 window->Window.Context = wglGetCurrentContext( );
1780                 if( ! window->Window.Context )
1781                     window->Window.Context =
1782                         wglCreateContext( window->Window.Device );
1783             }
1784
1785 #if !defined(_WIN32_WCE)
1786             fgNewWGLCreateContext( window );
1787 #endif
1788         }
1789
1790         window->State.NeedToResize = GL_TRUE;
1791         /* if we used CW_USEDEFAULT (thats a negative value) for the size
1792          * of the window, query the window now for the size at which it
1793          * was created.
1794          */
1795         if( ( window->State.Width < 0 ) || ( window->State.Height < 0 ) )
1796         {
1797             SFG_Window *current_window = fgStructure.CurrentWindow;
1798
1799             fgSetWindow( window );
1800             window->State.Width = glutGet( GLUT_WINDOW_WIDTH );
1801             window->State.Height = glutGet( GLUT_WINDOW_HEIGHT );
1802             fgSetWindow( current_window );
1803         }
1804
1805         ReleaseDC( window->Window.Handle, window->Window.Device );
1806
1807 #if defined(_WIN32_WCE)
1808         /* Take over button handling */
1809         {
1810             HINSTANCE dxDllLib=LoadLibrary(_T("gx.dll"));
1811             if (dxDllLib)
1812             {
1813                 GXGetDefaultKeys_=(GXGETDEFAULTKEYS)GetProcAddress(dxDllLib, _T("?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z"));
1814                 GXOpenInput_=(GXOPENINPUT)GetProcAddress(dxDllLib, _T("?GXOpenInput@@YAHXZ"));
1815             }
1816
1817             if(GXOpenInput_)
1818                 (*GXOpenInput_)();
1819             if(GXGetDefaultKeys_)
1820                 gxKeyList = (*GXGetDefaultKeys_)(GX_LANDSCAPEKEYS);
1821         }
1822
1823 #endif /* defined(_WIN32_WCE) */
1824         break;
1825
1826     case WM_SIZE:
1827         /*
1828          * If the window is visible, then it is the user manually resizing it.
1829          * If it is not, then it is the system sending us a dummy resize with
1830          * zero dimensions on a "glutIconifyWindow" call.
1831          */
1832         if( window->State.Visible )
1833         {
1834             window->State.NeedToResize = GL_TRUE;
1835 #if defined(_WIN32_WCE)
1836             window->State.Width  = HIWORD(lParam);
1837             window->State.Height = LOWORD(lParam);
1838 #else
1839             window->State.Width  = LOWORD(lParam);
1840             window->State.Height = HIWORD(lParam);
1841 #endif /* defined(_WIN32_WCE) */
1842         }
1843
1844         break;
1845
1846     case WM_SETFOCUS:
1847 /*        printf("WM_SETFOCUS: %p\n", window ); */
1848         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1849         INVOKE_WCB( *window, Entry, ( GLUT_ENTERED ) );
1850         break;
1851
1852     case WM_KILLFOCUS:
1853 /*        printf("WM_KILLFOCUS: %p\n", window ); */
1854         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1855         INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
1856
1857         if( window->IsMenu &&
1858             window->ActiveMenu && window->ActiveMenu->IsActive )
1859             fgUpdateMenuHighlight( window->ActiveMenu );
1860
1861         break;
1862
1863 #if 0
1864     case WM_ACTIVATE:
1865         if (LOWORD(wParam) != WA_INACTIVE)
1866         {
1867 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
1868                    window->State.Cursor ); */
1869             fgSetCursor( window, window->State.Cursor );
1870         }
1871
1872         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1873         break;
1874 #endif
1875
1876     case WM_SETCURSOR:
1877 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
1878         if( LOWORD( lParam ) == HTCLIENT )
1879             fgSetCursor ( window, window->State.Cursor ) ;
1880         else
1881             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1882         break;
1883
1884     case WM_SHOWWINDOW:
1885         window->State.Visible = GL_TRUE;
1886         window->State.Redisplay = GL_TRUE;
1887         break;
1888
1889     case WM_PAINT:
1890         /* Turn on the visibility in case it was turned off somehow */
1891         window->State.Visible = GL_TRUE;
1892         BeginPaint( hWnd, &ps );
1893         fghRedrawWindow( window );
1894         EndPaint( hWnd, &ps );
1895         break;
1896
1897     case WM_CLOSE:
1898         fgDestroyWindow ( window );
1899         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
1900             PostQuitMessage(0);
1901         break;
1902
1903     case WM_DESTROY:
1904         /*
1905          * The window already got destroyed, so don't bother with it.
1906          */
1907         return 0;
1908
1909     case WM_MOUSEMOVE:
1910     {
1911 #if defined(_WIN32_WCE)
1912         window->State.MouseX = 320-HIWORD( lParam );
1913         window->State.MouseY = LOWORD( lParam );
1914 #else
1915         window->State.MouseX = LOWORD( lParam );
1916         window->State.MouseY = HIWORD( lParam );
1917 #endif /* defined(_WIN32_WCE) */
1918         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1919         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1920         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1921         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1922
1923         if ( window->ActiveMenu )
1924         {
1925             fgUpdateMenuHighlight( window->ActiveMenu );
1926             break;
1927         }
1928         SetFocus(window->Window.Handle);
1929
1930         fgState.Modifiers = fghGetWin32Modifiers( );
1931
1932         if( ( wParam & MK_LBUTTON ) ||
1933             ( wParam & MK_MBUTTON ) ||
1934             ( wParam & MK_RBUTTON ) )
1935             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
1936                                            window->State.MouseY ) );
1937         else
1938             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
1939                                             window->State.MouseY ) );
1940
1941         fgState.Modifiers = INVALID_MODIFIERS;
1942     }
1943     break;
1944
1945     case WM_LBUTTONDOWN:
1946     case WM_MBUTTONDOWN:
1947     case WM_RBUTTONDOWN:
1948     case WM_LBUTTONUP:
1949     case WM_MBUTTONUP:
1950     case WM_RBUTTONUP:
1951     {
1952         GLboolean pressed = GL_TRUE;
1953         int button;
1954
1955 #if defined(_WIN32_WCE)
1956         window->State.MouseX = 320-HIWORD( lParam );
1957         window->State.MouseY = LOWORD( lParam );
1958 #else
1959         window->State.MouseX = LOWORD( lParam );
1960         window->State.MouseY = HIWORD( lParam );
1961 #endif /* defined(_WIN32_WCE) */
1962
1963         /* Restrict to [-32768, 32767] to match X11 behaviour       */
1964         /* See comment in "freeglut_developer" mailing list 10/4/04 */
1965         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
1966         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
1967
1968         switch( uMsg )
1969         {
1970         case WM_LBUTTONDOWN:
1971             pressed = GL_TRUE;
1972             button = GLUT_LEFT_BUTTON;
1973             break;
1974         case WM_MBUTTONDOWN:
1975             pressed = GL_TRUE;
1976             button = GLUT_MIDDLE_BUTTON;
1977             break;
1978         case WM_RBUTTONDOWN:
1979             pressed = GL_TRUE;
1980             button = GLUT_RIGHT_BUTTON;
1981             break;
1982         case WM_LBUTTONUP:
1983             pressed = GL_FALSE;
1984             button = GLUT_LEFT_BUTTON;
1985             break;
1986         case WM_MBUTTONUP:
1987             pressed = GL_FALSE;
1988             button = GLUT_MIDDLE_BUTTON;
1989             break;
1990         case WM_RBUTTONUP:
1991             pressed = GL_FALSE;
1992             button = GLUT_RIGHT_BUTTON;
1993             break;
1994         default:
1995             pressed = GL_FALSE;
1996             button = -1;
1997             break;
1998         }
1999
2000 #if !defined(_WIN32_WCE)
2001         if( GetSystemMetrics( SM_SWAPBUTTON ) )
2002         {
2003             if( button == GLUT_LEFT_BUTTON )
2004                 button = GLUT_RIGHT_BUTTON;
2005             else
2006                 if( button == GLUT_RIGHT_BUTTON )
2007                     button = GLUT_LEFT_BUTTON;
2008         }
2009 #endif /* !defined(_WIN32_WCE) */
2010
2011         if( button == -1 )
2012             return DefWindowProc( hWnd, uMsg, lParam, wParam );
2013
2014         /*
2015          * Do not execute the application's mouse callback if a menu
2016          * is hooked to this button.  In that case an appropriate
2017          * private call should be generated.
2018          */
2019         if( fgCheckActiveMenu( window, button, pressed,
2020                                window->State.MouseX, window->State.MouseY ) )
2021             break;
2022
2023         /* Set capture so that the window captures all the mouse messages */
2024         /*
2025          * XXX - Multiple button support:  Under X11, the mouse is not released
2026          * XXX - from the window until all buttons have been released, even if the
2027          * XXX - user presses a button in another window.  This will take more
2028          * XXX - code changes than I am up to at the moment (10/5/04).  The present
2029          * XXX - is a 90 percent solution.
2030          */
2031         if ( pressed == GL_TRUE )
2032           SetCapture ( window->Window.Handle ) ;
2033         else
2034           ReleaseCapture () ;
2035
2036         if( ! FETCH_WCB( *window, Mouse ) )
2037             break;
2038
2039         fgSetWindow( window );
2040         fgState.Modifiers = fghGetWin32Modifiers( );
2041
2042         INVOKE_WCB(
2043             *window, Mouse,
2044             ( button,
2045               pressed ? GLUT_DOWN : GLUT_UP,
2046               window->State.MouseX,
2047               window->State.MouseY
2048             )
2049         );
2050
2051         fgState.Modifiers = INVALID_MODIFIERS;
2052     }
2053     break;
2054
2055     case 0x020a:
2056         /* Should be WM_MOUSEWHEEL but my compiler doesn't recognize it */
2057     {
2058         int wheel_number = LOWORD( wParam );
2059         short ticks = ( short )HIWORD( wParam );
2060                 fgState.MouseWheelTicks += ticks;
2061
2062         /*
2063          * XXX Should use WHEEL_DELTA instead of 120
2064          */
2065                 if ( abs ( fgState.MouseWheelTicks ) > 120 )
2066                 {
2067                         int direction = ( fgState.MouseWheelTicks > 0 ) ? 1 : -1;
2068
2069             if( ! FETCH_WCB( *window, MouseWheel ) &&
2070                 ! FETCH_WCB( *window, Mouse ) )
2071                 break;
2072
2073             fgSetWindow( window );
2074             fgState.Modifiers = fghGetWin32Modifiers( );
2075
2076             /*
2077              * XXX Should use WHEEL_DELTA instead of 120
2078              */
2079             while( abs ( fgState.MouseWheelTicks ) > 120 )
2080                         {
2081                 if( FETCH_WCB( *window, MouseWheel ) )
2082                     INVOKE_WCB( *window, MouseWheel,
2083                                 ( wheel_number,
2084                                   direction,
2085                                   window->State.MouseX,
2086                                   window->State.MouseY
2087                                 )
2088                     );
2089                 else  /* No mouse wheel, call the mouse button callback twice */
2090                                 {
2091                     /*
2092                      * Map wheel zero to button 3 and 4; +1 to 3, -1 to 4
2093                      *  "    "   one                     +1 to 5, -1 to 6, ...
2094                      *
2095                      * XXX The below assumes that you have no more than 3 mouse
2096                      * XXX buttons.  Sorry.
2097                      */
2098                     int button = wheel_number * 2 + 3;
2099                     if( direction < 0 )
2100                         ++button;
2101                     INVOKE_WCB( *window, Mouse,
2102                                 ( button, GLUT_DOWN,
2103                                   window->State.MouseX, window->State.MouseY )
2104                     );
2105                     INVOKE_WCB( *window, Mouse,
2106                                 ( button, GLUT_UP,
2107                                   window->State.MouseX, window->State.MouseY )
2108                     );
2109                                 }
2110
2111                 /*
2112                  * XXX Should use WHEEL_DELTA instead of 120
2113                  */
2114                                 fgState.MouseWheelTicks -= 120 * direction;
2115                         }
2116
2117             fgState.Modifiers = INVALID_MODIFIERS;
2118                 }
2119     }
2120     break ;
2121
2122     case WM_SYSKEYDOWN:
2123     case WM_KEYDOWN:
2124     {
2125         int keypress = -1;
2126         POINT mouse_pos ;
2127
2128         if( ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
2129             break;
2130
2131         /*
2132          * Remember the current modifiers state. This is done here in order
2133          * to make sure the VK_DELETE keyboard callback is executed properly.
2134          */
2135         fgState.Modifiers = fghGetWin32Modifiers( );
2136
2137         GetCursorPos( &mouse_pos );
2138         ScreenToClient( window->Window.Handle, &mouse_pos );
2139
2140         window->State.MouseX = mouse_pos.x;
2141         window->State.MouseY = mouse_pos.y;
2142
2143         /* Convert the Win32 keystroke codes to GLUTtish way */
2144 #       define KEY(a,b) case a: keypress = b; break;
2145
2146         switch( wParam )
2147         {
2148             KEY( VK_F1,     GLUT_KEY_F1        );
2149             KEY( VK_F2,     GLUT_KEY_F2        );
2150             KEY( VK_F3,     GLUT_KEY_F3        );
2151             KEY( VK_F4,     GLUT_KEY_F4        );
2152             KEY( VK_F5,     GLUT_KEY_F5        );
2153             KEY( VK_F6,     GLUT_KEY_F6        );
2154             KEY( VK_F7,     GLUT_KEY_F7        );
2155             KEY( VK_F8,     GLUT_KEY_F8        );
2156             KEY( VK_F9,     GLUT_KEY_F9        );
2157             KEY( VK_F10,    GLUT_KEY_F10       );
2158             KEY( VK_F11,    GLUT_KEY_F11       );
2159             KEY( VK_F12,    GLUT_KEY_F12       );
2160             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
2161             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
2162             KEY( VK_HOME,   GLUT_KEY_HOME      );
2163             KEY( VK_END,    GLUT_KEY_END       );
2164             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
2165             KEY( VK_UP,     GLUT_KEY_UP        );
2166             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
2167             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
2168             KEY( VK_INSERT, GLUT_KEY_INSERT    );
2169             KEY( VK_LCONTROL, GLUT_KEY_CTRL_L  );
2170             KEY( VK_RCONTROL, GLUT_KEY_CTRL_R  );
2171             KEY( VK_LSHIFT, GLUT_KEY_SHIFT_L   );
2172             KEY( VK_RSHIFT, GLUT_KEY_SHIFT_R   );
2173             KEY( VK_LMENU,  GLUT_KEY_ALT_L     );
2174             KEY( VK_RMENU,  GLUT_KEY_ALT_R     );
2175
2176         case VK_DELETE:
2177             /* The delete key should be treated as an ASCII keypress: */
2178             INVOKE_WCB( *window, Keyboard,
2179                         ( 127, window->State.MouseX, window->State.MouseY )
2180             );
2181         }
2182
2183 #if defined(_WIN32_WCE)
2184         if(!(lParam & 0x40000000)) /* Prevent auto-repeat */
2185         {
2186             if(wParam==(unsigned)gxKeyList.vkRight)
2187                 keypress = GLUT_KEY_RIGHT;
2188             else if(wParam==(unsigned)gxKeyList.vkLeft)
2189                 keypress = GLUT_KEY_LEFT;
2190             else if(wParam==(unsigned)gxKeyList.vkUp)
2191                 keypress = GLUT_KEY_UP;
2192             else if(wParam==(unsigned)gxKeyList.vkDown)
2193                 keypress = GLUT_KEY_DOWN;
2194             else if(wParam==(unsigned)gxKeyList.vkA)
2195                 keypress = GLUT_KEY_F1;
2196             else if(wParam==(unsigned)gxKeyList.vkB)
2197                 keypress = GLUT_KEY_F2;
2198             else if(wParam==(unsigned)gxKeyList.vkC)
2199                 keypress = GLUT_KEY_F3;
2200             else if(wParam==(unsigned)gxKeyList.vkStart)
2201                 keypress = GLUT_KEY_F4;
2202         }
2203 #endif
2204
2205         if( keypress != -1 )
2206             INVOKE_WCB( *window, Special,
2207                         ( keypress,
2208                           window->State.MouseX, window->State.MouseY )
2209             );
2210
2211         fgState.Modifiers = INVALID_MODIFIERS;
2212     }
2213     break;
2214
2215     case WM_SYSKEYUP:
2216     case WM_KEYUP:
2217     {
2218         int keypress = -1;
2219         POINT mouse_pos;
2220
2221         /*
2222          * Remember the current modifiers state. This is done here in order
2223          * to make sure the VK_DELETE keyboard callback is executed properly.
2224          */
2225         fgState.Modifiers = fghGetWin32Modifiers( );
2226
2227         GetCursorPos( &mouse_pos );
2228         ScreenToClient( window->Window.Handle, &mouse_pos );
2229
2230         window->State.MouseX = mouse_pos.x;
2231         window->State.MouseY = mouse_pos.y;
2232
2233         /*
2234          * Convert the Win32 keystroke codes to GLUTtish way.
2235          * "KEY(a,b)" was defined under "WM_KEYDOWN"
2236          */
2237
2238         switch( wParam )
2239         {
2240             KEY( VK_F1,     GLUT_KEY_F1        );
2241             KEY( VK_F2,     GLUT_KEY_F2        );
2242             KEY( VK_F3,     GLUT_KEY_F3        );
2243             KEY( VK_F4,     GLUT_KEY_F4        );
2244             KEY( VK_F5,     GLUT_KEY_F5        );
2245             KEY( VK_F6,     GLUT_KEY_F6        );
2246             KEY( VK_F7,     GLUT_KEY_F7        );
2247             KEY( VK_F8,     GLUT_KEY_F8        );
2248             KEY( VK_F9,     GLUT_KEY_F9        );
2249             KEY( VK_F10,    GLUT_KEY_F10       );
2250             KEY( VK_F11,    GLUT_KEY_F11       );
2251             KEY( VK_F12,    GLUT_KEY_F12       );
2252             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
2253             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
2254             KEY( VK_HOME,   GLUT_KEY_HOME      );
2255             KEY( VK_END,    GLUT_KEY_END       );
2256             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
2257             KEY( VK_UP,     GLUT_KEY_UP        );
2258             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
2259             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
2260             KEY( VK_INSERT, GLUT_KEY_INSERT    );
2261             KEY( VK_LCONTROL, GLUT_KEY_CTRL_L  );
2262             KEY( VK_RCONTROL, GLUT_KEY_CTRL_R  );
2263             KEY( VK_LSHIFT, GLUT_KEY_SHIFT_L   );
2264             KEY( VK_RSHIFT, GLUT_KEY_SHIFT_R   );
2265             KEY( VK_LMENU,  GLUT_KEY_ALT_L     );
2266             KEY( VK_RMENU,  GLUT_KEY_ALT_R     );
2267
2268           case VK_DELETE:
2269               /* The delete key should be treated as an ASCII keypress: */
2270               INVOKE_WCB( *window, KeyboardUp,
2271                           ( 127, window->State.MouseX, window->State.MouseY )
2272               );
2273               break;
2274
2275         default:
2276         {
2277 #if !defined(_WIN32_WCE)
2278             BYTE state[ 256 ];
2279             WORD code[ 2 ];
2280
2281             GetKeyboardState( state );
2282
2283             if( ToAscii( (UINT)wParam, 0, state, code, 0 ) == 1 )
2284                 wParam=code[ 0 ];
2285
2286             INVOKE_WCB( *window, KeyboardUp,
2287                         ( (char)wParam,
2288                           window->State.MouseX, window->State.MouseY )
2289             );
2290 #endif /* !defined(_WIN32_WCE) */
2291         }
2292         }
2293
2294         if( keypress != -1 )
2295             INVOKE_WCB( *window, SpecialUp,
2296                         ( keypress,
2297                           window->State.MouseX, window->State.MouseY )
2298             );
2299
2300         fgState.Modifiers = INVALID_MODIFIERS;
2301     }
2302     break;
2303
2304     case WM_SYSCHAR:
2305     case WM_CHAR:
2306     {
2307       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
2308             break;
2309
2310         fgState.Modifiers = fghGetWin32Modifiers( );
2311         INVOKE_WCB( *window, Keyboard,
2312                     ( (char)wParam,
2313                       window->State.MouseX, window->State.MouseY )
2314         );
2315         fgState.Modifiers = INVALID_MODIFIERS;
2316     }
2317     break;
2318
2319     case WM_CAPTURECHANGED:
2320         /* User has finished resizing the window, force a redraw */
2321         INVOKE_WCB( *window, Display, ( ) );
2322
2323         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
2324         break;
2325
2326         /* Other messages that I have seen and which are not handled already */
2327     case WM_SETTEXT:  /* 0x000c */
2328         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2329         /* Pass it on to "DefWindowProc" to set the window text */
2330         break;
2331
2332     case WM_GETTEXT:  /* 0x000d */
2333         /* Ideally we would copy the title of the window into "lParam" */
2334         /* strncpy ( (char *)lParam, "Window Title", wParam );
2335            lRet = ( wParam > 12 ) ? 12 : wParam;  */
2336         /* the number of characters copied */
2337         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2338         break;
2339
2340     case WM_GETTEXTLENGTH:  /* 0x000e */
2341         /* Ideally we would get the length of the title of the window */
2342         lRet = 12;
2343         /* the number of characters in "Window Title\0" (see above) */
2344         break;
2345
2346     case WM_ERASEBKGND:  /* 0x0014 */
2347         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2348         break;
2349
2350 #if !defined(_WIN32_WCE)
2351     case WM_SYNCPAINT:  /* 0x0088 */
2352         /* Another window has moved, need to update this one */
2353         window->State.Redisplay = GL_TRUE;
2354         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2355         /* Help screen says this message must be passed to "DefWindowProc" */
2356         break;
2357
2358     case WM_NCPAINT:  /* 0x0085 */
2359       /* Need to update the border of this window */
2360         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2361         /* Pass it on to "DefWindowProc" to repaint a standard border */
2362         break;
2363
2364     case WM_SYSCOMMAND :  /* 0x0112 */
2365         {
2366           /*
2367            * We have received a system command message.  Try to act on it.
2368            * The commands are passed in through the "wParam" parameter:
2369            * The least significant digit seems to be which edge of the window
2370            * is being used for a resize event:
2371            *     4  3  5
2372            *     1     2
2373            *     7  6  8
2374            * Congratulations and thanks to Richard Rauch for figuring this out..
2375            */
2376             switch ( wParam & 0xfff0 )
2377             {
2378             case SC_SIZE       :
2379                 break ;
2380
2381             case SC_MOVE       :
2382                 break ;
2383
2384             case SC_MINIMIZE   :
2385                 /* User has clicked on the "-" to minimize the window */
2386                 /* Turn off the visibility */
2387                 window->State.Visible = GL_FALSE ;
2388
2389                 break ;
2390
2391             case SC_MAXIMIZE   :
2392                 break ;
2393
2394             case SC_NEXTWINDOW :
2395                 break ;
2396
2397             case SC_PREVWINDOW :
2398                 break ;
2399
2400             case SC_CLOSE      :
2401                 /* Followed very closely by a WM_CLOSE message */
2402                 break ;
2403
2404             case SC_VSCROLL    :
2405                 break ;
2406
2407             case SC_HSCROLL    :
2408                 break ;
2409
2410             case SC_MOUSEMENU  :
2411                 break ;
2412
2413             case SC_KEYMENU    :
2414                 break ;
2415
2416             case SC_ARRANGE    :
2417                 break ;
2418
2419             case SC_RESTORE    :
2420                 break ;
2421
2422             case SC_TASKLIST   :
2423                 break ;
2424
2425             case SC_SCREENSAVE :
2426                 break ;
2427
2428             case SC_HOTKEY     :
2429                 break ;
2430
2431 #if(WINVER >= 0x0400)
2432             case SC_DEFAULT    :
2433                 break ;
2434
2435             case SC_MONITORPOWER    :
2436                 break ;
2437
2438             case SC_CONTEXTHELP    :
2439                 break ;
2440 #endif /* WINVER >= 0x0400 */
2441
2442             default:
2443 #if _DEBUG
2444                 fgWarning( "Unknown wParam type 0x%x", wParam );
2445 #endif
2446                 break;
2447             }
2448         }
2449 #endif /* !defined(_WIN32_WCE) */
2450
2451         /* We need to pass the message on to the operating system as well */
2452         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2453         break;
2454
2455 #ifdef WM_TOUCH
2456         /* handle multi-touch messages */
2457         case WM_TOUCH:
2458         {
2459                 unsigned int numInputs = (unsigned int)wParam;
2460                 unsigned int i = 0;
2461                 TOUCHINPUT* ti = (TOUCHINPUT*)malloc( sizeof(TOUCHINPUT)*numInputs);
2462
2463                 if (fghGetTouchInputInfo == (pGetTouchInputInfo)0xDEADBEEF) {
2464                     fghGetTouchInputInfo = (pGetTouchInputInfo)GetProcAddress(GetModuleHandle("user32"),"GetTouchInputInfo");
2465                     fghCloseTouchInputHandle = (pCloseTouchInputHandle)GetProcAddress(GetModuleHandle("user32"),"CloseTouchInputHandle");
2466                 }
2467
2468                 if (!fghGetTouchInputInfo) { 
2469                         free( (void*)ti );
2470                         break;
2471                 }
2472
2473                 if (fghGetTouchInputInfo( (HTOUCHINPUT)lParam, numInputs, ti, sizeof(TOUCHINPUT) )) {
2474                         /* Handle each contact point */
2475                         for (i = 0; i < numInputs; ++i ) {
2476
2477                                 POINT tp;
2478                                 tp.x = TOUCH_COORD_TO_PIXEL(ti[i].x);
2479                                 tp.y = TOUCH_COORD_TO_PIXEL(ti[i].y);
2480                                 ScreenToClient( hWnd, &tp );
2481
2482                                 ti[i].dwID = ti[i].dwID * 2;
2483
2484                                 if (ti[i].dwFlags & TOUCHEVENTF_DOWN) {
2485                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_ENTERED ) );
2486                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_DOWN ) );
2487                                 } else if (ti[i].dwFlags & TOUCHEVENTF_MOVE) {
2488                                         INVOKE_WCB( *window, MultiMotion, ( ti[i].dwID, tp.x, tp.y ) );
2489                                 } else if (ti[i].dwFlags & TOUCHEVENTF_UP)   { 
2490                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_UP ) );
2491                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_LEFT ) );
2492                                 }
2493                         }
2494                 }
2495                 fghCloseTouchInputHandle((HTOUCHINPUT)lParam);
2496                 free( (void*)ti );
2497                 lRet = 0; /*DefWindowProc( hWnd, uMsg, wParam, lParam );*/
2498                 break;
2499         }
2500 #endif
2501     default:
2502         /* Handle unhandled messages */
2503         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
2504         break;
2505     }
2506
2507     return lRet;
2508 }
2509 #endif
2510
2511 /*** END OF FILE ***/