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