better to put code to check if menu should be deactivated in
[freeglut] / src / mswin / fg_window_mswin.c
1 /*
2  * freeglut_window_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: Sun Jan 22, 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 #define FREEGLUT_BUILDING_LIB
29 #include <GL/freeglut.h>
30 #include "../fg_internal.h"
31
32
33 /* The following include file is available from SGI but is not standard:
34  *   #include <GL/wglext.h>
35  * So we copy the necessary parts out of it.
36  * XXX: should local definitions for extensions be put in a separate include file?
37  */
38 typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
39
40 typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
41
42 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
43 #define WGL_ACCELERATION_ARB           0x2003
44 #define WGL_SUPPORT_OPENGL_ARB         0x2010
45 #define WGL_DOUBLE_BUFFER_ARB          0x2011
46 #define WGL_COLOR_BITS_ARB             0x2014
47 #define WGL_ALPHA_BITS_ARB             0x201B
48 #define WGL_DEPTH_BITS_ARB             0x2022
49 #define WGL_STENCIL_BITS_ARB           0x2023
50 #define WGL_FULL_ACCELERATION_ARB      0x2027
51
52 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
53 #define WGL_SAMPLES_ARB                0x2042
54
55 #define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
56
57 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
58
59 #ifndef WGL_ARB_create_context
60 #define WGL_ARB_create_context 1
61 #ifdef WGL_WGLEXT_PROTOTYPES
62 extern HGLRC WINAPI wglCreateContextAttribsARB (HDC, HGLRC, const int *);
63 #endif /* WGL_WGLEXT_PROTOTYPES */
64 typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
65
66 #define WGL_CONTEXT_MAJOR_VERSION_ARB  0x2091
67 #define WGL_CONTEXT_MINOR_VERSION_ARB  0x2092
68 #define WGL_CONTEXT_LAYER_PLANE_ARB    0x2093
69 #define WGL_CONTEXT_FLAGS_ARB          0x2094
70 #define WGL_CONTEXT_PROFILE_MASK_ARB   0x9126
71
72 #define WGL_CONTEXT_DEBUG_BIT_ARB      0x0001
73 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
74
75 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
76 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
77
78 #define ERROR_INVALID_VERSION_ARB      0x2095
79 #define ERROR_INVALID_PROFILE_ARB      0x2096
80 #endif
81 /* End of copying the necessary parts out of it. */
82
83 #ifdef WM_TOUCH
84 typedef BOOL (WINAPI *pRegisterTouchWindow)(HWND,ULONG);
85 static pRegisterTouchWindow fghRegisterTouchWindow = (pRegisterTouchWindow)0xDEADBEEF;
86 #endif
87
88
89 /*
90  * Setup the pixel format for a Win32 window
91  */
92
93 #if defined(_WIN32_WCE)
94 static wchar_t* fghWstrFromStr(const char* str)
95 {
96     int i,len=strlen(str);
97     wchar_t* wstr = (wchar_t*)malloc(2*len+2);
98     for(i=0; i<len; i++)
99         wstr[i] = str[i];
100     wstr[len] = 0;
101     return wstr;
102 }
103 #endif /* defined(_WIN32_WCE) */
104
105
106 static void fghFillContextAttributes( int *attributes ) {
107   int where = 0, contextFlags, contextProfile;
108
109   ATTRIB_VAL( WGL_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
110   ATTRIB_VAL( WGL_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
111
112   contextFlags =
113     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, WGL_CONTEXT_DEBUG_BIT_ARB ) |
114     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
115   if ( contextFlags != 0 ) {
116     ATTRIB_VAL( WGL_CONTEXT_FLAGS_ARB, contextFlags );
117   }
118
119   contextProfile =
120     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, WGL_CONTEXT_CORE_PROFILE_BIT_ARB ) |
121     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
122   if ( contextProfile != 0 ) {
123     ATTRIB_VAL( WGL_CONTEXT_PROFILE_MASK_ARB, contextProfile );
124   }
125
126   ATTRIB( 0 );
127 }
128
129 static int fghIsExtensionSupported( HDC hdc, const char *extension ) {
130     const char *pWglExtString;
131     PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetEntensionsStringARB =
132       (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
133     if ( wglGetEntensionsStringARB == NULL )
134     {
135       return FALSE;
136     }
137     pWglExtString = wglGetEntensionsStringARB( hdc );
138     return ( pWglExtString != NULL ) && ( strstr(pWglExtString, extension) != NULL );
139 }
140
141 void fgNewWGLCreateContext( SFG_Window* window )
142 {
143     HGLRC context;
144     int attributes[9];
145     PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
146
147     /* If nothing fancy has been required, leave the context as it is */
148     if ( fghIsLegacyContextRequested() )
149     {
150         return;
151     }
152
153     wglMakeCurrent( window->Window.pContext.Device, window->Window.Context );
154
155     if ( !fghIsExtensionSupported( window->Window.pContext.Device, "WGL_ARB_create_context" ) )
156     {
157         /* wglCreateContextAttribsARB not found, yet the user has requested the new context creation */
158         fgWarning( "OpenGL >2.1 context requested but wglCreateContextAttribsARB is not available! Falling back to legacy context creation" );
159         /* Legacy context already created at this point in WM_CREATE path of fgPlatformWindowProc, just return */
160         return;
161     }
162
163     /* new context creation */
164     fghFillContextAttributes( attributes );
165
166     wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress( "wglCreateContextAttribsARB" );
167     if ( wglCreateContextAttribsARB == NULL )
168     {
169         /* wglCreateContextAttribsARB not found, yet the user has requested the new context creation */
170         fgWarning( "OpenGL >2.1 context requested but wglCreateContextAttribsARB is not available! Falling back to legacy context creation" );
171         /* Legacy context already created at this point in WM_CREATE path of fgPlatformWindowProc, just return */
172         return;
173     }
174
175     context = wglCreateContextAttribsARB( window->Window.pContext.Device, 0, attributes );
176     if ( context == NULL )
177     {
178         fghContextCreationError();
179     }
180
181     wglMakeCurrent( NULL, NULL );
182     wglDeleteContext( window->Window.Context );
183     window->Window.Context = context;
184 }
185
186 #if !defined(_WIN32_WCE)
187
188 static void fghFillPFD( PIXELFORMATDESCRIPTOR *ppfd, HDC hdc, unsigned char layer_type )
189 {
190   int flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
191   if ( fgState.DisplayMode & GLUT_DOUBLE ) {
192         flags |= PFD_DOUBLEBUFFER;
193   }
194   if ( fgState.DisplayMode & GLUT_STEREO ) {
195     flags |= PFD_STEREO;
196   }
197
198 #if defined(_MSC_VER)
199 #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" )
200 #endif
201
202   /* Specify which pixel format do we opt for... */
203   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
204   ppfd->nVersion = 1;
205   ppfd->dwFlags = flags;
206
207   if( fgState.DisplayMode & GLUT_INDEX ) {
208     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
209     ppfd->cRedBits = 0;
210     ppfd->cGreenBits = 0;
211     ppfd->cBlueBits = 0;
212     ppfd->cAlphaBits = 0;
213   } else {
214     ppfd->iPixelType = PFD_TYPE_RGBA;
215     ppfd->cRedBits = 8;
216     ppfd->cGreenBits = 8;
217     ppfd->cBlueBits = 8;
218     ppfd->cAlphaBits = ( fgState.DisplayMode & GLUT_ALPHA ) ? 8 : 0;
219   }
220
221   ppfd->cColorBits = 24;
222   ppfd->cRedShift = 0;
223   ppfd->cGreenShift = 0;
224   ppfd->cBlueShift = 0;
225   ppfd->cAlphaShift = 0;
226   ppfd->cAccumBits = ( fgState.DisplayMode & GLUT_ACCUM ) ? 1 : 0;
227   ppfd->cAccumRedBits = 0;
228   ppfd->cAccumGreenBits = 0;
229   ppfd->cAccumBlueBits = 0;
230   ppfd->cAccumAlphaBits = 0;
231
232   /* Hmmm, or 32/0 instead of 24/8? */
233   ppfd->cDepthBits = 24;
234   ppfd->cStencilBits = 8;
235
236   ppfd->cAuxBuffers = fghNumberOfAuxBuffersRequested();
237   ppfd->iLayerType = layer_type;
238   ppfd->bReserved = 0;
239   ppfd->dwLayerMask = 0;
240   ppfd->dwVisibleMask = 0;
241   ppfd->dwDamageMask = 0;
242   
243   ppfd->cColorBits = (BYTE) GetDeviceCaps( hdc, BITSPIXEL );
244 }
245
246 static void fghFillPixelFormatAttributes( int *attributes, const PIXELFORMATDESCRIPTOR *ppfd )
247 {
248   int where = 0;
249
250   ATTRIB_VAL( WGL_DRAW_TO_WINDOW_ARB, GL_TRUE );
251   ATTRIB_VAL( WGL_SUPPORT_OPENGL_ARB, GL_TRUE );
252   ATTRIB_VAL( WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB );
253
254   ATTRIB_VAL( WGL_COLOR_BITS_ARB, ppfd->cColorBits );
255   ATTRIB_VAL( WGL_ALPHA_BITS_ARB, ppfd->cAlphaBits );
256   ATTRIB_VAL( WGL_DEPTH_BITS_ARB, ppfd->cDepthBits );
257   ATTRIB_VAL( WGL_STENCIL_BITS_ARB, ppfd->cStencilBits );
258
259   ATTRIB_VAL( WGL_DOUBLE_BUFFER_ARB, ( fgState.DisplayMode & GLUT_DOUBLE ) != 0 );
260
261   if ( fgState.DisplayMode & GLUT_SRGB ) {
262     ATTRIB_VAL( WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, TRUE );
263   }
264
265   ATTRIB_VAL( WGL_SAMPLE_BUFFERS_ARB, GL_TRUE );
266   ATTRIB_VAL( WGL_SAMPLES_ARB, fgState.SampleNumber );
267   ATTRIB( 0 );
268 }
269 #endif
270
271 GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
272                               unsigned char layer_type )
273 {
274 #if defined(_WIN32_WCE)
275     return GL_TRUE;
276 #else
277     PIXELFORMATDESCRIPTOR pfd;
278     PIXELFORMATDESCRIPTOR* ppfd = &pfd;
279     int pixelformat;
280     HDC current_hDC;
281     GLboolean success;
282
283     if (checkOnly)
284       current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL);
285     else
286       current_hDC = window->Window.pContext.Device;
287
288     fghFillPFD( ppfd, current_hDC, layer_type );
289     pixelformat = ChoosePixelFormat( current_hDC, ppfd );
290
291     /* windows hack for multismapling/sRGB */
292     if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) ||
293          ( fgState.DisplayMode & GLUT_SRGB ) )
294     {        
295         HGLRC rc, rc_before=wglGetCurrentContext();
296         HWND hWnd;
297         HDC hDC, hDC_before=wglGetCurrentDC();
298         WNDCLASS wndCls;
299
300         /* create a dummy window */
301         ZeroMemory(&wndCls, sizeof(wndCls));
302         wndCls.lpfnWndProc = DefWindowProc;
303         wndCls.hInstance = fgDisplay.pDisplay.Instance;
304         wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
305         wndCls.lpszClassName = _T("FREEGLUT_dummy");
306         RegisterClass( &wndCls );
307
308         hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.pDisplay.Instance, 0 );
309         hDC=GetDC(hWnd);
310         SetPixelFormat( hDC, pixelformat, ppfd );
311
312         rc = wglCreateContext( hDC );
313         wglMakeCurrent(hDC, rc);
314
315         if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) )
316         {
317             PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc =
318               (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
319             if ( wglChoosePixelFormatARBProc )
320             {
321                 int attributes[100];
322                 int iPixelFormat;
323                 BOOL bValid;
324                 float fAttributes[] = { 0, 0 };
325                 UINT numFormats;
326                 fghFillPixelFormatAttributes( attributes, ppfd );
327                 bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats);
328
329                 if ( bValid && numFormats > 0 )
330                 {
331                     pixelformat = iPixelFormat;
332                 }
333             }
334         }
335
336         wglMakeCurrent( hDC_before, rc_before);
337         wglDeleteContext(rc);
338         ReleaseDC(hWnd, hDC);
339         DestroyWindow(hWnd);
340         UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.pDisplay.Instance);
341     }
342
343     success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) );
344
345     if (checkOnly)
346         DeleteDC(current_hDC);
347
348     return success;
349 #endif /* defined(_WIN32_WCE) */
350 }
351
352
353
354 void fgPlatformSetWindow ( SFG_Window *window )
355 {
356     if ( window != fgStructure.CurrentWindow )
357     {
358         if( fgStructure.CurrentWindow )
359             ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
360                        fgStructure.CurrentWindow->Window.pContext.Device );
361
362         if ( window )
363         {
364             window->Window.pContext.Device = GetDC( window->Window.Handle );
365             wglMakeCurrent(
366                 window->Window.pContext.Device,
367                 window->Window.Context
368             );
369         }
370     }
371 }
372
373
374 /* Returns the width of the window borders based on the window's style.
375 */
376 void fghGetBorderWidth(const DWORD windowStyle, int* xBorderWidth, int* yBorderWidth)
377 {
378     if (windowStyle & WS_THICKFRAME)
379     {
380         *xBorderWidth = GetSystemMetrics(SM_CXSIZEFRAME);
381         *yBorderWidth = GetSystemMetrics(SM_CYSIZEFRAME);
382     }
383     else if (windowStyle & WS_DLGFRAME)
384     {
385         *xBorderWidth = GetSystemMetrics(SM_CXFIXEDFRAME);
386         *yBorderWidth = GetSystemMetrics(SM_CYFIXEDFRAME);
387     }
388     else
389     {
390         *xBorderWidth = 0;
391         *yBorderWidth = 0;
392     }
393 }
394
395
396
397 /* Computes position of corners of window Rect (outer position including
398  * decorations) based on the provided client rect and based on the style
399  * of the window in question.
400  * If posIsOutside is set to true, the input client Rect is taken to follow
401  * freeGLUT's window specification convention in which the top-left corner
402  * is at the outside of the window, while the size
403  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
404  * area.
405  */
406 void fghComputeWindowRectFromClientArea_UseStyle( const DWORD windowStyle, RECT *clientRect, BOOL posIsOutside )
407 {
408     int xBorderWidth = 0, yBorderWidth = 0;
409
410     /* If window has title bar, correct rect for it */
411     if (windowStyle & WS_MAXIMIZEBOX) /* Need to query for WS_MAXIMIZEBOX to see if we have a title bar, the WS_CAPTION query is also true for a WS_DLGFRAME only... */
412     {
413         if (posIsOutside)
414             clientRect->bottom += GetSystemMetrics( SM_CYCAPTION );
415         else
416             clientRect->top -= GetSystemMetrics( SM_CYCAPTION );
417     }
418
419     /* get width of window's borders (frame), correct rect for it.
420      * Note, borders can be of zero width if style does not specify borders
421      */
422     fghGetBorderWidth(windowStyle, &xBorderWidth, &yBorderWidth);
423     if (posIsOutside)
424     {
425         clientRect->right  += xBorderWidth * 2;
426         clientRect->bottom += yBorderWidth * 2;
427     }
428     else
429     {
430         clientRect->left   -= xBorderWidth;
431         clientRect->right  += xBorderWidth;
432         clientRect->top    -= yBorderWidth;
433         clientRect->bottom += yBorderWidth;
434     }
435 }
436
437 /* Computes position of corners of window Rect (outer position including
438  * decorations) based on the provided client rect and based on the style
439  * of the window in question. If the window pointer or the window handle
440  * is NULL, a fully decorated window (caption and border) is assumed.
441  * Furthermore, if posIsOutside is set to true, the input client Rect is
442  * taken to follow freeGLUT's window specification convention in which the
443  * top-left corner is at the outside of the window, while the size
444  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
445  * area.
446 */
447 void fghComputeWindowRectFromClientArea_QueryWindow( const SFG_Window *window, RECT *clientRect, BOOL posIsOutside )
448 {
449     DWORD windowStyle = 0;
450
451     if (window && window->Window.Handle)
452         windowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
453     else
454         windowStyle = WS_OVERLAPPEDWINDOW;
455
456     fghComputeWindowRectFromClientArea_UseStyle(windowStyle, clientRect, posIsOutside);
457 }
458
459 /* Computes position of corners of client area (drawable area) of a window
460  * based on the provided window Rect (outer position including decorations)
461  * and based on the style of the window in question. If the window pointer
462  * or the window handle is NULL, a fully decorated window (caption and
463  * border) is assumed.
464  * Furthermore, if wantPosOutside is set to true, the output client Rect
465  * will follow freeGLUT's window specification convention in which the
466  * top-left corner is at the outside of the window, the size
467  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
468  * area.
469  */
470 void fghComputeClientAreaFromWindowRect( const SFG_Window *window, RECT *windowRect, BOOL wantPosOutside )
471 {
472     DWORD windowStyle = 0;
473     int xBorderWidth = 0, yBorderWidth = 0;
474
475     if (window && window->Window.Handle)
476         windowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
477     else
478         windowStyle = WS_OVERLAPPEDWINDOW;
479
480     /* If window has title bar, correct rect for it */
481     if (windowStyle & WS_MAXIMIZEBOX) /* Need to query for WS_MAXIMIZEBOX to see if we have a title bar, the WS_CAPTION query is also true for a WS_DLGFRAME only... */
482     {
483         if (wantPosOutside)
484             windowRect->bottom -= GetSystemMetrics( SM_CYCAPTION );
485         else
486             windowRect->top    += GetSystemMetrics( SM_CYCAPTION );
487     }
488
489     /* get width of window's borders (frame), correct rect for it.
490      * Note, borders can be of zero width if style does not specify borders
491      */
492     fghGetBorderWidth(windowStyle, &xBorderWidth, &yBorderWidth);
493     if (wantPosOutside)
494     {
495         windowRect->right  -= xBorderWidth * 2;
496         windowRect->bottom -= yBorderWidth * 2;
497     }
498     else
499     {
500         windowRect->left   += xBorderWidth;
501         windowRect->right  -= xBorderWidth;
502         windowRect->top    += yBorderWidth;
503         windowRect->bottom -= yBorderWidth;
504     }
505 }
506
507 /* Gets the rect describing the client area (drawable area) of the
508  * specified window.
509  * Returns an empty rect if window pointer or window handle is NULL.
510  * If wantPosOutside is set to true, the output client Rect
511  * will follow freeGLUT's window specification convention in which the
512  * top-left corner is at the outside of the window, while the size
513  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
514  * area.
515  */
516 RECT fghGetClientArea( const SFG_Window *window, BOOL wantPosOutside )
517 {
518     RECT windowRect = {0,0,0,0};
519
520     freeglut_return_val_if_fail((window && window->Window.Handle),windowRect);
521     
522     /*
523      * call GetWindowRect()
524      * (this returns the pixel coordinates of the outside of the window)
525      * cannot use GetClientRect as it seems to return a rect relative to
526      * the top-left point of the client area (.top and .left are thus always 0)
527      */
528     GetWindowRect( window->Window.Handle, &windowRect );
529
530     /* Then correct the results */
531     fghComputeClientAreaFromWindowRect(window, &windowRect, wantPosOutside);
532
533     return windowRect;
534 }
535
536 #if(WINVER >= 0x500)
537 typedef struct
538 {
539       int *x;
540       int *y;
541       const char *name;
542 } m_proc_t;
543
544 static BOOL CALLBACK m_proc(HMONITOR mon,
545                             HDC hdc,
546                             LPRECT rect,
547                             LPARAM data)
548 {
549       m_proc_t *dp=(m_proc_t *)data;
550       MONITORINFOEX info;
551       BOOL res;
552       info.cbSize=sizeof(info);
553       res=GetMonitorInfo(mon,(LPMONITORINFO)&info);
554       if( res )
555       {
556           if( strcmp(dp->name,info.szDevice)==0 )
557           {
558               *(dp->x)=info.rcMonitor.left;
559               *(dp->y)=info.rcMonitor.top;
560               return FALSE;
561           }
562       }
563       return TRUE;
564 }
565
566 /* 
567  * this function returns the origin of the screen identified by
568  * fgDisplay.pDisplay.DisplayName, and 0 otherwise.
569  * This is used in fgOpenWindow to open the gamemode window on the screen
570  * identified by the -display command line argument. The function should
571  * not be called otherwise.
572  */
573
574 static void get_display_origin(int *xp,int *yp)
575 {
576     *xp = 0;
577     *yp = 0;
578
579     if( fgDisplay.pDisplay.DisplayName )
580     {
581         m_proc_t st;
582         st.x=xp;
583         st.y=yp;
584         st.name=fgDisplay.pDisplay.DisplayName;
585         EnumDisplayMonitors(0,0,m_proc,(LPARAM)&st);
586     }
587 }
588 #else
589 #pragma message( "-display parameter only works if compiled with WINVER >= 0x0500")
590
591 static void get_display_origin(int *xp,int *yp)
592 {
593     *xp = 0;
594     *yp = 0;
595
596     if( fgDisplay.pDisplay.DisplayName )
597     {
598         fgWarning( "for working -display support FreeGLUT must be compiled with WINVER >= 0x0500");
599     }
600 }
601 #endif
602
603
604
605 /*
606  * Opens a window. Requires a SFG_Window object created and attached
607  * to the freeglut structure. OpenGL context is created here.
608  */
609 void fgPlatformOpenWindow( SFG_Window* window, const char* title,
610                            GLboolean positionUse, int x, int y,
611                            GLboolean sizeUse, int w, int h,
612                            GLboolean gameMode, GLboolean isSubWindow )
613 {
614
615     WNDCLASS wc;
616     DWORD flags   = 0;
617     DWORD exFlags = 0;
618     ATOM atom;
619
620     /* Grab the window class we have registered on glutInit(): */
621     atom = GetClassInfo( fgDisplay.pDisplay.Instance, _T("FREEGLUT"), &wc );
622     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
623                                    "fgOpenWindow" );
624
625     /* Determine window style flags*/
626     if( gameMode )
627     {
628         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
629                                        "Game mode being invoked on a subwindow",
630                                        "fgOpenWindow" );
631
632         /*
633          * Set the window creation flags appropriately to make the window
634          * entirely visible:
635          */
636         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
637     }
638     else
639     {
640         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
641
642         /*
643          * There's a small difference between creating the top, child and
644          * menu windows
645          */
646         if ( window->IsMenu )
647         {
648             flags |= WS_POPUP;
649             exFlags |= WS_EX_TOOLWINDOW;
650         }
651 #if defined(_WIN32_WCE)
652         /* no decorations for windows CE */
653 #else
654         /* if this is not a subwindow (child), set its style based on the requested display mode */
655         else if( window->Parent == NULL )
656             if ( fgState.DisplayMode & GLUT_BORDERLESS )
657             {
658                 /* no window decorations needed */
659             }
660             else if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
661                 /* only window decoration is a border, no title bar or buttons */
662                 flags |= WS_DLGFRAME;
663             else
664                 /* window decoration are a border, title bar and buttons.
665                  * NB: we later query whether the window has a title bar or
666                  * not by testing for the maximize button, as the test for
667                  * WS_CAPTION can be true without the window having a title
668                  * bar. This style WS_OVERLAPPEDWINDOW gives you a maximize
669                  * button. */
670                 flags |= WS_OVERLAPPEDWINDOW;
671 #endif
672         else
673             /* subwindows always have no decoration, but are marked as a child window to the OS */
674             flags |= WS_CHILD;
675     }
676
677     /* determine window size and position */
678     if( gameMode )
679     {
680         /* if in gamemode, query the origin of specified by the -display
681          * command line parameter (if any) and offset the upper-left corner
682          * of the window so we create the window on that screen.
683          * The -display argument doesn't do anything if not trying to enter
684          * gamemode.
685          */
686         int xoff=0, yoff=0;
687         get_display_origin(&xoff,&yoff);
688         x += xoff;
689         y += yoff;
690     }
691     if( !positionUse )
692     {
693         x = CW_USEDEFAULT;
694         y = CW_USEDEFAULT;
695     }
696     if( !sizeUse )
697     {
698         if( ! window->IsMenu )
699         {
700             w = CW_USEDEFAULT;
701             h = CW_USEDEFAULT;
702         }
703         else /* fail safe - Windows can make a window of size (0, 0) */
704             w = h = 300; /* default window size */
705     }
706     /* store requested client area width and height */
707     window->State.Width = w;
708     window->State.Height = h;
709
710 #if !defined(_WIN32_WCE)    /* no decorations for windows CE */
711     if( sizeUse )
712     {
713         RECT windowRect;
714         /*
715          * Update the window dimensions, taking the window decorations
716          * into account.  FreeGLUT is to create the window with the
717          * topleft outside corner at (x,y) and with client area
718          * dimensions (w,h).
719          * note: don't need to do this when w=h=CW_USEDEFAULT, so in the
720          * if( sizeUse ) here is convenient.
721          */
722         windowRect.left     = x;
723         windowRect.top      = y;
724         windowRect.right    = x+w;
725         windowRect.bottom   = y+h;
726
727         fghComputeWindowRectFromClientArea_UseStyle(flags,&windowRect,TRUE);
728
729         w = windowRect.right - windowRect.left;
730         h = windowRect.bottom- windowRect.top;
731     }
732 #endif /* !defined(_WIN32_WCE) */
733
734 #if defined(_WIN32_WCE)
735     {
736         wchar_t* wstr = fghWstrFromStr(title);
737
738         window->Window.Handle = CreateWindow(
739             _T("FREEGLUT"),
740             wstr,
741             WS_VISIBLE | WS_POPUP,
742             0,0, 240,320,
743             NULL,
744             NULL,
745             fgDisplay.pDisplay.Instance,
746             (LPVOID) window
747         );
748
749         free(wstr);
750
751         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
752         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
753         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
754         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
755         ShowWindow(window->Window.Handle, SW_SHOW);
756         UpdateWindow(window->Window.Handle);
757     }
758 #else
759     window->Window.Handle = CreateWindowEx(
760         exFlags,
761         _T("FREEGLUT"),
762         title,
763         flags,
764         x, y, w, h,
765         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
766         (HMENU) NULL,
767         fgDisplay.pDisplay.Instance,
768         (LPVOID) window
769     );
770 #endif /* defined(_WIN32_WCE) */
771
772     if( !( window->Window.Handle ) )
773         fgError( "Failed to create a window (%s)!", title );
774
775 #if !defined(_WIN32_WCE)
776     /* Need to set requested style again, apparently Windows doesn't listen when requesting windows without title bar or borders */
777     SetWindowLong(window->Window.Handle, GWL_STYLE, flags);
778     SetWindowPos(window->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
779 #endif /* defined(_WIN32_WCE) */
780
781     /* Make a menu window always on top - fix Feature Request 947118 */
782     if( window->IsMenu || gameMode )
783         SetWindowPos(
784                         window->Window.Handle,
785                         HWND_TOPMOST,
786                         0, 0, 0, 0,
787                         SWP_NOMOVE | SWP_NOSIZE
788                     );
789
790     /* Enable multitouch: additional flag TWF_FINETOUCH, TWF_WANTPALM */
791     #ifdef WM_TOUCH
792         if (fghRegisterTouchWindow == (pRegisterTouchWindow)0xDEADBEEF) 
793                         fghRegisterTouchWindow = (pRegisterTouchWindow)GetProcAddress(GetModuleHandle("user32"),"RegisterTouchWindow");
794                 if (fghRegisterTouchWindow)
795              fghRegisterTouchWindow( window->Window.Handle, TWF_FINETOUCH | TWF_WANTPALM );
796     #endif
797
798 #if defined(_WIN32_WCE)
799     ShowWindow( window->Window.Handle, SW_SHOW );
800 #else
801     ShowWindow( window->Window.Handle,
802                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
803 #endif /* defined(_WIN32_WCE) */
804
805     UpdateWindow( window->Window.Handle );
806     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
807 }
808
809
810 /*
811  * Closes a window, destroying the frame and OpenGL context
812  */
813 void fgPlatformCloseWindow( SFG_Window* window )
814 {
815     /* Make sure we don't close a window with current context active */
816     if( fgStructure.CurrentWindow == window )
817         wglMakeCurrent( NULL, NULL );
818
819     /*
820      * Step through the list of windows.  If the rendering context
821      * is not being used by another window, then we delete it.
822      */
823     {
824         int used = FALSE ;
825         SFG_Window *iter ;
826
827         for( iter = (SFG_Window *)fgStructure.Windows.First;
828              iter;
829              iter = (SFG_Window *)iter->Node.Next )
830         {
831             if( ( iter->Window.Context == window->Window.Context ) &&
832                 ( iter != window ) )
833                 used = TRUE;
834         }
835
836         if( ! used )
837             wglDeleteContext( window->Window.Context );
838     }
839
840     DestroyWindow( window->Window.Handle );
841 }
842
843
844
845 /*
846  * This function makes the current window visible
847  */
848 void fgPlatformGlutShowWindow( void )
849 {
850     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
851 }
852
853 /*
854  * This function hides the current window
855  */
856 void fgPlatformGlutHideWindow( void )
857 {
858     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
859 }
860
861 /*
862  * Iconify the current window (top-level windows only)
863  */
864 void fgPlatformGlutIconifyWindow( void )
865 {
866     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
867 }
868
869 /*
870  * Set the current window's title
871  */
872 void fgPlatformGlutSetWindowTitle( const char* title )
873 {
874 #ifdef _WIN32_WCE
875     {
876         wchar_t* wstr = fghWstrFromStr(title);
877         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
878         free(wstr);
879     }
880 #else
881     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
882 #endif
883 }
884
885 /*
886  * Set the current window's iconified title
887  * There really isn't a way to set the icon name separate from the
888  * windows name in Win32, so, just set the windows name.
889  */
890 void fgPlatformGlutSetIconTitle( const char* title )
891 {
892 #ifdef _WIN32_WCE
893     {
894         wchar_t* wstr = fghWstrFromStr(title);
895         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
896         free(wstr);
897     }
898 #else
899     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
900 #endif
901 }
902
903 /*
904  * Change the current window's position
905  */
906 void fgPlatformGlutPositionWindow( int x, int y )
907 {
908     RECT winRect;
909
910     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
911     GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
912     MoveWindow(
913         fgStructure.CurrentWindow->Window.Handle,
914         x,
915         y,
916         winRect.right - winRect.left,
917         winRect.bottom - winRect.top,
918         TRUE
919     );
920 }
921
922 /*
923  * Lowers the current window (by Z order change)
924  */
925 void fgPlatformGlutPushWindow( void )
926 {
927     SetWindowPos(
928         fgStructure.CurrentWindow->Window.Handle,
929         HWND_BOTTOM,
930         0, 0, 0, 0,
931         SWP_NOSIZE | SWP_NOMOVE
932     );
933 }
934
935 /*
936  * Raises the current window (by Z order change)
937  */
938 void fgPlatformGlutPopWindow( void )
939 {
940     SetWindowPos(
941         fgStructure.CurrentWindow->Window.Handle,
942         HWND_TOP,
943         0, 0, 0, 0,
944         SWP_NOSIZE | SWP_NOMOVE
945     );
946 }
947
948 /*
949  * Resize the current window so that it fits the whole screen
950  */
951 void fgPlatformGlutFullScreen( SFG_Window *win )
952 {
953 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
954
955     if (glutGet(GLUT_FULL_SCREEN))
956     {
957         /*  Leave full screen state before entering fullscreen again (resizing?) */
958         glutLeaveFullScreen();
959     }
960
961     {
962 #if(WINVER >= 0x0500) /* Windows 2000 or later */
963         DWORD s;
964         RECT rect;
965         HMONITOR hMonitor;
966         MONITORINFO mi;
967
968         /* For fullscreen mode, first remove all window decoration
969          * and set style to popup so it will overlap the taskbar
970          * then force to maximize on the screen on which it has the most
971          * overlap.
972          */
973
974         
975         /* store current window rect */
976         GetWindowRect( win->Window.Handle, &win->State.pWState.OldRect );
977
978         /* store current window style */
979         win->State.pWState.OldStyle = s = GetWindowLong(win->Window.Handle, GWL_STYLE);
980
981         /* remove decorations from style and add popup style*/
982         s &= ~WS_OVERLAPPEDWINDOW;
983         s |= WS_POPUP;
984         SetWindowLong(win->Window.Handle, GWL_STYLE, s);
985         SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
986
987         /* For fullscreen mode, find the monitor that is covered the most
988          * by the window and get its rect as the resize target.
989              */
990         hMonitor= MonitorFromRect(&win->State.pWState.OldRect, MONITOR_DEFAULTTONEAREST);
991         mi.cbSize = sizeof(mi);
992         GetMonitorInfo(hMonitor, &mi);
993         rect = mi.rcMonitor;
994 #else   /* if (WINVER >= 0x0500) */
995         RECT rect;
996
997         /* For fullscreen mode, force the top-left corner to 0,0
998          * and adjust the window rectangle so that the client area
999          * covers the whole screen.
1000          */
1001
1002         rect.left   = 0;
1003         rect.top    = 0;
1004         rect.right  = fgDisplay.ScreenWidth;
1005         rect.bottom = fgDisplay.ScreenHeight;
1006
1007         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1008                                   WS_CLIPCHILDREN, FALSE );
1009 #endif  /* (WINVER >= 0x0500) */
1010
1011         /*
1012          * then resize window
1013          * SWP_NOACTIVATE     Do not activate the window
1014          * SWP_NOOWNERZORDER  Do not change position in z-order
1015          * SWP_NOSENDCHANGING Suppress WM_WINDOWPOSCHANGING message
1016          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1017          */
1018         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1019                       HWND_TOP,
1020                       rect.left,
1021                       rect.top,
1022                       rect.right  - rect.left,
1023                       rect.bottom - rect.top,
1024                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1025                       SWP_NOZORDER
1026                     );
1027
1028         win->State.IsFullscreen = GL_TRUE;
1029     }
1030 #endif
1031 }
1032
1033 /*
1034  * If we are fullscreen, resize the current window back to its original size
1035  */
1036 void fgPlatformGlutLeaveFullScreen( SFG_Window *win )
1037 {
1038 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1039     if (!glutGet(GLUT_FULL_SCREEN))
1040     {
1041         /* nothing to do */
1042         return;
1043     }
1044
1045     /* restore style of window before making it fullscreen */
1046     SetWindowLong(win->Window.Handle, GWL_STYLE, win->State.pWState.OldStyle);
1047     SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
1048
1049     /* Then resize */
1050     SetWindowPos(win->Window.Handle,
1051         HWND_TOP,
1052         win->State.pWState.OldRect.left,
1053         win->State.pWState.OldRect.top,
1054         win->State.pWState.OldRect.right  - win->State.pWState.OldRect.left,
1055         win->State.pWState.OldRect.bottom - win->State.pWState.OldRect.top,
1056         SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1057         SWP_NOZORDER
1058         );
1059
1060     win->State.IsFullscreen = GL_FALSE;
1061 #endif
1062 }
1063
1064 /*
1065  * Toggle the window's full screen state.
1066  */
1067 void fgPlatformGlutFullScreenToggle( SFG_Window *win )
1068 {
1069     if (!win->State.IsFullscreen)
1070         glutFullScreen();
1071     else
1072         glutLeaveFullScreen();
1073 }
1074
1075
1076 /* -- PLATFORM-SPECIFIC INTERFACE FUNCTION -------------------------------------------------- */
1077
1078 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1079 {
1080   __glutExitFunc = exit_function;
1081   return glutCreateWindow( title );
1082 }
1083