some clean up in WM_KILLFOCUS handler
[freeglut] / src / x11 / fg_main_x11.c
1 /*
2  * freeglut_main_x11.c
3  *
4  * The X11-specific 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  * Copied for Platform code by Evan Felix <karcaw at gmail.com>
9  * Creation date: Thur Feb 2 2012
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included
19  * in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
25  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28
29 #include <GL/freeglut.h>
30 #include "../fg_internal.h"
31 #ifdef HAVE_ERRNO_H
32 #    include <errno.h>
33 #endif
34 #include <stdarg.h>
35 #ifdef  HAVE_VFPRINTF
36 #    define VFPRINTF(s,f,a) vfprintf((s),(f),(a))
37 #elif defined(HAVE__DOPRNT)
38 #    define VFPRINTF(s,f,a) _doprnt((f),(a),(s))
39 #else
40 #    define VFPRINTF(s,f,a)
41 #endif
42
43 #include "fg_main.h"
44
45 /*
46  * Try to get the maximum value allowed for ints, falling back to the minimum
47  * guaranteed by ISO C99 if there is no suitable header.
48  */
49 #ifdef HAVE_LIMITS_H
50 #    include <limits.h>
51 #endif
52 #ifndef INT_MAX
53 #    define INT_MAX 32767
54 #endif
55
56 #ifndef MIN
57 #    define MIN(a,b) (((a)<(b)) ? (a) : (b))
58 #endif
59
60 /* used in the event handling code to match and discard stale mouse motion events */
61 static Bool match_motion(Display *dpy, XEvent *xev, XPointer arg);
62
63 /*
64  * TODO BEFORE THE STABLE RELEASE:
65  *
66  * There are some issues concerning window redrawing under X11, and maybe
67  * some events are not handled. The Win32 version lacks some more features,
68  * but seems acceptable for not demanding purposes.
69  *
70  * Need to investigate why the X11 version breaks out with an error when
71  * closing a window (using the window manager, not glutDestroyWindow)...
72  */
73  
74  
75 /*
76  * Request a window resize
77  */
78 void fgPlatformReshapeWindow ( SFG_Window *window, int width, int height )
79 {
80     XResizeWindow( fgDisplay.pDisplay.Display, window->Window.Handle,
81                    width, height );
82     XFlush( fgDisplay.pDisplay.Display ); /* XXX Shouldn't need this */
83 }
84
85
86 /*
87  * A static helper function to execute display callback for a window
88  */
89 void fgPlatformDisplayWindow ( SFG_Window *window )
90 {
91         fghRedrawWindow ( window ) ;
92 }
93
94
95 fg_time_t fgPlatformSystemTime ( void )
96 {
97 #ifdef CLOCK_MONOTONIC
98     struct timespec now;
99     clock_gettime(CLOCK_MONOTONIC, &now);
100     return now.tv_nsec/1000000 + now.tv_sec*1000;
101 #elif defined(HAVE_GETTIMEOFDAY)
102     struct timeval now;
103     gettimeofday( &now, NULL );
104     return now.tv_usec/1000 + now.tv_sec*1000;
105 #endif
106 }
107
108 /*
109  * Does the magic required to relinquish the CPU until something interesting
110  * happens.
111  */
112
113 void fgPlatformSleepForEvents( fg_time_t msec )
114 {
115     /*
116      * Possibly due to aggressive use of XFlush() and friends,
117      * it is possible to have our socket drained but still have
118      * unprocessed events.  (Or, this may just be normal with
119      * X, anyway?)  We do non-trivial processing of X events
120      * after the event-reading loop, in any case, so we
121      * need to allow that we may have an empty socket but non-
122      * empty event queue.
123      */
124     if( ! XPending( fgDisplay.pDisplay.Display ) )
125     {
126         fd_set fdset;
127         int err;
128         int socket;
129         struct timeval wait;
130
131         socket = ConnectionNumber( fgDisplay.pDisplay.Display );
132         FD_ZERO( &fdset );
133         FD_SET( socket, &fdset );
134         wait.tv_sec = msec / 1000;
135         wait.tv_usec = (msec % 1000) * 1000;
136         err = select( socket+1, &fdset, NULL, NULL, &wait );
137
138 #ifdef HAVE_ERRNO_H
139         if( ( -1 == err ) && ( errno != EINTR ) )
140             fgWarning ( "freeglut select() error: %d", errno );
141 #endif
142     }
143 }
144
145
146 /*
147  * Returns GLUT modifier mask for the state field of an X11 event.
148  */
149 int fgPlatformGetModifiers( int state )
150 {
151     int ret = 0;
152
153     if( state & ( ShiftMask | LockMask ) )
154         ret |= GLUT_ACTIVE_SHIFT;
155     if( state & ControlMask )
156         ret |= GLUT_ACTIVE_CTRL;
157     if( state & Mod1Mask )
158         ret |= GLUT_ACTIVE_ALT;
159
160     return ret;
161 }
162
163 static const char* fghTypeToString( int type )
164 {
165     switch( type ) {
166     case KeyPress: return "KeyPress";
167     case KeyRelease: return "KeyRelease";
168     case ButtonPress: return "ButtonPress";
169     case ButtonRelease: return "ButtonRelease";
170     case MotionNotify: return "MotionNotify";
171     case EnterNotify: return "EnterNotify";
172     case LeaveNotify: return "LeaveNotify";
173     case FocusIn: return "FocusIn";
174     case FocusOut: return "FocusOut";
175     case KeymapNotify: return "KeymapNotify";
176     case Expose: return "Expose";
177     case GraphicsExpose: return "GraphicsExpose";
178     case NoExpose: return "NoExpose";
179     case VisibilityNotify: return "VisibilityNotify";
180     case CreateNotify: return "CreateNotify";
181     case DestroyNotify: return "DestroyNotify";
182     case UnmapNotify: return "UnmapNotify";
183     case MapNotify: return "MapNotify";
184     case MapRequest: return "MapRequest";
185     case ReparentNotify: return "ReparentNotify";
186     case ConfigureNotify: return "ConfigureNotify";
187     case ConfigureRequest: return "ConfigureRequest";
188     case GravityNotify: return "GravityNotify";
189     case ResizeRequest: return "ResizeRequest";
190     case CirculateNotify: return "CirculateNotify";
191     case CirculateRequest: return "CirculateRequest";
192     case PropertyNotify: return "PropertyNotify";
193     case SelectionClear: return "SelectionClear";
194     case SelectionRequest: return "SelectionRequest";
195     case SelectionNotify: return "SelectionNotify";
196     case ColormapNotify: return "ColormapNotify";
197     case ClientMessage: return "ClientMessage";
198     case MappingNotify: return "MappingNotify";
199     default: return "UNKNOWN";
200     }
201 }
202
203 static const char* fghBoolToString( Bool b )
204 {
205     return b == False ? "False" : "True";
206 }
207
208 static const char* fghNotifyHintToString( char is_hint )
209 {
210     switch( is_hint ) {
211     case NotifyNormal: return "NotifyNormal";
212     case NotifyHint: return "NotifyHint";
213     default: return "UNKNOWN";
214     }
215 }
216
217 static const char* fghNotifyModeToString( int mode )
218 {
219     switch( mode ) {
220     case NotifyNormal: return "NotifyNormal";
221     case NotifyGrab: return "NotifyGrab";
222     case NotifyUngrab: return "NotifyUngrab";
223     case NotifyWhileGrabbed: return "NotifyWhileGrabbed";
224     default: return "UNKNOWN";
225     }
226 }
227
228 static const char* fghNotifyDetailToString( int detail )
229 {
230     switch( detail ) {
231     case NotifyAncestor: return "NotifyAncestor";
232     case NotifyVirtual: return "NotifyVirtual";
233     case NotifyInferior: return "NotifyInferior";
234     case NotifyNonlinear: return "NotifyNonlinear";
235     case NotifyNonlinearVirtual: return "NotifyNonlinearVirtual";
236     case NotifyPointer: return "NotifyPointer";
237     case NotifyPointerRoot: return "NotifyPointerRoot";
238     case NotifyDetailNone: return "NotifyDetailNone";
239     default: return "UNKNOWN";
240     }
241 }
242
243 static const char* fghVisibilityToString( int state ) {
244     switch( state ) {
245     case VisibilityUnobscured: return "VisibilityUnobscured";
246     case VisibilityPartiallyObscured: return "VisibilityPartiallyObscured";
247     case VisibilityFullyObscured: return "VisibilityFullyObscured";
248     default: return "UNKNOWN";
249     }
250 }
251
252 static const char* fghConfigureDetailToString( int detail )
253 {
254     switch( detail ) {
255     case Above: return "Above";
256     case Below: return "Below";
257     case TopIf: return "TopIf";
258     case BottomIf: return "BottomIf";
259     case Opposite: return "Opposite";
260     default: return "UNKNOWN";
261     }
262 }
263
264 static const char* fghPlaceToString( int place )
265 {
266     switch( place ) {
267     case PlaceOnTop: return "PlaceOnTop";
268     case PlaceOnBottom: return "PlaceOnBottom";
269     default: return "UNKNOWN";
270     }
271 }
272
273 static const char* fghMappingRequestToString( int request )
274 {
275     switch( request ) {
276     case MappingModifier: return "MappingModifier";
277     case MappingKeyboard: return "MappingKeyboard";
278     case MappingPointer: return "MappingPointer";
279     default: return "UNKNOWN";
280     }
281 }
282
283 static const char* fghPropertyStateToString( int state )
284 {
285     switch( state ) {
286     case PropertyNewValue: return "PropertyNewValue";
287     case PropertyDelete: return "PropertyDelete";
288     default: return "UNKNOWN";
289     }
290 }
291
292 static const char* fghColormapStateToString( int state )
293 {
294     switch( state ) {
295     case ColormapUninstalled: return "ColormapUninstalled";
296     case ColormapInstalled: return "ColormapInstalled";
297     default: return "UNKNOWN";
298     }
299 }
300
301 __fg_unused static void fghPrintEvent( XEvent *event )
302 {
303     switch( event->type ) {
304
305     case KeyPress:
306     case KeyRelease: {
307         XKeyEvent *e = &event->xkey;
308         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
309                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
310                    "keycode=%u, same_screen=%s", fghTypeToString( e->type ),
311                    e->window, e->root, e->subwindow, (unsigned long)e->time,
312                    e->x, e->y, e->x_root, e->y_root, e->state, e->keycode,
313                    fghBoolToString( e->same_screen ) );
314         break;
315     }
316
317     case ButtonPress:
318     case ButtonRelease: {
319         XButtonEvent *e = &event->xbutton;
320         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
321                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
322                    "button=%u, same_screen=%d", fghTypeToString( e->type ),
323                    e->window, e->root, e->subwindow, (unsigned long)e->time,
324                    e->x, e->y, e->x_root, e->y_root, e->state, e->button,
325                    fghBoolToString( e->same_screen ) );
326         break;
327     }
328
329     case MotionNotify: {
330         XMotionEvent *e = &event->xmotion;
331         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
332                    "(x,y)=(%d,%d), (x_root,y_root)=(%d,%d), state=0x%x, "
333                    "is_hint=%s, same_screen=%d", fghTypeToString( e->type ),
334                    e->window, e->root, e->subwindow, (unsigned long)e->time,
335                    e->x, e->y, e->x_root, e->y_root, e->state,
336                    fghNotifyHintToString( e->is_hint ),
337                    fghBoolToString( e->same_screen ) );
338         break;
339     }
340
341     case EnterNotify:
342     case LeaveNotify: {
343         XCrossingEvent *e = &event->xcrossing;
344         fgWarning( "%s: window=0x%x, root=0x%x, subwindow=0x%x, time=%lu, "
345                    "(x,y)=(%d,%d), mode=%s, detail=%s, same_screen=%d, "
346                    "focus=%d, state=0x%x", fghTypeToString( e->type ),
347                    e->window, e->root, e->subwindow, (unsigned long)e->time,
348                    e->x, e->y, fghNotifyModeToString( e->mode ),
349                    fghNotifyDetailToString( e->detail ), (int)e->same_screen,
350                    (int)e->focus, e->state );
351         break;
352     }
353
354     case FocusIn:
355     case FocusOut: {
356         XFocusChangeEvent *e = &event->xfocus;
357         fgWarning( "%s: window=0x%x, mode=%s, detail=%s",
358                    fghTypeToString( e->type ), e->window,
359                    fghNotifyModeToString( e->mode ),
360                    fghNotifyDetailToString( e->detail ) );
361         break;
362     }
363
364     case KeymapNotify: {
365         XKeymapEvent *e = &event->xkeymap;
366         char buf[32 * 2 + 1];
367         int i;
368         for ( i = 0; i < 32; i++ ) {
369             snprintf( &buf[ i * 2 ], sizeof( buf ) - i * 2,
370                       "%02x", e->key_vector[ i ] );
371         }
372         buf[ i ] = '\0';
373         fgWarning( "%s: window=0x%x, %s", fghTypeToString( e->type ), e->window,
374                    buf );
375         break;
376     }
377
378     case Expose: {
379         XExposeEvent *e = &event->xexpose;
380         fgWarning( "%s: window=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
381                    "count=%d", fghTypeToString( e->type ), e->window, e->x,
382                    e->y, e->width, e->height, e->count );
383         break;
384     }
385
386     case GraphicsExpose: {
387         XGraphicsExposeEvent *e = &event->xgraphicsexpose;
388         fgWarning( "%s: drawable=0x%x, (x,y)=(%d,%d), (width,height)=(%d,%d), "
389                    "count=%d, (major_code,minor_code)=(%d,%d)",
390                    fghTypeToString( e->type ), e->drawable, e->x, e->y,
391                    e->width, e->height, e->count, e->major_code,
392                    e->minor_code );
393         break;
394     }
395
396     case NoExpose: {
397         XNoExposeEvent *e = &event->xnoexpose;
398         fgWarning( "%s: drawable=0x%x, (major_code,minor_code)=(%d,%d)",
399                    fghTypeToString( e->type ), e->drawable, e->major_code,
400                    e->minor_code );
401         break;
402     }
403
404     case VisibilityNotify: {
405         XVisibilityEvent *e = &event->xvisibility;
406         fgWarning( "%s: window=0x%x, state=%s", fghTypeToString( e->type ),
407                    e->window, fghVisibilityToString( e->state) );
408         break;
409     }
410
411     case CreateNotify: {
412         XCreateWindowEvent *e = &event->xcreatewindow;
413         fgWarning( "%s: (x,y)=(%d,%d), (width,height)=(%d,%d), border_width=%d, "
414                    "window=0x%x, override_redirect=%s",
415                    fghTypeToString( e->type ), e->x, e->y, e->width, e->height,
416                    e->border_width, e->window,
417                    fghBoolToString( e->override_redirect ) );
418         break;
419     }
420
421     case DestroyNotify: {
422         XDestroyWindowEvent *e = &event->xdestroywindow;
423         fgWarning( "%s: event=0x%x, window=0x%x",
424                    fghTypeToString( e->type ), e->event, e->window );
425         break;
426     }
427
428     case UnmapNotify: {
429         XUnmapEvent *e = &event->xunmap;
430         fgWarning( "%s: event=0x%x, window=0x%x, from_configure=%s",
431                    fghTypeToString( e->type ), e->event, e->window,
432                    fghBoolToString( e->from_configure ) );
433         break;
434     }
435
436     case MapNotify: {
437         XMapEvent *e = &event->xmap;
438         fgWarning( "%s: event=0x%x, window=0x%x, override_redirect=%s",
439                    fghTypeToString( e->type ), e->event, e->window,
440                    fghBoolToString( e->override_redirect ) );
441         break;
442     }
443
444     case MapRequest: {
445         XMapRequestEvent *e = &event->xmaprequest;
446         fgWarning( "%s: parent=0x%x, window=0x%x",
447                    fghTypeToString( event->type ), e->parent, e->window );
448         break;
449     }
450
451     case ReparentNotify: {
452         XReparentEvent *e = &event->xreparent;
453         fgWarning( "%s: event=0x%x, window=0x%x, parent=0x%x, (x,y)=(%d,%d), "
454                    "override_redirect=%s", fghTypeToString( e->type ),
455                    e->event, e->window, e->parent, e->x, e->y,
456                    fghBoolToString( e->override_redirect ) );
457         break;
458     }
459
460     case ConfigureNotify: {
461         XConfigureEvent *e = &event->xconfigure;
462         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d), "
463                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
464                    "override_redirect=%s", fghTypeToString( e->type ), e->event,
465                    e->window, e->x, e->y, e->width, e->height, e->border_width,
466                    e->above, fghBoolToString( e->override_redirect ) );
467         break;
468     }
469
470     case ConfigureRequest: {
471         XConfigureRequestEvent *e = &event->xconfigurerequest;
472         fgWarning( "%s: parent=0x%x, window=0x%x, (x,y)=(%d,%d), "
473                    "(width,height)=(%d,%d), border_width=%d, above=0x%x, "
474                    "detail=%s, value_mask=%lx", fghTypeToString( e->type ),
475                    e->parent, e->window, e->x, e->y, e->width, e->height,
476                    e->border_width, e->above,
477                    fghConfigureDetailToString( e->detail ), e->value_mask );
478         break;
479     }
480
481     case GravityNotify: {
482         XGravityEvent *e = &event->xgravity;
483         fgWarning( "%s: event=0x%x, window=0x%x, (x,y)=(%d,%d)",
484                    fghTypeToString( e->type ), e->event, e->window, e->x, e->y );
485         break;
486     }
487
488     case ResizeRequest: {
489         XResizeRequestEvent *e = &event->xresizerequest;
490         fgWarning( "%s: window=0x%x, (width,height)=(%d,%d)",
491                    fghTypeToString( e->type ), e->window, e->width, e->height );
492         break;
493     }
494
495     case CirculateNotify: {
496         XCirculateEvent *e = &event->xcirculate;
497         fgWarning( "%s: event=0x%x, window=0x%x, place=%s",
498                    fghTypeToString( e->type ), e->event, e->window,
499                    fghPlaceToString( e->place ) );
500         break;
501     }
502
503     case CirculateRequest: {
504         XCirculateRequestEvent *e = &event->xcirculaterequest;
505         fgWarning( "%s: parent=0x%x, window=0x%x, place=%s",
506                    fghTypeToString( e->type ), e->parent, e->window,
507                    fghPlaceToString( e->place ) );
508         break;
509     }
510
511     case PropertyNotify: {
512         XPropertyEvent *e = &event->xproperty;
513         fgWarning( "%s: window=0x%x, atom=%lu, time=%lu, state=%s",
514                    fghTypeToString( e->type ), e->window,
515                    (unsigned long)e->atom, (unsigned long)e->time,
516                    fghPropertyStateToString( e->state ) );
517         break;
518     }
519
520     case SelectionClear: {
521         XSelectionClearEvent *e = &event->xselectionclear;
522         fgWarning( "%s: window=0x%x, selection=%lu, time=%lu",
523                    fghTypeToString( e->type ), e->window,
524                    (unsigned long)e->selection, (unsigned long)e->time );
525         break;
526     }
527
528     case SelectionRequest: {
529         XSelectionRequestEvent *e = &event->xselectionrequest;
530         fgWarning( "%s: owner=0x%x, requestor=0x%x, selection=0x%x, "
531                    "target=0x%x, property=%lu, time=%lu",
532                    fghTypeToString( e->type ), e->owner, e->requestor,
533                    (unsigned long)e->selection, (unsigned long)e->target,
534                    (unsigned long)e->property, (unsigned long)e->time );
535         break;
536     }
537
538     case SelectionNotify: {
539         XSelectionEvent *e = &event->xselection;
540         fgWarning( "%s: requestor=0x%x, selection=0x%x, target=0x%x, "
541                    "property=%lu, time=%lu", fghTypeToString( e->type ),
542                    e->requestor, (unsigned long)e->selection,
543                    (unsigned long)e->target, (unsigned long)e->property,
544                    (unsigned long)e->time );
545         break;
546     }
547
548     case ColormapNotify: {
549         XColormapEvent *e = &event->xcolormap;
550         fgWarning( "%s: window=0x%x, colormap=%lu, new=%s, state=%s",
551                    fghTypeToString( e->type ), e->window,
552                    (unsigned long)e->colormap, fghBoolToString( e->new ),
553                    fghColormapStateToString( e->state ) );
554         break;
555     }
556
557     case ClientMessage: {
558         XClientMessageEvent *e = &event->xclient;
559         char buf[ 61 ];
560         char* p = buf;
561         char* end = buf + sizeof( buf );
562         int i;
563         switch( e->format ) {
564         case 8:
565           for ( i = 0; i < 20; i++, p += 3 ) {
566                 snprintf( p, end - p, " %02x", e->data.b[ i ] );
567             }
568             break;
569         case 16:
570             for ( i = 0; i < 10; i++, p += 5 ) {
571                 snprintf( p, end - p, " %04x", e->data.s[ i ] );
572             }
573             break;
574         case 32:
575             for ( i = 0; i < 5; i++, p += 9 ) {
576                 snprintf( p, end - p, " %08lx", e->data.l[ i ] );
577             }
578             break;
579         }
580         *p = '\0';
581         fgWarning( "%s: window=0x%x, message_type=%lu, format=%d, data=(%s )",
582                    fghTypeToString( e->type ), e->window,
583                    (unsigned long)e->message_type, e->format, buf );
584         break;
585     }
586
587     case MappingNotify: {
588         XMappingEvent *e = &event->xmapping;
589         fgWarning( "%s: window=0x%x, request=%s, first_keycode=%d, count=%d",
590                    fghTypeToString( e->type ), e->window,
591                    fghMappingRequestToString( e->request ), e->first_keycode,
592                    e->count );
593         break;
594     }
595
596     default: {
597         fgWarning( "%s", fghTypeToString( event->type ) );
598         break;
599     }
600     }
601 }
602
603
604 void fgPlatformProcessSingleEvent ( void )
605 {
606     SFG_Window* window;
607     XEvent event;
608
609     /* This code was repeated constantly, so here it goes into a definition: */
610 #define GETWINDOW(a)                             \
611     window = fgWindowByHandle( event.a.window ); \
612     if( window == NULL )                         \
613         break;
614
615 #define GETMOUSE(a)                              \
616     window->State.MouseX = event.a.x;            \
617     window->State.MouseY = event.a.y;
618
619     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
620
621     while( XPending( fgDisplay.pDisplay.Display ) )
622     {
623         XNextEvent( fgDisplay.pDisplay.Display, &event );
624 #if _DEBUG
625         fghPrintEvent( &event );
626 #endif
627
628         switch( event.type )
629         {
630         case ClientMessage:
631             if(fgIsSpaceballXEvent(&event)) {
632                 fgSpaceballHandleXEvent(&event);
633                 break;
634             }
635             /* Destroy the window when the WM_DELETE_WINDOW message arrives */
636             if( (Atom) event.xclient.data.l[ 0 ] == fgDisplay.pDisplay.DeleteWindow )
637             {
638                 GETWINDOW( xclient );
639
640                 fgDestroyWindow ( window );
641
642                 if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
643                 {
644                     fgDeinitialize( );
645                     exit( 0 );
646                 }
647                 else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
648                     fgState.ExecState = GLUT_EXEC_STATE_STOP;
649
650                 return;
651             }
652             break;
653
654             /*
655              * CreateNotify causes a configure-event so that sub-windows are
656              * handled compatibly with GLUT.  Otherwise, your sub-windows
657              * (in freeglut only) will not get an initial reshape event,
658              * which can break things.
659              *
660              * GLUT presumably does this because it generally tries to treat
661              * sub-windows the same as windows.
662              */
663         case CreateNotify:
664         case ConfigureNotify:
665             {
666                 int width, height;
667                 if( event.type == CreateNotify ) {
668                     GETWINDOW( xcreatewindow );
669                     width = event.xcreatewindow.width;
670                     height = event.xcreatewindow.height;
671                 } else {
672                     GETWINDOW( xconfigure );
673                     width = event.xconfigure.width;
674                     height = event.xconfigure.height;
675                 }
676
677                 if( ( width != window->State.pWState.OldWidth ) ||
678                     ( height != window->State.pWState.OldHeight ) )
679                 {
680                     SFG_Window *current_window = fgStructure.CurrentWindow;
681
682                     window->State.pWState.OldWidth = width;
683                     window->State.pWState.OldHeight = height;
684                     if( FETCH_WCB( *window, Reshape ) )
685                         INVOKE_WCB( *window, Reshape, ( width, height ) );
686                     else
687                     {
688                         fgSetWindow( window );
689                         glViewport( 0, 0, width, height );
690                     }
691                     glutPostRedisplay( );
692                     if( window->IsMenu )
693                         fgSetWindow( current_window );
694                 }
695             }
696             break;
697
698         case DestroyNotify:
699             /*
700              * This is sent to confirm the XDestroyWindow call.
701              *
702              * XXX WHY is this commented out?  Should we re-enable it?
703              */
704             /* fgAddToWindowDestroyList ( window ); */
705             break;
706
707         case Expose:
708             /*
709              * We are too dumb to process partial exposes...
710              *
711              * XXX Well, we could do it.  However, it seems to only
712              * XXX be potentially useful for single-buffered (since
713              * XXX double-buffered does not respect viewport when we
714              * XXX do a buffer-swap).
715              *
716              */
717             if( event.xexpose.count == 0 )
718             {
719                 GETWINDOW( xexpose );
720                 window->State.Redisplay = GL_TRUE;
721             }
722             break;
723
724         case MapNotify:
725             break;
726
727         case UnmapNotify:
728             /* We get this when iconifying a window. */ 
729             GETWINDOW( xunmap );
730             INVOKE_WCB( *window, WindowStatus, ( GLUT_HIDDEN ) );
731             window->State.Visible = GL_FALSE;
732             break;
733
734         case MappingNotify:
735             /*
736              * Have the client's keyboard knowledge updated (xlib.ps,
737              * page 206, says that's a good thing to do)
738              */
739             XRefreshKeyboardMapping( (XMappingEvent *) &event );
740             break;
741
742         case VisibilityNotify:
743         {
744             /*
745              * Sending this event, the X server can notify us that the window
746              * has just acquired one of the three possible visibility states:
747              * VisibilityUnobscured, VisibilityPartiallyObscured or
748              * VisibilityFullyObscured. Note that we DO NOT receive a
749              * VisibilityNotify event when iconifying a window, we only get an
750              * UnmapNotify then.
751              */
752             GETWINDOW( xvisibility );
753             switch( event.xvisibility.state )
754             {
755             case VisibilityUnobscured:
756                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_RETAINED ) );
757                 window->State.Visible = GL_TRUE;
758                 break;
759
760             case VisibilityPartiallyObscured:
761                 INVOKE_WCB( *window, WindowStatus,
762                             ( GLUT_PARTIALLY_RETAINED ) );
763                 window->State.Visible = GL_TRUE;
764                 break;
765
766             case VisibilityFullyObscured:
767                 INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_COVERED ) );
768                 window->State.Visible = GL_FALSE;
769                 break;
770
771             default:
772                 fgWarning( "Unknown X visibility state: %d",
773                            event.xvisibility.state );
774                 break;
775             }
776         }
777         break;
778
779         case EnterNotify:
780         case LeaveNotify:
781             GETWINDOW( xcrossing );
782             GETMOUSE( xcrossing );
783             if( ( event.type == LeaveNotify ) && window->IsMenu &&
784                 window->ActiveMenu && window->ActiveMenu->IsActive )
785                 fgUpdateMenuHighlight( window->ActiveMenu );
786
787             INVOKE_WCB( *window, Entry, ( ( EnterNotify == event.type ) ?
788                                           GLUT_ENTERED :
789                                           GLUT_LEFT ) );
790             break;
791
792         case MotionNotify:
793         {
794             /* if GLUT_SKIP_STALE_MOTION_EVENTS is true, then discard all but
795              * the last motion event from the queue
796              */
797             if(fgState.SkipStaleMotion) {
798                 while(XCheckIfEvent(fgDisplay.pDisplay.Display, &event, match_motion, 0));
799             }
800
801             GETWINDOW( xmotion );
802             GETMOUSE( xmotion );
803
804             if( window->ActiveMenu )
805             {
806                 if( window == window->ActiveMenu->ParentWindow )
807                 {
808                     window->ActiveMenu->Window->State.MouseX =
809                         event.xmotion.x_root - window->ActiveMenu->X;
810                     window->ActiveMenu->Window->State.MouseY =
811                         event.xmotion.y_root - window->ActiveMenu->Y;
812                 }
813
814                 fgUpdateMenuHighlight( window->ActiveMenu );
815
816                 break;
817             }
818
819             /*
820              * XXX For more than 5 buttons, just check {event.xmotion.state},
821              * XXX rather than a host of bit-masks?  Or maybe we need to
822              * XXX track ButtonPress/ButtonRelease events in our own
823              * XXX bit-mask?
824              */
825             fgState.Modifiers = fgPlatformGetModifiers( event.xmotion.state );
826             if ( event.xmotion.state & ( Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask ) ) {
827                 INVOKE_WCB( *window, Motion, ( event.xmotion.x,
828                                                event.xmotion.y ) );
829             } else {
830                 INVOKE_WCB( *window, Passive, ( event.xmotion.x,
831                                                 event.xmotion.y ) );
832             }
833             fgState.Modifiers = INVALID_MODIFIERS;
834         }
835         break;
836
837         case ButtonRelease:
838         case ButtonPress:
839         {
840             GLboolean pressed = GL_TRUE;
841             int button;
842
843             if( event.type == ButtonRelease )
844                 pressed = GL_FALSE ;
845
846             /*
847              * A mouse button has been pressed or released. Traditionally,
848              * break if the window was found within the freeglut structures.
849              */
850             GETWINDOW( xbutton );
851             GETMOUSE( xbutton );
852
853             /*
854              * An X button (at least in XFree86) is numbered from 1.
855              * A GLUT button is numbered from 0.
856              * Old GLUT passed through buttons other than just the first
857              * three, though it only gave symbolic names and official
858              * support to the first three.
859              */
860             button = event.xbutton.button - 1;
861
862             /*
863              * Do not execute the application's mouse callback if a menu
864              * is hooked to this button.  In that case an appropriate
865              * private call should be generated.
866              */
867             if( fgCheckActiveMenu( window, button, pressed,
868                                    event.xbutton.x_root, event.xbutton.y_root ) )
869                 break;
870
871             /*
872              * Check if there is a mouse or mouse wheel callback hooked to the
873              * window
874              */
875             if( ! FETCH_WCB( *window, Mouse ) &&
876                 ! FETCH_WCB( *window, MouseWheel ) )
877                 break;
878
879             fgState.Modifiers = fgPlatformGetModifiers( event.xbutton.state );
880
881             /* Finally execute the mouse or mouse wheel callback */
882             if( ( button < glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS ) ) || ( ! FETCH_WCB( *window, MouseWheel ) ) )
883                 INVOKE_WCB( *window, Mouse, ( button,
884                                               pressed ? GLUT_DOWN : GLUT_UP,
885                                               event.xbutton.x,
886                                               event.xbutton.y )
887                 );
888             else
889             {
890                 /*
891                  * Map 4 and 5 to wheel zero; EVEN to +1, ODD to -1
892                  *  "  6 and 7 "    "   one; ...
893                  *
894                  * XXX This *should* be behind some variables/macros,
895                  * XXX since the order and numbering isn't certain
896                  * XXX See XFree86 configuration docs (even back in the
897                  * XXX 3.x days, and especially with 4.x).
898                  *
899                  * XXX Note that {button} has already been decremented
900                  * XXX in mapping from X button numbering to GLUT.
901                                  *
902                                  * XXX Should add support for partial wheel turns as Windows does -- 5/27/11
903                  */
904                 int wheel_number = (button - glutDeviceGet ( GLUT_NUM_MOUSE_BUTTONS )) / 2;
905                 int direction = -1;
906                 if( button % 2 )
907                     direction = 1;
908
909                 if( pressed )
910                     INVOKE_WCB( *window, MouseWheel, ( wheel_number,
911                                                        direction,
912                                                        event.xbutton.x,
913                                                        event.xbutton.y )
914                     );
915             }
916             fgState.Modifiers = INVALID_MODIFIERS;
917         }
918         break;
919
920         case KeyRelease:
921         case KeyPress:
922         {
923             FGCBKeyboard keyboard_cb;
924             FGCBSpecial special_cb;
925
926             GETWINDOW( xkey );
927             GETMOUSE( xkey );
928
929             /* Detect auto repeated keys, if configured globally or per-window */
930
931             if ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE )
932             {
933                 if (event.type==KeyRelease)
934                 {
935                     /*
936                      * Look at X11 keystate to detect repeat mode.
937                      * While X11 says the key is actually held down, we'll ignore KeyRelease/KeyPress pairs.
938                      */
939
940                     char keys[32];
941                     XQueryKeymap( fgDisplay.pDisplay.Display, keys ); /* Look at X11 keystate to detect repeat mode */
942
943                     if ( event.xkey.keycode<256 )            /* XQueryKeymap is limited to 256 keycodes    */
944                     {
945                         if ( keys[event.xkey.keycode>>3] & (1<<(event.xkey.keycode%8)) )
946                             window->State.KeyRepeating = GL_TRUE;
947                         else
948                             window->State.KeyRepeating = GL_FALSE;
949                     }
950                 }
951             }
952             else
953                 window->State.KeyRepeating = GL_FALSE;
954
955             /* Cease processing this event if it is auto repeated */
956
957             if (window->State.KeyRepeating)
958             {
959                 if (event.type == KeyPress) window->State.KeyRepeating = GL_FALSE;
960                 break;
961             }
962
963             if( event.type == KeyPress )
964             {
965                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, Keyboard ));
966                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, Special  ));
967             }
968             else
969             {
970                 keyboard_cb = (FGCBKeyboard)( FETCH_WCB( *window, KeyboardUp ));
971                 special_cb  = (FGCBSpecial) ( FETCH_WCB( *window, SpecialUp  ));
972             }
973
974             /* Is there a keyboard/special callback hooked for this window? */
975             if( keyboard_cb || special_cb )
976             {
977                 XComposeStatus composeStatus;
978                 char asciiCode[ 32 ];
979                 KeySym keySym;
980                 int len;
981
982                 /* Check for the ASCII/KeySym codes associated with the event: */
983                 len = XLookupString( &event.xkey, asciiCode, sizeof(asciiCode),
984                                      &keySym, &composeStatus
985                 );
986
987                 /* GLUT API tells us to have two separate callbacks... */
988                 if( len > 0 )
989                 {
990                     /* ...one for the ASCII translateable keypresses... */
991                     if( keyboard_cb )
992                     {
993                         fgSetWindow( window );
994                         fgState.Modifiers = fgPlatformGetModifiers( event.xkey.state );
995                         keyboard_cb( asciiCode[ 0 ],
996                                      event.xkey.x, event.xkey.y
997                         );
998                         fgState.Modifiers = INVALID_MODIFIERS;
999                     }
1000                 }
1001                 else
1002                 {
1003                     int special = -1;
1004
1005                     /*
1006                      * ...and one for all the others, which need to be
1007                      * translated to GLUT_KEY_Xs...
1008                      */
1009                     switch( keySym )
1010                     {
1011                     case XK_F1:     special = GLUT_KEY_F1;     break;
1012                     case XK_F2:     special = GLUT_KEY_F2;     break;
1013                     case XK_F3:     special = GLUT_KEY_F3;     break;
1014                     case XK_F4:     special = GLUT_KEY_F4;     break;
1015                     case XK_F5:     special = GLUT_KEY_F5;     break;
1016                     case XK_F6:     special = GLUT_KEY_F6;     break;
1017                     case XK_F7:     special = GLUT_KEY_F7;     break;
1018                     case XK_F8:     special = GLUT_KEY_F8;     break;
1019                     case XK_F9:     special = GLUT_KEY_F9;     break;
1020                     case XK_F10:    special = GLUT_KEY_F10;    break;
1021                     case XK_F11:    special = GLUT_KEY_F11;    break;
1022                     case XK_F12:    special = GLUT_KEY_F12;    break;
1023
1024                     case XK_KP_Left:
1025                     case XK_Left:   special = GLUT_KEY_LEFT;   break;
1026                     case XK_KP_Right:
1027                     case XK_Right:  special = GLUT_KEY_RIGHT;  break;
1028                     case XK_KP_Up:
1029                     case XK_Up:     special = GLUT_KEY_UP;     break;
1030                     case XK_KP_Down:
1031                     case XK_Down:   special = GLUT_KEY_DOWN;   break;
1032
1033                     case XK_KP_Prior:
1034                     case XK_Prior:  special = GLUT_KEY_PAGE_UP; break;
1035                     case XK_KP_Next:
1036                     case XK_Next:   special = GLUT_KEY_PAGE_DOWN; break;
1037                     case XK_KP_Home:
1038                     case XK_Home:   special = GLUT_KEY_HOME;   break;
1039                     case XK_KP_End:
1040                     case XK_End:    special = GLUT_KEY_END;    break;
1041                     case XK_KP_Insert:
1042                     case XK_Insert: special = GLUT_KEY_INSERT; break;
1043
1044                     case XK_Num_Lock :  special = GLUT_KEY_NUM_LOCK;  break;
1045                     case XK_KP_Begin :  special = GLUT_KEY_BEGIN;     break;
1046                     case XK_KP_Delete:  special = GLUT_KEY_DELETE;    break;
1047
1048                     case XK_Shift_L:   special = GLUT_KEY_SHIFT_L;    break;
1049                     case XK_Shift_R:   special = GLUT_KEY_SHIFT_R;    break;
1050                     case XK_Control_L: special = GLUT_KEY_CTRL_L;     break;
1051                     case XK_Control_R: special = GLUT_KEY_CTRL_R;     break;
1052                     case XK_Alt_L:     special = GLUT_KEY_ALT_L;      break;
1053                     case XK_Alt_R:     special = GLUT_KEY_ALT_R;      break;
1054                     }
1055
1056                     /*
1057                      * Execute the callback (if one has been specified),
1058                      * given that the special code seems to be valid...
1059                      */
1060                     if( special_cb && (special != -1) )
1061                     {
1062                         fgSetWindow( window );
1063                         fgState.Modifiers = fgPlatformGetModifiers( event.xkey.state );
1064                         special_cb( special, event.xkey.x, event.xkey.y );
1065                         fgState.Modifiers = INVALID_MODIFIERS;
1066                     }
1067                 }
1068             }
1069         }
1070         break;
1071
1072         case ReparentNotify:
1073             break; /* XXX Should disable this event */
1074
1075         /* Not handled */
1076         case GravityNotify:
1077             break;
1078
1079         default:
1080             /* enter handling of Extension Events here */
1081             #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1082                 fgHandleExtensionEvents( &event );
1083             #endif
1084             break;
1085         }
1086     }
1087 }
1088
1089
1090 static Bool match_motion(Display *dpy, XEvent *xev, XPointer arg)
1091 {
1092     return xev->type == MotionNotify;
1093 }
1094
1095 void fgPlatformMainLoopPreliminaryWork ( void )
1096 {
1097 }
1098