reimplemented the client-area/window-area conversion code. It should now
[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 /* Get window style and extended window style of a FreeGLUT window
375  * If the window pointer or the window handle is NULL, a fully
376  * decorated window (caption and border) is assumed.
377  */
378 void fghGetStyleFromWindow( const SFG_Window *window, DWORD *windowStyle, DWORD *windowExStyle )
379 {
380     if (window && window->Window.Handle)
381     {
382         *windowStyle   = GetWindowLong(window->Window.Handle, GWL_STYLE);
383         *windowExStyle = GetWindowLong(window->Window.Handle, GWL_EXSTYLE);
384     }
385     else
386     {
387         /* WindowExStyle==0 is fine/default, exStyle is currently only used for menu windows */
388         *windowStyle   = WS_OVERLAPPEDWINDOW;
389         *windowExStyle = 0;
390     }
391 }
392
393
394 /* Computes position of corners of window Rect (outer position including
395  * decorations) based on the provided client rect and based on the style
396  * of the window in question.
397  * If posIsOutside is set to true, the input client Rect is taken to follow
398  * freeGLUT's window specification convention in which the top-left corner
399  * is at the outside of the window, while the size
400  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
401  * area.
402  */
403 void fghComputeWindowRectFromClientArea_UseStyle( RECT *clientRect, const DWORD windowStyle, const DWORD windowExStyle, BOOL posIsOutside )
404 {
405     RECT windowRect   = {0,0,0,0};
406     CopyRect(&windowRect,clientRect);
407
408     /* Get rect including non-client area */
409     AdjustWindowRectEx(&windowRect,windowStyle,FALSE,windowExStyle);
410
411     /* Move window right and down by non-client area extent on left and top, if wanted */
412     if (posIsOutside)
413     {
414         windowRect.right   += clientRect->left-windowRect.left;
415         windowRect.bottom  += clientRect->top -windowRect.top;
416         windowRect.left     = clientRect->left;
417         windowRect.top      = clientRect->top;
418     }
419     
420     /* done, copy windowRect to output */
421     CopyRect(clientRect,&windowRect);
422 }
423
424 /* Computes position of corners of window Rect (outer position including
425  * decorations) based on the provided client rect and based on the style
426  * of the window in question. If the window pointer or the window handle
427  * is NULL, a fully decorated window (caption and border) is assumed.
428  * Furthermore, if posIsOutside is set to true, the input client Rect is
429  * taken to follow freeGLUT's window specification convention in which the
430  * top-left corner is at the outside of the window, while the size
431  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
432  * area.
433 */
434 void fghComputeWindowRectFromClientArea_QueryWindow( RECT *clientRect, const SFG_Window *window, BOOL posIsOutside )
435 {
436     DWORD windowStyle = 0, windowExStyle = 0;
437     fghGetStyleFromWindow(window,&windowStyle,&windowExStyle);
438
439     fghComputeWindowRectFromClientArea_UseStyle(clientRect, windowStyle, windowExStyle, posIsOutside);
440 }
441
442
443 /* Gets the rect describing the client area (drawable area) of the
444  * specified window. Output is position of corners of client area (drawable area) on the screen.
445  * Returns an empty rect if window pointer or window handle is NULL.
446  * If wantPosOutside is set to true, the output client Rect
447  * will follow freeGLUT's window specification convention in which the
448  * top-left corner is at the outside of the window, while the size
449  * (rect.right-rect.left,rect.bottom-rect.top) is the size of the drawable
450  * area.
451  */
452 void fghGetClientArea( RECT *clientRect, const SFG_Window *window, BOOL wantPosOutside )
453 {
454     POINT topLeftClient = {0,0};
455     POINT topLeftWindow = {0,0};
456
457     freeglut_return_if_fail((window && window->Window.Handle));
458     
459     /*
460      * call GetWindowRect()
461      * (this returns the pixel coordinates of the outside of the window)
462      * cannot use GetClientRect as it returns a rect relative to
463      * the top-left point of the client area (.top and .left are thus always 0)
464      * and is thus only useful for querying the size of the client area, not
465      * its position.
466      */
467     GetWindowRect( window->Window.Handle, clientRect );
468     topLeftWindow.x = clientRect->top;
469     topLeftWindow.y = clientRect->left;
470     
471     /* Get size of client rect */
472     GetClientRect(window->Window.Handle, clientRect);
473     /* Get position of top-left of client area on the screen */
474     ClientToScreen(window->Window.Handle,&topLeftClient);
475     /* Add top-left offset */
476     OffsetRect(clientRect,topLeftClient.x,topLeftClient.y);
477
478     /* replace top and left with top and left of window, if wanted */
479     if (wantPosOutside)
480     {
481         clientRect->left = topLeftWindow.x;
482         clientRect->top  = topLeftWindow.y;
483     }
484 }
485
486 #if(WINVER >= 0x500)
487 typedef struct
488 {
489       int *x;
490       int *y;
491       const char *name;
492 } m_proc_t;
493
494 static BOOL CALLBACK m_proc(HMONITOR mon,
495                             HDC hdc,
496                             LPRECT rect,
497                             LPARAM data)
498 {
499       m_proc_t *dp=(m_proc_t *)data;
500       MONITORINFOEX info;
501       BOOL res;
502       info.cbSize=sizeof(info);
503       res=GetMonitorInfo(mon,(LPMONITORINFO)&info);
504       if( res )
505       {
506           if( strcmp(dp->name,info.szDevice)==0 )
507           {
508               *(dp->x)=info.rcMonitor.left;
509               *(dp->y)=info.rcMonitor.top;
510               return FALSE;
511           }
512       }
513       return TRUE;
514 }
515
516 /* 
517  * this function returns the origin of the screen identified by
518  * fgDisplay.pDisplay.DisplayName, and 0 otherwise.
519  * This is used in fgOpenWindow to open the gamemode window on the screen
520  * identified by the -display command line argument. The function should
521  * not be called otherwise.
522  */
523
524 static void get_display_origin(int *xp,int *yp)
525 {
526     *xp = 0;
527     *yp = 0;
528
529     if( fgDisplay.pDisplay.DisplayName )
530     {
531         m_proc_t st;
532         st.x=xp;
533         st.y=yp;
534         st.name=fgDisplay.pDisplay.DisplayName;
535         EnumDisplayMonitors(0,0,m_proc,(LPARAM)&st);
536     }
537 }
538 #else
539 #pragma message( "-display parameter only works if compiled with WINVER >= 0x0500")
540
541 static void get_display_origin(int *xp,int *yp)
542 {
543     *xp = 0;
544     *yp = 0;
545
546     if( fgDisplay.pDisplay.DisplayName )
547     {
548         fgWarning( "for working -display support FreeGLUT must be compiled with WINVER >= 0x0500");
549     }
550 }
551 #endif
552
553
554
555 /*
556  * Opens a window. Requires a SFG_Window object created and attached
557  * to the freeglut structure. OpenGL context is created here.
558  */
559 void fgPlatformOpenWindow( SFG_Window* window, const char* title,
560                            GLboolean positionUse, int x, int y,
561                            GLboolean sizeUse, int w, int h,
562                            GLboolean gameMode, GLboolean isSubWindow )
563 {
564
565     WNDCLASS wc;
566     DWORD flags   = 0;
567     DWORD exFlags = 0;
568     ATOM atom;
569
570     /* Grab the window class we have registered on glutInit(): */
571     atom = GetClassInfo( fgDisplay.pDisplay.Instance, _T("FREEGLUT"), &wc );
572     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
573                                    "fgOpenWindow" );
574
575     /* Determine window style flags*/
576     if( gameMode )
577     {
578         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
579                                        "Game mode being invoked on a subwindow",
580                                        "fgOpenWindow" );
581
582         /*
583          * Set the window creation flags appropriately to make the window
584          * entirely visible:
585          */
586         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
587     }
588     else
589     {
590         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
591
592         /*
593          * There's a small difference between creating the top, child and
594          * menu windows
595          */
596         if ( window->IsMenu )
597         {
598             flags |= WS_POPUP;
599             exFlags |= WS_EX_TOOLWINDOW;
600         }
601 #if defined(_WIN32_WCE)
602         /* no decorations for windows CE */
603 #else
604         /* if this is not a subwindow (child), set its style based on the requested display mode */
605         else if( window->Parent == NULL )
606             if ( fgState.DisplayMode & GLUT_BORDERLESS )
607             {
608                 /* no window decorations needed */
609             }
610             else if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
611                 /* only window decoration is a border, no title bar or buttons */
612                 flags |= WS_DLGFRAME;
613             else
614                 /* window decoration are a border, title bar and buttons.
615                  * NB: we later query whether the window has a title bar or
616                  * not by testing for the maximize button, as the test for
617                  * WS_CAPTION can be true without the window having a title
618                  * bar. This style WS_OVERLAPPEDWINDOW gives you a maximize
619                  * button. */
620                 flags |= WS_OVERLAPPEDWINDOW;
621 #endif
622         else
623             /* subwindows always have no decoration, but are marked as a child window to the OS */
624             flags |= WS_CHILD;
625     }
626
627     /* determine window size and position */
628     if( gameMode )
629     {
630         /* if in gamemode, query the origin of specified by the -display
631          * command line parameter (if any) and offset the upper-left corner
632          * of the window so we create the window on that screen.
633          * The -display argument doesn't do anything if not trying to enter
634          * gamemode.
635          */
636         int xoff=0, yoff=0;
637         get_display_origin(&xoff,&yoff);
638         x += xoff;
639         y += yoff;
640     }
641     if( !positionUse )
642     {
643         x = CW_USEDEFAULT;
644         y = CW_USEDEFAULT;
645     }
646     if( !sizeUse )
647     {
648         if( ! window->IsMenu )
649         {
650             w = CW_USEDEFAULT;
651             h = CW_USEDEFAULT;
652         }
653         else /* fail safe - Windows can make a window of size (0, 0) */
654             w = h = 300; /* default window size */
655     }
656     /* store requested client area width and height */
657     window->State.Width = w;
658     window->State.Height = h;
659
660 #if !defined(_WIN32_WCE)    /* no decorations for windows CE */
661     if( sizeUse )
662     {
663         RECT windowRect;
664         /*
665          * Update the window dimensions, taking the window decorations
666          * into account.  FreeGLUT is to create the window with the
667          * topleft outside corner at (x,y) and with client area
668          * dimensions (w,h).
669          * note: don't need to do this when w=h=CW_USEDEFAULT, so in the
670          * if( sizeUse ) here is convenient.
671          */
672         windowRect.left     = x;
673         windowRect.top      = y;
674         windowRect.right    = x+w;
675         windowRect.bottom   = y+h;
676
677         fghComputeWindowRectFromClientArea_UseStyle(&windowRect,flags,exFlags,TRUE);
678
679         /* NB: w and h are now width and height of window including non-client area! */
680         w = windowRect.right - windowRect.left;
681         h = windowRect.bottom- windowRect.top;
682     }
683 #endif /* !defined(_WIN32_WCE) */
684
685 #if defined(_WIN32_WCE)
686     {
687         wchar_t* wstr = fghWstrFromStr(title);
688
689         window->Window.Handle = CreateWindow(
690             _T("FREEGLUT"),
691             wstr,
692             WS_VISIBLE | WS_POPUP,
693             0,0, 240,320,
694             NULL,
695             NULL,
696             fgDisplay.pDisplay.Instance,
697             (LPVOID) window
698         );
699
700         free(wstr);
701
702         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
703         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
704         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
705         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
706         ShowWindow(window->Window.Handle, SW_SHOW);
707         UpdateWindow(window->Window.Handle);
708     }
709 #else
710     window->Window.Handle = CreateWindowEx(
711         exFlags,
712         _T("FREEGLUT"),
713         title,
714         flags,
715         x, y, w, h,
716         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
717         (HMENU) NULL,
718         fgDisplay.pDisplay.Instance,
719         (LPVOID) window
720     );
721 #endif /* defined(_WIN32_WCE) */
722
723     if( !( window->Window.Handle ) )
724         fgError( "Failed to create a window (%s)!", title );
725
726 #if !defined(_WIN32_WCE)
727     /* Need to set requested style again, apparently Windows doesn't listen when requesting windows without title bar or borders */
728     SetWindowLong(window->Window.Handle, GWL_STYLE, flags);
729     SetWindowPos(window->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
730 #endif /* defined(_WIN32_WCE) */
731
732     /* Make a menu window always on top - fix Feature Request 947118 */
733     if( window->IsMenu || gameMode )
734         SetWindowPos(
735                         window->Window.Handle,
736                         HWND_TOPMOST,
737                         0, 0, 0, 0,
738                         SWP_NOMOVE | SWP_NOSIZE
739                     );
740
741     /* Enable multitouch: additional flag TWF_FINETOUCH, TWF_WANTPALM */
742     #ifdef WM_TOUCH
743         if (fghRegisterTouchWindow == (pRegisterTouchWindow)0xDEADBEEF) 
744                         fghRegisterTouchWindow = (pRegisterTouchWindow)GetProcAddress(GetModuleHandle("user32"),"RegisterTouchWindow");
745                 if (fghRegisterTouchWindow)
746              fghRegisterTouchWindow( window->Window.Handle, TWF_FINETOUCH | TWF_WANTPALM );
747     #endif
748
749 #if defined(_WIN32_WCE)
750     ShowWindow( window->Window.Handle, SW_SHOW );
751 #else
752     ShowWindow( window->Window.Handle,
753                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
754 #endif /* defined(_WIN32_WCE) */
755
756     UpdateWindow( window->Window.Handle );
757     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
758 }
759
760
761 /*
762  * Closes a window, destroying the frame and OpenGL context
763  */
764 void fgPlatformCloseWindow( SFG_Window* window )
765 {
766     /* Make sure we don't close a window with current context active */
767     if( fgStructure.CurrentWindow == window )
768         wglMakeCurrent( NULL, NULL );
769
770     /*
771      * Step through the list of windows.  If the rendering context
772      * is not being used by another window, then we delete it.
773      */
774     {
775         int used = FALSE ;
776         SFG_Window *iter ;
777
778         for( iter = (SFG_Window *)fgStructure.Windows.First;
779              iter;
780              iter = (SFG_Window *)iter->Node.Next )
781         {
782             if( ( iter->Window.Context == window->Window.Context ) &&
783                 ( iter != window ) )
784                 used = TRUE;
785         }
786
787         if( ! used )
788             wglDeleteContext( window->Window.Context );
789     }
790
791     DestroyWindow( window->Window.Handle );
792 }
793
794
795
796 /*
797  * This function makes the current window visible
798  */
799 void fgPlatformGlutShowWindow( void )
800 {
801     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
802 }
803
804 /*
805  * This function hides the current window
806  */
807 void fgPlatformGlutHideWindow( void )
808 {
809     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
810 }
811
812 /*
813  * Iconify the current window (top-level windows only)
814  */
815 void fgPlatformGlutIconifyWindow( void )
816 {
817     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
818 }
819
820 /*
821  * Set the current window's title
822  */
823 void fgPlatformGlutSetWindowTitle( const char* title )
824 {
825 #ifdef _WIN32_WCE
826     {
827         wchar_t* wstr = fghWstrFromStr(title);
828         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
829         free(wstr);
830     }
831 #else
832     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
833 #endif
834 }
835
836 /*
837  * Set the current window's iconified title
838  * There really isn't a way to set the icon name separate from the
839  * windows name in Win32, so, just set the windows name.
840  */
841 void fgPlatformGlutSetIconTitle( const char* title )
842 {
843 #ifdef _WIN32_WCE
844     {
845         wchar_t* wstr = fghWstrFromStr(title);
846         SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
847         free(wstr);
848     }
849 #else
850     SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
851 #endif
852 }
853
854 /*
855  * Change the current window's position
856  */
857 void fgPlatformGlutPositionWindow( int x, int y )
858 {
859     RECT winRect;
860
861     /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
862     GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
863     MoveWindow(
864         fgStructure.CurrentWindow->Window.Handle,
865         x,
866         y,
867         winRect.right - winRect.left,
868         winRect.bottom - winRect.top,
869         TRUE
870     );
871 }
872
873 /*
874  * Lowers the current window (by Z order change)
875  */
876 void fgPlatformGlutPushWindow( void )
877 {
878     SetWindowPos(
879         fgStructure.CurrentWindow->Window.Handle,
880         HWND_BOTTOM,
881         0, 0, 0, 0,
882         SWP_NOSIZE | SWP_NOMOVE
883     );
884 }
885
886 /*
887  * Raises the current window (by Z order change)
888  */
889 void fgPlatformGlutPopWindow( void )
890 {
891     SetWindowPos(
892         fgStructure.CurrentWindow->Window.Handle,
893         HWND_TOP,
894         0, 0, 0, 0,
895         SWP_NOSIZE | SWP_NOMOVE
896     );
897 }
898
899 /*
900  * Resize the current window so that it fits the whole screen
901  */
902 void fgPlatformGlutFullScreen( SFG_Window *win )
903 {
904 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
905
906     if (glutGet(GLUT_FULL_SCREEN))
907     {
908         /*  Leave full screen state before entering fullscreen again (resizing?) */
909         glutLeaveFullScreen();
910     }
911
912     {
913 #if(WINVER >= 0x0500) /* Windows 2000 or later */
914         DWORD s;
915         RECT rect;
916         HMONITOR hMonitor;
917         MONITORINFO mi;
918
919         /* For fullscreen mode, first remove all window decoration
920          * and set style to popup so it will overlap the taskbar
921          * then force to maximize on the screen on which it has the most
922          * overlap.
923          */
924
925         
926         /* store current window rect */
927         GetWindowRect( win->Window.Handle, &win->State.pWState.OldRect );
928
929         /* store current window style */
930         win->State.pWState.OldStyle = s = GetWindowLong(win->Window.Handle, GWL_STYLE);
931
932         /* remove decorations from style and add popup style*/
933         s &= ~WS_OVERLAPPEDWINDOW;
934         s |= WS_POPUP;
935         SetWindowLong(win->Window.Handle, GWL_STYLE, s);
936         SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
937
938         /* For fullscreen mode, find the monitor that is covered the most
939          * by the window and get its rect as the resize target.
940              */
941         hMonitor= MonitorFromRect(&win->State.pWState.OldRect, MONITOR_DEFAULTTONEAREST);
942         mi.cbSize = sizeof(mi);
943         GetMonitorInfo(hMonitor, &mi);
944         rect = mi.rcMonitor;
945 #else   /* if (WINVER >= 0x0500) */
946         RECT rect;
947
948         /* For fullscreen mode, force the top-left corner to 0,0
949          * and adjust the window rectangle so that the client area
950          * covers the whole screen.
951          */
952
953         rect.left   = 0;
954         rect.top    = 0;
955         rect.right  = fgDisplay.ScreenWidth;
956         rect.bottom = fgDisplay.ScreenHeight;
957
958         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
959                                   WS_CLIPCHILDREN, FALSE );
960 #endif  /* (WINVER >= 0x0500) */
961
962         /*
963          * then resize window
964          * SWP_NOACTIVATE     Do not activate the window
965          * SWP_NOOWNERZORDER  Do not change position in z-order
966          * SWP_NOSENDCHANGING Suppress WM_WINDOWPOSCHANGING message
967          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
968          */
969         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
970                       HWND_TOP,
971                       rect.left,
972                       rect.top,
973                       rect.right  - rect.left,
974                       rect.bottom - rect.top,
975                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
976                       SWP_NOZORDER
977                     );
978
979         win->State.IsFullscreen = GL_TRUE;
980     }
981 #endif
982 }
983
984 /*
985  * If we are fullscreen, resize the current window back to its original size
986  */
987 void fgPlatformGlutLeaveFullScreen( SFG_Window *win )
988 {
989 #if !defined(_WIN32_WCE) /* FIXME: what about WinCE */
990     if (!glutGet(GLUT_FULL_SCREEN))
991     {
992         /* nothing to do */
993         return;
994     }
995
996     /* restore style of window before making it fullscreen */
997     SetWindowLong(win->Window.Handle, GWL_STYLE, win->State.pWState.OldStyle);
998     SetWindowPos(win->Window.Handle, HWND_TOP, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
999
1000     /* Then resize */
1001     SetWindowPos(win->Window.Handle,
1002         HWND_TOP,
1003         win->State.pWState.OldRect.left,
1004         win->State.pWState.OldRect.top,
1005         win->State.pWState.OldRect.right  - win->State.pWState.OldRect.left,
1006         win->State.pWState.OldRect.bottom - win->State.pWState.OldRect.top,
1007         SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1008         SWP_NOZORDER
1009         );
1010
1011     win->State.IsFullscreen = GL_FALSE;
1012 #endif
1013 }
1014
1015 /*
1016  * Toggle the window's full screen state.
1017  */
1018 void fgPlatformGlutFullScreenToggle( SFG_Window *win )
1019 {
1020     if (!win->State.IsFullscreen)
1021         glutFullScreen();
1022     else
1023         glutLeaveFullScreen();
1024 }
1025
1026
1027 /* -- PLATFORM-SPECIFIC INTERFACE FUNCTION -------------------------------------------------- */
1028
1029 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1030 {
1031   __glutExitFunc = exit_function;
1032   return glutCreateWindow( title );
1033 }
1034