better to put code to check if menu should be deactivated in
[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  * Helper functions for getting client area from the window rect
63  * and the window rect from the client area given the style of the window
64  * (or a valid window pointer from which the style can be queried).
65  */
66 extern void fghComputeWindowRectFromClientArea_QueryWindow( const SFG_Window *window, RECT *clientRect, BOOL posIsOutside );
67 extern RECT fghGetClientArea                              ( const SFG_Window *window,                   BOOL wantPosOutside );
68
69
70 void fgPlatformReshapeWindow ( SFG_Window *window, int width, int height )
71 {
72     RECT windowRect;
73
74     /*
75      * For windowed mode, get the current position of the
76      * window and resize taking the size of the frame
77      * decorations into account.
78      */
79
80     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
81     GetWindowRect( window->Window.Handle, &windowRect );
82
83     /* Create rect in FreeGLUT format, (X,Y) topleft outside window, WxH of client area */
84     windowRect.right    = windowRect.left+width;
85     windowRect.bottom   = windowRect.top+height;
86
87     if (window->Parent == NULL)
88         /* get the window rect from this to feed to SetWindowPos, correct for window decorations */
89         fghComputeWindowRectFromClientArea_QueryWindow(window,&windowRect,TRUE);
90     else
91     {
92         /* correct rect for position client area of parent window
93          * (SetWindowPos input for child windows is in coordinates
94          * relative to the parent's client area).
95          * Child windows don't have decoration, so no need to correct
96          * for them.
97          */
98         RECT parentRect;
99         parentRect = fghGetClientArea( window->Parent, FALSE );
100         windowRect.left   -= parentRect.left;
101         windowRect.right  -= parentRect.left;
102         windowRect.top    -= parentRect.top;
103         windowRect.bottom -= parentRect.top;
104     }
105     
106     /* Do the actual resizing */
107     SetWindowPos( window->Window.Handle,
108                   HWND_TOP,
109                   windowRect.left, windowRect.top,
110                   windowRect.right - windowRect.left,
111                   windowRect.bottom- windowRect.top,
112                   SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
113                   SWP_NOZORDER
114     );
115 }
116
117
118 void fgPlatformDisplayWindow ( SFG_Window *window )
119 {
120     RedrawWindow(
121         window->Window.Handle, NULL, NULL,
122         RDW_NOERASE | RDW_INTERNALPAINT | RDW_INVALIDATE | RDW_UPDATENOW
123     );
124 }
125
126
127 fg_time_t fgPlatformSystemTime ( void )
128 {
129 #if defined(_WIN32_WCE)
130     return GetTickCount();
131 #else
132     /* TODO: do this with QueryPerformanceCounter as timeGetTime has
133      * insufficient resolution (only about 5 ms on system under low load).
134      * See:
135      * http://msdn.microsoft.com/en-us/library/windows/desktop/dd757629(v=vs.85).aspx
136      * Or maybe QueryPerformanceCounter is not a good idea either, see
137      * http://old.nabble.com/Re%3A-glutTimerFunc-does-not-detect-if-system-time-moved-backward-p33479674.html
138      * for some other ideas (at bottom)...
139      */
140     return timeGetTime();
141 #endif
142 }
143
144
145 void fgPlatformSleepForEvents( fg_time_t msec )
146 {
147     MsgWaitForMultipleObjects( 0, NULL, FALSE, (DWORD) msec, QS_ALLINPUT );
148 }
149
150
151 void fgPlatformProcessSingleEvent ( void )
152 {
153     MSG stMsg;
154
155     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutMainLoopEvent" );
156
157     while( PeekMessage( &stMsg, NULL, 0, 0, PM_NOREMOVE ) )
158     {
159         if( GetMessage( &stMsg, NULL, 0, 0 ) == 0 )
160         {
161             if( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
162             {
163                 fgDeinitialize( );
164                 exit( 0 );
165             }
166             else if( fgState.ActionOnWindowClose == GLUT_ACTION_GLUTMAINLOOP_RETURNS )
167                 fgState.ExecState = GLUT_EXEC_STATE_STOP;
168
169             return;
170         }
171
172         TranslateMessage( &stMsg );
173         DispatchMessage( &stMsg );
174     }
175 }
176
177
178
179 void fgPlatformMainLoopPreliminaryWork ( void )
180 {
181     SFG_Window *window = (SFG_Window *)fgStructure.Windows.First ;
182
183     /*
184      * Processing before the main loop:  If there is a window which is open and
185      * which has a visibility callback, call it.  I know this is an ugly hack,
186      * but I'm not sure what else to do about it.  Ideally we should leave
187      * something uninitialized in the create window code and initialize it in
188      * the main loop, and have that initialization create a "WM_ACTIVATE"
189      * message.  Then we would put the visibility callback code in the
190      * "case WM_ACTIVATE" block below.         - John Fay -- 10/24/02
191      */
192     while( window )
193     {
194         if ( FETCH_WCB( *window, Visibility ) )
195         {
196             SFG_Window *current_window = fgStructure.CurrentWindow ;
197
198             INVOKE_WCB( *window, Visibility, ( window->State.Visible ) );
199             fgSetWindow( current_window );
200         }
201
202         window = (SFG_Window *)window->Node.Next ;
203     }
204 }
205
206
207 /*
208  * Determine a GLUT modifer mask based on MS-WINDOWS system info.
209  */
210 static int fgPlatformGetModifiers (void)
211 {
212     return
213         ( ( ( GetKeyState( VK_LSHIFT   ) < 0 ) ||
214             ( GetKeyState( VK_RSHIFT   ) < 0 )) ? GLUT_ACTIVE_SHIFT : 0 ) |
215         ( ( ( GetKeyState( VK_LCONTROL ) < 0 ) ||
216             ( GetKeyState( VK_RCONTROL ) < 0 )) ? GLUT_ACTIVE_CTRL  : 0 ) |
217         ( ( ( GetKeyState( VK_LMENU    ) < 0 ) ||
218             ( GetKeyState( VK_RMENU    ) < 0 )) ? GLUT_ACTIVE_ALT   : 0 );
219 }
220
221 /*
222  * The window procedure for handling Win32 events
223  */
224 LRESULT CALLBACK fgPlatformWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam,
225                                        LPARAM lParam )
226 {
227     static unsigned char lControl = 0, rControl = 0, lShift = 0,
228                          rShift = 0, lAlt = 0, rAlt = 0;
229
230     SFG_Window *window, *child_window = NULL;
231     PAINTSTRUCT ps;
232     LRESULT lRet = 1;
233
234     FREEGLUT_INTERNAL_ERROR_EXIT_IF_NOT_INITIALISED ( "Event Handler" ) ;
235
236     window = fgWindowByHandle( hWnd );
237
238     if ( ( window == NULL ) && ( uMsg != WM_CREATE ) )
239       return DefWindowProc( hWnd, uMsg, wParam, lParam );
240
241     /* printf ( "Window %3d message <%04x> %12d %12d\n", window?window->ID:0,
242              uMsg, wParam, lParam ); */
243
244     /* Some events only sent to main window. Check if the current window that
245      * the mouse is over is a child window. Below when handling some messages,
246      * we make sure that we process callbacks on the child window instead.
247      * This mirrors how GLUT does things.
248      */
249     if (window && window->Children.First)
250     {
251         POINT mouse_pos;
252         SFG_WindowHandleType hwnd;
253         SFG_Window* temp_window;
254
255         GetCursorPos( &mouse_pos );
256         ScreenToClient( window->Window.Handle, &mouse_pos );
257         hwnd = ChildWindowFromPoint(window->Window.Handle, mouse_pos);
258         if (hwnd)   /* can be NULL if mouse outside parent by the time we get here */
259         {
260             temp_window = fgWindowByHandle(hwnd);
261             if (temp_window->Parent)    /* Verify we got a child window */
262                 child_window = temp_window;
263         }
264     }
265
266     if ( window )
267     {
268       SFG_Window* temp_window = child_window?child_window:window;
269
270       fgState.Modifiers = fgPlatformGetModifiers( );
271
272       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Down! */
273       if ( !lControl && GetAsyncKeyState ( VK_LCONTROL ) )
274       {
275           INVOKE_WCB  ( *temp_window, Special,
276                         ( GLUT_KEY_CTRL_L, temp_window->State.MouseX, temp_window->State.MouseY )
277                       );
278
279           lControl = 1;
280       }
281
282       if ( !rControl && GetAsyncKeyState ( VK_RCONTROL ) )
283       {
284           INVOKE_WCB ( *temp_window, Special,
285                        ( GLUT_KEY_CTRL_R, temp_window->State.MouseX, temp_window->State.MouseY )
286                      );
287
288           rControl = 1;
289       }
290
291       if ( !lShift && GetAsyncKeyState ( VK_LSHIFT ) )
292       {
293           INVOKE_WCB ( *temp_window, Special,
294                        ( GLUT_KEY_SHIFT_L, temp_window->State.MouseX, temp_window->State.MouseY )
295                      );
296
297           lShift = 1;
298       }
299
300       if ( !rShift && GetAsyncKeyState ( VK_RSHIFT ) )
301       {
302           INVOKE_WCB ( *temp_window, Special,
303                        ( GLUT_KEY_SHIFT_R, temp_window->State.MouseX, temp_window->State.MouseY )
304                      );
305
306           rShift = 1;
307       }
308
309       if ( !lAlt && GetAsyncKeyState ( VK_LMENU ) )
310       {
311           INVOKE_WCB ( *temp_window, Special,
312                        ( GLUT_KEY_ALT_L, temp_window->State.MouseX, temp_window->State.MouseY )
313                      );
314
315           lAlt = 1;
316       }
317
318       if ( !rAlt && GetAsyncKeyState ( VK_RMENU ) )
319       {
320           INVOKE_WCB ( *temp_window, Special,
321                        ( GLUT_KEY_ALT_R, temp_window->State.MouseX, temp_window->State.MouseY )
322                      );
323
324           rAlt = 1;
325       }
326
327       /* Checking for CTRL, ALT, and SHIFT key positions:  Key Up! */
328       if ( lControl && !GetAsyncKeyState ( VK_LCONTROL ) )
329       {
330           INVOKE_WCB ( *temp_window, SpecialUp,
331                        ( GLUT_KEY_CTRL_L, temp_window->State.MouseX, temp_window->State.MouseY )
332                      );
333
334           lControl = 0;
335       }
336
337       if ( rControl && !GetAsyncKeyState ( VK_RCONTROL ) )
338       {
339           INVOKE_WCB ( *temp_window, SpecialUp,
340                        ( GLUT_KEY_CTRL_R, temp_window->State.MouseX, temp_window->State.MouseY )
341                      );
342
343           rControl = 0;
344       }
345
346       if ( lShift && !GetAsyncKeyState ( VK_LSHIFT ) )
347       {
348           INVOKE_WCB ( *temp_window, SpecialUp,
349                        ( GLUT_KEY_SHIFT_L, temp_window->State.MouseX, temp_window->State.MouseY )
350                      );
351
352           lShift = 0;
353       }
354
355       if ( rShift && !GetAsyncKeyState ( VK_RSHIFT ) )
356       {
357           INVOKE_WCB ( *temp_window, SpecialUp,
358                        ( GLUT_KEY_SHIFT_R, temp_window->State.MouseX, temp_window->State.MouseY )
359                      );
360
361           rShift = 0;
362       }
363
364       if ( lAlt && !GetAsyncKeyState ( VK_LMENU ) )
365       {
366           INVOKE_WCB ( *temp_window, SpecialUp,
367                        ( GLUT_KEY_ALT_L, temp_window->State.MouseX, temp_window->State.MouseY )
368                      );
369
370           lAlt = 0;
371       }
372
373       if ( rAlt && !GetAsyncKeyState ( VK_RMENU ) )
374       {
375           INVOKE_WCB ( *temp_window, SpecialUp,
376                        ( GLUT_KEY_ALT_R, temp_window->State.MouseX, temp_window->State.MouseY )
377                      );
378
379           rAlt = 0;
380       }
381
382       fgState.Modifiers = INVALID_MODIFIERS;
383     }
384
385     switch( uMsg )
386     {
387     case WM_CREATE:
388         /* The window structure is passed as the creation structure parameter... */
389         window = (SFG_Window *) (((LPCREATESTRUCT) lParam)->lpCreateParams);
390         FREEGLUT_INTERNAL_ERROR_EXIT ( ( window != NULL ), "Cannot create window",
391                                        "fgPlatformWindowProc" );
392
393         window->Window.Handle = hWnd;
394         window->Window.pContext.Device = GetDC( hWnd );
395         if( window->IsMenu )
396         {
397             unsigned int current_DisplayMode = fgState.DisplayMode;
398             fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH;
399 #if !defined(_WIN32_WCE)
400             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
401 #endif
402             fgState.DisplayMode = current_DisplayMode;
403
404             if( fgStructure.MenuContext )
405                 wglMakeCurrent( window->Window.pContext.Device,
406                                 fgStructure.MenuContext->MContext
407                 );
408             else
409             {
410                 fgStructure.MenuContext =
411                     (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
412                 fgStructure.MenuContext->MContext =
413                     wglCreateContext( window->Window.pContext.Device );
414             }
415
416             /* window->Window.Context = wglGetCurrentContext ();   */
417             window->Window.Context = wglCreateContext( window->Window.pContext.Device );
418         }
419         else
420         {
421 #if !defined(_WIN32_WCE)
422             fgSetupPixelFormat( window, GL_FALSE, PFD_MAIN_PLANE );
423 #endif
424
425             if( ! fgState.UseCurrentContext )
426                 window->Window.Context =
427                     wglCreateContext( window->Window.pContext.Device );
428             else
429             {
430                 window->Window.Context = wglGetCurrentContext( );
431                 if( ! window->Window.Context )
432                     window->Window.Context =
433                         wglCreateContext( window->Window.pContext.Device );
434             }
435
436 #if !defined(_WIN32_WCE)
437             fgNewWGLCreateContext( window );
438 #endif
439         }
440
441         window->State.NeedToResize = GL_TRUE;
442         /* if we used CW_USEDEFAULT (thats a negative value) for the size
443          * of the window, query the window now for the size at which it
444          * was created.
445          */
446         if( ( window->State.Width < 0 ) || ( window->State.Height < 0 ) )
447         {
448             SFG_Window *current_window = fgStructure.CurrentWindow;
449
450             fgSetWindow( window );
451             window->State.Width = glutGet( GLUT_WINDOW_WIDTH );
452             window->State.Height = glutGet( GLUT_WINDOW_HEIGHT );
453             fgSetWindow( current_window );
454         }
455
456         ReleaseDC( window->Window.Handle, window->Window.pContext.Device );
457
458 #if defined(_WIN32_WCE)
459         /* Take over button handling */
460         {
461             HINSTANCE dxDllLib=LoadLibrary(_T("gx.dll"));
462             if (dxDllLib)
463             {
464                 GXGetDefaultKeys_=(GXGETDEFAULTKEYS)GetProcAddress(dxDllLib, _T("?GXGetDefaultKeys@@YA?AUGXKeyList@@H@Z"));
465                 GXOpenInput_=(GXOPENINPUT)GetProcAddress(dxDllLib, _T("?GXOpenInput@@YAHXZ"));
466             }
467
468             if(GXOpenInput_)
469                 (*GXOpenInput_)();
470             if(GXGetDefaultKeys_)
471                 gxKeyList = (*GXGetDefaultKeys_)(GX_LANDSCAPEKEYS);
472         }
473
474 #endif /* defined(_WIN32_WCE) */
475         break;
476
477     case WM_SIZE:
478         /*
479          * If the window is visible, then it is the user manually resizing it.
480          * If it is not, then it is the system sending us a dummy resize with
481          * zero dimensions on a "glutIconifyWindow" call.
482          */
483         if( window->State.Visible )
484         {
485             window->State.NeedToResize = GL_TRUE;
486 #if defined(_WIN32_WCE)
487             window->State.Width  = HIWORD(lParam);
488             window->State.Height = LOWORD(lParam);
489 #else
490             window->State.Width  = LOWORD(lParam);
491             window->State.Height = HIWORD(lParam);
492 #endif /* defined(_WIN32_WCE) */
493         }
494
495         break;
496
497     case WM_SETFOCUS:
498 /*        printf("WM_SETFOCUS: %p\n", window ); */
499
500         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
501
502         if (child_window)
503         {
504             /* If child should have focus instead, set it here. */
505             SetFocus(child_window->Window.Handle);
506             SetActiveWindow( child_window->Window.Handle );
507             INVOKE_WCB( *child_window, Entry, ( GLUT_ENTERED ) );
508             UpdateWindow ( child_window->Window.Handle );
509         }
510         else
511         {
512             SetActiveWindow( window->Window.Handle );
513             INVOKE_WCB( *window, Entry, ( GLUT_ENTERED ) );
514         }
515         /* Always request update on main window to be safe */
516         UpdateWindow ( hWnd );
517
518         break;
519
520     case WM_KILLFOCUS:
521         {
522             SFG_Window* saved_window = fgStructure.CurrentWindow;
523 /*            printf("WM_KILLFOCUS: %p\n", window ); */
524             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
525             INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
526             fgSetWindow(saved_window);
527
528             /* Check if there are any open menus that need to be closed */
529             fgPlatformCheckMenuDeactivate();
530         }
531         break;
532
533 #if 0
534     case WM_ACTIVATE:
535         if (LOWORD(wParam) != WA_INACTIVE)
536         {
537 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
538                    window->State.Cursor ); */
539             fgSetCursor( window, window->State.Cursor );
540         }
541
542         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
543         break;
544 #endif
545
546     case WM_SETCURSOR:
547 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
548         if( LOWORD( lParam ) == HTCLIENT )
549             fgSetCursor ( window, window->State.Cursor ) ;
550         else
551             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
552         break;
553
554     case WM_SHOWWINDOW:
555         window->State.Visible = GL_TRUE;
556         window->State.Redisplay = GL_TRUE;
557         break;
558
559     case WM_PAINT:
560         /* Turn on the visibility in case it was turned off somehow */
561         window->State.Visible = GL_TRUE;
562         InvalidateRect( hWnd, NULL, GL_FALSE ); /* Make sure whole window is repainted. Bt of a hack, but a safe on from what google turns up... */
563         BeginPaint( hWnd, &ps );
564         fghRedrawWindow( window );
565         EndPaint( hWnd, &ps );
566         break;
567
568     case WM_CLOSE:
569         fgDestroyWindow ( window );
570         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
571             PostQuitMessage(0);
572         break;
573
574     case WM_DESTROY:
575         /*
576          * The window already got destroyed, so don't bother with it.
577          */
578         return 0;
579
580     case WM_MOUSEMOVE:
581     {
582 #if defined(_WIN32_WCE)
583         window->State.MouseX = 320-HIWORD( lParam );
584         window->State.MouseY = LOWORD( lParam );
585 #else
586         window->State.MouseX = LOWORD( lParam );
587         window->State.MouseY = HIWORD( lParam );
588 #endif /* defined(_WIN32_WCE) */
589         /* Restrict to [-32768, 32767] to match X11 behaviour       */
590         /* See comment in "freeglut_developer" mailing list 10/4/04 */
591         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
592         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
593
594         if ( window->ActiveMenu )
595         {
596             fgUpdateMenuHighlight( window->ActiveMenu );
597             break;
598         }
599
600         fgState.Modifiers = fgPlatformGetModifiers( );
601
602         if( ( wParam & MK_LBUTTON ) ||
603             ( wParam & MK_MBUTTON ) ||
604             ( wParam & MK_RBUTTON ) )
605             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
606                                            window->State.MouseY ) );
607         else
608             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
609                                             window->State.MouseY ) );
610
611         fgState.Modifiers = INVALID_MODIFIERS;
612     }
613     break;
614
615     case WM_LBUTTONDOWN:
616     case WM_MBUTTONDOWN:
617     case WM_RBUTTONDOWN:
618     case WM_LBUTTONUP:
619     case WM_MBUTTONUP:
620     case WM_RBUTTONUP:
621     {
622         GLboolean pressed = GL_TRUE;
623         int button;
624
625 #if defined(_WIN32_WCE)
626         window->State.MouseX = 320-HIWORD( lParam );
627         window->State.MouseY = LOWORD( lParam );
628 #else
629         window->State.MouseX = LOWORD( lParam );
630         window->State.MouseY = HIWORD( lParam );
631 #endif /* defined(_WIN32_WCE) */
632
633         /* Restrict to [-32768, 32767] to match X11 behaviour       */
634         /* See comment in "freeglut_developer" mailing list 10/4/04 */
635         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
636         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
637
638         switch( uMsg )
639         {
640         case WM_LBUTTONDOWN:
641             pressed = GL_TRUE;
642             button = GLUT_LEFT_BUTTON;
643             break;
644         case WM_MBUTTONDOWN:
645             pressed = GL_TRUE;
646             button = GLUT_MIDDLE_BUTTON;
647             break;
648         case WM_RBUTTONDOWN:
649             pressed = GL_TRUE;
650             button = GLUT_RIGHT_BUTTON;
651             break;
652         case WM_LBUTTONUP:
653             pressed = GL_FALSE;
654             button = GLUT_LEFT_BUTTON;
655             break;
656         case WM_MBUTTONUP:
657             pressed = GL_FALSE;
658             button = GLUT_MIDDLE_BUTTON;
659             break;
660         case WM_RBUTTONUP:
661             pressed = GL_FALSE;
662             button = GLUT_RIGHT_BUTTON;
663             break;
664         default:
665             pressed = GL_FALSE;
666             button = -1;
667             break;
668         }
669
670 #if !defined(_WIN32_WCE)
671         if( GetSystemMetrics( SM_SWAPBUTTON ) )
672         {
673             if( button == GLUT_LEFT_BUTTON )
674                 button = GLUT_RIGHT_BUTTON;
675             else
676                 if( button == GLUT_RIGHT_BUTTON )
677                     button = GLUT_LEFT_BUTTON;
678         }
679 #endif /* !defined(_WIN32_WCE) */
680
681         if( button == -1 )
682             return DefWindowProc( hWnd, uMsg, lParam, wParam );
683
684         /*
685          * Do not execute the application's mouse callback if a menu
686          * is hooked to this button.  In that case an appropriate
687          * private call should be generated.
688          */
689         if( fgCheckActiveMenu( window, button, pressed,
690                                window->State.MouseX, window->State.MouseY ) )
691             break;
692
693         /* Set capture so that the window captures all the mouse messages */
694         /*
695          * XXX - Multiple button support:  Under X11, the mouse is not released
696          * XXX - from the window until all buttons have been released, even if the
697          * XXX - user presses a button in another window.  This will take more
698          * XXX - code changes than I am up to at the moment (10/5/04).  The present
699          * XXX - is a 90 percent solution.
700          */
701         if ( pressed == GL_TRUE )
702           SetCapture ( window->Window.Handle ) ;
703         else
704           ReleaseCapture () ;
705
706         if( ! FETCH_WCB( *window, Mouse ) )
707             break;
708
709         fgSetWindow( window );
710         fgState.Modifiers = fgPlatformGetModifiers( );
711
712         INVOKE_WCB(
713             *window, Mouse,
714             ( button,
715               pressed ? GLUT_DOWN : GLUT_UP,
716               window->State.MouseX,
717               window->State.MouseY
718             )
719         );
720
721         fgState.Modifiers = INVALID_MODIFIERS;
722     }
723     break;
724
725     case WM_MOUSEWHEEL:
726     {
727         int wheel_number = LOWORD( wParam );
728         short ticks = ( short )HIWORD( wParam );
729                 fgState.MouseWheelTicks += ticks;
730
731         /*
732          * XXX Should use WHEEL_DELTA instead of 120
733          */
734                 if ( abs ( fgState.MouseWheelTicks ) >= 120 )
735                 {
736                         int direction = ( fgState.MouseWheelTicks > 0 ) ? 1 : -1;
737
738             if( ! FETCH_WCB( *window, MouseWheel ) &&
739                 ! FETCH_WCB( *window, Mouse ) )
740                 break;
741
742             fgSetWindow( window );
743             fgState.Modifiers = fgPlatformGetModifiers( );
744
745             /*
746              * XXX Should use WHEEL_DELTA instead of 120
747              */
748             while( abs ( fgState.MouseWheelTicks ) >= 120 )
749                         {
750                 if( FETCH_WCB( *window, MouseWheel ) )
751                     INVOKE_WCB( *window, MouseWheel,
752                                 ( wheel_number,
753                                   direction,
754                                   window->State.MouseX,
755                                   window->State.MouseY
756                                 )
757                     );
758                 else  /* No mouse wheel, call the mouse button callback twice */
759                                 {
760                     /*
761                      * Map wheel zero to button 3 and 4; +1 to 3, -1 to 4
762                      *  "    "   one                     +1 to 5, -1 to 6, ...
763                      *
764                      * XXX The below assumes that you have no more than 3 mouse
765                      * XXX buttons.  Sorry.
766                      */
767                     int button = wheel_number * 2 + 3;
768                     if( direction < 0 )
769                         ++button;
770                     INVOKE_WCB( *window, Mouse,
771                                 ( button, GLUT_DOWN,
772                                   window->State.MouseX, window->State.MouseY )
773                     );
774                     INVOKE_WCB( *window, Mouse,
775                                 ( button, GLUT_UP,
776                                   window->State.MouseX, window->State.MouseY )
777                     );
778                                 }
779
780                 /*
781                  * XXX Should use WHEEL_DELTA instead of 120
782                  */
783                                 fgState.MouseWheelTicks -= 120 * direction;
784                         }
785
786             fgState.Modifiers = INVALID_MODIFIERS;
787                 }
788     }
789     break ;
790
791     case WM_SYSKEYDOWN:
792     case WM_KEYDOWN:
793     {
794         int keypress = -1;
795         POINT mouse_pos ;
796
797         if (child_window)
798             window = child_window;
799
800         if( ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
801             break;
802
803         /*
804          * Remember the current modifiers state. This is done here in order
805          * to make sure the VK_DELETE keyboard callback is executed properly.
806          */
807         fgState.Modifiers = fgPlatformGetModifiers( );
808
809         GetCursorPos( &mouse_pos );
810         ScreenToClient( window->Window.Handle, &mouse_pos );
811
812         window->State.MouseX = mouse_pos.x;
813         window->State.MouseY = mouse_pos.y;
814
815         /* Convert the Win32 keystroke codes to GLUTtish way */
816 #       define KEY(a,b) case a: keypress = b; break;
817
818         switch( wParam )
819         {
820             KEY( VK_F1,     GLUT_KEY_F1        );
821             KEY( VK_F2,     GLUT_KEY_F2        );
822             KEY( VK_F3,     GLUT_KEY_F3        );
823             KEY( VK_F4,     GLUT_KEY_F4        );
824             KEY( VK_F5,     GLUT_KEY_F5        );
825             KEY( VK_F6,     GLUT_KEY_F6        );
826             KEY( VK_F7,     GLUT_KEY_F7        );
827             KEY( VK_F8,     GLUT_KEY_F8        );
828             KEY( VK_F9,     GLUT_KEY_F9        );
829             KEY( VK_F10,    GLUT_KEY_F10       );
830             KEY( VK_F11,    GLUT_KEY_F11       );
831             KEY( VK_F12,    GLUT_KEY_F12       );
832             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
833             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
834             KEY( VK_HOME,   GLUT_KEY_HOME      );
835             KEY( VK_END,    GLUT_KEY_END       );
836             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
837             KEY( VK_UP,     GLUT_KEY_UP        );
838             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
839             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
840             KEY( VK_INSERT, GLUT_KEY_INSERT    );
841
842         case VK_LCONTROL:  case VK_RCONTROL:  case VK_CONTROL:
843         case VK_LSHIFT:    case VK_RSHIFT:    case VK_SHIFT:
844         case VK_LMENU:     case VK_RMENU:     case VK_MENU:
845             /* These keypresses and releases are handled earlier in the function */
846             break;
847
848         case VK_DELETE:
849             /* The delete key should be treated as an ASCII keypress: */
850             INVOKE_WCB( *window, Keyboard,
851                         ( 127, window->State.MouseX, window->State.MouseY )
852             );
853         }
854
855 #if defined(_WIN32_WCE)
856         if(!(lParam & 0x40000000)) /* Prevent auto-repeat */
857         {
858             if(wParam==(unsigned)gxKeyList.vkRight)
859                 keypress = GLUT_KEY_RIGHT;
860             else if(wParam==(unsigned)gxKeyList.vkLeft)
861                 keypress = GLUT_KEY_LEFT;
862             else if(wParam==(unsigned)gxKeyList.vkUp)
863                 keypress = GLUT_KEY_UP;
864             else if(wParam==(unsigned)gxKeyList.vkDown)
865                 keypress = GLUT_KEY_DOWN;
866             else if(wParam==(unsigned)gxKeyList.vkA)
867                 keypress = GLUT_KEY_F1;
868             else if(wParam==(unsigned)gxKeyList.vkB)
869                 keypress = GLUT_KEY_F2;
870             else if(wParam==(unsigned)gxKeyList.vkC)
871                 keypress = GLUT_KEY_F3;
872             else if(wParam==(unsigned)gxKeyList.vkStart)
873                 keypress = GLUT_KEY_F4;
874         }
875 #endif
876
877         if( keypress != -1 )
878             INVOKE_WCB( *window, Special,
879                         ( keypress,
880                           window->State.MouseX, window->State.MouseY )
881             );
882
883         fgState.Modifiers = INVALID_MODIFIERS;
884     }
885     break;
886
887     case WM_SYSKEYUP:
888     case WM_KEYUP:
889     {
890         int keypress = -1;
891         POINT mouse_pos;
892
893         if (child_window)
894             window = child_window;
895
896         /*
897          * Remember the current modifiers state. This is done here in order
898          * to make sure the VK_DELETE keyboard callback is executed properly.
899          */
900         fgState.Modifiers = fgPlatformGetModifiers( );
901
902         GetCursorPos( &mouse_pos );
903         ScreenToClient( window->Window.Handle, &mouse_pos );
904
905         window->State.MouseX = mouse_pos.x;
906         window->State.MouseY = mouse_pos.y;
907
908         /*
909          * Convert the Win32 keystroke codes to GLUTtish way.
910          * "KEY(a,b)" was defined under "WM_KEYDOWN"
911          */
912
913         switch( wParam )
914         {
915             KEY( VK_F1,     GLUT_KEY_F1        );
916             KEY( VK_F2,     GLUT_KEY_F2        );
917             KEY( VK_F3,     GLUT_KEY_F3        );
918             KEY( VK_F4,     GLUT_KEY_F4        );
919             KEY( VK_F5,     GLUT_KEY_F5        );
920             KEY( VK_F6,     GLUT_KEY_F6        );
921             KEY( VK_F7,     GLUT_KEY_F7        );
922             KEY( VK_F8,     GLUT_KEY_F8        );
923             KEY( VK_F9,     GLUT_KEY_F9        );
924             KEY( VK_F10,    GLUT_KEY_F10       );
925             KEY( VK_F11,    GLUT_KEY_F11       );
926             KEY( VK_F12,    GLUT_KEY_F12       );
927             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
928             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
929             KEY( VK_HOME,   GLUT_KEY_HOME      );
930             KEY( VK_END,    GLUT_KEY_END       );
931             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
932             KEY( VK_UP,     GLUT_KEY_UP        );
933             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
934             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
935             KEY( VK_INSERT, GLUT_KEY_INSERT    );
936
937           case VK_LCONTROL:  case VK_RCONTROL:  case VK_CONTROL:
938           case VK_LSHIFT:    case VK_RSHIFT:    case VK_SHIFT:
939           case VK_LMENU:     case VK_RMENU:     case VK_MENU:
940               /* These keypresses and releases are handled earlier in the function */
941               break;
942
943           case VK_DELETE:
944               /* The delete key should be treated as an ASCII keypress: */
945               INVOKE_WCB( *window, KeyboardUp,
946                           ( 127, window->State.MouseX, window->State.MouseY )
947               );
948               break;
949
950         default:
951         {
952 #if !defined(_WIN32_WCE)
953             BYTE state[ 256 ];
954             WORD code[ 2 ];
955
956             GetKeyboardState( state );
957
958             if( ToAscii( (UINT)wParam, 0, state, code, 0 ) == 1 )
959                 wParam=code[ 0 ];
960
961             INVOKE_WCB( *window, KeyboardUp,
962                         ( (char)wParam,
963                           window->State.MouseX, window->State.MouseY )
964             );
965 #endif /* !defined(_WIN32_WCE) */
966         }
967         }
968
969         if( keypress != -1 )
970             INVOKE_WCB( *window, SpecialUp,
971                         ( keypress,
972                           window->State.MouseX, window->State.MouseY )
973             );
974
975         fgState.Modifiers = INVALID_MODIFIERS;
976     }
977     break;
978
979     case WM_SYSCHAR:
980     case WM_CHAR:
981     {
982       if (child_window)
983         window = child_window;
984
985       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
986             break;
987
988         fgState.Modifiers = fgPlatformGetModifiers( );
989         INVOKE_WCB( *window, Keyboard,
990                     ( (char)wParam,
991                       window->State.MouseX, window->State.MouseY )
992         );
993         fgState.Modifiers = INVALID_MODIFIERS;
994     }
995     break;
996
997     case WM_CAPTURECHANGED:
998         /* User has finished resizing the window, force a redraw */
999         INVOKE_WCB( *window, Display, ( ) );
1000
1001         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
1002         break;
1003
1004         /* Other messages that I have seen and which are not handled already */
1005     case WM_SETTEXT:  /* 0x000c */
1006         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1007         /* Pass it on to "DefWindowProc" to set the window text */
1008         break;
1009
1010     case WM_GETTEXT:  /* 0x000d */
1011         /* Ideally we would copy the title of the window into "lParam" */
1012         /* strncpy ( (char *)lParam, "Window Title", wParam );
1013            lRet = ( wParam > 12 ) ? 12 : wParam;  */
1014         /* the number of characters copied */
1015         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1016         break;
1017
1018     case WM_GETTEXTLENGTH:  /* 0x000e */
1019         /* Ideally we would get the length of the title of the window */
1020         lRet = 12;
1021         /* the number of characters in "Window Title\0" (see above) */
1022         break;
1023
1024     case WM_ERASEBKGND:  /* 0x0014 */
1025         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1026         break;
1027
1028 #if !defined(_WIN32_WCE)
1029     case WM_SYNCPAINT:  /* 0x0088 */
1030         /* Another window has moved, need to update this one */
1031         window->State.Redisplay = GL_TRUE;
1032         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1033         /* Help screen says this message must be passed to "DefWindowProc" */
1034         break;
1035
1036     case WM_NCPAINT:  /* 0x0085 */
1037       /* Need to update the border of this window */
1038         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1039         /* Pass it on to "DefWindowProc" to repaint a standard border */
1040         break;
1041
1042     case WM_SYSCOMMAND :  /* 0x0112 */
1043         {
1044           /*
1045            * We have received a system command message.  Try to act on it.
1046            * The commands are passed in through the "wParam" parameter:
1047            * The least significant digit seems to be which edge of the window
1048            * is being used for a resize event:
1049            *     4  3  5
1050            *     1     2
1051            *     7  6  8
1052            * Congratulations and thanks to Richard Rauch for figuring this out..
1053            */
1054             switch ( wParam & 0xfff0 )
1055             {
1056             case SC_SIZE       :
1057                 break ;
1058
1059             case SC_MOVE       :
1060                 break ;
1061
1062             case SC_MINIMIZE   :
1063                 /* User has clicked on the "-" to minimize the window */
1064                 /* Turn off the visibility */
1065                 window->State.Visible = GL_FALSE ;
1066
1067                 break ;
1068
1069             case SC_MAXIMIZE   :
1070                 break ;
1071
1072             case SC_NEXTWINDOW :
1073                 break ;
1074
1075             case SC_PREVWINDOW :
1076                 break ;
1077
1078             case SC_CLOSE      :
1079                 /* Followed very closely by a WM_CLOSE message */
1080                 break ;
1081
1082             case SC_VSCROLL    :
1083                 break ;
1084
1085             case SC_HSCROLL    :
1086                 break ;
1087
1088             case SC_MOUSEMENU  :
1089                 break ;
1090
1091             case SC_KEYMENU    :
1092                 break ;
1093
1094             case SC_ARRANGE    :
1095                 break ;
1096
1097             case SC_RESTORE    :
1098                 break ;
1099
1100             case SC_TASKLIST   :
1101                 break ;
1102
1103             case SC_SCREENSAVE :
1104                 break ;
1105
1106             case SC_HOTKEY     :
1107                 break ;
1108
1109 #if(WINVER >= 0x0400)
1110             case SC_DEFAULT    :
1111                 break ;
1112
1113             case SC_MONITORPOWER    :
1114                 break ;
1115
1116             case SC_CONTEXTHELP    :
1117                 break ;
1118 #endif /* WINVER >= 0x0400 */
1119
1120             default:
1121 #if _DEBUG
1122                 fgWarning( "Unknown wParam type 0x%x", wParam );
1123 #endif
1124                 break;
1125             }
1126         }
1127 #endif /* !defined(_WIN32_WCE) */
1128
1129         /* We need to pass the message on to the operating system as well */
1130         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1131         break;
1132
1133 #ifdef WM_TOUCH
1134         /* handle multi-touch messages */
1135         case WM_TOUCH:
1136         {
1137                 unsigned int numInputs = (unsigned int)wParam;
1138                 unsigned int i = 0;
1139                 TOUCHINPUT* ti = (TOUCHINPUT*)malloc( sizeof(TOUCHINPUT)*numInputs);
1140
1141                 if (fghGetTouchInputInfo == (pGetTouchInputInfo)0xDEADBEEF) {
1142                     fghGetTouchInputInfo = (pGetTouchInputInfo)GetProcAddress(GetModuleHandle("user32"),"GetTouchInputInfo");
1143                     fghCloseTouchInputHandle = (pCloseTouchInputHandle)GetProcAddress(GetModuleHandle("user32"),"CloseTouchInputHandle");
1144                 }
1145
1146                 if (!fghGetTouchInputInfo) { 
1147                         free( (void*)ti );
1148                         break;
1149                 }
1150
1151                 if (fghGetTouchInputInfo( (HTOUCHINPUT)lParam, numInputs, ti, sizeof(TOUCHINPUT) )) {
1152                         /* Handle each contact point */
1153                         for (i = 0; i < numInputs; ++i ) {
1154
1155                                 POINT tp;
1156                                 tp.x = TOUCH_COORD_TO_PIXEL(ti[i].x);
1157                                 tp.y = TOUCH_COORD_TO_PIXEL(ti[i].y);
1158                                 ScreenToClient( hWnd, &tp );
1159
1160                                 ti[i].dwID = ti[i].dwID * 2;
1161
1162                                 if (ti[i].dwFlags & TOUCHEVENTF_DOWN) {
1163                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_ENTERED ) );
1164                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_DOWN ) );
1165                                 } else if (ti[i].dwFlags & TOUCHEVENTF_MOVE) {
1166                                         INVOKE_WCB( *window, MultiMotion, ( ti[i].dwID, tp.x, tp.y ) );
1167                                 } else if (ti[i].dwFlags & TOUCHEVENTF_UP)   { 
1168                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_UP ) );
1169                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_LEFT ) );
1170                                 }
1171                         }
1172                 }
1173                 fghCloseTouchInputHandle((HTOUCHINPUT)lParam);
1174                 free( (void*)ti );
1175                 lRet = 0; /*DefWindowProc( hWnd, uMsg, wParam, lParam );*/
1176                 break;
1177         }
1178 #endif
1179     default:
1180         /* Handle unhandled messages */
1181         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1182         break;
1183     }
1184
1185     return lRet;
1186 }