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