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