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