now added fix suggested by Ioannis to make menus work when an entryfunc
[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             SFG_Window* saved_window = fgStructure.CurrentWindow;
522 /*            printf("WM_KILLFOCUS: %p\n", window ); */
523             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
524             INVOKE_WCB( *window, Entry, ( GLUT_LEFT ) );
525             fgSetWindow(saved_window);
526
527             /* If we have an open menu, see if the open menu should be closed
528              * when focus was lost because user either switched
529              * application or FreeGLUT window (if one is running multiple
530              * windows). If so, close menu the active menu.
531              */
532             if ( fgStructure.Menus.First )
533                 menu = fgGetActiveMenu();
534
535             if ( menu )
536             {
537                 SFG_Window* wnd = NULL;
538                 HWND hwnd = GetFocus();  /* Get window with current focus - NULL for non freeglut windows */
539                 if (hwnd)
540                     /* See which of our windows it is */
541                     wnd = fgWindowByHandle(hwnd);
542
543                 if (!hwnd || !wnd)
544                     /* User switched to another application*/
545                     fgDeactivateMenu(menu->ParentWindow);
546                 else if (!wnd->IsMenu)      /* Make sure we don't kill the menu when trying to enter a submenu */
547                 {
548                     if (wnd!=menu->ParentWindow)
549                         /* User switched to another FreeGLUT window */
550                         fgDeactivateMenu(menu->ParentWindow);
551                     else
552                     {
553                         /* Check if focus lost because non-client area of
554                          * window was pressed (pressing on client area is
555                          * handled in fgCheckActiveMenu)
556                          */
557                         POINT mouse_pos;
558                         RECT clientArea = fghGetClientArea(menu->ParentWindow, GL_FALSE);
559                         GetCursorPos(&mouse_pos);
560                         if ( !PtInRect( &clientArea, mouse_pos ) )
561                             fgDeactivateMenu(menu->ParentWindow);
562                     }
563                 }
564             }
565         }
566         break;
567
568 #if 0
569     case WM_ACTIVATE:
570         if (LOWORD(wParam) != WA_INACTIVE)
571         {
572 /*            printf("WM_ACTIVATE: fgSetCursor( %p, %d)\n", window,
573                    window->State.Cursor ); */
574             fgSetCursor( window, window->State.Cursor );
575         }
576
577         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
578         break;
579 #endif
580
581     case WM_SETCURSOR:
582 /*      printf ( "Cursor event %x %x %x %x\n", window, window->State.Cursor, lParam, wParam ) ; */
583         if( LOWORD( lParam ) == HTCLIENT )
584             fgSetCursor ( window, window->State.Cursor ) ;
585         else
586             lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
587         break;
588
589     case WM_SHOWWINDOW:
590         window->State.Visible = GL_TRUE;
591         window->State.Redisplay = GL_TRUE;
592         break;
593
594     case WM_PAINT:
595         /* Turn on the visibility in case it was turned off somehow */
596         window->State.Visible = GL_TRUE;
597         BeginPaint( hWnd, &ps );
598         fghRedrawWindow( window );
599         EndPaint( hWnd, &ps );
600         break;
601
602     case WM_CLOSE:
603         fgDestroyWindow ( window );
604         if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
605             PostQuitMessage(0);
606         break;
607
608     case WM_DESTROY:
609         /*
610          * The window already got destroyed, so don't bother with it.
611          */
612         return 0;
613
614     case WM_MOUSEMOVE:
615     {
616 #if defined(_WIN32_WCE)
617         window->State.MouseX = 320-HIWORD( lParam );
618         window->State.MouseY = LOWORD( lParam );
619 #else
620         window->State.MouseX = LOWORD( lParam );
621         window->State.MouseY = HIWORD( lParam );
622 #endif /* defined(_WIN32_WCE) */
623         /* Restrict to [-32768, 32767] to match X11 behaviour       */
624         /* See comment in "freeglut_developer" mailing list 10/4/04 */
625         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
626         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
627
628         if ( window->ActiveMenu )
629         {
630             fgUpdateMenuHighlight( window->ActiveMenu );
631             break;
632         }
633
634         fgState.Modifiers = fgPlatformGetModifiers( );
635
636         if( ( wParam & MK_LBUTTON ) ||
637             ( wParam & MK_MBUTTON ) ||
638             ( wParam & MK_RBUTTON ) )
639             INVOKE_WCB( *window, Motion, ( window->State.MouseX,
640                                            window->State.MouseY ) );
641         else
642             INVOKE_WCB( *window, Passive, ( window->State.MouseX,
643                                             window->State.MouseY ) );
644
645         fgState.Modifiers = INVALID_MODIFIERS;
646     }
647     break;
648
649     case WM_LBUTTONDOWN:
650     case WM_MBUTTONDOWN:
651     case WM_RBUTTONDOWN:
652     case WM_LBUTTONUP:
653     case WM_MBUTTONUP:
654     case WM_RBUTTONUP:
655     {
656         GLboolean pressed = GL_TRUE;
657         int button;
658
659 #if defined(_WIN32_WCE)
660         window->State.MouseX = 320-HIWORD( lParam );
661         window->State.MouseY = LOWORD( lParam );
662 #else
663         window->State.MouseX = LOWORD( lParam );
664         window->State.MouseY = HIWORD( lParam );
665 #endif /* defined(_WIN32_WCE) */
666
667         /* Restrict to [-32768, 32767] to match X11 behaviour       */
668         /* See comment in "freeglut_developer" mailing list 10/4/04 */
669         if ( window->State.MouseX > 32767 ) window->State.MouseX -= 65536;
670         if ( window->State.MouseY > 32767 ) window->State.MouseY -= 65536;
671
672         switch( uMsg )
673         {
674         case WM_LBUTTONDOWN:
675             pressed = GL_TRUE;
676             button = GLUT_LEFT_BUTTON;
677             break;
678         case WM_MBUTTONDOWN:
679             pressed = GL_TRUE;
680             button = GLUT_MIDDLE_BUTTON;
681             break;
682         case WM_RBUTTONDOWN:
683             pressed = GL_TRUE;
684             button = GLUT_RIGHT_BUTTON;
685             break;
686         case WM_LBUTTONUP:
687             pressed = GL_FALSE;
688             button = GLUT_LEFT_BUTTON;
689             break;
690         case WM_MBUTTONUP:
691             pressed = GL_FALSE;
692             button = GLUT_MIDDLE_BUTTON;
693             break;
694         case WM_RBUTTONUP:
695             pressed = GL_FALSE;
696             button = GLUT_RIGHT_BUTTON;
697             break;
698         default:
699             pressed = GL_FALSE;
700             button = -1;
701             break;
702         }
703
704 #if !defined(_WIN32_WCE)
705         if( GetSystemMetrics( SM_SWAPBUTTON ) )
706         {
707             if( button == GLUT_LEFT_BUTTON )
708                 button = GLUT_RIGHT_BUTTON;
709             else
710                 if( button == GLUT_RIGHT_BUTTON )
711                     button = GLUT_LEFT_BUTTON;
712         }
713 #endif /* !defined(_WIN32_WCE) */
714
715         if( button == -1 )
716             return DefWindowProc( hWnd, uMsg, lParam, wParam );
717
718         /*
719          * Do not execute the application's mouse callback if a menu
720          * is hooked to this button.  In that case an appropriate
721          * private call should be generated.
722          */
723         if( fgCheckActiveMenu( window, button, pressed,
724                                window->State.MouseX, window->State.MouseY ) )
725             break;
726
727         /* Set capture so that the window captures all the mouse messages */
728         /*
729          * XXX - Multiple button support:  Under X11, the mouse is not released
730          * XXX - from the window until all buttons have been released, even if the
731          * XXX - user presses a button in another window.  This will take more
732          * XXX - code changes than I am up to at the moment (10/5/04).  The present
733          * XXX - is a 90 percent solution.
734          */
735         if ( pressed == GL_TRUE )
736           SetCapture ( window->Window.Handle ) ;
737         else
738           ReleaseCapture () ;
739
740         if( ! FETCH_WCB( *window, Mouse ) )
741             break;
742
743         fgSetWindow( window );
744         fgState.Modifiers = fgPlatformGetModifiers( );
745
746         INVOKE_WCB(
747             *window, Mouse,
748             ( button,
749               pressed ? GLUT_DOWN : GLUT_UP,
750               window->State.MouseX,
751               window->State.MouseY
752             )
753         );
754
755         fgState.Modifiers = INVALID_MODIFIERS;
756     }
757     break;
758
759     case WM_MOUSEWHEEL:
760     {
761         int wheel_number = LOWORD( wParam );
762         short ticks = ( short )HIWORD( wParam );
763                 fgState.MouseWheelTicks += ticks;
764
765         /*
766          * XXX Should use WHEEL_DELTA instead of 120
767          */
768                 if ( abs ( fgState.MouseWheelTicks ) >= 120 )
769                 {
770                         int direction = ( fgState.MouseWheelTicks > 0 ) ? 1 : -1;
771
772             if( ! FETCH_WCB( *window, MouseWheel ) &&
773                 ! FETCH_WCB( *window, Mouse ) )
774                 break;
775
776             fgSetWindow( window );
777             fgState.Modifiers = fgPlatformGetModifiers( );
778
779             /*
780              * XXX Should use WHEEL_DELTA instead of 120
781              */
782             while( abs ( fgState.MouseWheelTicks ) >= 120 )
783                         {
784                 if( FETCH_WCB( *window, MouseWheel ) )
785                     INVOKE_WCB( *window, MouseWheel,
786                                 ( wheel_number,
787                                   direction,
788                                   window->State.MouseX,
789                                   window->State.MouseY
790                                 )
791                     );
792                 else  /* No mouse wheel, call the mouse button callback twice */
793                                 {
794                     /*
795                      * Map wheel zero to button 3 and 4; +1 to 3, -1 to 4
796                      *  "    "   one                     +1 to 5, -1 to 6, ...
797                      *
798                      * XXX The below assumes that you have no more than 3 mouse
799                      * XXX buttons.  Sorry.
800                      */
801                     int button = wheel_number * 2 + 3;
802                     if( direction < 0 )
803                         ++button;
804                     INVOKE_WCB( *window, Mouse,
805                                 ( button, GLUT_DOWN,
806                                   window->State.MouseX, window->State.MouseY )
807                     );
808                     INVOKE_WCB( *window, Mouse,
809                                 ( button, GLUT_UP,
810                                   window->State.MouseX, window->State.MouseY )
811                     );
812                                 }
813
814                 /*
815                  * XXX Should use WHEEL_DELTA instead of 120
816                  */
817                                 fgState.MouseWheelTicks -= 120 * direction;
818                         }
819
820             fgState.Modifiers = INVALID_MODIFIERS;
821                 }
822     }
823     break ;
824
825     case WM_SYSKEYDOWN:
826     case WM_KEYDOWN:
827     {
828         int keypress = -1;
829         POINT mouse_pos ;
830
831         if (child_window)
832             window = child_window;
833
834         if( ( fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE ) && (HIWORD(lParam) & KF_REPEAT) )
835             break;
836
837         /*
838          * Remember the current modifiers state. This is done here in order
839          * to make sure the VK_DELETE keyboard callback is executed properly.
840          */
841         fgState.Modifiers = fgPlatformGetModifiers( );
842
843         GetCursorPos( &mouse_pos );
844         ScreenToClient( window->Window.Handle, &mouse_pos );
845
846         window->State.MouseX = mouse_pos.x;
847         window->State.MouseY = mouse_pos.y;
848
849         /* Convert the Win32 keystroke codes to GLUTtish way */
850 #       define KEY(a,b) case a: keypress = b; break;
851
852         switch( wParam )
853         {
854             KEY( VK_F1,     GLUT_KEY_F1        );
855             KEY( VK_F2,     GLUT_KEY_F2        );
856             KEY( VK_F3,     GLUT_KEY_F3        );
857             KEY( VK_F4,     GLUT_KEY_F4        );
858             KEY( VK_F5,     GLUT_KEY_F5        );
859             KEY( VK_F6,     GLUT_KEY_F6        );
860             KEY( VK_F7,     GLUT_KEY_F7        );
861             KEY( VK_F8,     GLUT_KEY_F8        );
862             KEY( VK_F9,     GLUT_KEY_F9        );
863             KEY( VK_F10,    GLUT_KEY_F10       );
864             KEY( VK_F11,    GLUT_KEY_F11       );
865             KEY( VK_F12,    GLUT_KEY_F12       );
866             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
867             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
868             KEY( VK_HOME,   GLUT_KEY_HOME      );
869             KEY( VK_END,    GLUT_KEY_END       );
870             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
871             KEY( VK_UP,     GLUT_KEY_UP        );
872             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
873             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
874             KEY( VK_INSERT, GLUT_KEY_INSERT    );
875
876         case VK_LCONTROL:  case VK_RCONTROL:  case VK_CONTROL:
877         case VK_LSHIFT:    case VK_RSHIFT:    case VK_SHIFT:
878         case VK_LMENU:     case VK_RMENU:     case VK_MENU:
879             /* These keypresses and releases are handled earlier in the function */
880             break;
881
882         case VK_DELETE:
883             /* The delete key should be treated as an ASCII keypress: */
884             INVOKE_WCB( *window, Keyboard,
885                         ( 127, window->State.MouseX, window->State.MouseY )
886             );
887         }
888
889 #if defined(_WIN32_WCE)
890         if(!(lParam & 0x40000000)) /* Prevent auto-repeat */
891         {
892             if(wParam==(unsigned)gxKeyList.vkRight)
893                 keypress = GLUT_KEY_RIGHT;
894             else if(wParam==(unsigned)gxKeyList.vkLeft)
895                 keypress = GLUT_KEY_LEFT;
896             else if(wParam==(unsigned)gxKeyList.vkUp)
897                 keypress = GLUT_KEY_UP;
898             else if(wParam==(unsigned)gxKeyList.vkDown)
899                 keypress = GLUT_KEY_DOWN;
900             else if(wParam==(unsigned)gxKeyList.vkA)
901                 keypress = GLUT_KEY_F1;
902             else if(wParam==(unsigned)gxKeyList.vkB)
903                 keypress = GLUT_KEY_F2;
904             else if(wParam==(unsigned)gxKeyList.vkC)
905                 keypress = GLUT_KEY_F3;
906             else if(wParam==(unsigned)gxKeyList.vkStart)
907                 keypress = GLUT_KEY_F4;
908         }
909 #endif
910
911         if( keypress != -1 )
912             INVOKE_WCB( *window, Special,
913                         ( keypress,
914                           window->State.MouseX, window->State.MouseY )
915             );
916
917         fgState.Modifiers = INVALID_MODIFIERS;
918     }
919     break;
920
921     case WM_SYSKEYUP:
922     case WM_KEYUP:
923     {
924         int keypress = -1;
925         POINT mouse_pos;
926
927         if (child_window)
928             window = child_window;
929
930         /*
931          * Remember the current modifiers state. This is done here in order
932          * to make sure the VK_DELETE keyboard callback is executed properly.
933          */
934         fgState.Modifiers = fgPlatformGetModifiers( );
935
936         GetCursorPos( &mouse_pos );
937         ScreenToClient( window->Window.Handle, &mouse_pos );
938
939         window->State.MouseX = mouse_pos.x;
940         window->State.MouseY = mouse_pos.y;
941
942         /*
943          * Convert the Win32 keystroke codes to GLUTtish way.
944          * "KEY(a,b)" was defined under "WM_KEYDOWN"
945          */
946
947         switch( wParam )
948         {
949             KEY( VK_F1,     GLUT_KEY_F1        );
950             KEY( VK_F2,     GLUT_KEY_F2        );
951             KEY( VK_F3,     GLUT_KEY_F3        );
952             KEY( VK_F4,     GLUT_KEY_F4        );
953             KEY( VK_F5,     GLUT_KEY_F5        );
954             KEY( VK_F6,     GLUT_KEY_F6        );
955             KEY( VK_F7,     GLUT_KEY_F7        );
956             KEY( VK_F8,     GLUT_KEY_F8        );
957             KEY( VK_F9,     GLUT_KEY_F9        );
958             KEY( VK_F10,    GLUT_KEY_F10       );
959             KEY( VK_F11,    GLUT_KEY_F11       );
960             KEY( VK_F12,    GLUT_KEY_F12       );
961             KEY( VK_PRIOR,  GLUT_KEY_PAGE_UP   );
962             KEY( VK_NEXT,   GLUT_KEY_PAGE_DOWN );
963             KEY( VK_HOME,   GLUT_KEY_HOME      );
964             KEY( VK_END,    GLUT_KEY_END       );
965             KEY( VK_LEFT,   GLUT_KEY_LEFT      );
966             KEY( VK_UP,     GLUT_KEY_UP        );
967             KEY( VK_RIGHT,  GLUT_KEY_RIGHT     );
968             KEY( VK_DOWN,   GLUT_KEY_DOWN      );
969             KEY( VK_INSERT, GLUT_KEY_INSERT    );
970
971           case VK_LCONTROL:  case VK_RCONTROL:  case VK_CONTROL:
972           case VK_LSHIFT:    case VK_RSHIFT:    case VK_SHIFT:
973           case VK_LMENU:     case VK_RMENU:     case VK_MENU:
974               /* These keypresses and releases are handled earlier in the function */
975               break;
976
977           case VK_DELETE:
978               /* The delete key should be treated as an ASCII keypress: */
979               INVOKE_WCB( *window, KeyboardUp,
980                           ( 127, window->State.MouseX, window->State.MouseY )
981               );
982               break;
983
984         default:
985         {
986 #if !defined(_WIN32_WCE)
987             BYTE state[ 256 ];
988             WORD code[ 2 ];
989
990             GetKeyboardState( state );
991
992             if( ToAscii( (UINT)wParam, 0, state, code, 0 ) == 1 )
993                 wParam=code[ 0 ];
994
995             INVOKE_WCB( *window, KeyboardUp,
996                         ( (char)wParam,
997                           window->State.MouseX, window->State.MouseY )
998             );
999 #endif /* !defined(_WIN32_WCE) */
1000         }
1001         }
1002
1003         if( keypress != -1 )
1004             INVOKE_WCB( *window, SpecialUp,
1005                         ( keypress,
1006                           window->State.MouseX, window->State.MouseY )
1007             );
1008
1009         fgState.Modifiers = INVALID_MODIFIERS;
1010     }
1011     break;
1012
1013     case WM_SYSCHAR:
1014     case WM_CHAR:
1015     {
1016       if (child_window)
1017         window = child_window;
1018
1019       if( (fgState.KeyRepeat==GLUT_KEY_REPEAT_OFF || window->State.IgnoreKeyRepeat==GL_TRUE) && (HIWORD(lParam) & KF_REPEAT) )
1020             break;
1021
1022         fgState.Modifiers = fgPlatformGetModifiers( );
1023         INVOKE_WCB( *window, Keyboard,
1024                     ( (char)wParam,
1025                       window->State.MouseX, window->State.MouseY )
1026         );
1027         fgState.Modifiers = INVALID_MODIFIERS;
1028     }
1029     break;
1030
1031     case WM_CAPTURECHANGED:
1032         /* User has finished resizing the window, force a redraw */
1033         INVOKE_WCB( *window, Display, ( ) );
1034
1035         /*lRet = DefWindowProc( hWnd, uMsg, wParam, lParam ); */
1036         break;
1037
1038         /* Other messages that I have seen and which are not handled already */
1039     case WM_SETTEXT:  /* 0x000c */
1040         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1041         /* Pass it on to "DefWindowProc" to set the window text */
1042         break;
1043
1044     case WM_GETTEXT:  /* 0x000d */
1045         /* Ideally we would copy the title of the window into "lParam" */
1046         /* strncpy ( (char *)lParam, "Window Title", wParam );
1047            lRet = ( wParam > 12 ) ? 12 : wParam;  */
1048         /* the number of characters copied */
1049         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1050         break;
1051
1052     case WM_GETTEXTLENGTH:  /* 0x000e */
1053         /* Ideally we would get the length of the title of the window */
1054         lRet = 12;
1055         /* the number of characters in "Window Title\0" (see above) */
1056         break;
1057
1058     case WM_ERASEBKGND:  /* 0x0014 */
1059         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1060         break;
1061
1062 #if !defined(_WIN32_WCE)
1063     case WM_SYNCPAINT:  /* 0x0088 */
1064         /* Another window has moved, need to update this one */
1065         window->State.Redisplay = GL_TRUE;
1066         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1067         /* Help screen says this message must be passed to "DefWindowProc" */
1068         break;
1069
1070     case WM_NCPAINT:  /* 0x0085 */
1071       /* Need to update the border of this window */
1072         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1073         /* Pass it on to "DefWindowProc" to repaint a standard border */
1074         break;
1075
1076     case WM_SYSCOMMAND :  /* 0x0112 */
1077         {
1078           /*
1079            * We have received a system command message.  Try to act on it.
1080            * The commands are passed in through the "wParam" parameter:
1081            * The least significant digit seems to be which edge of the window
1082            * is being used for a resize event:
1083            *     4  3  5
1084            *     1     2
1085            *     7  6  8
1086            * Congratulations and thanks to Richard Rauch for figuring this out..
1087            */
1088             switch ( wParam & 0xfff0 )
1089             {
1090             case SC_SIZE       :
1091                 break ;
1092
1093             case SC_MOVE       :
1094                 break ;
1095
1096             case SC_MINIMIZE   :
1097                 /* User has clicked on the "-" to minimize the window */
1098                 /* Turn off the visibility */
1099                 window->State.Visible = GL_FALSE ;
1100
1101                 break ;
1102
1103             case SC_MAXIMIZE   :
1104                 break ;
1105
1106             case SC_NEXTWINDOW :
1107                 break ;
1108
1109             case SC_PREVWINDOW :
1110                 break ;
1111
1112             case SC_CLOSE      :
1113                 /* Followed very closely by a WM_CLOSE message */
1114                 break ;
1115
1116             case SC_VSCROLL    :
1117                 break ;
1118
1119             case SC_HSCROLL    :
1120                 break ;
1121
1122             case SC_MOUSEMENU  :
1123                 break ;
1124
1125             case SC_KEYMENU    :
1126                 break ;
1127
1128             case SC_ARRANGE    :
1129                 break ;
1130
1131             case SC_RESTORE    :
1132                 break ;
1133
1134             case SC_TASKLIST   :
1135                 break ;
1136
1137             case SC_SCREENSAVE :
1138                 break ;
1139
1140             case SC_HOTKEY     :
1141                 break ;
1142
1143 #if(WINVER >= 0x0400)
1144             case SC_DEFAULT    :
1145                 break ;
1146
1147             case SC_MONITORPOWER    :
1148                 break ;
1149
1150             case SC_CONTEXTHELP    :
1151                 break ;
1152 #endif /* WINVER >= 0x0400 */
1153
1154             default:
1155 #if _DEBUG
1156                 fgWarning( "Unknown wParam type 0x%x", wParam );
1157 #endif
1158                 break;
1159             }
1160         }
1161 #endif /* !defined(_WIN32_WCE) */
1162
1163         /* We need to pass the message on to the operating system as well */
1164         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1165         break;
1166
1167 #ifdef WM_TOUCH
1168         /* handle multi-touch messages */
1169         case WM_TOUCH:
1170         {
1171                 unsigned int numInputs = (unsigned int)wParam;
1172                 unsigned int i = 0;
1173                 TOUCHINPUT* ti = (TOUCHINPUT*)malloc( sizeof(TOUCHINPUT)*numInputs);
1174
1175                 if (fghGetTouchInputInfo == (pGetTouchInputInfo)0xDEADBEEF) {
1176                     fghGetTouchInputInfo = (pGetTouchInputInfo)GetProcAddress(GetModuleHandle("user32"),"GetTouchInputInfo");
1177                     fghCloseTouchInputHandle = (pCloseTouchInputHandle)GetProcAddress(GetModuleHandle("user32"),"CloseTouchInputHandle");
1178                 }
1179
1180                 if (!fghGetTouchInputInfo) { 
1181                         free( (void*)ti );
1182                         break;
1183                 }
1184
1185                 if (fghGetTouchInputInfo( (HTOUCHINPUT)lParam, numInputs, ti, sizeof(TOUCHINPUT) )) {
1186                         /* Handle each contact point */
1187                         for (i = 0; i < numInputs; ++i ) {
1188
1189                                 POINT tp;
1190                                 tp.x = TOUCH_COORD_TO_PIXEL(ti[i].x);
1191                                 tp.y = TOUCH_COORD_TO_PIXEL(ti[i].y);
1192                                 ScreenToClient( hWnd, &tp );
1193
1194                                 ti[i].dwID = ti[i].dwID * 2;
1195
1196                                 if (ti[i].dwFlags & TOUCHEVENTF_DOWN) {
1197                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_ENTERED ) );
1198                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_DOWN ) );
1199                                 } else if (ti[i].dwFlags & TOUCHEVENTF_MOVE) {
1200                                         INVOKE_WCB( *window, MultiMotion, ( ti[i].dwID, tp.x, tp.y ) );
1201                                 } else if (ti[i].dwFlags & TOUCHEVENTF_UP)   { 
1202                                         INVOKE_WCB( *window, MultiButton, ( ti[i].dwID, tp.x, tp.y, 0, GLUT_UP ) );
1203                                         INVOKE_WCB( *window, MultiEntry,  ( ti[i].dwID, GLUT_LEFT ) );
1204                                 }
1205                         }
1206                 }
1207                 fghCloseTouchInputHandle((HTOUCHINPUT)lParam);
1208                 free( (void*)ti );
1209                 lRet = 0; /*DefWindowProc( hWnd, uMsg, wParam, lParam );*/
1210                 break;
1211         }
1212 #endif
1213     default:
1214         /* Handle unhandled messages */
1215         lRet = DefWindowProc( hWnd, uMsg, wParam, lParam );
1216         break;
1217     }
1218
1219     return lRet;
1220 }