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