41c3fe76ab7507aec45adf7b46ede0ee1768a024
[freeglut] / src / freeglut_window.c
1 /*
2  * freeglut_window.c
3  *
4  * Window management methods.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Fri Dec 3 1999
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 "freeglut_internal.h"
31
32 #if TARGET_HOST_POSIX_X11
33 #include <limits.h>  /* LONG_MAX */
34 #include <unistd.h>  /* usleep */
35 #endif
36
37 #if defined(_WIN32_WCE)
38 #   include <Aygshell.h>
39 #   ifdef FREEGLUT_LIB_PRAGMAS
40 #       pragma comment( lib, "Aygshell.lib" )
41 #   endif
42 #endif /* defined(_WIN32_WCE) */
43
44
45 #if TARGET_HOST_POSIX_X11
46 #ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
47 #define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20B2
48 #endif
49
50 #ifndef GLX_CONTEXT_MAJOR_VERSION_ARB
51 #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
52 #endif
53
54 #ifndef GLX_CONTEXT_MINOR_VERSION_ARB
55 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
56 #endif
57
58 #ifndef GLX_CONTEXT_FLAGS_ARB
59 #define GLX_CONTEXT_FLAGS_ARB 0x2094
60 #endif
61
62 #ifndef GLX_CONTEXT_PROFILE_MASK_ARB
63 #define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
64 #endif
65
66 #ifndef GLX_CONTEXT_DEBUG_BIT_ARB
67 #define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001
68 #endif
69
70 #ifndef GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB
71 #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
72 #endif
73
74 #ifndef GLX_CONTEXT_CORE_PROFILE_BIT_ARB
75 #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
76 #endif
77
78 #ifndef GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
79 #define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
80 #endif
81
82 #ifndef GLX_RGBA_FLOAT_TYPE
83 #define GLX_RGBA_FLOAT_TYPE 0x20B9
84 #endif
85
86 #ifndef GLX_RGBA_FLOAT_BIT
87 #define GLX_RGBA_FLOAT_BIT 0x00000004
88 #endif
89 #endif  /* TARGET_HOST_POSIX_X11 */
90
91
92 #if TARGET_HOST_MS_WINDOWS
93 /* The following include file is available from SGI but is not standard:
94  *   #include <GL/wglext.h>
95  * So we copy the necessary parts out of it.
96  * XXX: should local definitions for extensions be put in a separate include file?
97  */
98 typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
99
100 typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
101
102 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
103 #define WGL_ACCELERATION_ARB           0x2003
104 #define WGL_SUPPORT_OPENGL_ARB         0x2010
105 #define WGL_DOUBLE_BUFFER_ARB          0x2011
106 #define WGL_COLOR_BITS_ARB             0x2014
107 #define WGL_ALPHA_BITS_ARB             0x201B
108 #define WGL_DEPTH_BITS_ARB             0x2022
109 #define WGL_STENCIL_BITS_ARB           0x2023
110 #define WGL_FULL_ACCELERATION_ARB      0x2027
111
112 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
113 #define WGL_SAMPLES_ARB                0x2042
114
115 #define WGL_TYPE_RGBA_FLOAT_ARB        0x21A0
116
117 #define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9
118
119 #ifndef WGL_ARB_create_context
120 #define WGL_ARB_create_context 1
121 #ifdef WGL_WGLEXT_PROTOTYPES
122 extern HGLRC WINAPI wglCreateContextAttribsARB (HDC, HGLRC, const int *);
123 #endif /* WGL_WGLEXT_PROTOTYPES */
124 typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
125
126 #define WGL_CONTEXT_MAJOR_VERSION_ARB  0x2091
127 #define WGL_CONTEXT_MINOR_VERSION_ARB  0x2092
128 #define WGL_CONTEXT_LAYER_PLANE_ARB    0x2093
129 #define WGL_CONTEXT_FLAGS_ARB          0x2094
130 #define WGL_CONTEXT_PROFILE_MASK_ARB   0x9126
131
132 #define WGL_CONTEXT_DEBUG_BIT_ARB      0x0001
133 #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
134
135 #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
136 #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
137
138 #define ERROR_INVALID_VERSION_ARB      0x2095
139 #define ERROR_INVALID_PROFILE_ARB      0x2096
140 #endif
141
142 #endif  /* TARGET_HOST_MS_WINDOWS */
143
144 #ifdef WM_TOUCH
145         typedef BOOL (*pRegisterTouchWindow)(HWND,ULONG);
146    static pRegisterTouchWindow fghRegisterTouchWindow = (pRegisterTouchWindow)0xDEADBEEF;
147 #endif
148
149 /* pushing attribute/value pairs into an array */
150 #define ATTRIB(a) attributes[where++]=(a)
151 #define ATTRIB_VAL(a,v) {ATTRIB(a); ATTRIB(v);}
152
153 /*
154  * TODO BEFORE THE STABLE RELEASE:
155  *
156  *  fgChooseFBConfig()      -- OK, but what about glutInitDisplayString()?
157  *  fgSetupPixelFormat      -- ignores the display mode settings
158  *  fgOpenWindow()          -- check the Win32 version, -iconic handling!
159  *  fgCloseWindow()         -- check the Win32 version
160  *  glutCreateWindow()      -- Check when default position and size is {-1,-1}
161  *  glutCreateSubWindow()   -- Check when default position and size is {-1,-1}
162  *  glutDestroyWindow()     -- check the Win32 version
163  *  glutSetWindow()         -- check the Win32 version
164  *  glutGetWindow()         -- OK
165  *  glutSetWindowTitle()    -- check the Win32 version
166  *  glutSetIconTitle()      -- check the Win32 version
167  *  glutShowWindow()        -- check the Win32 version
168  *  glutHideWindow()        -- check the Win32 version
169  *  glutIconifyWindow()     -- check the Win32 version
170  *  glutReshapeWindow()     -- check the Win32 version
171  *  glutPositionWindow()    -- check the Win32 version
172  *  glutPushWindow()        -- check the Win32 version
173  *  glutPopWindow()         -- check the Win32 version
174  */
175
176 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
177
178 static int fghIsLegacyContextVersionRequested( void )
179 {
180   return fgState.MajorVersion == 1 && fgState.MinorVersion == 0;
181 }
182
183 static int fghIsLegacyContextRequested( void )
184 {
185   return fghIsLegacyContextVersionRequested() &&
186          fgState.ContextFlags == 0 &&
187          fgState.ContextProfile == 0;
188 }
189
190 static int fghNumberOfAuxBuffersRequested( void )
191 {
192   if ( fgState.DisplayMode & GLUT_AUX4 ) {
193     return 4;
194   }
195   if ( fgState.DisplayMode & GLUT_AUX3 ) {
196     return 3;
197   }
198   if ( fgState.DisplayMode & GLUT_AUX2 ) {
199     return 2;
200   }
201   if ( fgState.DisplayMode & GLUT_AUX1 ) { /* NOTE: Same as GLUT_AUX! */
202     return fgState.AuxiliaryBufferNumber;
203   }
204   return 0;
205 }
206
207 static int fghMapBit( int mask, int from, int to )
208 {
209   return ( mask & from ) ? to : 0;
210
211 }
212
213 static void fghContextCreationError( void )
214 {
215     fgError( "Unable to create OpenGL %d.%d context (flags %x, profile %x)",
216              fgState.MajorVersion, fgState.MinorVersion, fgState.ContextFlags,
217              fgState.ContextProfile );
218 }
219
220
221 /* -- SYSTEM-DEPENDENT PRIVATE FUNCTIONS ------------------------------------ */
222
223 #if TARGET_HOST_POSIX_X11
224 /*
225  * Chooses a visual basing on the current display mode settings
226  */
227
228 GLXFBConfig* fgChooseFBConfig( int *numcfgs )
229 {
230   GLboolean wantIndexedMode = GL_FALSE;
231   int attributes[ 100 ];
232   int where = 0, numAuxBuffers;
233
234   /* First we have to process the display mode settings... */
235   if( fgState.DisplayMode & GLUT_INDEX ) {
236     ATTRIB_VAL( GLX_BUFFER_SIZE, 8 );
237     /*  Buffer size is selected later.  */
238
239     ATTRIB_VAL( GLX_RENDER_TYPE, GLX_COLOR_INDEX_BIT );
240     wantIndexedMode = GL_TRUE;
241   } else {
242     ATTRIB_VAL( GLX_RED_SIZE,   1 );
243     ATTRIB_VAL( GLX_GREEN_SIZE, 1 );
244     ATTRIB_VAL( GLX_BLUE_SIZE,  1 );
245     if( fgState.DisplayMode & GLUT_ALPHA ) {
246       ATTRIB_VAL( GLX_ALPHA_SIZE, 1 );
247     }
248   }
249
250   if( fgState.DisplayMode & GLUT_DOUBLE ) {
251     ATTRIB_VAL( GLX_DOUBLEBUFFER, True );
252   }
253
254   if( fgState.DisplayMode & GLUT_STEREO ) {
255     ATTRIB_VAL( GLX_STEREO, True );
256   }
257
258   if( fgState.DisplayMode & GLUT_DEPTH ) {
259     ATTRIB_VAL( GLX_DEPTH_SIZE, 1 );
260   }
261
262   if( fgState.DisplayMode & GLUT_STENCIL ) {
263     ATTRIB_VAL( GLX_STENCIL_SIZE, 1 );
264   }
265
266   if( fgState.DisplayMode & GLUT_ACCUM ) {
267     ATTRIB_VAL( GLX_ACCUM_RED_SIZE, 1 );
268     ATTRIB_VAL( GLX_ACCUM_GREEN_SIZE, 1 );
269     ATTRIB_VAL( GLX_ACCUM_BLUE_SIZE, 1 );
270     if( fgState.DisplayMode & GLUT_ALPHA ) {
271       ATTRIB_VAL( GLX_ACCUM_ALPHA_SIZE, 1 );
272     }
273   }
274
275   numAuxBuffers = fghNumberOfAuxBuffersRequested();
276   if ( numAuxBuffers > 0 ) {
277     ATTRIB_VAL( GLX_AUX_BUFFERS, numAuxBuffers );
278   }
279
280   if( fgState.DisplayMode & GLUT_SRGB ) {
281     ATTRIB_VAL( GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, True );
282   }
283
284   if (fgState.DisplayMode & GLUT_MULTISAMPLE) {
285     ATTRIB_VAL(GLX_SAMPLE_BUFFERS, 1);
286     ATTRIB_VAL(GLX_SAMPLES, fgState.SampleNumber);
287   }
288
289   /* Push a terminator at the end of the list */
290   ATTRIB( None );
291
292     {
293         GLXFBConfig * fbconfigArray;  /*  Array of FBConfigs  */
294         GLXFBConfig * fbconfig;       /*  The FBConfig we want  */
295         int fbconfigArraySize;        /*  Number of FBConfigs in the array  */
296
297
298         /*  Get all FBConfigs that match "attributes".  */
299         fbconfigArray = glXChooseFBConfig( fgDisplay.Display,
300                                            fgDisplay.Screen,
301                                            attributes,
302                                            &fbconfigArraySize );
303
304         if (fbconfigArray != NULL)
305         {
306             int result;  /* Returned by glXGetFBConfigAttrib, not checked. */
307
308
309             if( wantIndexedMode )
310             {
311                 /*
312                  * In index mode, we want the largest buffer size, i.e. visual
313                  * depth.  Here, FBConfigs are sorted by increasing buffer size
314                  * first, so FBConfigs with the largest size come last.
315                  */
316
317                 int bufferSizeMin, bufferSizeMax;
318
319                 /*  Get bufferSizeMin.  */
320                 result =
321                   glXGetFBConfigAttrib( fgDisplay.Display,
322                                         fbconfigArray[0],
323                                         GLX_BUFFER_SIZE,
324                                         &bufferSizeMin );
325                 /*  Get bufferSizeMax.  */
326                 result =
327                   glXGetFBConfigAttrib( fgDisplay.Display,
328                                         fbconfigArray[fbconfigArraySize - 1],
329                                         GLX_BUFFER_SIZE,
330                                         &bufferSizeMax );
331
332                 if (bufferSizeMax > bufferSizeMin)
333                 {
334                     /* 
335                      * Free and reallocate fbconfigArray, keeping only FBConfigs
336                      * with the largest buffer size.
337                      */
338                     XFree(fbconfigArray);
339
340                     /*  Add buffer size token at the end of the list.  */
341                     where--;
342                     ATTRIB_VAL( GLX_BUFFER_SIZE, bufferSizeMax );
343                     ATTRIB( None );
344
345                     fbconfigArray = glXChooseFBConfig( fgDisplay.Display,
346                                                        fgDisplay.Screen,
347                                                        attributes,
348                                                        &fbconfigArraySize );
349                 }
350             }
351
352             /*
353              * We now have an array of FBConfigs, the first one being the "best"
354              * one.  So we should return only this FBConfig:
355              *
356              * int fbconfigXID;
357              *
358              *  - pick the XID of the FBConfig we want
359              * result = glXGetFBConfigAttrib( fgDisplay.Display,
360              *                                fbconfigArray[0],
361              *                                GLX_FBCONFIG_ID,
362              *                                &fbconfigXID );
363              *
364              * - free the array
365              * XFree(fbconfigArray);
366              *
367              * - reset "attributes" with the XID
368              * where = 0;
369              * ATTRIB_VAL( GLX_FBCONFIG_ID, fbconfigXID );
370              * ATTRIB( None );
371              *
372              * - get our FBConfig only
373              * fbconfig = glXChooseFBConfig( fgDisplay.Display,
374              *                               fgDisplay.Screen,
375              *                               attributes,
376              *                               &fbconfigArraySize );
377              *
378              * However, for some configurations (for instance multisampling with
379              * Mesa 6.5.2 and ATI drivers), this does not work:
380              * glXChooseFBConfig returns NULL, whereas fbconfigXID is a valid
381              * XID.  Further investigation is needed.
382              *
383              * So, for now, we return the whole array of FBConfigs.  This should
384              * not produce any side effects elsewhere.
385              */
386             fbconfig = fbconfigArray;
387         }
388         else
389         {
390            fbconfig = NULL;
391         }
392
393         if (numcfgs)
394                 *numcfgs = fbconfigArraySize;
395
396         return fbconfig;
397     }
398 }
399
400
401 static void fghFillContextAttributes( int *attributes ) {
402   int where = 0, contextFlags, contextProfile;
403
404   if ( !fghIsLegacyContextVersionRequested() ) {
405     ATTRIB_VAL( GLX_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
406     ATTRIB_VAL( GLX_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
407   }
408
409   contextFlags =
410     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, GLX_CONTEXT_DEBUG_BIT_ARB ) |
411     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
412   if ( contextFlags != 0 ) {
413     ATTRIB_VAL( GLX_CONTEXT_FLAGS_ARB, contextFlags );
414   }
415
416   contextProfile =
417     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, GLX_CONTEXT_CORE_PROFILE_BIT_ARB ) |
418     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
419   if ( contextProfile != 0 ) {
420     ATTRIB_VAL( GLX_CONTEXT_PROFILE_MASK_ARB, contextProfile );
421   }
422
423   ATTRIB( 0 );
424 }
425
426 typedef GLXContext (*CreateContextAttribsProc)(Display *dpy, GLXFBConfig config,
427                                                GLXContext share_list, Bool direct,
428                                                const int *attrib_list);
429
430 static GLXContext fghCreateNewContext( SFG_Window* window )
431 {
432   /* for color model calculation */
433   int menu = ( window->IsMenu && !fgStructure.MenuContext );
434   int index_mode = ( fgState.DisplayMode & GLUT_INDEX );
435
436   /* "classic" context creation */
437   Display *dpy = fgDisplay.Display;
438   GLXFBConfig config = *(window->Window.FBConfig);
439   int render_type = ( !menu && index_mode ) ? GLX_COLOR_INDEX_TYPE : GLX_RGBA_TYPE;
440   GLXContext share_list = NULL;
441   Bool direct = ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT );
442   GLXContext context;
443
444   /* new context creation */
445   int attributes[9];
446   CreateContextAttribsProc createContextAttribs;
447
448   /* If nothing fancy has been required, simply use the old context creation GLX API entry */
449   if ( fghIsLegacyContextRequested() )
450   {
451     context = glXCreateNewContext( dpy, config, render_type, share_list, direct );
452     if ( context == NULL ) {
453       fghContextCreationError();
454     }
455     return context;
456   }
457
458   /* color index mode is not available anymore with OpenGL 3.0 */
459   if ( render_type == GLX_COLOR_INDEX_TYPE ) {
460     fgWarning( "color index mode is deprecated, using RGBA mode" );
461   }
462
463   fghFillContextAttributes( attributes );
464
465   createContextAttribs = (CreateContextAttribsProc) fghGetProcAddress( "glXCreateContextAttribsARB" );
466   if ( createContextAttribs == NULL ) {
467     fgError( "glXCreateContextAttribsARB not found" );
468   }
469
470   context = createContextAttribs( dpy, config, share_list, direct, attributes );
471   if ( context == NULL ) {
472     fghContextCreationError();
473   }
474   return context;
475 }
476
477
478 #define _NET_WM_STATE_TOGGLE    2
479 static int fghResizeFullscrToggle(void)
480 {
481     XWindowAttributes attributes;
482
483     if(glutGet(GLUT_FULL_SCREEN)) {
484         /* restore original window size */
485         SFG_Window *win = fgStructure.CurrentWindow;
486         fgStructure.CurrentWindow->State.NeedToResize = GL_TRUE;
487         fgStructure.CurrentWindow->State.Width  = win->State.OldWidth;
488         fgStructure.CurrentWindow->State.Height = win->State.OldHeight;
489
490     } else {
491         /* resize the window to cover the entire screen */
492         XGetWindowAttributes(fgDisplay.Display,
493                 fgStructure.CurrentWindow->Window.Handle,
494                 &attributes);
495         
496         /*
497          * The "x" and "y" members of "attributes" are the window's coordinates
498          * relative to its parent, i.e. to the decoration window.
499          */
500         XMoveResizeWindow(fgDisplay.Display,
501                 fgStructure.CurrentWindow->Window.Handle,
502                 -attributes.x,
503                 -attributes.y,
504                 fgDisplay.ScreenWidth,
505                 fgDisplay.ScreenHeight);
506     }
507     return 0;
508 }
509
510 static int fghEwmhFullscrToggle(void)
511 {
512     XEvent xev;
513     long evmask = SubstructureRedirectMask | SubstructureNotifyMask;
514
515     if(!fgDisplay.State || !fgDisplay.StateFullScreen) {
516         return -1;
517     }
518
519     xev.type = ClientMessage;
520     xev.xclient.window = fgStructure.CurrentWindow->Window.Handle;
521     xev.xclient.message_type = fgDisplay.State;
522     xev.xclient.format = 32;
523     xev.xclient.data.l[0] = _NET_WM_STATE_TOGGLE;
524     xev.xclient.data.l[1] = fgDisplay.StateFullScreen;
525     xev.xclient.data.l[2] = 0;  /* no second property to toggle */
526     xev.xclient.data.l[3] = 1;  /* source indication: application */
527     xev.xclient.data.l[4] = 0;  /* unused */
528
529     if(!XSendEvent(fgDisplay.Display, fgDisplay.RootWindow, 0, evmask, &xev)) {
530         return -1;
531     }
532     return 0;
533 }
534
535 static int fghToggleFullscreen(void)
536 {
537     /* first try the EWMH (_NET_WM_STATE) method ... */
538     if(fghEwmhFullscrToggle() != -1) {
539         return 0;
540     }
541
542     /* fall back to resizing the window */
543     if(fghResizeFullscrToggle() != -1) {
544         return 0;
545     }
546     return -1;
547 }
548
549
550 #endif  /* TARGET_HOST_POSIX_X11 */
551
552
553 #if TARGET_HOST_MS_WINDOWS
554 /*
555  * Setup the pixel format for a Win32 window
556  */
557
558 #if defined(_WIN32_WCE)
559 static wchar_t* fghWstrFromStr(const char* str)
560 {
561     int i,len=strlen(str);
562     wchar_t* wstr = (wchar_t*)malloc(2*len+2);
563     for(i=0; i<len; i++)
564         wstr[i] = str[i];
565     wstr[len] = 0;
566     return wstr;
567 }
568 #endif /* defined(_WIN32_WCE) */
569
570
571 static void fghFillContextAttributes( int *attributes ) {
572   int where = 0, contextFlags, contextProfile;
573
574   if ( !fghIsLegacyContextVersionRequested() ) {
575     ATTRIB_VAL( WGL_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
576     ATTRIB_VAL( WGL_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
577   }
578
579   contextFlags =
580     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, WGL_CONTEXT_DEBUG_BIT_ARB ) |
581     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
582   if ( contextFlags != 0 ) {
583     ATTRIB_VAL( WGL_CONTEXT_FLAGS_ARB, contextFlags );
584   }
585
586   contextProfile =
587     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, WGL_CONTEXT_CORE_PROFILE_BIT_ARB ) |
588     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
589   if ( contextProfile != 0 ) {
590     ATTRIB_VAL( WGL_CONTEXT_PROFILE_MASK_ARB, contextProfile );
591   }
592
593   ATTRIB( 0 );
594 }
595
596 static int fghIsExtensionSupported( HDC hdc, const char *extension ) {
597     const char *pWglExtString;
598     PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetEntensionsStringARB =
599       (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
600     if ( wglGetEntensionsStringARB == NULL )
601     {
602       return FALSE;
603     }
604     pWglExtString = wglGetEntensionsStringARB( hdc );
605     return ( pWglExtString != NULL ) && ( strstr(pWglExtString, extension) != NULL );
606 }
607
608 void fgNewWGLCreateContext( SFG_Window* window )
609 {
610     HGLRC context;
611     int attributes[9];
612     PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
613
614     /* If nothing fancy has been required, leave the context as it is */
615     if ( fghIsLegacyContextRequested() )
616     {
617         return;
618     }
619
620     wglMakeCurrent( window->Window.Device, window->Window.Context );
621
622     if ( !fghIsExtensionSupported( window->Window.Device, "WGL_ARB_create_context" ) )
623     {
624         return;
625     }
626
627     /* new context creation */
628     fghFillContextAttributes( attributes );
629
630     wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress( "wglCreateContextAttribsARB" );
631     if ( wglCreateContextAttribsARB == NULL )
632     {
633         fgError( "wglCreateContextAttribsARB not found" );
634     }
635
636     context = wglCreateContextAttribsARB( window->Window.Device, 0, attributes );
637     if ( context == NULL )
638     {
639         fghContextCreationError();
640     }
641
642     wglMakeCurrent( NULL, NULL );
643     wglDeleteContext( window->Window.Context );
644     window->Window.Context = context;
645 }
646
647 #if !defined(_WIN32_WCE)
648
649 static void fghFillPFD( PIXELFORMATDESCRIPTOR *ppfd, HDC hdc, unsigned char layer_type )
650 {
651   int flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
652   if ( fgState.DisplayMode & GLUT_DOUBLE ) {
653         flags |= PFD_DOUBLEBUFFER;
654   }
655   if ( fgState.DisplayMode & GLUT_STEREO ) {
656     flags |= PFD_STEREO;
657   }
658
659 #if defined(_MSC_VER)
660 #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" )
661 #endif
662
663   /* Specify which pixel format do we opt for... */
664   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
665   ppfd->nVersion = 1;
666   ppfd->dwFlags = flags;
667
668   if( fgState.DisplayMode & GLUT_INDEX ) {
669     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
670     ppfd->cRedBits = 0;
671     ppfd->cGreenBits = 0;
672     ppfd->cBlueBits = 0;
673     ppfd->cAlphaBits = 0;
674   } else {
675     ppfd->iPixelType = PFD_TYPE_RGBA;
676     ppfd->cRedBits = 8;
677     ppfd->cGreenBits = 8;
678     ppfd->cBlueBits = 8;
679     ppfd->cAlphaBits = ( fgState.DisplayMode & GLUT_ALPHA ) ? 8 : 0;
680   }
681
682   ppfd->cColorBits = 24;
683   ppfd->cRedShift = 0;
684   ppfd->cGreenShift = 0;
685   ppfd->cBlueShift = 0;
686   ppfd->cAlphaShift = 0;
687   ppfd->cAccumBits = ( fgState.DisplayMode & GLUT_ACCUM ) ? 1 : 0;
688   ppfd->cAccumRedBits = 0;
689   ppfd->cAccumGreenBits = 0;
690   ppfd->cAccumBlueBits = 0;
691   ppfd->cAccumAlphaBits = 0;
692
693   /* Hmmm, or 32/0 instead of 24/8? */
694   ppfd->cDepthBits = 24;
695   ppfd->cStencilBits = 8;
696
697   ppfd->cAuxBuffers = fghNumberOfAuxBuffersRequested();
698   ppfd->iLayerType = layer_type;
699   ppfd->bReserved = 0;
700   ppfd->dwLayerMask = 0;
701   ppfd->dwVisibleMask = 0;
702   ppfd->dwDamageMask = 0;
703   
704   ppfd->cColorBits = (BYTE) GetDeviceCaps( hdc, BITSPIXEL );
705 }
706
707 static void fghFillPixelFormatAttributes( int *attributes, const PIXELFORMATDESCRIPTOR *ppfd )
708 {
709   int where = 0;
710
711   ATTRIB_VAL( WGL_DRAW_TO_WINDOW_ARB, GL_TRUE );
712   ATTRIB_VAL( WGL_SUPPORT_OPENGL_ARB, GL_TRUE );
713   ATTRIB_VAL( WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB );
714
715   ATTRIB_VAL( WGL_COLOR_BITS_ARB, ppfd->cColorBits );
716   ATTRIB_VAL( WGL_ALPHA_BITS_ARB, ppfd->cAlphaBits );
717   ATTRIB_VAL( WGL_DEPTH_BITS_ARB, ppfd->cDepthBits );
718   ATTRIB_VAL( WGL_STENCIL_BITS_ARB, ppfd->cStencilBits );
719
720   ATTRIB_VAL( WGL_DOUBLE_BUFFER_ARB, ( fgState.DisplayMode & GLUT_DOUBLE ) != 0 );
721
722   if ( fgState.DisplayMode & GLUT_SRGB ) {
723     ATTRIB_VAL( WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, TRUE );
724   }
725
726   ATTRIB_VAL( WGL_SAMPLE_BUFFERS_ARB, GL_TRUE );
727   ATTRIB_VAL( WGL_SAMPLES_ARB, fgState.SampleNumber );
728   ATTRIB( 0 );
729 }
730 #endif
731
732 GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
733                               unsigned char layer_type )
734 {
735 #if defined(_WIN32_WCE)
736     return GL_TRUE;
737 #else
738     PIXELFORMATDESCRIPTOR pfd;
739     PIXELFORMATDESCRIPTOR* ppfd = &pfd;
740     int pixelformat;
741     HDC current_hDC;
742     GLboolean success;
743
744     if (checkOnly)
745       current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL);
746     else
747       current_hDC = window->Window.Device;
748
749     fghFillPFD( ppfd, current_hDC, layer_type );
750     pixelformat = ChoosePixelFormat( current_hDC, ppfd );
751
752     /* windows hack for multismapling/sRGB */
753     if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) ||
754          ( fgState.DisplayMode & GLUT_SRGB ) )
755     {        
756         HGLRC rc, rc_before=wglGetCurrentContext();
757         HWND hWnd;
758         HDC hDC, hDC_before=wglGetCurrentDC();
759         WNDCLASS wndCls;
760
761         /* create a dummy window */
762         ZeroMemory(&wndCls, sizeof(wndCls));
763         wndCls.lpfnWndProc = DefWindowProc;
764         wndCls.hInstance = fgDisplay.Instance;
765         wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
766         wndCls.lpszClassName = _T("FREEGLUT_dummy");
767         RegisterClass( &wndCls );
768
769         hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.Instance, 0 );
770         hDC=GetDC(hWnd);
771         SetPixelFormat( hDC, pixelformat, ppfd );
772
773         rc = wglCreateContext( hDC );
774         wglMakeCurrent(hDC, rc);
775
776         if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) )
777         {
778             PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc =
779               (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
780             if ( wglChoosePixelFormatARBProc )
781             {
782                 int attributes[100];
783                 int iPixelFormat;
784                 BOOL bValid;
785                 float fAttributes[] = { 0, 0 };
786                 UINT numFormats;
787                 fghFillPixelFormatAttributes( attributes, ppfd );
788                 bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats);
789
790                 if ( bValid && numFormats > 0 )
791                 {
792                     pixelformat = iPixelFormat;
793                 }
794             }
795         }
796
797         wglMakeCurrent( hDC_before, rc_before);
798         wglDeleteContext(rc);
799         ReleaseDC(hWnd, hDC);
800         DestroyWindow(hWnd);
801         UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.Instance);
802     }
803
804     success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) );
805
806     if (checkOnly)
807         DeleteDC(current_hDC);
808
809     return success;
810 #endif /* defined(_WIN32_WCE) */
811 }
812
813 #endif  /* TARGET_HOST_MS_WINDOWS */
814
815 /*
816  * Sets the OpenGL context and the fgStructure "Current Window" pointer to
817  * the window structure passed in.
818  */
819 void fgSetWindow ( SFG_Window *window )
820 {
821 #if TARGET_HOST_POSIX_X11
822     if ( window )
823     {
824         glXMakeContextCurrent(
825             fgDisplay.Display,
826             window->Window.Handle,
827             window->Window.Handle,
828             window->Window.Context
829         );
830     }
831 #elif TARGET_HOST_MS_WINDOWS
832     if ( window != fgStructure.CurrentWindow )
833     {
834         if( fgStructure.CurrentWindow )
835             ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
836                        fgStructure.CurrentWindow->Window.Device );
837
838         if ( window )
839         {
840             window->Window.Device = GetDC( window->Window.Handle );
841             wglMakeCurrent(
842                 window->Window.Device,
843                 window->Window.Context
844             );
845         }
846     }
847 #endif
848     fgStructure.CurrentWindow = window;
849 }
850
851 #if TARGET_HOST_MS_WINDOWS
852
853 #if(WINVER >= 0x500)
854 typedef struct {
855       int *x;
856       int *y;
857       const char *name;
858 }m_proc_t ;
859
860 static BOOL CALLBACK m_proc(HMONITOR mon,
861                             HDC hdc,
862                             LPRECT rect,
863                             LPARAM data)
864 {
865       m_proc_t *dp=(m_proc_t *)data;
866       MONITORINFOEX info;
867       BOOL res;
868       info.cbSize=sizeof(info);
869       res=GetMonitorInfo(mon,(LPMONITORINFO)&info);
870       if( res )
871       {
872           if( !strcmp(dp->name,info.szDevice) )
873           {
874               *(dp->x)=info.rcMonitor.left;
875               *(dp->y)=info.rcMonitor.top;
876               return FALSE;
877           }
878       }
879       return TRUE;
880 }
881
882 /* 
883  * this function is only used in fgOpenWindow. Currently it only sets 
884  * its output parameters, if the DisplayName is set in fgDisplay 
885  * (and if it is able to recognize the display)
886  */
887
888 static void get_display_origin(int *xp,int *yp)
889 {
890     if( fgDisplay.DisplayName )
891     {
892         m_proc_t st;
893         st.x=xp;
894         st.y=yp;
895         st.name=fgDisplay.DisplayName;
896         EnumDisplayMonitors(0,0,m_proc,(LPARAM)&st);
897      }
898 }
899 #else
900 #pragma message( "-display parameter only works if compiled with WINVER >= 0x0500")
901
902 static void get_display_origin(int *xp,int *yp)
903 {
904     if( fgDisplay.DisplayName )
905     {
906         fgWarning( "for working -display support FreeGLUT must be compiled with WINVER >= 0x0500");
907     }
908 }
909 #endif
910 #endif
911
912
913 #if TARGET_HOST_POSIX_X11
914 static Bool fghWindowIsVisible( Display *display, XEvent *event, XPointer arg)
915 {
916     Window window = arg;
917     return (event->type == MapNotify) && (event->xmap.window == window);
918 }
919 #endif
920
921
922 /*
923  * Opens a window. Requires a SFG_Window object created and attached
924  * to the freeglut structure. OpenGL context is created here.
925  */
926 void fgOpenWindow( SFG_Window* window, const char* title,
927                    GLboolean positionUse, int x, int y,
928                    GLboolean sizeUse, int w, int h,
929                    GLboolean gameMode, GLboolean isSubWindow )
930 {
931 #if TARGET_HOST_POSIX_X11
932     XVisualInfo * visualInfo;
933     XSetWindowAttributes winAttr;
934     XTextProperty textProperty;
935     XSizeHints sizeHints;
936     XWMHints wmHints;
937     XEvent eventReturnBuffer; /* return buffer required for a call */
938     unsigned long mask;
939     int num_FBConfigs, i;
940     unsigned int current_DisplayMode = fgState.DisplayMode ;
941
942     /* Save the display mode if we are creating a menu window */
943     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
944         fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB ;
945
946     window->Window.FBConfig = fgChooseFBConfig( &num_FBConfigs );
947
948     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
949         fgState.DisplayMode = current_DisplayMode ;
950
951     if( ! window->Window.FBConfig )
952     {
953         /*
954          * The "fgChooseFBConfig" returned a null meaning that the visual
955          * context is not available.
956          * Try a couple of variations to see if they will work.
957          */
958         if( !( fgState.DisplayMode & GLUT_DOUBLE ) )
959         {
960             fgState.DisplayMode |= GLUT_DOUBLE ;
961             window->Window.FBConfig = fgChooseFBConfig( &num_FBConfigs );
962             fgState.DisplayMode &= ~GLUT_DOUBLE;
963         }
964
965         if( fgState.DisplayMode & GLUT_MULTISAMPLE )
966         {
967             fgState.DisplayMode &= ~GLUT_MULTISAMPLE ;
968             window->Window.FBConfig = fgChooseFBConfig( &num_FBConfigs );
969             fgState.DisplayMode |= GLUT_MULTISAMPLE;
970         }
971     }
972
973     FREEGLUT_INTERNAL_ERROR_EXIT( window->Window.FBConfig != NULL,
974                                   "FBConfig with necessary capabilities not found", "fgOpenWindow" );
975
976     /*  Get the X visual.  */
977     for (i = 0; i < num_FBConfigs; i++) {
978             visualInfo = glXGetVisualFromFBConfig( fgDisplay.Display,
979                                                    window->Window.FBConfig[i] );
980             if (visualInfo)
981                 break;
982     }
983
984     FREEGLUT_INTERNAL_ERROR_EXIT( visualInfo != NULL,
985                                   "visualInfo could not be retrieved from FBConfig", "fgOpenWindow" );
986
987     /*
988      * XXX HINT: the masks should be updated when adding/removing callbacks.
989      * XXX       This might speed up message processing. Is that true?
990      * XXX
991      * XXX A: Not appreciably, but it WILL make it easier to debug.
992      * XXX    Try tracing old GLUT and try tracing freeglut.  Old GLUT
993      * XXX    turns off events that it doesn't need and is a whole lot
994      * XXX    more pleasant to trace.  (Think mouse-motion!  Tons of
995      * XXX    ``bonus'' GUI events stream in.)
996      */
997     winAttr.event_mask        =
998         StructureNotifyMask | SubstructureNotifyMask | ExposureMask |
999         ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
1000         VisibilityChangeMask | EnterWindowMask | LeaveWindowMask |
1001         PointerMotionMask | ButtonMotionMask;
1002     winAttr.background_pixmap = None;
1003     winAttr.background_pixel  = 0;
1004     winAttr.border_pixel      = 0;
1005
1006     winAttr.colormap = XCreateColormap(
1007         fgDisplay.Display, fgDisplay.RootWindow,
1008         visualInfo->visual, AllocNone
1009     );
1010
1011     mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
1012
1013     if( window->IsMenu || ( gameMode == GL_TRUE ) )
1014     {
1015         winAttr.override_redirect = True;
1016         mask |= CWOverrideRedirect;
1017     }
1018
1019     if( ! positionUse )
1020         x = y = -1; /* default window position */
1021     if( ! sizeUse )
1022         w = h = 300; /* default window size */
1023
1024     window->Window.Handle = XCreateWindow(
1025         fgDisplay.Display,
1026         window->Parent == NULL ? fgDisplay.RootWindow :
1027         window->Parent->Window.Handle,
1028         x, y, w, h, 0,
1029         visualInfo->depth, InputOutput,
1030         visualInfo->visual, mask,
1031         &winAttr
1032     );
1033
1034     /*
1035      * The GLX context creation, possibly trying the direct context rendering
1036      *  or else use the current context if the user has so specified
1037      */
1038
1039     if( window->IsMenu )
1040     {
1041         /*
1042          * If there isn't already an OpenGL rendering context for menu
1043          * windows, make one
1044          */
1045         if( !fgStructure.MenuContext )
1046         {
1047             fgStructure.MenuContext =
1048                 (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
1049             fgStructure.MenuContext->MContext = fghCreateNewContext( window );
1050         }
1051
1052         /* window->Window.Context = fgStructure.MenuContext->MContext; */
1053         window->Window.Context = fghCreateNewContext( window );
1054     }
1055     else if( fgState.UseCurrentContext )
1056     {
1057         window->Window.Context = glXGetCurrentContext( );
1058
1059         if( ! window->Window.Context )
1060             window->Window.Context = fghCreateNewContext( window );
1061     }
1062     else
1063         window->Window.Context = fghCreateNewContext( window );
1064
1065 #if !defined( __FreeBSD__ ) && !defined( __NetBSD__ )
1066     if(  !glXIsDirect( fgDisplay.Display, window->Window.Context ) )
1067     {
1068       if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
1069         fgError( "Unable to force direct context rendering for window '%s'",
1070                  title );
1071     }
1072 #endif
1073
1074     /*
1075      * XXX Assume the new window is visible by default
1076      * XXX Is this a  safe assumption?
1077      */
1078     window->State.Visible = GL_TRUE;
1079
1080     sizeHints.flags = 0;
1081     if ( positionUse )
1082         sizeHints.flags |= USPosition;
1083     if ( sizeUse )
1084         sizeHints.flags |= USSize;
1085
1086     /*
1087      * Fill in the size hints values now (the x, y, width and height
1088      * settings are obsolete, are there any more WMs that support them?)
1089      * Unless the X servers actually stop supporting these, we should
1090      * continue to fill them in.  It is *not* our place to tell the user
1091      * that they should replace a window manager that they like, and which
1092      * works, just because *we* think that it's not "modern" enough.
1093      */
1094     sizeHints.x      = x;
1095     sizeHints.y      = y;
1096     sizeHints.width  = w;
1097     sizeHints.height = h;
1098
1099     wmHints.flags = StateHint;
1100     wmHints.initial_state = fgState.ForceIconic ? IconicState : NormalState;
1101     /* Prepare the window and iconified window names... */
1102     XStringListToTextProperty( (char **) &title, 1, &textProperty );
1103
1104     XSetWMProperties(
1105         fgDisplay.Display,
1106         window->Window.Handle,
1107         &textProperty,
1108         &textProperty,
1109         0,
1110         0,
1111         &sizeHints,
1112         &wmHints,
1113         NULL
1114     );
1115     XFree( textProperty.value );
1116
1117     XSetWMProtocols( fgDisplay.Display, window->Window.Handle,
1118                      &fgDisplay.DeleteWindow, 1 );
1119
1120     glXMakeContextCurrent(
1121         fgDisplay.Display,
1122         window->Window.Handle,
1123         window->Window.Handle,
1124         window->Window.Context
1125     );
1126
1127     /* register extension events _before_ window is mapped */
1128     #ifdef HAVE_X11_EXTENSIONS_XINPUT2_H
1129        fgRegisterDevices( fgDisplay.Display, &(window->Window.Handle) );
1130     #endif
1131
1132     XMapWindow( fgDisplay.Display, window->Window.Handle );
1133
1134     XFree(visualInfo);
1135
1136     if( !isSubWindow)
1137         XPeekIfEvent( fgDisplay.Display, &eventReturnBuffer, &fghWindowIsVisible, window->Window.Handle );
1138
1139 #elif TARGET_HOST_MS_WINDOWS
1140
1141     WNDCLASS wc;
1142     DWORD flags;
1143     DWORD exFlags = 0;
1144     ATOM atom;
1145     int WindowStyle = 0;
1146
1147     /* Grab the window class we have registered on glutInit(): */
1148     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
1149     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
1150                                    "fgOpenWindow" );
1151
1152     if( gameMode )
1153     {
1154         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
1155                                        "Game mode being invoked on a subwindow",
1156                                        "fgOpenWindow" );
1157
1158         /*
1159          * Set the window creation flags appropriately to make the window
1160          * entirely visible:
1161          */
1162         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
1163     }
1164     else
1165     {
1166         int worig = w, horig = h;
1167
1168 #if !defined(_WIN32_WCE)
1169         if ( ( ! isSubWindow ) && ( ! window->IsMenu ) )
1170         {
1171             /*
1172              * Update the window dimensions, taking account of window
1173              * decorations.  "freeglut" is to create the window with the
1174              * outside of its border at (x,y) and with dimensions (w,h).
1175              */
1176             w += (GetSystemMetrics( SM_CXSIZEFRAME ) )*2;
1177             h += (GetSystemMetrics( SM_CYSIZEFRAME ) )*2 +
1178                 GetSystemMetrics( SM_CYCAPTION );
1179         }
1180 #endif /* defined(_WIN32_WCE) */
1181
1182         if( ! positionUse )
1183         {
1184             x = CW_USEDEFAULT;
1185             y = CW_USEDEFAULT;
1186         }
1187         /* setting State.Width/Height to call resize callback later */
1188         if( ! sizeUse )
1189         {
1190             if( ! window->IsMenu )
1191             {
1192                 w = CW_USEDEFAULT;
1193                 h = CW_USEDEFAULT;
1194             }
1195             else /* fail safe - Windows can make a window of size (0, 0) */
1196                 w = h = 300; /* default window size */
1197             window->State.Width = window->State.Height = -1;
1198         }
1199         else
1200         {
1201             window->State.Width = worig;
1202             window->State.Height = horig;
1203         }
1204
1205         /*
1206          * There's a small difference between creating the top, child and
1207          * game mode windows
1208          */
1209         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
1210
1211         if ( window->IsMenu )
1212         {
1213             flags |= WS_POPUP;
1214             exFlags |= WS_EX_TOOLWINDOW;
1215         }
1216 #if !defined(_WIN32_WCE)
1217         else if( window->Parent == NULL )
1218             flags |= WS_OVERLAPPEDWINDOW;
1219 #endif
1220         else
1221             flags |= WS_CHILD;
1222     }
1223
1224 #if defined(_WIN32_WCE)
1225     {
1226         wchar_t* wstr = fghWstrFromStr(title);
1227
1228         window->Window.Handle = CreateWindow(
1229             _T("FREEGLUT"),
1230             wstr,
1231             WS_VISIBLE | WS_POPUP,
1232             0,0, 240,320,
1233             NULL,
1234             NULL,
1235             fgDisplay.Instance,
1236             (LPVOID) window
1237         );
1238
1239         free(wstr);
1240
1241         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
1242         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
1243         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
1244         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
1245         ShowWindow(window->Window.Handle, SW_SHOW);
1246         UpdateWindow(window->Window.Handle);
1247     }
1248 #else
1249     {
1250       /* xoff and yoff are used to place window relative to current display */
1251       /* The operation of gamemode also depends on this */
1252         int xoff=0,yoff=0;
1253         get_display_origin(&xoff,&yoff);
1254
1255         window->Window.Handle = CreateWindowEx(
1256             exFlags,
1257             _T("FREEGLUT"),
1258             title,
1259             flags,
1260             x+xoff, y+yoff, w, h,
1261             (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
1262             (HMENU) NULL,
1263             fgDisplay.Instance,
1264             (LPVOID) window
1265         );
1266     }
1267 #endif /* defined(_WIN32_WCE) */
1268
1269     if( !( window->Window.Handle ) )
1270         fgError( "Failed to create a window (%s)!", title );
1271
1272     /* Make a menu window always on top - fix Feature Request 947118 */
1273     if( window->IsMenu || gameMode )
1274         SetWindowPos(
1275                         window->Window.Handle,
1276                         HWND_TOPMOST,
1277                         0, 0, 0, 0,
1278                         SWP_NOMOVE | SWP_NOSIZE
1279                     );
1280
1281     /* Hack to remove the caption (title bar) and/or border
1282      * and all the system menu controls.
1283      */
1284     WindowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
1285     if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
1286     {
1287         SetWindowLong ( window->Window.Handle, GWL_STYLE,
1288                         WindowStyle & ~(WS_DLGFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX));
1289     }
1290     else if ( fgState.DisplayMode & GLUT_BORDERLESS )
1291     {
1292         SetWindowLong ( window->Window.Handle, GWL_STYLE,
1293                         WindowStyle & ~(WS_BORDER | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_DLGFRAME | WS_SIZEBOX));
1294     }
1295 /*  SetWindowPos(window->Window.Handle, NULL, 0, 0, 0, 0,
1296      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); */
1297
1298     /* Enable multitouch: additional flag TWF_FINETOUCH, TWF_WANTPALM */
1299     #ifdef WM_TOUCH
1300         if (fghRegisterTouchWindow == (pRegisterTouchWindow)0xDEADBEEF) 
1301                         fghRegisterTouchWindow = (pRegisterTouchWindow)GetProcAddress(GetModuleHandle("user32"),"RegisterTouchWindow");
1302                 if (fghRegisterTouchWindow)
1303              fghRegisterTouchWindow( window->Window.Handle, TWF_FINETOUCH | TWF_WANTPALM );
1304     #endif
1305
1306 #if defined(_WIN32_WCE)
1307     ShowWindow( window->Window.Handle, SW_SHOW );
1308 #else
1309     ShowWindow( window->Window.Handle,
1310                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
1311 #endif /* defined(_WIN32_WCE) */
1312
1313     UpdateWindow( window->Window.Handle );
1314     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
1315
1316 #endif
1317
1318     fgSetWindow( window );
1319
1320     window->Window.DoubleBuffered =
1321         ( fgState.DisplayMode & GLUT_DOUBLE ) ? 1 : 0;
1322
1323     if ( ! window->Window.DoubleBuffered )
1324     {
1325         glDrawBuffer ( GL_FRONT );
1326         glReadBuffer ( GL_FRONT );
1327     }
1328 }
1329
1330 /*
1331  * Closes a window, destroying the frame and OpenGL context
1332  */
1333 void fgCloseWindow( SFG_Window* window )
1334 {
1335     /* if we're in gamemode, call glutLeaveGameMode first to make sure the
1336      * gamemode is properly closed before closing the window
1337      */
1338     if (fgStructure.GameModeWindow != NULL)
1339         glutLeaveGameMode();
1340
1341 #if TARGET_HOST_POSIX_X11
1342
1343     if( window->Window.Context )
1344         glXDestroyContext( fgDisplay.Display, window->Window.Context );
1345     XFree( window->Window.FBConfig );
1346
1347     if( window->Window.Handle ) {
1348         XDestroyWindow( fgDisplay.Display, window->Window.Handle );
1349     }
1350     /* XFlush( fgDisplay.Display ); */ /* XXX Shouldn't need this */
1351
1352 #elif TARGET_HOST_MS_WINDOWS
1353
1354     /* Make sure we don't close a window with current context active */
1355     if( fgStructure.CurrentWindow == window )
1356         wglMakeCurrent( NULL, NULL );
1357
1358     /*
1359      * Step through the list of windows.  If the rendering context
1360      * is not being used by another window, then we delete it.
1361      */
1362     {
1363         int used = FALSE ;
1364         SFG_Window *iter ;
1365
1366         for( iter = (SFG_Window *)fgStructure.Windows.First;
1367              iter;
1368              iter = (SFG_Window *)iter->Node.Next )
1369         {
1370             if( ( iter->Window.Context == window->Window.Context ) &&
1371                 ( iter != window ) )
1372                 used = TRUE;
1373         }
1374
1375         if( ! used )
1376             wglDeleteContext( window->Window.Context );
1377     }
1378
1379     DestroyWindow( window->Window.Handle );
1380 #endif
1381 }
1382
1383
1384 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
1385
1386 /*
1387  * Creates a new top-level freeglut window
1388  */
1389 int FGAPIENTRY glutCreateWindow( const char* title )
1390 {
1391     /* XXX GLUT does not exit; it simply calls "glutInit" quietly if the
1392      * XXX application has not already done so.  The "freeglut" community
1393      * XXX decided not to go this route (freeglut-developer e-mail from
1394      * XXX Steve Baker, 12/16/04, 4:22 PM CST, "Re: [Freeglut-developer]
1395      * XXX Desired 'freeglut' behaviour when there is no current window"
1396      */
1397     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateWindow" );
1398
1399     return fgCreateWindow( NULL, title, fgState.Position.Use,
1400                            fgState.Position.X, fgState.Position.Y,
1401                            fgState.Size.Use, fgState.Size.X, fgState.Size.Y,
1402                            GL_FALSE, GL_FALSE )->ID;
1403 }
1404
1405 #if TARGET_HOST_MS_WINDOWS
1406 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1407 {
1408   __glutExitFunc = exit_function;
1409   return glutCreateWindow( title );
1410 }
1411 #endif
1412
1413 /*
1414  * This function creates a sub window.
1415  */
1416 int FGAPIENTRY glutCreateSubWindow( int parentID, int x, int y, int w, int h )
1417 {
1418     int ret = 0;
1419     SFG_Window* window = NULL;
1420     SFG_Window* parent = NULL;
1421
1422     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateSubWindow" );
1423     parent = fgWindowByID( parentID );
1424     freeglut_return_val_if_fail( parent != NULL, 0 );
1425     if ( x < 0 )
1426     {
1427         x = parent->State.Width + x ;
1428         if ( w >= 0 ) x -= w ;
1429     }
1430
1431     if ( w < 0 ) w = parent->State.Width - x + w ;
1432     if ( w < 0 )
1433     {
1434         x += w ;
1435         w = -w ;
1436     }
1437
1438     if ( y < 0 )
1439     {
1440         y = parent->State.Height + y ;
1441         if ( h >= 0 ) y -= h ;
1442     }
1443
1444     if ( h < 0 ) h = parent->State.Height - y + h ;
1445     if ( h < 0 )
1446     {
1447         y += h ;
1448         h = -h ;
1449     }
1450
1451     window = fgCreateWindow( parent, "", GL_TRUE, x, y, GL_TRUE, w, h, GL_FALSE, GL_FALSE );
1452     ret = window->ID;
1453
1454     return ret;
1455 }
1456
1457 /*
1458  * Destroys a window and all of its subwindows
1459  */
1460 void FGAPIENTRY glutDestroyWindow( int windowID )
1461 {
1462     SFG_Window* window;
1463     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDestroyWindow" );
1464     window = fgWindowByID( windowID );
1465     freeglut_return_if_fail( window != NULL );
1466     {
1467         fgExecutionState ExecState = fgState.ExecState;
1468         fgAddToWindowDestroyList( window );
1469         fgState.ExecState = ExecState;
1470     }
1471 }
1472
1473 /*
1474  * This function selects the current window
1475  */
1476 void FGAPIENTRY glutSetWindow( int ID )
1477 {
1478     SFG_Window* window = NULL;
1479
1480     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindow" );
1481     if( fgStructure.CurrentWindow != NULL )
1482         if( fgStructure.CurrentWindow->ID == ID )
1483             return;
1484
1485     window = fgWindowByID( ID );
1486     if( window == NULL )
1487     {
1488         fgWarning( "glutSetWindow(): window ID %d not found!", ID );
1489         return;
1490     }
1491
1492     fgSetWindow( window );
1493 }
1494
1495 /*
1496  * This function returns the ID number of the current window, 0 if none exists
1497  */
1498 int FGAPIENTRY glutGetWindow( void )
1499 {
1500     SFG_Window *win = fgStructure.CurrentWindow;
1501     /*
1502      * Since GLUT did not throw an error if this function was called without a prior call to
1503      * "glutInit", this function shouldn't do so here.  Instead let us return a zero.
1504      * See Feature Request "[ 1307049 ] glutInit check".
1505      */
1506     if ( ! fgState.Initialised )
1507         return 0;
1508
1509     while ( win && win->IsMenu )
1510         win = win->Parent;
1511     return win ? win->ID : 0;
1512 }
1513
1514 /*
1515  * This function makes the current window visible
1516  */
1517 void FGAPIENTRY glutShowWindow( void )
1518 {
1519     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutShowWindow" );
1520     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutShowWindow" );
1521
1522 #if TARGET_HOST_POSIX_X11
1523
1524     XMapWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1525     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1526
1527 #elif TARGET_HOST_MS_WINDOWS
1528
1529     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
1530
1531 #endif
1532
1533     fgStructure.CurrentWindow->State.Redisplay = GL_TRUE;
1534 }
1535
1536 /*
1537  * This function hides the current window
1538  */
1539 void FGAPIENTRY glutHideWindow( void )
1540 {
1541     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutHideWindow" );
1542     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutHideWindow" );
1543
1544 #if TARGET_HOST_POSIX_X11
1545
1546     if( fgStructure.CurrentWindow->Parent == NULL )
1547         XWithdrawWindow( fgDisplay.Display,
1548                          fgStructure.CurrentWindow->Window.Handle,
1549                          fgDisplay.Screen );
1550     else
1551         XUnmapWindow( fgDisplay.Display,
1552                       fgStructure.CurrentWindow->Window.Handle );
1553     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1554
1555 #elif TARGET_HOST_MS_WINDOWS
1556
1557     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
1558
1559 #endif
1560
1561     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
1562 }
1563
1564 /*
1565  * Iconify the current window (top-level windows only)
1566  */
1567 void FGAPIENTRY glutIconifyWindow( void )
1568 {
1569     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutIconifyWindow" );
1570     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutIconifyWindow" );
1571
1572     fgStructure.CurrentWindow->State.Visible   = GL_FALSE;
1573 #if TARGET_HOST_POSIX_X11
1574
1575     XIconifyWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
1576                     fgDisplay.Screen );
1577     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1578
1579 #elif TARGET_HOST_MS_WINDOWS
1580
1581     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
1582
1583 #endif
1584
1585     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
1586 }
1587
1588 /*
1589  * Set the current window's title
1590  */
1591 void FGAPIENTRY glutSetWindowTitle( const char* title )
1592 {
1593     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowTitle" );
1594     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowTitle" );
1595     if( ! fgStructure.CurrentWindow->Parent )
1596     {
1597 #if TARGET_HOST_POSIX_X11
1598
1599         XTextProperty text;
1600
1601         text.value = (unsigned char *) title;
1602         text.encoding = XA_STRING;
1603         text.format = 8;
1604         text.nitems = strlen( title );
1605
1606         XSetWMName(
1607             fgDisplay.Display,
1608             fgStructure.CurrentWindow->Window.Handle,
1609             &text
1610         );
1611
1612         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1613
1614 #elif TARGET_HOST_MS_WINDOWS
1615 #    ifdef _WIN32_WCE
1616         {
1617             wchar_t* wstr = fghWstrFromStr(title);
1618             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
1619             free(wstr);
1620         }
1621 #    else
1622         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
1623 #    endif
1624
1625 #endif
1626     }
1627 }
1628
1629 /*
1630  * Set the current window's iconified title
1631  */
1632 void FGAPIENTRY glutSetIconTitle( const char* title )
1633 {
1634     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetIconTitle" );
1635     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetIconTitle" );
1636
1637     if( ! fgStructure.CurrentWindow->Parent )
1638     {
1639 #if TARGET_HOST_POSIX_X11
1640
1641         XTextProperty text;
1642
1643         text.value = (unsigned char *) title;
1644         text.encoding = XA_STRING;
1645         text.format = 8;
1646         text.nitems = strlen( title );
1647
1648         XSetWMIconName(
1649             fgDisplay.Display,
1650             fgStructure.CurrentWindow->Window.Handle,
1651             &text
1652         );
1653
1654         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1655
1656 #elif TARGET_HOST_MS_WINDOWS
1657 #    ifdef _WIN32_WCE
1658         {
1659             wchar_t* wstr = fghWstrFromStr(title);
1660             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
1661             free(wstr);
1662         }
1663 #    else
1664         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
1665 #    endif
1666
1667 #endif
1668     }
1669 }
1670
1671 /*
1672  * Change the current window's size
1673  */
1674 void FGAPIENTRY glutReshapeWindow( int width, int height )
1675 {
1676     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutReshapeWindow" );
1677     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutReshapeWindow" );
1678
1679     if (glutGet(GLUT_FULL_SCREEN))
1680     {
1681       /*  Leave full screen state before resizing. */
1682       glutFullScreenToggle();
1683     }
1684
1685     fgStructure.CurrentWindow->State.NeedToResize = GL_TRUE;
1686     fgStructure.CurrentWindow->State.Width  = width ;
1687     fgStructure.CurrentWindow->State.Height = height;
1688 }
1689
1690 /*
1691  * Change the current window's position
1692  */
1693 void FGAPIENTRY glutPositionWindow( int x, int y )
1694 {
1695     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPositionWindow" );
1696     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPositionWindow" );
1697
1698     if (glutGet(GLUT_FULL_SCREEN))
1699     {
1700       /*  Leave full screen state before moving. */
1701       glutFullScreenToggle();
1702     }
1703
1704 #if TARGET_HOST_POSIX_X11
1705
1706     XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
1707                  x, y );
1708     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1709
1710 #elif TARGET_HOST_MS_WINDOWS
1711
1712     {
1713         RECT winRect;
1714
1715         /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
1716         GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
1717         MoveWindow(
1718             fgStructure.CurrentWindow->Window.Handle,
1719             x,
1720             y,
1721             winRect.right - winRect.left,
1722             winRect.bottom - winRect.top,
1723             TRUE
1724         );
1725     }
1726
1727 #endif
1728 }
1729
1730 /*
1731  * Lowers the current window (by Z order change)
1732  */
1733 void FGAPIENTRY glutPushWindow( void )
1734 {
1735     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPushWindow" );
1736     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPushWindow" );
1737
1738 #if TARGET_HOST_POSIX_X11
1739
1740     XLowerWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1741
1742 #elif TARGET_HOST_MS_WINDOWS
1743
1744     SetWindowPos(
1745         fgStructure.CurrentWindow->Window.Handle,
1746         HWND_BOTTOM,
1747         0, 0, 0, 0,
1748         SWP_NOSIZE | SWP_NOMOVE
1749     );
1750
1751 #endif
1752 }
1753
1754 /*
1755  * Raises the current window (by Z order change)
1756  */
1757 void FGAPIENTRY glutPopWindow( void )
1758 {
1759     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPopWindow" );
1760     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPopWindow" );
1761
1762 #if TARGET_HOST_POSIX_X11
1763
1764     XRaiseWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1765
1766 #elif TARGET_HOST_MS_WINDOWS
1767
1768     SetWindowPos(
1769         fgStructure.CurrentWindow->Window.Handle,
1770         HWND_TOP,
1771         0, 0, 0, 0,
1772         SWP_NOSIZE | SWP_NOMOVE
1773     );
1774
1775 #endif
1776 }
1777
1778 /*
1779  * Resize the current window so that it fits the whole screen
1780  */
1781 void FGAPIENTRY glutFullScreen( void )
1782 {
1783     SFG_Window *win;
1784
1785     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" );
1786     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" );
1787
1788     win = fgStructure.CurrentWindow;
1789
1790 #if TARGET_HOST_POSIX_X11
1791     if(!glutGet(GLUT_FULL_SCREEN)) {
1792         if(fghToggleFullscreen() != -1) {
1793             win->State.IsFullscreen = GL_TRUE;
1794         }
1795     }
1796
1797 #elif TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1798
1799     if (glutGet(GLUT_FULL_SCREEN))
1800     {
1801         /*  Leave full screen state before resizing. */
1802         glutFullScreenToggle();
1803     }
1804
1805     {
1806         RECT rect;
1807
1808         /* For fullscreen mode, force the top-left corner to 0,0
1809          * and adjust the window rectangle so that the client area
1810          * covers the whole screen.
1811          */
1812
1813         rect.left   = 0;
1814         rect.top    = 0;
1815         get_display_origin(&rect.left,&rect.top);
1816         rect.right  = fgDisplay.ScreenWidth+rect.left;
1817         rect.bottom = fgDisplay.ScreenHeight+rect.top;
1818
1819         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1820                                   WS_CLIPCHILDREN, FALSE );
1821
1822         /*
1823          * SWP_NOACTIVATE     Do not activate the window
1824          * SWP_NOOWNERZORDER  Do not change position in z-order
1825          * SWP_NOSENDCHANGING Supress WM_WINDOWPOSCHANGING message
1826          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1827          */
1828
1829         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1830                       HWND_TOP,
1831                       rect.left,
1832                       rect.top,
1833                       rect.right  - rect.left,
1834                       rect.bottom - rect.top,
1835                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1836                       SWP_NOZORDER
1837                     );
1838         
1839         win->State.IsFullscreen = GL_TRUE;
1840     }
1841 #endif
1842 }
1843
1844 /*
1845  * Toggle the window's full screen state.
1846  */
1847 void FGAPIENTRY glutFullScreenToggle( void )
1848 {
1849     SFG_Window *win;
1850
1851     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreenToggle" );
1852     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreenToggle" );
1853
1854     win = fgStructure.CurrentWindow;
1855
1856 #if TARGET_HOST_POSIX_X11
1857     if(fghToggleFullscreen() != -1) {
1858         win->State.IsFullscreen = !win->State.IsFullscreen;
1859     }
1860 #elif TARGET_HOST_MS_WINDOWS
1861     glutFullScreen();
1862     win->State.IsFullscreen = !win->State.IsFullscreen;
1863 #endif
1864 }
1865
1866 /*
1867  * A.Donev: Set and retrieve the window's user data
1868  */
1869 void* FGAPIENTRY glutGetWindowData( void )
1870 {
1871     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetWindowData" );
1872     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutGetWindowData" );
1873     return fgStructure.CurrentWindow->UserData;
1874 }
1875
1876 void FGAPIENTRY glutSetWindowData(void* data)
1877 {
1878     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowData" );
1879     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowData" );
1880     fgStructure.CurrentWindow->UserData = data;
1881 }
1882
1883 /*** END OF FILE ***/