Implementing "glutEntryFunc" for Windows properly. I also moved the menu highlight...
[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         glXMakeContextCurrent(
597             fgDisplay.Display,
598             window->Window.Handle,
599             window->Window.Handle,
600             window->Window.Context
601         );
602 #elif TARGET_HOST_MS_WINDOWS
603     if( fgStructure.CurrentWindow )
604         ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
605                    fgStructure.CurrentWindow->Window.Device );
606
607     if ( window )
608     {
609         window->Window.Device = GetDC( window->Window.Handle );
610         wglMakeCurrent(
611             window->Window.Device,
612             window->Window.Context
613         );
614     }
615 #endif
616     fgStructure.CurrentWindow = window;
617 }
618
619
620
621 #if TARGET_HOST_POSIX_X11
622
623 #ifndef GLX_CONTEXT_MAJOR_VERSION_ARB
624 #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
625 #endif
626
627 #ifndef GLX_CONTEXT_MINOR_VERSION_ARB
628 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
629 #endif
630
631 #ifndef GLX_CONTEXT_FLAGS_ARB
632 #define GLX_CONTEXT_FLAGS_ARB 0x2094
633 #endif
634
635 #ifndef GLX_CONTEXT_PROFILE_MASK_ARB
636 #define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
637 #endif
638
639 #ifndef GLX_CONTEXT_DEBUG_BIT_ARB
640 #define GLX_CONTEXT_DEBUG_BIT_ARB 0x0001
641 #endif
642
643 #ifndef GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB
644 #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x0002
645 #endif
646
647 #ifndef GLX_CONTEXT_CORE_PROFILE_BIT_ARB
648 #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
649 #endif
650
651 #ifndef GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB
652 #define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
653 #endif
654
655 #ifndef GLX_RGBA_FLOAT_TYPE
656 #define GLX_RGBA_FLOAT_TYPE 0x20B9
657 #endif
658
659 #ifndef GLX_RGBA_FLOAT_BIT
660 #define GLX_RGBA_FLOAT_BIT 0x00000004
661 #endif
662
663 static void fghFillContextAttributes( int *attributes ) {
664   int where = 0, contextFlags, contextProfile;
665
666   if ( !fghIsLegacyContextVersionRequested() ) {
667     ATTRIB_VAL( GLX_CONTEXT_MAJOR_VERSION_ARB, fgState.MajorVersion );
668     ATTRIB_VAL( GLX_CONTEXT_MINOR_VERSION_ARB, fgState.MinorVersion );
669   }
670
671   contextFlags =
672     fghMapBit( fgState.ContextFlags, GLUT_DEBUG, GLX_CONTEXT_DEBUG_BIT_ARB ) |
673     fghMapBit( fgState.ContextFlags, GLUT_FORWARD_COMPATIBLE, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB );
674   if ( contextFlags != 0 ) {
675     ATTRIB_VAL( GLX_CONTEXT_FLAGS_ARB, contextFlags );
676   }
677
678   contextProfile =
679     fghMapBit( fgState.ContextProfile, GLUT_CORE_PROFILE, GLX_CONTEXT_CORE_PROFILE_BIT_ARB ) |
680     fghMapBit( fgState.ContextProfile, GLUT_COMPATIBILITY_PROFILE, GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB );
681   if ( contextProfile != 0 ) {
682     ATTRIB_VAL( GLX_CONTEXT_PROFILE_MASK_ARB, contextProfile );
683   }
684
685   ATTRIB( 0 );
686 }
687
688 typedef GLXContext (*CreateContextAttribsProc)(Display *dpy, GLXFBConfig config,
689                                                GLXContext share_list, Bool direct,
690                                                const int *attrib_list);
691
692 static GLXContext fghCreateNewContext( SFG_Window* window )
693 {
694   /* for color model calculation */
695   int menu = ( window->IsMenu && !fgStructure.MenuContext );
696   int index_mode = ( fgState.DisplayMode & GLUT_INDEX );
697
698   /* "classic" context creation */
699   Display *dpy = fgDisplay.Display;
700   GLXFBConfig config = *(window->Window.FBConfig);
701   int render_type = ( !menu && index_mode ) ? GLX_COLOR_INDEX_TYPE : GLX_RGBA_TYPE;
702   GLXContext share_list = NULL;
703   Bool direct = ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT );
704   GLXContext context;
705
706   /* new context creation */
707   int attributes[9];
708   CreateContextAttribsProc createContextAttribs;
709
710   /* If nothing fancy has been required, simply use the old context creation GLX API entry */
711   if ( fghIsLegacyContextRequested() )
712   {
713     context = glXCreateNewContext( dpy, config, render_type, share_list, direct );
714     if ( context == NULL ) {
715       fghContextCreationError();
716     }
717     return context;
718   }
719
720   /* color index mode is not available anymore with OpenGL 3.0 */
721   if ( render_type == GLX_COLOR_INDEX_TYPE ) {
722     fgWarning( "color index mode is deprecated, using RGBA mode" );
723   }
724
725   fghFillContextAttributes( attributes );
726
727   createContextAttribs = (CreateContextAttribsProc) fghGetProcAddress( "glXCreateContextAttribsARB" );
728   if ( createContextAttribs == NULL ) {
729     fgError( "glXCreateContextAttribsARB not found" );
730   }
731
732   context = createContextAttribs( dpy, config, share_list, direct, attributes );
733   if ( context == NULL ) {
734     fghContextCreationError();
735   }
736   return context;
737 }
738 #endif
739
740
741 /*
742  * Opens a window. Requires a SFG_Window object created and attached
743  * to the freeglut structure. OpenGL context is created here.
744  */
745 void fgOpenWindow( SFG_Window* window, const char* title,
746                    GLboolean positionUse, int x, int y,
747                    GLboolean sizeUse, int w, int h,
748                    GLboolean gameMode, GLboolean isSubWindow )
749 {
750 #if TARGET_HOST_POSIX_X11
751     XVisualInfo * visualInfo;
752     XSetWindowAttributes winAttr;
753     XTextProperty textProperty;
754     XSizeHints sizeHints;
755     XWMHints wmHints;
756     unsigned long mask;
757     unsigned int current_DisplayMode = fgState.DisplayMode ;
758
759     /* Save the display mode if we are creating a menu window */
760     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
761         fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB ;
762
763     window->Window.FBConfig = fgChooseFBConfig( );
764
765     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
766         fgState.DisplayMode = current_DisplayMode ;
767
768     if( ! window->Window.FBConfig )
769     {
770         /*
771          * The "fgChooseFBConfig" returned a null meaning that the visual
772          * context is not available.
773          * Try a couple of variations to see if they will work.
774          */
775         if( !( fgState.DisplayMode & GLUT_DOUBLE ) )
776         {
777             fgState.DisplayMode |= GLUT_DOUBLE ;
778             window->Window.FBConfig = fgChooseFBConfig( );
779             fgState.DisplayMode &= ~GLUT_DOUBLE;
780         }
781
782         if( fgState.DisplayMode & GLUT_MULTISAMPLE )
783         {
784             fgState.DisplayMode &= ~GLUT_MULTISAMPLE ;
785             window->Window.FBConfig = fgChooseFBConfig( );
786             fgState.DisplayMode |= GLUT_MULTISAMPLE;
787         }
788     }
789
790     FREEGLUT_INTERNAL_ERROR_EXIT( window->Window.FBConfig != NULL,
791                                   "FBConfig with necessary capabilities not found", "fgOpenWindow" );
792
793     /*  Get the X visual.  */
794     visualInfo = glXGetVisualFromFBConfig( fgDisplay.Display,
795                                            *(window->Window.FBConfig) );
796
797     /*
798      * XXX HINT: the masks should be updated when adding/removing callbacks.
799      * XXX       This might speed up message processing. Is that true?
800      * XXX
801      * XXX A: Not appreciably, but it WILL make it easier to debug.
802      * XXX    Try tracing old GLUT and try tracing freeglut.  Old GLUT
803      * XXX    turns off events that it doesn't need and is a whole lot
804      * XXX    more pleasant to trace.  (Think mouse-motion!  Tons of
805      * XXX    ``bonus'' GUI events stream in.)
806      */
807     winAttr.event_mask        =
808         StructureNotifyMask | SubstructureNotifyMask | ExposureMask |
809         ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
810         VisibilityChangeMask | EnterWindowMask | LeaveWindowMask |
811         PointerMotionMask | ButtonMotionMask;
812     winAttr.background_pixmap = None;
813     winAttr.background_pixel  = 0;
814     winAttr.border_pixel      = 0;
815
816     winAttr.colormap = XCreateColormap(
817         fgDisplay.Display, fgDisplay.RootWindow,
818         visualInfo->visual, AllocNone
819     );
820
821     mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
822
823     if( window->IsMenu || ( gameMode == GL_TRUE ) )
824     {
825         winAttr.override_redirect = True;
826         mask |= CWOverrideRedirect;
827     }
828
829     if( ! positionUse )
830         x = y = -1; /* default window position */
831     if( ! sizeUse )
832         w = h = 300; /* default window size */
833
834     window->Window.Handle = XCreateWindow(
835         fgDisplay.Display,
836         window->Parent == NULL ? fgDisplay.RootWindow :
837         window->Parent->Window.Handle,
838         x, y, w, h, 0,
839         visualInfo->depth, InputOutput,
840         visualInfo->visual, mask,
841         &winAttr
842     );
843
844     /*
845      * The GLX context creation, possibly trying the direct context rendering
846      *  or else use the current context if the user has so specified
847      */
848
849     if( window->IsMenu )
850     {
851         /*
852          * If there isn't already an OpenGL rendering context for menu
853          * windows, make one
854          */
855         if( !fgStructure.MenuContext )
856         {
857             fgStructure.MenuContext =
858                 (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
859             fgStructure.MenuContext->MContext = fghCreateNewContext( window );
860         }
861
862         /* window->Window.Context = fgStructure.MenuContext->MContext; */
863         window->Window.Context = fghCreateNewContext( window );
864     }
865     else if( fgState.UseCurrentContext )
866     {
867         window->Window.Context = glXGetCurrentContext( );
868
869         if( ! window->Window.Context )
870             window->Window.Context = fghCreateNewContext( window );
871     }
872     else
873         window->Window.Context = fghCreateNewContext( window );
874
875 #if !defined( __FreeBSD__ ) && !defined( __NetBSD__ )
876     if(  !glXIsDirect( fgDisplay.Display, window->Window.Context ) )
877     {
878       if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
879         fgError( "Unable to force direct context rendering for window '%s'",
880                  title );
881     }
882 #endif
883
884     /*
885      * XXX Assume the new window is visible by default
886      * XXX Is this a  safe assumption?
887      */
888     window->State.Visible = GL_TRUE;
889
890     sizeHints.flags = 0;
891     if ( positionUse )
892         sizeHints.flags |= USPosition;
893     if ( sizeUse )
894         sizeHints.flags |= USSize;
895
896     /*
897      * Fill in the size hints values now (the x, y, width and height
898      * settings are obsolete, are there any more WMs that support them?)
899      * Unless the X servers actually stop supporting these, we should
900      * continue to fill them in.  It is *not* our place to tell the user
901      * that they should replace a window manager that they like, and which
902      * works, just because *we* think that it's not "modern" enough.
903      */
904     sizeHints.x      = x;
905     sizeHints.y      = y;
906     sizeHints.width  = w;
907     sizeHints.height = h;
908
909     wmHints.flags = StateHint;
910     wmHints.initial_state = fgState.ForceIconic ? IconicState : NormalState;
911     /* Prepare the window and iconified window names... */
912     XStringListToTextProperty( (char **) &title, 1, &textProperty );
913
914     XSetWMProperties(
915         fgDisplay.Display,
916         window->Window.Handle,
917         &textProperty,
918         &textProperty,
919         0,
920         0,
921         &sizeHints,
922         &wmHints,
923         NULL
924     );
925     XFree( textProperty.value );
926
927     XSetWMProtocols( fgDisplay.Display, window->Window.Handle,
928                      &fgDisplay.DeleteWindow, 1 );
929
930     glXMakeContextCurrent(
931         fgDisplay.Display,
932         window->Window.Handle,
933         window->Window.Handle,
934         window->Window.Context
935     );
936
937     XMapWindow( fgDisplay.Display, window->Window.Handle );
938
939     XFree(visualInfo);
940
941 #elif TARGET_HOST_MS_WINDOWS
942
943     WNDCLASS wc;
944     DWORD flags;
945     DWORD exFlags = 0;
946     ATOM atom;
947     int WindowStyle = 0;
948
949     /* Grab the window class we have registered on glutInit(): */
950     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
951     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
952                                    "fgOpenWindow" );
953
954     if( gameMode )
955     {
956         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
957                                        "Game mode being invoked on a subwindow",
958                                        "fgOpenWindow" );
959
960         /*
961          * Set the window creation flags appropriately to make the window
962          * entirely visible:
963          */
964         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
965     }
966     else
967     {
968         int worig = w, horig = h;
969
970 #if !defined(_WIN32_WCE)
971         if ( ( ! isSubWindow ) && ( ! window->IsMenu ) )
972         {
973             /*
974              * Update the window dimensions, taking account of window
975              * decorations.  "freeglut" is to create the window with the
976              * outside of its border at (x,y) and with dimensions (w,h).
977              */
978             w += (GetSystemMetrics( SM_CXSIZEFRAME ) )*2;
979             h += (GetSystemMetrics( SM_CYSIZEFRAME ) )*2 +
980                 GetSystemMetrics( SM_CYCAPTION );
981         }
982 #endif /* defined(_WIN32_WCE) */
983
984         if( ! positionUse )
985         {
986             x = CW_USEDEFAULT;
987             y = CW_USEDEFAULT;
988         }
989         /* setting State.Width/Height to call resize callback later */
990         if( ! sizeUse )
991         {
992             if( ! window->IsMenu )
993             {
994                 w = CW_USEDEFAULT;
995                 h = CW_USEDEFAULT;
996             }
997             else /* fail safe - Windows can make a window of size (0, 0) */
998                 w = h = 300; /* default window size */
999             window->State.Width = window->State.Height = -1;
1000         }
1001         else
1002         {
1003             window->State.Width = worig;
1004             window->State.Height = horig;
1005         }
1006
1007         /*
1008          * There's a small difference between creating the top, child and
1009          * game mode windows
1010          */
1011         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
1012
1013         if ( window->IsMenu )
1014         {
1015             flags |= WS_POPUP;
1016             exFlags |= WS_EX_TOOLWINDOW;
1017         }
1018 #if !defined(_WIN32_WCE)
1019         else if( window->Parent == NULL )
1020             flags |= WS_OVERLAPPEDWINDOW;
1021 #endif
1022         else
1023             flags |= WS_CHILD;
1024     }
1025
1026 #if defined(_WIN32_WCE)
1027     {
1028         wchar_t* wstr = fghWstrFromStr(title);
1029
1030         window->Window.Handle = CreateWindow(
1031             _T("FREEGLUT"),
1032             wstr,
1033             WS_VISIBLE | WS_POPUP,
1034             0,0, 240,320,
1035             NULL,
1036             NULL,
1037             fgDisplay.Instance,
1038             (LPVOID) window
1039         );
1040
1041         free(wstr);
1042
1043         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
1044         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
1045         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
1046         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
1047         ShowWindow(window->Window.Handle, SW_SHOW);
1048         UpdateWindow(window->Window.Handle);
1049     }
1050 #else
1051     window->Window.Handle = CreateWindowEx(
1052         exFlags,
1053         _T("FREEGLUT"),
1054         title,
1055         flags,
1056         x, y, w, h,
1057         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
1058         (HMENU) NULL,
1059         fgDisplay.Instance,
1060         (LPVOID) window
1061     );
1062 #endif /* defined(_WIN32_WCE) */
1063
1064     if( !( window->Window.Handle ) )
1065         fgError( "Failed to create a window (%s)!", title );
1066
1067     /* Make a menu window always on top - fix Feature Request 947118 */
1068     if( window->IsMenu || gameMode )
1069         SetWindowPos(
1070                         window->Window.Handle,
1071                         HWND_TOPMOST,
1072                         0, 0, 0, 0,
1073                         SWP_NOMOVE | SWP_NOSIZE
1074                     );
1075
1076     /* Hack to remove the caption (title bar) and/or border
1077      * and all the system menu controls.
1078      */
1079     WindowStyle = GetWindowLong(window->Window.Handle, GWL_STYLE);
1080     if ( fgState.DisplayMode & GLUT_CAPTIONLESS )
1081     {
1082         SetWindowLong ( window->Window.Handle, GWL_STYLE,
1083                         WindowStyle & ~(WS_DLGFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX));
1084     }
1085     else if ( fgState.DisplayMode & GLUT_BORDERLESS )
1086     {
1087         SetWindowLong ( window->Window.Handle, GWL_STYLE,
1088                         WindowStyle & ~(WS_BORDER | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX));
1089     }
1090 /*  SetWindowPos(window->Window.Handle, NULL, 0, 0, 0, 0,
1091      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); */
1092
1093
1094 #if defined(_WIN32_WCE)
1095     ShowWindow( window->Window.Handle, SW_SHOW );
1096 #else
1097     ShowWindow( window->Window.Handle,
1098                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
1099 #endif /* defined(_WIN32_WCE) */
1100
1101     UpdateWindow( window->Window.Handle );
1102     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
1103
1104 #endif
1105
1106     fgSetWindow( window );
1107
1108     window->Window.DoubleBuffered =
1109         ( fgState.DisplayMode & GLUT_DOUBLE ) ? 1 : 0;
1110
1111     if ( ! window->Window.DoubleBuffered )
1112     {
1113         glDrawBuffer ( GL_FRONT );
1114         glReadBuffer ( GL_FRONT );
1115     }
1116 }
1117
1118 /*
1119  * Closes a window, destroying the frame and OpenGL context
1120  */
1121 void fgCloseWindow( SFG_Window* window )
1122 {
1123 #if TARGET_HOST_POSIX_X11
1124
1125     if( window->Window.Context )
1126         glXDestroyContext( fgDisplay.Display, window->Window.Context );
1127     XFree( window->Window.FBConfig );
1128     XDestroyWindow( fgDisplay.Display, window->Window.Handle );
1129     /* XFlush( fgDisplay.Display ); */ /* XXX Shouldn't need this */
1130
1131 #elif TARGET_HOST_MS_WINDOWS
1132
1133     /* Make sure we don't close a window with current context active */
1134     if( fgStructure.CurrentWindow == window )
1135         wglMakeCurrent( NULL, NULL );
1136
1137     /*
1138      * Step through the list of windows.  If the rendering context
1139      * is not being used by another window, then we delete it.
1140      */
1141     {
1142         int used = FALSE ;
1143         SFG_Window *iter ;
1144
1145         for( iter = (SFG_Window *)fgStructure.Windows.First;
1146              iter;
1147              iter = (SFG_Window *)iter->Node.Next )
1148         {
1149             if( ( iter->Window.Context == window->Window.Context ) &&
1150                 ( iter != window ) )
1151                 used = TRUE;
1152         }
1153
1154         if( ! used )
1155             wglDeleteContext( window->Window.Context );
1156     }
1157
1158     DestroyWindow( window->Window.Handle );
1159 #endif
1160 }
1161
1162
1163 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
1164
1165 /*
1166  * Creates a new top-level freeglut window
1167  */
1168 int FGAPIENTRY glutCreateWindow( const char* title )
1169 {
1170     /* XXX GLUT does not exit; it simply calls "glutInit" quietly if the
1171      * XXX application has not already done so.  The "freeglut" community
1172      * XXX decided not to go this route (freeglut-developer e-mail from
1173      * XXX Steve Baker, 12/16/04, 4:22 PM CST, "Re: [Freeglut-developer]
1174      * XXX Desired 'freeglut' behaviour when there is no current window"
1175      */
1176     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateWindow" );
1177
1178     return fgCreateWindow( NULL, title, fgState.Position.Use,
1179                            fgState.Position.X, fgState.Position.Y,
1180                            fgState.Size.Use, fgState.Size.X, fgState.Size.Y,
1181                            GL_FALSE, GL_FALSE )->ID;
1182 }
1183
1184 #if TARGET_HOST_MS_WINDOWS
1185 int FGAPIENTRY __glutCreateWindowWithExit( const char *title, void (__cdecl *exit_function)(int) )
1186 {
1187   __glutExitFunc = exit_function;
1188   return glutCreateWindow( title );
1189 }
1190 #endif
1191
1192 /*
1193  * This function creates a sub window.
1194  */
1195 int FGAPIENTRY glutCreateSubWindow( int parentID, int x, int y, int w, int h )
1196 {
1197     int ret = 0;
1198     SFG_Window* window = NULL;
1199     SFG_Window* parent = NULL;
1200
1201     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateSubWindow" );
1202     parent = fgWindowByID( parentID );
1203     freeglut_return_val_if_fail( parent != NULL, 0 );
1204     if ( x < 0 )
1205     {
1206         x = parent->State.Width + x ;
1207         if ( w >= 0 ) x -= w ;
1208     }
1209
1210     if ( w < 0 ) w = parent->State.Width - x + w ;
1211     if ( w < 0 )
1212     {
1213         x += w ;
1214         w = -w ;
1215     }
1216
1217     if ( y < 0 )
1218     {
1219         y = parent->State.Height + y ;
1220         if ( h >= 0 ) y -= h ;
1221     }
1222
1223     if ( h < 0 ) h = parent->State.Height - y + h ;
1224     if ( h < 0 )
1225     {
1226         y += h ;
1227         h = -h ;
1228     }
1229
1230     window = fgCreateWindow( parent, "", GL_TRUE, x, y, GL_TRUE, w, h, GL_FALSE, GL_FALSE );
1231     ret = window->ID;
1232
1233     return ret;
1234 }
1235
1236 /*
1237  * Destroys a window and all of its subwindows
1238  */
1239 void FGAPIENTRY glutDestroyWindow( int windowID )
1240 {
1241     SFG_Window* window;
1242     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDestroyWindow" );
1243     window = fgWindowByID( windowID );
1244     freeglut_return_if_fail( window != NULL );
1245     {
1246         fgExecutionState ExecState = fgState.ExecState;
1247         fgAddToWindowDestroyList( window );
1248         fgState.ExecState = ExecState;
1249     }
1250 }
1251
1252 /*
1253  * This function selects the current window
1254  */
1255 void FGAPIENTRY glutSetWindow( int ID )
1256 {
1257     SFG_Window* window = NULL;
1258
1259     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindow" );
1260     if( fgStructure.CurrentWindow != NULL )
1261         if( fgStructure.CurrentWindow->ID == ID )
1262             return;
1263
1264     window = fgWindowByID( ID );
1265     if( window == NULL )
1266     {
1267         fgWarning( "glutSetWindow(): window ID %d not found!", ID );
1268         return;
1269     }
1270
1271     fgSetWindow( window );
1272 }
1273
1274 /*
1275  * This function returns the ID number of the current window, 0 if none exists
1276  */
1277 int FGAPIENTRY glutGetWindow( void )
1278 {
1279     SFG_Window *win = fgStructure.CurrentWindow;
1280     /*
1281      * Since GLUT did not throw an error if this function was called without a prior call to
1282      * "glutInit", this function shouldn't do so here.  Instead let us return a zero.
1283      * See Feature Request "[ 1307049 ] glutInit check".
1284      */
1285     if ( ! fgState.Initialised )
1286         return 0;
1287
1288     while ( win && win->IsMenu )
1289         win = win->Parent;
1290     return win ? win->ID : 0;
1291 }
1292
1293 /*
1294  * This function makes the current window visible
1295  */
1296 void FGAPIENTRY glutShowWindow( void )
1297 {
1298     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutShowWindow" );
1299     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutShowWindow" );
1300
1301 #if TARGET_HOST_POSIX_X11
1302
1303     XMapWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1304     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1305
1306 #elif TARGET_HOST_MS_WINDOWS
1307
1308     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
1309
1310 #endif
1311
1312     fgStructure.CurrentWindow->State.Redisplay = GL_TRUE;
1313 }
1314
1315 /*
1316  * This function hides the current window
1317  */
1318 void FGAPIENTRY glutHideWindow( void )
1319 {
1320     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutHideWindow" );
1321     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutHideWindow" );
1322
1323 #if TARGET_HOST_POSIX_X11
1324
1325     if( fgStructure.CurrentWindow->Parent == NULL )
1326         XWithdrawWindow( fgDisplay.Display,
1327                          fgStructure.CurrentWindow->Window.Handle,
1328                          fgDisplay.Screen );
1329     else
1330         XUnmapWindow( fgDisplay.Display,
1331                       fgStructure.CurrentWindow->Window.Handle );
1332     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1333
1334 #elif TARGET_HOST_MS_WINDOWS
1335
1336     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
1337
1338 #endif
1339
1340     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
1341 }
1342
1343 /*
1344  * Iconify the current window (top-level windows only)
1345  */
1346 void FGAPIENTRY glutIconifyWindow( void )
1347 {
1348     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutIconifyWindow" );
1349     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutIconifyWindow" );
1350
1351     fgStructure.CurrentWindow->State.Visible   = GL_FALSE;
1352 #if TARGET_HOST_POSIX_X11
1353
1354     XIconifyWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
1355                     fgDisplay.Screen );
1356     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1357
1358 #elif TARGET_HOST_MS_WINDOWS
1359
1360     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
1361
1362 #endif
1363
1364     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
1365 }
1366
1367 /*
1368  * Set the current window's title
1369  */
1370 void FGAPIENTRY glutSetWindowTitle( const char* title )
1371 {
1372     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowTitle" );
1373     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowTitle" );
1374     if( ! fgStructure.CurrentWindow->Parent )
1375     {
1376 #if TARGET_HOST_POSIX_X11
1377
1378         XTextProperty text;
1379
1380         text.value = (unsigned char *) title;
1381         text.encoding = XA_STRING;
1382         text.format = 8;
1383         text.nitems = strlen( title );
1384
1385         XSetWMName(
1386             fgDisplay.Display,
1387             fgStructure.CurrentWindow->Window.Handle,
1388             &text
1389         );
1390
1391         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1392
1393 #elif TARGET_HOST_MS_WINDOWS
1394 #    ifdef _WIN32_WCE
1395         {
1396             wchar_t* wstr = fghWstrFromStr(title);
1397             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
1398             free(wstr);
1399         }
1400 #    else
1401         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
1402 #    endif
1403
1404 #endif
1405     }
1406 }
1407
1408 /*
1409  * Set the current window's iconified title
1410  */
1411 void FGAPIENTRY glutSetIconTitle( const char* title )
1412 {
1413     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetIconTitle" );
1414     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetIconTitle" );
1415
1416     if( ! fgStructure.CurrentWindow->Parent )
1417     {
1418 #if TARGET_HOST_POSIX_X11
1419
1420         XTextProperty text;
1421
1422         text.value = (unsigned char *) title;
1423         text.encoding = XA_STRING;
1424         text.format = 8;
1425         text.nitems = strlen( title );
1426
1427         XSetWMIconName(
1428             fgDisplay.Display,
1429             fgStructure.CurrentWindow->Window.Handle,
1430             &text
1431         );
1432
1433         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1434
1435 #elif TARGET_HOST_MS_WINDOWS
1436 #    ifdef _WIN32_WCE
1437         {
1438             wchar_t* wstr = fghWstrFromStr(title);
1439             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
1440             free(wstr);
1441         }
1442 #    else
1443         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
1444 #    endif
1445
1446 #endif
1447     }
1448 }
1449
1450 /*
1451  * Change the current window's size
1452  */
1453 void FGAPIENTRY glutReshapeWindow( int width, int height )
1454 {
1455     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutReshapeWindow" );
1456     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutReshapeWindow" );
1457
1458     if (glutGet(GLUT_FULL_SCREEN))
1459     {
1460       /*  Leave full screen state before resizing. */
1461       glutFullScreenToggle();
1462     }
1463
1464     fgStructure.CurrentWindow->State.NeedToResize = GL_TRUE;
1465     fgStructure.CurrentWindow->State.Width  = width ;
1466     fgStructure.CurrentWindow->State.Height = height;
1467 }
1468
1469 /*
1470  * Change the current window's position
1471  */
1472 void FGAPIENTRY glutPositionWindow( int x, int y )
1473 {
1474     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPositionWindow" );
1475     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPositionWindow" );
1476
1477     if (glutGet(GLUT_FULL_SCREEN))
1478     {
1479       /*  Leave full screen state before moving. */
1480       glutFullScreenToggle();
1481     }
1482
1483 #if TARGET_HOST_POSIX_X11
1484
1485     XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
1486                  x, y );
1487     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1488
1489 #elif TARGET_HOST_MS_WINDOWS
1490
1491     {
1492         RECT winRect;
1493
1494         /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
1495         GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
1496         MoveWindow(
1497             fgStructure.CurrentWindow->Window.Handle,
1498             x,
1499             y,
1500             winRect.right - winRect.left,
1501             winRect.bottom - winRect.top,
1502             TRUE
1503         );
1504     }
1505
1506 #endif
1507 }
1508
1509 /*
1510  * Lowers the current window (by Z order change)
1511  */
1512 void FGAPIENTRY glutPushWindow( void )
1513 {
1514     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPushWindow" );
1515     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPushWindow" );
1516
1517 #if TARGET_HOST_POSIX_X11
1518
1519     XLowerWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1520
1521 #elif TARGET_HOST_MS_WINDOWS
1522
1523     SetWindowPos(
1524         fgStructure.CurrentWindow->Window.Handle,
1525         HWND_BOTTOM,
1526         0, 0, 0, 0,
1527         SWP_NOSIZE | SWP_NOMOVE
1528     );
1529
1530 #endif
1531 }
1532
1533 /*
1534  * Raises the current window (by Z order change)
1535  */
1536 void FGAPIENTRY glutPopWindow( void )
1537 {
1538     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPopWindow" );
1539     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPopWindow" );
1540
1541 #if TARGET_HOST_POSIX_X11
1542
1543     XRaiseWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1544
1545 #elif TARGET_HOST_MS_WINDOWS
1546
1547     SetWindowPos(
1548         fgStructure.CurrentWindow->Window.Handle,
1549         HWND_TOP,
1550         0, 0, 0, 0,
1551         SWP_NOSIZE | SWP_NOMOVE
1552     );
1553
1554 #endif
1555 }
1556
1557 /*
1558  * Resize the current window so that it fits the whole screen
1559  */
1560 void FGAPIENTRY glutFullScreen( void )
1561 {
1562     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" );
1563     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" );
1564
1565     if (glutGet(GLUT_FULL_SCREEN))
1566     {
1567       /*  Leave full screen state before resizing. */
1568       glutFullScreenToggle();
1569     }
1570
1571     {
1572 #if TARGET_HOST_POSIX_X11
1573
1574         Status status;  /* Returned by XGetWindowAttributes(), not checked. */
1575         XWindowAttributes attributes;
1576
1577         status = XGetWindowAttributes(fgDisplay.Display,
1578                                       fgStructure.CurrentWindow->Window.Handle,
1579                                       &attributes);
1580         /*
1581          * The "x" and "y" members of "attributes" are the window's coordinates
1582          * relative to its parent, i.e. to the decoration window.
1583          */
1584         XMoveResizeWindow(fgDisplay.Display,
1585                           fgStructure.CurrentWindow->Window.Handle,
1586                           -attributes.x,
1587                           -attributes.y,
1588                           fgDisplay.ScreenWidth,
1589                           fgDisplay.ScreenHeight);
1590
1591 #elif TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1592         RECT rect;
1593
1594         /* For fullscreen mode, force the top-left corner to 0,0
1595          * and adjust the window rectangle so that the client area
1596          * covers the whole screen.
1597          */
1598
1599         rect.left   = 0;
1600         rect.top    = 0;
1601         rect.right  = fgDisplay.ScreenWidth;
1602         rect.bottom = fgDisplay.ScreenHeight;
1603
1604         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1605                                   WS_CLIPCHILDREN, FALSE );
1606
1607         /*
1608          * SWP_NOACTIVATE     Do not activate the window
1609          * SWP_NOOWNERZORDER  Do not change position in z-order
1610          * SWP_NOSENDCHANGING Supress WM_WINDOWPOSCHANGING message
1611          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1612          */
1613
1614         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1615                       HWND_TOP,
1616                       rect.left,
1617                       rect.top,
1618                       rect.right  - rect.left,
1619                       rect.bottom - rect.top,
1620                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1621                       SWP_NOZORDER
1622                     );
1623 #endif
1624     }
1625 }
1626
1627 /*
1628  * Toggle the window's full screen state.
1629  */
1630 void FGAPIENTRY glutFullScreenToggle( void )
1631 {
1632     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreenToggle" );
1633     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreenToggle" );
1634
1635     {
1636 #if TARGET_HOST_POSIX_X11
1637
1638       if (fgDisplay.StateFullScreen != None)
1639       {
1640         XEvent xevent;
1641         long event_mask;
1642         int status;
1643
1644         xevent.type = ClientMessage;
1645         xevent.xclient.type = ClientMessage;
1646         xevent.xclient.serial = 0;
1647         xevent.xclient.send_event = True;
1648         xevent.xclient.display = fgDisplay.Display;
1649         xevent.xclient.window = fgStructure.CurrentWindow->Window.Handle;
1650         xevent.xclient.message_type = fgDisplay.State;
1651         xevent.xclient.format = 32;
1652         xevent.xclient.data.l[0] = 2;  /* _NET_WM_STATE_TOGGLE */
1653         xevent.xclient.data.l[1] = fgDisplay.StateFullScreen;
1654         xevent.xclient.data.l[2] = 0;
1655         xevent.xclient.data.l[3] = 0;
1656         xevent.xclient.data.l[4] = 0;
1657
1658         /*** Don't really understand how event masks work... ***/
1659         event_mask = SubstructureRedirectMask | SubstructureNotifyMask;
1660
1661         status = XSendEvent(fgDisplay.Display,
1662           fgDisplay.RootWindow,
1663           False,
1664           event_mask,
1665           &xevent);
1666         FREEGLUT_INTERNAL_ERROR_EXIT(status != 0,
1667           "XSendEvent failed",
1668           "glutFullScreenToggle");
1669       }
1670       else
1671 #endif
1672       {
1673         /*
1674          * If the window manager is not Net WM compliant, fall back to legacy
1675          * behaviour.
1676          */
1677         glutFullScreen();
1678       }
1679     }
1680 }
1681
1682 /*
1683  * A.Donev: Set and retrieve the window's user data
1684  */
1685 void* FGAPIENTRY glutGetWindowData( void )
1686 {
1687     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetWindowData" );
1688     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutGetWindowData" );
1689     return fgStructure.CurrentWindow->UserData;
1690 }
1691
1692 void FGAPIENTRY glutSetWindowData(void* data)
1693 {
1694     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowData" );
1695     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowData" );
1696     fgStructure.CurrentWindow->UserData = data;
1697 }
1698
1699 /*** END OF FILE ***/