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