7cd993e6fceec6d135fb1e3b377ab174110eff87
[freeglut] / src / mswin / fg_main_mswin.c
1 /*
2  * freeglut_main_mswin.c
3  *
4  * The Windows-specific mouse cursor related stuff.
5  *
6  * Copyright (c) 2012 Stephen J. Baker. All Rights Reserved.
7  * Written by John F. Fay, <fayjf@sourceforge.net>
8  * Creation date: Sat Jan 21, 2012
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 "../fg_internal.h"
30
31
32 extern void fghRedrawWindow ( SFG_Window *window );
33
34 extern void fgNewWGLCreateContext( SFG_Window* window );
35 extern GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
36                                      unsigned char layer_type );
37
38 extern void fgPlatformCheckMenuDeactivate();
39
40 #ifdef WM_TOUCH
41 typedef BOOL (WINAPI *pGetTouchInputInfo)(HTOUCHINPUT,UINT,PTOUCHINPUT,int);
42 typedef BOOL (WINAPI *pCloseTouchInputHandle)(HTOUCHINPUT);
43 static pGetTouchInputInfo fghGetTouchInputInfo = (pGetTouchInputInfo)0xDEADBEEF;
44 static pCloseTouchInputHandle fghCloseTouchInputHandle = (pCloseTouchInputHandle)0xDEADBEEF;
45 #endif
46
47 #ifdef _WIN32_WCE
48 typedef struct GXDisplayProperties GXDisplayProperties;
49 typedef struct GXKeyList GXKeyList;
50 #include <gx.h>
51
52 typedef struct GXKeyList (*GXGETDEFAULTKEYS)(int);
53 typedef int (*GXOPENINPUT)();
54
55 GXGETDEFAULTKEYS GXGetDefaultKeys_ = NULL;
56 GXOPENINPUT GXOpenInput_ = NULL;
57
58 struct GXKeyList gxKeyList;
59 #endif /* _WIN32_WCE */
60
61
62 /* Get system time, taking special precautions against 32bit timer wrap.
63    We use timeGetTime and not GetTickCount because of its better stability,
64    and because we can increase its granularity (to 1 ms in
65    fgPlatformInitialize). For that reason we can't use GetTickCount64 which
66    wouldn't have the wrap issue.
67    Credit: this is based on code in glibc (https://mail.gnome.org/archives/commits-list/2011-November/msg04588.html)
68    */
69 static fg_time_t lastTime32 = 0;
70 static fg_time_t timeEpoch = 0;
71 void fgPlatformInitSystemTime()
72 {
73 #if defined(_WIN32_WCE)
74     lastTime32 = GetTickCount();
75 #else
76     lastTime32 = timeGetTime();
77 #endif
78 }
79 fg_time_t fgPlatformSystemTime ( void )
80 {
81     fg_time_t currTime32;
82 #if defined(_WIN32_WCE)
83     currTime32 = GetTickCount();
84 #else
85     currTime32 = timeGetTime();
86 #endif
87     /* Check if we just wrapped */
88     if (currTime32 < lastTime32)
89         timeEpoch++;
90     
91     lastTime32 = currTime32;
92
93     return currTime32 | timeEpoch << 32;
94 }
95
96
97 void fgPlatformSleepForEvents( fg_time_t msec )
98 {
99     MsgWaitForMultipleObjects( 0, NULL, FALSE, (DWORD) msec, QS_ALLINPUT );
100 }
101
102
103 void fgPlatformProcessSingleEvent ( void )
104 {
105     MSG stMsg;
106
107     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
108
109     while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
110     {
111         if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
112         {
113             if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
114             {
115                 fgDeinitialize( );
116                 exit( 0 );
117             }
118             else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
119                 fgState.ExecState = GLUT_EXEC_STATE_STOP;
120
121             return;
122         }
123
124         TranslateMessage( &stMsg );
125         DispatchMessage( &stMsg );
126     }
127 }
128
129
130
131 void fgPlatformMainLoopPreliminaryWork ( void )
132 {
133     SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
134
135     /*
136      * Processing before the main loop:  If there is a window which is open and
137      * which has a visibility callback, call it.  I know this is an ugly hack,
138      * but I'm not sure what else to do about it.  Ideally we should leave
139      * something uninitialized in the create window code and initialize it in
140      * the main loop, and have that initialization create a "WM_ACTIVATE"
141      * message.  Then we would put the visibility callback code in the
142      * "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
143      */
144     while( window )
145     {
146         if ( FETCH_WCB( *window, Visibility ) )
147         {
148             SFG_Window *current_window = fgStructure.CurrentWindow ;
149
150             INVOKE_WCB( *window, Visibility, ( window->State.Visible ) );
151             fgSetWindow( current_window );
152         }
153
154         window = (SFG_Window *)window->Node.Next ;
155     }
156 }
157
158
159 /*
160  * Determine a GLUT modifier mask based on MS-WINDOWS system info.
161  */
162 static int fgPlatformGetModifiers (void)
163 {
164     return
165         ( ( ( GetKeyState( VK_LSHIFT   ) < 0 ) ||
166             ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
167         ( ( ( GetKeyState( VK_LCONTROL ) < 0 ) ||
168             ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
169         ( ( ( GetKeyState( VK_LMENU    ) < 0 ) ||
170             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
171 }
172
173 static LRESULT fghWindowProcKeyPress(SFG_Window *window, UINT uMsg, GLboolean keydown, WPARAM wParam, LPARAM lParam)
174 {
175     static unsigned char lControl = 0, lShift = 0, lAlt = 0,
176                          rControl = 0, rShift = 0, rAlt = 0;
177
178     int keypress = -1;
179     
180     /* if keydown, check for repeat */
181     /* If repeat is globally switched off, it cannot be switched back on per window.
182      * But if it is globally switched on, it can be switched off per window. This matches
183      * GLUT's behavior on X11, but not Nate Robbins' win32 GLUT, as he didn't implement the
184      * global state switch.
185      */
186     if( keydown && ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
187         return 1;
188     
189     /* Remember the current modifiers state so user can query it from their callback */
190     fgState.Modifiers = fgPlatformGetModifiers( );
191
192     /* Convert the Win32 keystroke codes to GLUTtish way */
193 #   define KEY(a,b) case a: keypress = b; break;
194
195     switch( wParam )
196     {
197         KEY( VK_F1,     GLUT_KEY_F1        );
198         KEY( VK_F2,     GLUT_KEY_F2        );
199         KEY( VK_F3,     GLUT_KEY_F3        );
200         KEY( VK_F4,     GLUT_KEY_F4        );
201         KEY( VK_F5,     GLUT_KEY_F5        );
202         KEY( VK_F6,     GLUT_KEY_F6        );
203         KEY( VK_F7,     GLUT_KEY_F7        );
204         KEY( VK_F8,     GLUT_KEY_F8        );
205         KEY( VK_F9,     GLUT_KEY_F9        );
206         KEY( VK_F10,    GLUT_KEY_F10       );
207         KEY( VK_F11,    GLUT_KEY_F11       );
208         KEY( VK_F12,    GLUT_KEY_F12       );
209         KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
210         KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
211         KEY( VK_HOME,   GLUT_KEY_HOME      );
212         KEY( VK_END,    GLUT_KEY_END       );
213         KEY( VK_LEFT,   GLUT_KEY_LEFT      );
214         KEY( VK_UP,     GLUT_KEY_UP        );
215         KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
216         KEY( VK_DOWN,   GLUT_KEY_DOWN      );
217         KEY( VK_INSERT, GLUT_KEY_INSERT    );
218
219     /* handle control, alt and shift. For GLUT, we want to distinguish between left and right presses.
220      * The VK_L* & VK_R* left and right Alt, Ctrl and Shift virtual keys are however only used as parameters to GetAsyncKeyState() and GetKeyState()
221      * so when we get an alt, shift or control keypress here, we manually check whether it was the left or the right
222      */
223 #define ASYNC_KEY_EVENT(winKey,glutKey,keyStateVar)\
224     if (!keyStateVar && GetAsyncKeyState ( winKey ))\
225     {\
226         keypress   = glutKey;\
227         keyStateVar = 1;\
228     }\
229     else if (keyStateVar && !GetAsyncKeyState ( winKey ))\
230     {\
231         keypress   = glutKey;\
232         keyStateVar = 0;\
233     }
234     case VK_CONTROL:
235         ASYNC_KEY_EVENT(VK_LCONTROL,GLUT_KEY_CTRL_L,lControl);
236         ASYNC_KEY_EVENT(VK_RCONTROL,GLUT_KEY_CTRL_R,rControl);
237         break;
238     case VK_SHIFT:
239         ASYNC_KEY_EVENT(VK_LSHIFT,GLUT_KEY_SHIFT_L,lShift);
240         ASYNC_KEY_EVENT(VK_RSHIFT,GLUT_KEY_SHIFT_R,rShift);
241         break;
242     case VK_MENU:
243         ASYNC_KEY_EVENT(VK_LMENU,GLUT_KEY_ALT_L,lAlt);
244         ASYNC_KEY_EVENT(VK_RMENU,GLUT_KEY_ALT_R,rAlt);
245         break;
246 #undef ASYNC_KEY_EVENT
247
248     case VK_DELETE:
249         /* The delete key should be treated as an ASCII keypress: */
250         if (keydown)
251             INVOKE_WCB( *window, Keyboard,
252                         ( 127, window->State.MouseX, window->State.MouseY )
253             );
254         else
255             INVOKE_WCB( *window, KeyboardUp,
256                         ( 127, window->State.MouseX, window->State.MouseY )
257             );
258         break;
259
260 #if !defined(_WIN32_WCE)
261     default:
262         /* keydown displayable characters are handled with WM_CHAR message, but no corresponding up is generated. So get that here. */
263         if (!keydown)
264         {
265             BYTE state[ 256 ];
266             WORD code[ 2 ];
267
268             GetKeyboardState( state );
269
270             if( ToAscii( (UINT)wParam, 0, state, code, 0 ) == 1 )
271                 wParam=code[ 0 ];
272
273             INVOKE_WCB( *window, KeyboardUp,
274                    ( (char)wParam,
275                         window->State.MouseX, window->State.MouseY )
276             );
277         }
278 #endif
279     }
280
281 #if defined(_WIN32_WCE)
282     if(keydown && !(lParam & 0x40000000)) /* Prevent auto-repeat */
283     {
284         if(wParam==(unsigned)gxKeyList.vkRight)
285             keypress = GLUT_KEY_RIGHT;
286         else if(wParam==(unsigned)gxKeyList.vkLeft)
287             keypress = GLUT_KEY_LEFT;
288         else if(wParam==(unsigned)gxKeyList.vkUp)
289             keypress = GLUT_KEY_UP;
290         else if(wParam==(unsigned)gxKeyList.vkDown)
291             keypress = GLUT_KEY_DOWN;
292         else if(wParam==(unsigned)gxKeyList.vkA)
293             keypress = GLUT_KEY_F1;
294         else if(wParam==(unsigned)gxKeyList.vkB)
295             keypress = GLUT_KEY_F2;
296         else if(wParam==(unsigned)gxKeyList.vkC)
297             keypress = GLUT_KEY_F3;
298         else if(wParam==(unsigned)gxKeyList.vkStart)
299             keypress = GLUT_KEY_F4;
300     }
301 #endif
302     
303     if( keypress != -1 )
304         if (keydown)
305             INVOKE_WCB( *window, Special,
306                         ( keypress,
307                             window->State.MouseX, window->State.MouseY )
308             );
309         else
310             INVOKE_WCB( *window, SpecialUp,
311                         ( keypress,
312                             window->State.MouseX, window->State.MouseY )
313             );
314
315     fgState.Modifiers = INVALID_MODIFIERS;
316
317     /* SYSKEY events should be sent to default window proc for system to handle them */
318     if (uMsg==WM_SYSKEYDOWN || uMsg==WM_SYSKEYUP)
319         return DefWindowProc( window->Window.Handle, uMsg, wParam, lParam );
320     else
321         return 1;
322 }
323
324 void fghWindowUnderCursor(SFG_Window *window, SFG_Window **child_window)
325 {
326     /* Check if the current window that the mouse is over is a child window
327      * of the window the message was sent to. Some events only sent to main window,
328      * and when handling some messages, we need to make sure that we process
329      * callbacks on the child window instead. This mirrors how GLUT does things.
330      */
331     if (window && window->Children.First)
332     {
333         POINT mouse_pos;
334         SFG_WindowHandleType hwnd;
335         SFG_Window* temp_window;
336
337         /* Get mouse position at time of message */
338         DWORD mouse_pos_Dword = GetMessagePos();
339         mouse_pos.x = GET_X_LPARAM(mouse_pos_Dword);
340         mouse_pos.y = GET_Y_LPARAM(mouse_pos_Dword);
341         ScreenToClient( window->Window.Handle, &mouse_pos );
342         
343         hwnd = ChildWindowFromPoint(window->Window.Handle, mouse_pos);
344         if (hwnd && hwnd!=window->Window.Handle)   /* can be NULL if mouse outside parent by the time we get here, or can be same as parent if we didn't find a child */
345         {
346             temp_window = fgWindowByHandle(hwnd);
347             if (temp_window)    /* Verify we got a FreeGLUT window */
348             {
349                 *child_window = temp_window;
350                 /* ChildWindowFromPoint only searches immediate children, so search again to see if actually in grandchild or further descendant */
351                 fghWindowUnderCursor(temp_window,child_window);
352             }
353         }
354     }
355 }
356
357 /*
358  * The window procedure for handling Win32 events
359  */
360 LRESULT CALLBACK fgPlatformWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
361 {
362     SFG_Window *window;
363     LRESULT lRet = 1;
364
365     FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED ( "Event Handler" ) ;
366
367     window = fgWindowByHandle( hWnd );
368
369     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
370       return DefWindowProc( hWnd, uMsg, wParam, lParam );
371
372     /* printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0,
373              uMsg, wParam, lParam ); */
374
375     switch( uMsg )
376     {
377     case WM_CREATE:
378         /* The window structure is passed as the creation structure parameter... */
379         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
380         FREEGLUT_INTERNAL_ERROR_EXIT ( ( window != NULL ), "Cannot create window",
381                                        "fgPlatformWindowProc" );
382
383         window->Window.Handle = hWnd;
384         window->Window.pContext.Device = GetDC( hWnd );
385         if( window->IsMenu )
386         {
387             unsigned int current_DisplayMode = fgState.DisplayMode;
388             fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH;
389 #if !defined(_WIN32_WCE)
390             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
391 #endif
392             fgState.DisplayMode = current_DisplayMode;
393
394             if( fgStructure.MenuContext )
395                 wglMakeCurrent( window->Window.pContext.Device,
396                                 fgStructure.MenuContext->MContext
397                 );
398             else
399             {
400                 fgStructure.MenuContext =
401                     (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
402                 fgStructure.MenuContext->MContext =
403                     wglCreateContext( window->Window.pContext.Device );
404             }
405
406             /* window->Window.Context = wglGetCurrentContext ();   */
407             window->Window.Context = wglCreateContext( window->Window.pContext.Device );
408         }
409         else
410         {
411 #if !defined(_WIN32_WCE)
412             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
413 #endif
414
415             if( ! fgState.UseCurrentContext )
416                 window->Window.Context =
417                     wglCreateContext( window->Window.pContext.Device );
418             else
419             {
420                 window->Window.Context = wglGetCurrentContext( );
421                 if( ! window->Window.Context )
422                     window->Window.Context =
423                         wglCreateContext( window->Window.pContext.Device );
424             }
425
426 #if !defined(_WIN32_WCE)
427             fgNewWGLCreateContext( window );
428 #endif
429         }
430
431         window->State.NeedToResize = GL_TRUE;
432         /* if we used CW_USEDEFAULT (thats a negative value) for the size
433          * of the window, query the window now for the size at which it
434          * was created.
435          */
436         if( ( window->State.Width < 0 ) || ( window->State.Height < 0 ) )
437         {
438             SFG_Window *current_window = fgStructure.CurrentWindow;
439
440             fgSetWindow( window );
441             window->State.Width = glutGet( GLUT_WINDOW_WIDTH );
442             window->State.Height = glutGet( GLUT_WINDOW_HEIGHT );
443             fgSetWindow( current_window );
444         }
445
446         ReleaseDC( window->Window.Handle, window->Window.pContext.Device );
447
448 #if defined(_WIN32_WCE)
449         /* Take over button handling */
450         {
451             HINSTANCE dxDllLib=LoadLibrary(_T("gx.dll"));
452             if (dxDllLib)
453             {
454                 GXGetDefaultKeys_=(GXGETDEFAULTKEYS)GetProcAddress(dxDllLib, _T("?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z"));
455                 GXOpenInput_=(GXOPENINPUT)GetProcAddress(dxDllLib, _T("?GXOpenInput@@YAHXZ"));
456             }
457
458             if(GXOpenInput_)
459                 (*GXOpenInput_)();
460             if(GXGetDefaultKeys_)
461                 gxKeyList = (*GXGetDefaultKeys_)(GX_LANDSCAPEKEYS);
462         }
463
464 #endif /* defined(_WIN32_WCE) */
465         break;
466
467     case WM_SIZE:
468         /*
469          * If the window is visible, then it is the user manually resizing it.
470          * If it is not, then it is the system sending us a dummy resize with
471          * zero dimensions on a "glutIconifyWindow" call.
472          */
473         if( window->State.Visible )
474         {
475             /* get old values first to compare to below */
476             int width = window->State.Width, height=window->State.Height;
477 #if defined(_WIN32_WCE)
478             window->State.Width  = HIWORD(lParam);
479             window->State.Height = LOWORD(lParam);
480 #else
481             window->State.Width  = LOWORD(lParam);
482             window->State.Height = HIWORD(lParam);
483 #endif /* defined(_WIN32_WCE) */
484             
485             if (width!=window->State.Width || height!=window->State.Height)
486                 /* Something changed, need to resize */
487                 window->State.NeedToResize = GL_TRUE;
488         }
489
490         break;
491
492     case WM_MOVE:
493         {
494             SFG_Window* saved_window = fgStructure.CurrentWindow;
495             RECT windowRect;
496             GetWindowRect( window->Window.Handle, &windowRect );
497             
498             if (window->Parent)
499             {
500                 /* For child window, we should return relative to upper-left
501                 * of parent's client area.
502                 */
503                 POINT topleft = {windowRect.left,windowRect.top};
504
505                 ScreenToClient(window->Parent->Window.Handle,&topleft);
506                 windowRect.left = topleft.x;
507                 windowRect.top  = topleft.y;
508             }
509
510             INVOKE_WCB( *window, Position, ( windowRect.left, windowRect.top ) );
511             fgSetWindow(saved_window);
512         }
513         break;
514
515     case WM_SETFOCUS:
516 /*        printf("WM_SETFOCUS: %p\n", window ); */
517
518         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
519
520         SetActiveWindow( window->Window.Handle );
521         INVOKE_WCB( *window, Entry, ( GLUT_ENTERED ) );
522         UpdateWindow ( hWnd );
523
524         break;
525
526     case WM_KILLFOCUS:
527         {
528             SFG_Window* saved_window = fgStructure.CurrentWindow;
529 /*            printf("WM_KILLFOCUS: %p\n", window ); */
530             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
531             INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
532             fgSetWindow(saved_window);
533
534             /* Check if there are any open menus that need to be closed */
535             fgPlatformCheckMenuDeactivate();
536         }
537         break;
538
539 #if 0
540     case WM_ACTIVATE:
541         //printf("WM_ACTIVATE: %x %d %d\n",lParam, HIWORD(wParam), LOWORD(wParam));
542         if (LOWORD(wParam) != WA_INACTIVE)
543         {
544 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
545                    window->State.Cursor ); */
546             fgSetCursor( window, window->State.Cursor );
547         }
548
549         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
550         break;
551 #endif
552
553     case WM_SETCURSOR:
554 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
555         if( LOWORD( lParam ) == HTCLIENT )
556             fgSetCursor ( window, window->State.Cursor ) ;
557         else
558             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
559         break;
560
561     case WM_SHOWWINDOW:
562         window->State.Visible = GL_TRUE;
563         window->State.Redisplay = GL_TRUE;
564         break;
565
566     case WM_PAINT:
567     {
568         PAINTSTRUCT ps;
569         /* Turn on the visibility in case it was turned off somehow */
570         window->State.Visible = GL_TRUE;
571         InvalidateRect( hWnd, NULL, GL_FALSE ); /* Make sure whole window is repainted. Bit of a hack, but a safe one from what google turns up... */
572         BeginPaint( hWnd, &ps );
573         fghRedrawWindow( window );
574         EndPaint( hWnd, &ps );
575     }
576     break;
577
578     case WM_CLOSE:
579         fgDestroyWindow ( window );
580         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
581             PostQuitMessage(0);
582         break;
583
584     case WM_DESTROY:
585         /*
586          * The window already got destroyed, so don't bother with it.
587          */
588         return 0;
589
590     case WM_MOUSEMOVE:
591     {
592 #if defined(_WIN32_WCE)
593         window->State.MouseX = 320-HIWORD( lParam );
594         window->State.MouseY = LOWORD( lParam );
595 #else
596         window->State.MouseX = LOWORD( lParam );
597         window->State.MouseY = HIWORD( lParam );
598 #endif /* defined(_WIN32_WCE) */
599         /* Restrict to [-32768, 32767] to match X11 behaviour       */
600         /* See comment in "freeglut_developer" mailing list 10/4/04 */
601         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
602         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
603
604         if ( window->ActiveMenu )
605         {
606             fgUpdateMenuHighlight( window->ActiveMenu );
607             break;
608         }
609
610         fgState.Modifiers = fgPlatformGetModifiers( );
611
612         if( ( wParam & MK_LBUTTON ) ||
613             ( wParam & MK_MBUTTON ) ||
614             ( wParam & MK_RBUTTON ) )
615             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
616                                            window->State.MouseY ) );
617         else
618             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
619                                             window->State.MouseY ) );
620
621         fgState.Modifiers = INVALID_MODIFIERS;
622     }
623     break;
624
625     case WM_LBUTTONDOWN:
626     case WM_MBUTTONDOWN:
627     case WM_RBUTTONDOWN:
628     case WM_LBUTTONUP:
629     case WM_MBUTTONUP:
630     case WM_RBUTTONUP:
631     {
632         GLboolean pressed = GL_TRUE;
633         int button;
634
635 #if defined(_WIN32_WCE)
636         window->State.MouseX = 320-HIWORD( lParam );
637         window->State.MouseY = LOWORD( lParam );
638 #else
639         window->State.MouseX = LOWORD( lParam );
640         window->State.MouseY = HIWORD( lParam );
641 #endif /* defined(_WIN32_WCE) */
642
643         /* Restrict to [-32768, 32767] to match X11 behaviour       */
644         /* See comment in "freeglut_developer" mailing list 10/4/04 */
645         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
646         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
647
648         switch( uMsg )
649         {
650         case WM_LBUTTONDOWN:
651             pressed = GL_TRUE;
652             button = GLUT_LEFT_BUTTON;
653             break;
654         case WM_MBUTTONDOWN:
655             pressed = GL_TRUE;
656             button = GLUT_MIDDLE_BUTTON;
657             break;
658         case WM_RBUTTONDOWN:
659             pressed = GL_TRUE;
660             button = GLUT_RIGHT_BUTTON;
661             break;
662         case WM_LBUTTONUP:
663             pressed = GL_FALSE;
664             button = GLUT_LEFT_BUTTON;
665             break;
666         case WM_MBUTTONUP:
667             pressed = GL_FALSE;
668             button = GLUT_MIDDLE_BUTTON;
669             break;
670         case WM_RBUTTONUP:
671             pressed = GL_FALSE;
672             button = GLUT_RIGHT_BUTTON;
673             break;
674         default:
675             pressed = GL_FALSE;
676             button = -1;
677             break;
678         }
679
680 #if !defined(_WIN32_WCE)
681         if( GetSystemMetrics( SM_SWAPBUTTON ) )
682         {
683             if( button == GLUT_LEFT_BUTTON )
684                 button = GLUT_RIGHT_BUTTON;
685             else
686                 if( button == GLUT_RIGHT_BUTTON )
687                     button = GLUT_LEFT_BUTTON;
688         }
689 #endif /* !defined(_WIN32_WCE) */
690
691         if( button == -1 )
692             return DefWindowProc( hWnd, uMsg, lParam, wParam );
693
694         /*
695          * Do not execute the application's mouse callback if a menu
696          * is hooked to this button.  In that case an appropriate
697          * private call should be generated.
698          */
699         if( fgCheckActiveMenu( window, button, pressed,
700                                window->State.MouseX, window->State.MouseY ) )
701             break;
702
703         /* Set capture so that the window captures all the mouse messages */
704         /*
705          * XXX - Multiple button support:  Under X11, the mouse is not released
706          * XXX - from the window until all buttons have been released, even if the
707          * XXX - user presses a button in another window.  This will take more
708          * XXX - code changes than I am up to at the moment (10/5/04).  The present
709          * XXX - is a 90 percent solution.
710          */
711         if ( pressed == GL_TRUE )
712           SetCapture ( window->Window.Handle ) ;
713         else
714           ReleaseCapture () ;
715
716         if( ! FETCH_WCB( *window, Mouse ) )
717             break;
718
719         fgSetWindow( window );
720         fgState.Modifiers = fgPlatformGetModifiers( );
721
722         INVOKE_WCB(
723             *window, Mouse,
724             ( button,
725               pressed ? GLUT_DOWN : GLUT_UP,
726               window->State.MouseX,
727               window->State.MouseY
728             )
729         );
730
731         fgState.Modifiers = INVALID_MODIFIERS;
732     }
733     break;
734
735     case WM_MOUSEWHEEL:
736     {
737         SFG_Window *child_window = NULL;
738         int wheel_number = LOWORD( wParam );
739         short ticks = ( short )HIWORD( wParam );
740
741         fghWindowUnderCursor(window, &child_window);
742         if (child_window)
743             window = child_window;
744
745                 fgState.MouseWheelTicks += ticks;
746         if ( abs ( fgState.MouseWheelTicks ) >= WHEEL_DELTA )
747                 {
748                         int direction = ( fgState.MouseWheelTicks > 0 ) ? 1 : -1;
749
750             if( ! FETCH_WCB( *window, MouseWheel ) &&
751                 ! FETCH_WCB( *window, Mouse ) )
752                 break;
753
754             fgSetWindow( window );
755             fgState.Modifiers = fgPlatformGetModifiers( );
756
757             while( abs ( fgState.MouseWheelTicks ) >= WHEEL_DELTA )
758                         {
759                 if( FETCH_WCB( *window, MouseWheel ) )
760                     INVOKE_WCB( *window, MouseWheel,
761                                 ( wheel_number,
762                                   direction,
763                                   window->State.MouseX,
764                                   window->State.MouseY
765                                 )
766                     );
767                 else  /* No mouse wheel, call the mouse button callback twice */
768                                 {
769                     /*
770                      * Map wheel zero to button 3 and 4; +1 to 3, -1 to 4
771                      *  "    "   one                     +1 to 5, -1 to 6, ...
772                      *
773                      * XXX The below assumes that you have no more than 3 mouse
774                      * XXX buttons.  Sorry.
775                      */
776                     int button = wheel_number * 2 + 3;
777                     if( direction < 0 )
778                         ++button;
779                     INVOKE_WCB( *window, Mouse,
780                                 ( button, GLUT_DOWN,
781                                   window->State.MouseX, window->State.MouseY )
782                     );
783                     INVOKE_WCB( *window, Mouse,
784                                 ( button, GLUT_UP,
785                                   window->State.MouseX, window->State.MouseY )
786                     );
787                                 }
788
789                                 fgState.MouseWheelTicks -= WHEEL_DELTA * direction;
790                         }
791
792             fgState.Modifiers = INVALID_MODIFIERS;
793                 }
794     }
795     break ;
796
797     case WM_SYSKEYDOWN:
798     case WM_KEYDOWN:
799     {
800         SFG_Window *child_window = NULL;
801         fghWindowUnderCursor(window, &child_window);
802         lRet = fghWindowProcKeyPress(child_window?child_window:window,uMsg,GL_TRUE,wParam,lParam);
803     }
804     break;
805
806     case WM_SYSKEYUP:
807     case WM_KEYUP:
808     {
809         SFG_Window *child_window = NULL;
810         fghWindowUnderCursor(window, &child_window);
811         lRet = fghWindowProcKeyPress(child_window?child_window:window,uMsg,GL_FALSE,wParam,lParam);
812     }
813     break;
814
815     case WM_SYSCHAR:
816     case WM_CHAR:
817     {
818       SFG_Window *child_window = NULL;
819       fghWindowUnderCursor(window, &child_window);
820       if (child_window)
821         window = child_window;
822
823       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
824             break;
825
826         fgState.Modifiers = fgPlatformGetModifiers( );
827         INVOKE_WCB( *window, Keyboard,
828                     ( (char)wParam,
829                       window->State.MouseX, window->State.MouseY )
830         );
831         fgState.Modifiers = INVALID_MODIFIERS;
832     }
833     break;
834
835     case WM_CAPTURECHANGED:
836         /* User has finished resizing the window, force a redraw */
837         INVOKE_WCB( *window, Display, ( ) );
838
839         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
840         break;
841
842         /* Other messages that I have seen and which are not handled already */
843     case WM_SETTEXT:  /* 0x000c */
844         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
845         /* Pass it on to "DefWindowProc" to set the window text */
846         break;
847
848     case WM_GETTEXT:  /* 0x000d */
849         /* Ideally we would copy the title of the window into "lParam" */
850         /* strncpy ( (char *)lParam, "Window Title", wParam );
851            lRet = ( wParam > 12 ) ? 12 : wParam;  */
852         /* the number of characters copied */
853         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
854         break;
855
856     case WM_GETTEXTLENGTH:  /* 0x000e */
857         /* Ideally we would get the length of the title of the window */
858         lRet = 12;
859         /* the number of characters in "Window Title\0" (see above) */
860         break;
861
862     case WM_ERASEBKGND:  /* 0x0014 */
863         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
864         break;
865
866 #if !defined(_WIN32_WCE)
867     case WM_SYNCPAINT:  /* 0x0088 */
868         /* Another window has moved, need to update this one */
869         window->State.Redisplay = GL_TRUE;
870         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
871         /* Help screen says this message must be passed to "DefWindowProc" */
872         break;
873
874     case WM_NCPAINT:  /* 0x0085 */
875       /* Need to update the border of this window */
876         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
877         /* Pass it on to "DefWindowProc" to repaint a standard border */
878         break;
879
880     case WM_SYSCOMMAND :  /* 0x0112 */
881         {
882           /*
883            * We have received a system command message.  Try to act on it.
884            * The commands are passed in through the "wParam" parameter:
885            * The least significant digit seems to be which edge of the window
886            * is being used for a resize event:
887            *     4  3  5
888            *     1     2
889            *     7  6  8
890            * Congratulations and thanks to Richard Rauch for figuring this out..
891            */
892             switch ( wParam & 0xfff0 )
893             {
894             case SC_SIZE       :
895                 break ;
896
897             case SC_MOVE       :
898                 break ;
899
900             case SC_MINIMIZE   :
901                 /* User has clicked on the "-" to minimize the window */
902                 /* Turn off the visibility */
903                 window->State.Visible = GL_FALSE ;
904
905                 break ;
906
907             case SC_MAXIMIZE   :
908                 break ;
909
910             case SC_NEXTWINDOW :
911                 break ;
912
913             case SC_PREVWINDOW :
914                 break ;
915
916             case SC_CLOSE      :
917                 /* Followed very closely by a WM_CLOSE message */
918                 break ;
919
920             case SC_VSCROLL    :
921                 break ;
922
923             case SC_HSCROLL    :
924                 break ;
925
926             case SC_MOUSEMENU  :
927                 break ;
928
929             case SC_KEYMENU    :
930                 break ;
931
932             case SC_ARRANGE    :
933                 break ;
934
935             case SC_RESTORE    :
936                 break ;
937
938             case SC_TASKLIST   :
939                 break ;
940
941             case SC_SCREENSAVE :
942                 break ;
943
944             case SC_HOTKEY     :
945                 break ;
946
947 #if(WINVER >= 0x0400)
948             case SC_DEFAULT    :
949                 break ;
950
951             case SC_MONITORPOWER    :
952                 break ;
953
954             case SC_CONTEXTHELP    :
955                 break ;
956 #endif /* WINVER >= 0x0400 */
957
958             default:
959 #if _DEBUG
960                 fgWarning( "Unknown wParam type 0x%x", wParam );
961 #endif
962                 break;
963             }
964         }
965 #endif /* !defined(_WIN32_WCE) */
966
967         /* We need to pass the message on to the operating system as well */
968         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
969         break;
970
971 #ifdef WM_TOUCH
972         /* handle multi-touch messages */
973         case WM_TOUCH:
974         {
975                 unsigned int numInputs = (unsigned int)wParam;
976                 unsigned int i = 0;
977                 TOUCHINPUT* ti = (TOUCHINPUT*)malloc( sizeof(TOUCHINPUT)*numInputs);
978
979                 if (fghGetTouchInputInfo == (pGetTouchInputInfo)0xDEADBEEF) {
980                     fghGetTouchInputInfo = (pGetTouchInputInfo)GetProcAddress(GetModuleHandle("user32"),"GetTouchInputInfo");
981                     fghCloseTouchInputHandle = (pCloseTouchInputHandle)GetProcAddress(GetModuleHandle("user32"),"CloseTouchInputHandle");
982                 }
983
984                 if (!fghGetTouchInputInfo) { 
985                         free( (void*)ti );
986                         break;
987                 }
988
989                 if (fghGetTouchInputInfo( (HTOUCHINPUT)lParam, numInputs, ti, sizeof(TOUCHINPUT) )) {
990                         /* Handle each contact point */
991                         for (i = 0; i < numInputs; ++i ) {
992
993                                 POINT tp;
994                                 tp.x = TOUCH_COORD_TO_PIXEL(ti[i].x);
995                                 tp.y = TOUCH_COORD_TO_PIXEL(ti[i].y);
996                                 ScreenToClient( hWnd, &tp );
997
998                                 ti[i].dwID = ti[i].dwID * 2;
999
1000                                 if (ti[i].dwFlags & TOUCHEVENTF_DOWN) {
1001                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_ENTERED ) );
1002                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_DOWN ) );
1003                                 } else if (ti[i].dwFlags & TOUCHEVENTF_MOVE) {
1004                                         INVOKE_WCB( *window, MultiMotion, ( ti[i].dwID, tp.x, tp.y ) );
1005                                 } else if (ti[i].dwFlags & TOUCHEVENTF_UP)   { 
1006                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_UP ) );
1007                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_LEFT ) );
1008                                 }
1009                         }
1010                 }
1011                 fghCloseTouchInputHandle((HTOUCHINPUT)lParam);
1012                 free( (void*)ti );
1013                 lRet = 0; /*DefWindowProc( hWnd, uMsg, wParam, lParam );*/
1014                 break;
1015         }
1016 #endif
1017     default:
1018         /* Handle unhandled messages */
1019         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1020         break;
1021     }
1022
1023     return lRet;
1024 }