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