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