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