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