58e95f49c81c8b383a4fad3022f70d68ac988a57
[freeglut] / src / freeglut_window.c
1 /*
2  * freeglut_window.c
3  *
4  * Window management methods.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Fri Dec 3 1999
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included
18  * in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26  */
27
28 #include <GL/freeglut.h>
29 #include "freeglut_internal.h"
30
31 #if defined(_WIN32_WCE)
32 #include <aygshell.h>
33 #pragma comment( lib, "Aygshell.lib" ) /* library pragmas are bad */
34
35 static wchar_t* fghWstrFromStr(const char* str)
36 {
37     int i,len=strlen(str);
38     wchar_t* wstr = (wchar_t*)malloc(2*len+2);
39     for(i=0; i<len; i++)
40         wstr[i] = str[i];
41     wstr[len] = 0;
42     return wstr;
43 }
44
45
46 #endif /* defined(_WIN32_WCE) */
47
48 /*
49  * TODO BEFORE THE STABLE RELEASE:
50  *
51  *  fgChooseVisual()        -- OK, but what about glutInitDisplayString()?
52  *  fgSetupPixelFormat      -- ignores the display mode settings
53  *  fgOpenWindow()          -- check the Win32 version, -iconic handling!
54  *  fgCloseWindow()         -- check the Win32 version
55  *  glutCreateWindow()      -- Check when default position and size is {-1,-1}
56  *  glutCreateSubWindow()   -- Check when default position and size is {-1,-1}
57  *  glutDestroyWindow()     -- check the Win32 version
58  *  glutSetWindow()         -- check the Win32 version
59  *  glutGetWindow()         -- OK
60  *  glutSetWindowTitle()    -- check the Win32 version
61  *  glutSetIconTitle()      -- check the Win32 version
62  *  glutShowWindow()        -- check the Win32 version
63  *  glutHideWindow()        -- check the Win32 version
64  *  glutIconifyWindow()     -- check the Win32 version
65  *  glutReshapeWindow()     -- check the Win32 version
66  *  glutPositionWindow()    -- check the Win32 version
67  *  glutPushWindow()        -- check the Win32 version
68  *  glutPopWindow()         -- check the Win32 version
69  */
70
71 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
72
73 /*
74  * Chooses a visual basing on the current display mode settings
75  */
76 #if TARGET_HOST_POSIX_X11
77
78 XVisualInfo* fgChooseVisual( void )
79 {
80 #define BUFFER_SIZES 6
81     int bufferSize[BUFFER_SIZES] = { 16, 12, 8, 4, 2, 1 };
82     GLboolean wantIndexedMode = GL_FALSE;
83     int attributes[ 32 ];
84     int where = 0;
85
86     /* First we have to process the display mode settings... */
87 /*
88  * XXX Why is there a semi-colon in this #define?  The code
89  * XXX that uses the macro seems to always add more semicolons...
90  */
91 #define ATTRIB(a) attributes[where++]=a;
92 #define ATTRIB_VAL(a,v) {ATTRIB(a); ATTRIB(v);}
93
94     if( fgState.DisplayMode & GLUT_INDEX )
95     {
96         ATTRIB_VAL( GLX_BUFFER_SIZE, 8 );
97         wantIndexedMode = GL_TRUE;
98     }
99     else
100     {
101         ATTRIB( GLX_RGBA );
102         ATTRIB_VAL( GLX_RED_SIZE,   1 );
103         ATTRIB_VAL( GLX_GREEN_SIZE, 1 );
104         ATTRIB_VAL( GLX_BLUE_SIZE,  1 );
105         if( fgState.DisplayMode & GLUT_ALPHA )
106             ATTRIB_VAL( GLX_ALPHA_SIZE, 1 );
107     }
108
109     if( fgState.DisplayMode & GLUT_DOUBLE )
110         ATTRIB( GLX_DOUBLEBUFFER );
111
112     if( fgState.DisplayMode & GLUT_STEREO )
113         ATTRIB( GLX_STEREO );
114
115     if( fgState.DisplayMode & GLUT_DEPTH )
116         ATTRIB_VAL( GLX_DEPTH_SIZE, 1 );
117
118     if( fgState.DisplayMode & GLUT_STENCIL )
119         ATTRIB_VAL( GLX_STENCIL_SIZE, 1 );
120
121     if( fgState.DisplayMode & GLUT_ACCUM )
122     {
123         ATTRIB_VAL( GLX_ACCUM_RED_SIZE,   1 );
124         ATTRIB_VAL( GLX_ACCUM_GREEN_SIZE, 1 );
125         ATTRIB_VAL( GLX_ACCUM_BLUE_SIZE,  1 );
126         if( fgState.DisplayMode & GLUT_ALPHA )
127             ATTRIB_VAL( GLX_ACCUM_ALPHA_SIZE, 1 );
128     }
129
130     if( fgState.DisplayMode & GLUT_AUX1 )
131         ATTRIB_VAL( GLX_AUX_BUFFERS, 1 );
132     if( fgState.DisplayMode & GLUT_AUX2 )
133         ATTRIB_VAL( GLX_AUX_BUFFERS, 2 );
134     if( fgState.DisplayMode & GLUT_AUX3 )
135         ATTRIB_VAL( GLX_AUX_BUFFERS, 3 );
136     if( fgState.DisplayMode & GLUT_AUX4 )
137         ATTRIB_VAL( GLX_AUX_BUFFERS, 4 );
138     if ( fgState.DisplayMode & GLUT_MULTISAMPLE )
139         ATTRIB_VAL( GLX_SAMPLES_SGIS, 4 );
140
141
142     /* Push a null at the end of the list */
143     ATTRIB( None );
144
145     if( ! wantIndexedMode )
146         return glXChooseVisual( fgDisplay.Display, fgDisplay.Screen,
147                                 attributes );
148     else
149     {
150         XVisualInfo* visualInfo;
151         int i;
152
153         /*
154          * In indexed mode, we need to check how many bits of depth can we
155          * achieve.  We do this by trying each possibility from the list
156          * given in the {bufferSize} array.  If we match, we return to caller.
157          */
158         for( i=0; i<BUFFER_SIZES; i++ )
159         {
160             attributes[ 1 ] = bufferSize[ i ];
161             visualInfo = glXChooseVisual( fgDisplay.Display, fgDisplay.Screen,
162                                           attributes );
163             if( visualInfo != NULL )
164                 return visualInfo;
165         }
166         return NULL;
167     }
168 }
169 #endif
170
171 /*
172  * Setup the pixel format for a Win32 window
173  */
174 #if TARGET_HOST_MS_WINDOWS
175 /* WRONG-- FIXME */
176 /* The following include file is available from SGI but is not standard:
177  *   #include <GL/wglext.h>
178  * So we copy the necessary parts out of it.
179  */
180 typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
181
182 typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
183
184 #define WGL_DRAW_TO_WINDOW_ARB         0x2001
185 #define WGL_ACCELERATION_ARB           0x2003
186 #define WGL_SUPPORT_OPENGL_ARB         0x2010
187 #define WGL_DOUBLE_BUFFER_ARB          0x2011
188 #define WGL_COLOR_BITS_ARB             0x2014
189 #define WGL_ALPHA_BITS_ARB             0x201B
190 #define WGL_DEPTH_BITS_ARB             0x2022
191 #define WGL_STENCIL_BITS_ARB           0x2023
192 #define WGL_FULL_ACCELERATION_ARB      0x2027
193
194 #define WGL_SAMPLE_BUFFERS_ARB         0x2041
195 #define WGL_SAMPLES_ARB                0x2042
196
197
198 GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly,
199                               unsigned char layer_type )
200 {
201 #if defined(_WIN32_WCE)
202     return GL_TRUE;
203 #else
204     PIXELFORMATDESCRIPTOR* ppfd, pfd;
205     int flags, pixelformat;
206
207     freeglut_return_val_if_fail( window != NULL, 0 );
208     flags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
209     if( fgState.DisplayMode & GLUT_DOUBLE )
210         flags |= PFD_DOUBLEBUFFER;
211
212     if( fgState.DisplayMode & GLUT_STEREO )
213         flags |= PFD_STEREO;
214
215 #if defined(_MSC_VER)
216 #pragma message( "fgSetupPixelFormat(): there is still some work to do here!" )
217 #endif
218
219     /* Specify which pixel format do we opt for... */
220     pfd.nSize           = sizeof(PIXELFORMATDESCRIPTOR);
221     pfd.nVersion        = 1;
222     pfd.dwFlags         = flags;
223
224     if( fgState.DisplayMode & GLUT_INDEX )
225     {
226         pfd.iPixelType = PFD_TYPE_COLORINDEX;
227         pfd.cRedBits                = 0;
228         pfd.cGreenBits            = 0;
229         pfd.cBlueBits             = 0;
230         pfd.cAlphaBits            = 0;
231     }
232     else
233     {
234         pfd.iPixelType      = PFD_TYPE_RGBA;
235         pfd.cRedBits                = 8;
236         pfd.cGreenBits            = 8;
237         pfd.cBlueBits             = 8;
238         if ( fgState.DisplayMode & GLUT_ALPHA )
239             pfd.cAlphaBits            = 8;
240         else
241             pfd.cAlphaBits            = 0;
242     }
243
244     pfd.cColorBits      = 24;
245     pfd.cRedShift       = 0;
246     pfd.cGreenShift     = 0;
247     pfd.cBlueShift      = 0;
248     pfd.cAlphaShift     = 0;
249     pfd.cAccumBits      = 0;
250     pfd.cAccumRedBits   = 0;
251     pfd.cAccumGreenBits = 0;
252     pfd.cAccumBlueBits  = 0;
253     pfd.cAccumAlphaBits = 0;
254 #if 0
255     pfd.cDepthBits      = 32;
256     pfd.cStencilBits    = 0;
257 #else
258     pfd.cDepthBits      = 24;
259     pfd.cStencilBits    = 8;
260 #endif
261     if( fgState.DisplayMode & GLUT_AUX4 )
262         pfd.cAuxBuffers = 4;
263     else if( fgState.DisplayMode & GLUT_AUX3 )
264         pfd.cAuxBuffers = 3;
265     else if( fgState.DisplayMode & GLUT_AUX2 )
266         pfd.cAuxBuffers = 2;
267     else if( fgState.DisplayMode & GLUT_AUX1 )
268         pfd.cAuxBuffers = 1;
269     else
270         pfd.cAuxBuffers = 0;
271
272     pfd.iLayerType      = layer_type;
273     pfd.bReserved       = 0;
274     pfd.dwLayerMask     = 0;
275     pfd.dwVisibleMask   = 0;
276     pfd.dwDamageMask    = 0;
277
278     pfd.cColorBits = (BYTE) GetDeviceCaps( window->Window.Device, BITSPIXEL );
279     ppfd = &pfd;
280
281     pixelformat = ChoosePixelFormat( window->Window.Device, ppfd );
282
283     /* windows hack for multismapling */
284     if (fgState.DisplayMode&GLUT_MULTISAMPLE)
285     {        
286         PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetEntensionsStringARB=NULL;
287         HGLRC rc, rc_before=wglGetCurrentContext();
288         HWND hWnd;
289         HDC hDC, hDC_before=wglGetCurrentDC();
290         WNDCLASS wndCls;
291         ATOM atom;
292
293         /* create a dummy window */
294         ZeroMemory(&wndCls, sizeof(wndCls));
295                 wndCls.lpfnWndProc        = DefWindowProc;
296                 wndCls.hInstance            = fgDisplay.Instance;
297                 wndCls.style                    = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
298                 wndCls.lpszClassName    = _T("FREEGLUT_dummy");
299         atom = RegisterClass( &wndCls );
300
301         hWnd=CreateWindow((LPCSTR)atom, _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.Instance, 0 );
302         hDC=GetDC(hWnd);
303         SetPixelFormat( hDC, pixelformat, ppfd );
304         
305         rc = wglCreateContext( hDC );
306         wglMakeCurrent(hDC, rc);
307         
308         wglGetEntensionsStringARB=(PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
309         if (wglGetEntensionsStringARB)
310         {
311             const char * pWglExtString=wglGetEntensionsStringARB(hDC);
312             if (pWglExtString)
313             {
314                 if (strstr(pWglExtString, "WGL_ARB_multisample"))
315                 {
316                     int pAttributes[100];
317                     int iCounter=0;
318                     int iPixelFormat;
319                     BOOL bValid;
320                     float fAttributes[] = {0,0};
321                     UINT numFormats;
322                     PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc=NULL;
323
324                     wglChoosePixelFormatARBProc=(PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
325                     if ( wglChoosePixelFormatARBProc )
326                     {
327                         pAttributes[iCounter++]=WGL_DRAW_TO_WINDOW_ARB;        pAttributes[iCounter++]=GL_TRUE;
328                         pAttributes[iCounter++]=WGL_SUPPORT_OPENGL_ARB;        pAttributes[iCounter++]=GL_TRUE;
329                         pAttributes[iCounter++]=WGL_ACCELERATION_ARB;        pAttributes[iCounter++]=WGL_FULL_ACCELERATION_ARB;
330
331                         pAttributes[iCounter++]=WGL_COLOR_BITS_ARB;            pAttributes[iCounter++]=pfd.cColorBits ;
332                         pAttributes[iCounter++]=WGL_ALPHA_BITS_ARB;            pAttributes[iCounter++]=pfd.cAlphaBits;
333                         pAttributes[iCounter++]=WGL_DEPTH_BITS_ARB;            pAttributes[iCounter++]=pfd.cDepthBits;
334                         pAttributes[iCounter++]=WGL_STENCIL_BITS_ARB;        pAttributes[iCounter++]=pfd.cStencilBits;
335
336                         pAttributes[iCounter++]=WGL_DOUBLE_BUFFER_ARB;        pAttributes[iCounter++]=(fgState.DisplayMode & GLUT_DOUBLE)!=0;
337                         pAttributes[iCounter++]=WGL_SAMPLE_BUFFERS_ARB;        pAttributes[iCounter++]=GL_TRUE;
338                         pAttributes[iCounter++]=WGL_SAMPLES_ARB;            pAttributes[iCounter++]=4;
339                         pAttributes[iCounter++]=0;                            pAttributes[iCounter++]=0;    /* terminator */
340
341                         bValid = wglChoosePixelFormatARBProc(window->Window.Device,pAttributes,fAttributes,1,&iPixelFormat,&numFormats);
342
343                         if (bValid && numFormats>0)
344                             pixelformat=iPixelFormat;
345                     }
346                 }
347                 wglMakeCurrent( hDC_before, rc_before);
348                 wglDeleteContext(rc);
349                 ReleaseDC(hWnd, hDC);
350                 DestroyWindow(hWnd);
351                 UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.Instance);
352             }
353         }
354     }
355
356     if( pixelformat == 0 )
357         return GL_FALSE;
358
359     if( checkOnly )
360         return GL_TRUE;
361     return SetPixelFormat( window->Window.Device, pixelformat, ppfd );
362 #endif /* defined(_WIN32_WCE) */
363 }
364 #endif /* TARGET_HOST_MS_WINDOWS */
365
366 /*
367  * Sets the OpenGL context and the fgStructure "Current Window" pointer to
368  * the window structure passed in.
369  */
370 void fgSetWindow ( SFG_Window *window )
371 {
372 #if TARGET_HOST_POSIX_X11
373     if ( window )
374         glXMakeCurrent(
375             fgDisplay.Display,
376             window->Window.Handle,
377             window->Window.Context
378         );
379 #elif TARGET_HOST_MS_WINDOWS
380     if( fgStructure.CurrentWindow )
381         ReleaseDC( fgStructure.CurrentWindow->Window.Handle,
382                    fgStructure.CurrentWindow->Window.Device );
383
384     if ( window )
385     {
386         window->Window.Device = GetDC( window->Window.Handle );
387         wglMakeCurrent(
388             window->Window.Device,
389             window->Window.Context
390         );
391     }
392 #endif
393     fgStructure.CurrentWindow = window;
394 }
395
396
397 /*
398  * Opens a window. Requires a SFG_Window object created and attached
399  * to the freeglut structure. OpenGL context is created here.
400  */
401 void fgOpenWindow( SFG_Window* window, const char* title,
402                    int x, int y, int w, int h,
403                    GLboolean gameMode, GLboolean isSubWindow )
404 {
405 #if TARGET_HOST_POSIX_X11
406     XSetWindowAttributes winAttr;
407     XTextProperty textProperty;
408     XSizeHints sizeHints;
409     XWMHints wmHints;
410     unsigned long mask;
411     unsigned int current_DisplayMode = fgState.DisplayMode ;
412
413     /* Save the display mode if we are creating a menu window */
414     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
415         fgState.DisplayMode = GLUT_DOUBLE | GLUT_RGB ;
416
417     window->Window.VisualInfo = fgChooseVisual( );
418
419     if( window->IsMenu && ( ! fgStructure.MenuContext ) )
420         fgState.DisplayMode = current_DisplayMode ;
421
422     if( ! window->Window.VisualInfo )
423     {
424         /*
425          * The "fgChooseVisual" returned a null meaning that the visual
426          * context is not available.
427          * Try a couple of variations to see if they will work.
428          */
429         if( !( fgState.DisplayMode & GLUT_DOUBLE ) )
430         {
431             fgState.DisplayMode |= GLUT_DOUBLE ;
432             window->Window.VisualInfo = fgChooseVisual( );
433             fgState.DisplayMode &= ~GLUT_DOUBLE;
434         }
435
436         /*
437          * GLUT also checks for multi-sampling, but I don't see that
438          * anywhere else in FREEGLUT so I won't bother with it for the moment.
439          */
440     }
441
442     FREEGLUT_INTERNAL_ERROR_EXIT( window->Window.VisualInfo != NULL,
443                                   "Visual with necessary capabilities not found", "fgOpenWindow" );
444
445     /*
446      * XXX HINT: the masks should be updated when adding/removing callbacks.
447      * XXX       This might speed up message processing. Is that true?
448      * XXX
449      * XXX A: Not appreciably, but it WILL make it easier to debug.
450      * XXX    Try tracing old GLUT and try tracing freeglut.  Old GLUT
451      * XXX    turns off events that it doesn't need and is a whole lot
452      * XXX    more pleasant to trace.  (Think mouse-motion!  Tons of
453      * XXX    ``bonus'' GUI events stream in.)
454      */
455     winAttr.event_mask        =
456         StructureNotifyMask | SubstructureNotifyMask | ExposureMask |
457         ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask |
458         VisibilityChangeMask | EnterWindowMask | LeaveWindowMask |
459         PointerMotionMask | ButtonMotionMask;
460     winAttr.background_pixmap = None;
461     winAttr.background_pixel  = 0;
462     winAttr.border_pixel      = 0;
463
464     winAttr.colormap = XCreateColormap(
465         fgDisplay.Display, fgDisplay.RootWindow,
466         window->Window.VisualInfo->visual, AllocNone
467     );
468
469     mask = CWBackPixmap | CWBorderPixel | CWColormap | CWEventMask;
470
471     if( window->IsMenu || ( gameMode == GL_TRUE ) )
472     {
473         winAttr.override_redirect = True;
474         mask |= CWOverrideRedirect;
475     }
476
477     window->Window.Handle = XCreateWindow(
478         fgDisplay.Display,
479         window->Parent == NULL ? fgDisplay.RootWindow :
480         window->Parent->Window.Handle,
481         x, y, w, h, 0,
482         window->Window.VisualInfo->depth, InputOutput,
483         window->Window.VisualInfo->visual, mask,
484         &winAttr
485     );
486
487     /*
488      * The GLX context creation, possibly trying the direct context rendering
489      *  or else use the current context if the user has so specified
490      */
491     if( window->IsMenu )
492     {
493         /*
494          * If there isn't already an OpenGL rendering context for menu
495          * windows, make one
496          */
497         if( !fgStructure.MenuContext )
498         {
499             fgStructure.MenuContext =
500                 (SFG_MenuContext *)malloc( sizeof(SFG_MenuContext) );
501             fgStructure.MenuContext->MVisualInfo = window->Window.VisualInfo;
502             fgStructure.MenuContext->MContext = glXCreateContext(
503                 fgDisplay.Display, fgStructure.MenuContext->MVisualInfo,
504                 NULL, ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT )
505             );
506         }
507
508         /* window->Window.Context = fgStructure.MenuContext->MContext; */
509         window->Window.Context = glXCreateContext(
510             fgDisplay.Display, window->Window.VisualInfo,
511             NULL, ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT )
512         );
513     }
514     else if( fgState.UseCurrentContext )
515     {
516         window->Window.Context = glXGetCurrentContext( );
517
518         if( ! window->Window.Context )
519             window->Window.Context = glXCreateContext(
520                 fgDisplay.Display, window->Window.VisualInfo,
521                 NULL, ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT )
522             );
523     }
524     else
525         window->Window.Context = glXCreateContext(
526             fgDisplay.Display, window->Window.VisualInfo,
527             NULL, ( fgState.DirectContext != GLUT_FORCE_INDIRECT_CONTEXT )
528         );
529
530 #if !defined( __FreeBSD__ ) && !defined( __NetBSD__ )
531     if(  !glXIsDirect( fgDisplay.Display, window->Window.Context ) )
532     {
533       if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
534         fgError( "Unable to force direct context rendering for window '%s'",
535                  title );
536       else if( fgState.DirectContext == GLUT_TRY_DIRECT_CONTEXT )
537         fgWarning( "Unable to create direct context rendering for window '%s'\nThis may hurt performance.",
538                  title );
539     }
540 #endif
541
542     /*
543      * XXX Assume the new window is visible by default
544      * XXX Is this a  safe assumption?
545      */
546     window->State.Visible = GL_TRUE;
547
548     sizeHints.flags = 0;
549     if ( fgState.Position.Use )
550         sizeHints.flags |= USPosition;
551     if ( fgState.Size.Use )
552         sizeHints.flags |= USSize;
553
554     /*
555      * Fill in the size hints values now (the x, y, width and height
556      * settings are obsolete, are there any more WMs that support them?)
557      * Unless the X servers actually stop supporting these, we should
558      * continue to fill them in.  It is *not* our place to tell the user
559      * that they should replace a window manager that they like, and which
560      * works, just because *we* think that it's not "modern" enough.
561      */
562     sizeHints.x      = x;
563     sizeHints.y      = y;
564     sizeHints.width  = w;
565     sizeHints.height = h;
566
567     wmHints.flags = StateHint;
568     wmHints.initial_state = fgState.ForceIconic ? IconicState : NormalState;
569     /* Prepare the window and iconified window names... */
570     XStringListToTextProperty( (char **) &title, 1, &textProperty );
571
572     XSetWMProperties(
573         fgDisplay.Display,
574         window->Window.Handle,
575         &textProperty,
576         &textProperty,
577         0,
578         0,
579         &sizeHints,
580         &wmHints,
581         NULL
582     );
583     XFree( textProperty.value );
584
585     XSetWMProtocols( fgDisplay.Display, window->Window.Handle,
586                      &fgDisplay.DeleteWindow, 1 );
587
588     glXMakeCurrent(
589         fgDisplay.Display,
590         window->Window.Handle,
591         window->Window.Context
592     );
593
594     XMapWindow( fgDisplay.Display, window->Window.Handle );
595
596 #elif TARGET_HOST_MS_WINDOWS
597
598     WNDCLASS wc;
599     DWORD flags;
600     DWORD exFlags = 0;
601     ATOM atom;
602
603     /* Grab the window class we have registered on glutInit(): */
604     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
605     FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Info Not Found",
606                                    "fgOpenWindow" );
607
608     if( gameMode )
609     {
610         FREEGLUT_INTERNAL_ERROR_EXIT ( window->Parent == NULL,
611                                        "Game mode being invoked on a subwindow",
612                                        "fgOpenWindow" );
613
614         /*
615          * Set the window creation flags appropriately to make the window
616          * entirely visible:
617          */
618         flags = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
619     }
620     else
621     {
622 #if !defined(_WIN32_WCE)
623         if ( ( ! isSubWindow ) && ( ! window->IsMenu ) )
624         {
625             /*
626              * Update the window dimensions, taking account of window
627              * decorations.  "freeglut" is to create the window with the
628              * outside of its border at (x,y) and with dimensions (w,h).
629              */
630             w += (GetSystemMetrics( SM_CXSIZEFRAME ) )*2;
631             h += (GetSystemMetrics( SM_CYSIZEFRAME ) )*2 +
632                 GetSystemMetrics( SM_CYCAPTION );
633         }
634 #endif /* defined(_WIN32_WCE) */
635
636         if( ! fgState.Position.Use )
637         {
638             x = CW_USEDEFAULT;
639             y = CW_USEDEFAULT;
640         }
641         if( ! fgState.Size.Use )
642         {
643             w = CW_USEDEFAULT;
644             h = CW_USEDEFAULT;
645         }
646
647         /*
648          * There's a small difference between creating the top, child and
649          * game mode windows
650          */
651         flags = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
652
653         if ( window->IsMenu )
654         {
655             flags |= WS_POPUP;
656             exFlags |= WS_EX_TOOLWINDOW;
657         }
658 #if !defined(_WIN32_WCE)
659         else if( window->Parent == NULL )
660             flags |= WS_OVERLAPPEDWINDOW;
661 #endif
662         else
663             flags |= WS_CHILD;
664     }
665
666 #if defined(_WIN32_WCE)
667     {
668         wchar_t* wstr = fghWstrFromStr(title);
669
670         window->Window.Handle = CreateWindow(
671             _T("FREEGLUT"),
672             wstr,
673             WS_VISIBLE | WS_POPUP,
674             0,0, 240,320,
675             NULL,
676             NULL,
677             fgDisplay.Instance,
678             (LPVOID) window
679         );
680
681         free(wstr);
682
683         SHFullScreen(window->Window.Handle, SHFS_HIDESTARTICON);
684         SHFullScreen(window->Window.Handle, SHFS_HIDESIPBUTTON);
685         SHFullScreen(window->Window.Handle, SHFS_HIDETASKBAR);
686         MoveWindow(window->Window.Handle, 0, 0, 240, 320, TRUE);
687         ShowWindow(window->Window.Handle, SW_SHOW);
688         UpdateWindow(window->Window.Handle);
689     }
690 #else
691     window->Window.Handle = CreateWindowEx(
692         exFlags,
693         "FREEGLUT",
694         title,
695         flags,
696         x, y, w, h,
697         (HWND) window->Parent == NULL ? NULL : window->Parent->Window.Handle,
698         (HMENU) NULL,
699         fgDisplay.Instance,
700         (LPVOID) window
701     );
702 #endif /* defined(_WIN32_WCE) */
703
704     if( !( window->Window.Handle ) )
705         fgError( "Failed to create a window (%s)!", title );
706
707 #if defined(_WIN32_WCE)
708     ShowWindow( window->Window.Handle, SW_SHOW );
709 #else
710     ShowWindow( window->Window.Handle,
711                 fgState.ForceIconic ? SW_SHOWMINIMIZED : SW_SHOW );
712 #endif /* defined(_WIN32_WCE) */
713
714     UpdateWindow( window->Window.Handle );
715     ShowCursor( TRUE );  /* XXX Old comments say "hide cursor"! */
716
717 #endif
718
719     fgSetWindow( window );
720
721     window->Window.DoubleBuffered =
722         ( fgState.DisplayMode & GLUT_DOUBLE ) ? 1 : 0;
723
724     if ( ! window->Window.DoubleBuffered )
725     {
726         glDrawBuffer ( GL_FRONT );
727         glReadBuffer ( GL_FRONT );
728     }
729 }
730
731 /*
732  * Closes a window, destroying the frame and OpenGL context
733  */
734 void fgCloseWindow( SFG_Window* window )
735 {
736 #if TARGET_HOST_POSIX_X11
737
738     glXDestroyContext( fgDisplay.Display, window->Window.Context );
739     XFree( window->Window.VisualInfo );
740     XDestroyWindow( fgDisplay.Display, window->Window.Handle );
741     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
742
743 #elif TARGET_HOST_MS_WINDOWS
744
745     /* Make sure we don't close a window with current context active */
746     if( fgStructure.CurrentWindow == window )
747         wglMakeCurrent( NULL, NULL );
748
749     /*
750      * Step through the list of windows.  If the rendering context
751      * is not being used by another window, then we delete it.
752      */
753     {
754         int used = FALSE ;
755         SFG_Window *iter ;
756
757         for( iter = (SFG_Window *)fgStructure.Windows.First;
758              iter;
759              iter = (SFG_Window *)iter->Node.Next )
760         {
761             if( ( iter->Window.Context == window->Window.Context ) &&
762                 ( iter != window ) )
763                 used = TRUE;
764         }
765
766         if( ! used )
767             wglDeleteContext( window->Window.Context );
768     }
769
770     DestroyWindow( window->Window.Handle );
771 #endif
772 }
773
774
775 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
776
777 /*
778  * Creates a new top-level freeglut window
779  */
780 int FGAPIENTRY glutCreateWindow( const char* title )
781 {
782     /* XXX GLUT does not exit; it simply calls "glutInit" quietly if the
783      * XXX application has not already done so.  The "freeglut" community
784      * XXX decided not to go this route (freeglut-developer e-mail from
785      * XXX Steve Baker, 12/16/04, 4:22 PM CST, "Re: [Freeglut-developer]
786      * XXX Desired 'freeglut' behaviour when there is no current window"
787      */
788     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateWindow" );
789
790     return fgCreateWindow( NULL, title, fgState.Position.X, fgState.Position.Y,
791                            fgState.Size.X, fgState.Size.Y, GL_FALSE,
792                            GL_FALSE )->ID;
793 }
794
795 /*
796  * This function creates a sub window.
797  */
798 int FGAPIENTRY glutCreateSubWindow( int parentID, int x, int y, int w, int h )
799 {
800     int ret = 0;
801     SFG_Window* window = NULL;
802     SFG_Window* parent = NULL;
803
804     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutCreateSubWindow" );
805     parent = fgWindowByID( parentID );
806     freeglut_return_val_if_fail( parent != NULL, 0 );
807     if ( x < 0 )
808     {
809         x = parent->State.Width + x ;
810         if ( w >= 0 ) x -= w ;
811     }
812
813     if ( w < 0 ) w = parent->State.Width - x + w ;
814     if ( w < 0 )
815     {
816         x += w ;
817         w = -w ;
818     }
819
820     if ( y < 0 )
821     {
822         y = parent->State.Height + y ;
823         if ( h >= 0 ) y -= h ;
824     }
825
826     if ( h < 0 ) h = parent->State.Height - y + h ;
827     if ( h < 0 )
828     {
829         y += h ;
830         h = -h ;
831     }
832
833     window = fgCreateWindow( parent, "", x, y, w, h, GL_FALSE, GL_FALSE );
834     ret = window->ID;
835
836     return ret;
837 }
838
839 /*
840  * Destroys a window and all of its subwindows
841  */
842 void FGAPIENTRY glutDestroyWindow( int windowID )
843 {
844     SFG_Window* window;
845     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutDestroyWindow" );
846     window = fgWindowByID( windowID );
847     freeglut_return_if_fail( window != NULL );
848     {
849         fgExecutionState ExecState = fgState.ExecState;
850         fgAddToWindowDestroyList( window );
851         fgState.ExecState = ExecState;
852     }
853 }
854
855 /*
856  * This function selects the current window
857  */
858 void FGAPIENTRY glutSetWindow( int ID )
859 {
860     SFG_Window* window = NULL;
861
862     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindow" );
863     if( fgStructure.CurrentWindow != NULL )
864         if( fgStructure.CurrentWindow->ID == ID )
865             return;
866
867     window = fgWindowByID( ID );
868     if( window == NULL )
869     {
870         fgWarning( "glutSetWindow(): window ID %d not found!", ID );
871         return;
872     }
873
874     fgSetWindow( window );
875 }
876
877 /*
878  * This function returns the ID number of the current window, 0 if none exists
879  */
880 int FGAPIENTRY glutGetWindow( void )
881 {
882     SFG_Window *win = fgStructure.CurrentWindow;
883     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetWindow" );
884     while ( win && win->IsMenu )
885         win = win->Parent;
886     return win ? win->ID : 0;
887 }
888
889 /*
890  * This function makes the current window visible
891  */
892 void FGAPIENTRY glutShowWindow( void )
893 {
894     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutShowWindow" );
895     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutShowWindow" );
896
897 #if TARGET_HOST_POSIX_X11
898
899     XMapWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
900     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
901
902 #elif TARGET_HOST_MS_WINDOWS
903
904     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_SHOW );
905
906 #endif
907
908     fgStructure.CurrentWindow->State.Redisplay = GL_TRUE;
909 }
910
911 /*
912  * This function hides the current window
913  */
914 void FGAPIENTRY glutHideWindow( void )
915 {
916     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutHideWindow" );
917     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutHideWindow" );
918
919 #if TARGET_HOST_POSIX_X11
920
921     if( fgStructure.CurrentWindow->Parent == NULL )
922         XWithdrawWindow( fgDisplay.Display,
923                          fgStructure.CurrentWindow->Window.Handle,
924                          fgDisplay.Screen );
925     else
926         XUnmapWindow( fgDisplay.Display,
927                       fgStructure.CurrentWindow->Window.Handle );
928     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
929
930 #elif TARGET_HOST_MS_WINDOWS
931
932     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_HIDE );
933
934 #endif
935
936     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
937 }
938
939 /*
940  * Iconify the current window (top-level windows only)
941  */
942 void FGAPIENTRY glutIconifyWindow( void )
943 {
944     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutIconifyWindow" );
945     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutIconifyWindow" );
946
947     fgStructure.CurrentWindow->State.Visible   = GL_FALSE;
948 #if TARGET_HOST_POSIX_X11
949
950     XIconifyWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
951                     fgDisplay.Screen );
952     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
953
954 #elif TARGET_HOST_MS_WINDOWS
955
956     ShowWindow( fgStructure.CurrentWindow->Window.Handle, SW_MINIMIZE );
957
958 #endif
959
960     fgStructure.CurrentWindow->State.Redisplay = GL_FALSE;
961 }
962
963 /*
964  * Set the current window's title
965  */
966 void FGAPIENTRY glutSetWindowTitle( const char* title )
967 {
968     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowTitle" );
969     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowTitle" );
970     if( ! fgStructure.CurrentWindow->Parent )
971     {
972 #if TARGET_HOST_POSIX_X11
973
974         XTextProperty text;
975
976         text.value = (unsigned char *) title;
977         text.encoding = XA_STRING;
978         text.format = 8;
979         text.nitems = strlen( title );
980
981         XSetWMName(
982             fgDisplay.Display,
983             fgStructure.CurrentWindow->Window.Handle,
984             &text
985         );
986
987         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
988
989 #elif TARGET_HOST_MS_WINDOWS
990 #    ifdef _WIN32_WCE
991         {
992             wchar_t* wstr = fghWstrFromStr(title);
993             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
994             free(wstr);
995         }
996 #    else
997         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
998 #    endif
999
1000 #endif
1001     }
1002 }
1003
1004 /*
1005  * Set the current window's iconified title
1006  */
1007 void FGAPIENTRY glutSetIconTitle( const char* title )
1008 {
1009     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetIconTitle" );
1010     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetIconTitle" );
1011
1012     if( ! fgStructure.CurrentWindow->Parent )
1013     {
1014 #if TARGET_HOST_POSIX_X11
1015
1016         XTextProperty text;
1017
1018         text.value = (unsigned char *) title;
1019         text.encoding = XA_STRING;
1020         text.format = 8;
1021         text.nitems = strlen( title );
1022
1023         XSetWMIconName(
1024             fgDisplay.Display,
1025             fgStructure.CurrentWindow->Window.Handle,
1026             &text
1027         );
1028
1029         XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1030
1031 #elif TARGET_HOST_MS_WINDOWS
1032 #    ifdef _WIN32_WCE
1033         {
1034             wchar_t* wstr = fghWstrFromStr(title);
1035             SetWindowText( fgStructure.CurrentWindow->Window.Handle, wstr );
1036             free(wstr);
1037         }
1038 #    else
1039         SetWindowText( fgStructure.CurrentWindow->Window.Handle, title );
1040 #    endif
1041
1042 #endif
1043     }
1044 }
1045
1046 /*
1047  * Change the current window's size
1048  */
1049 void FGAPIENTRY glutReshapeWindow( int width, int height )
1050 {
1051     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutReshapeWindow" );
1052     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutReshapeWindow" );
1053
1054     fgStructure.CurrentWindow->State.NeedToResize = GL_TRUE;
1055     fgStructure.CurrentWindow->State.Width  = width ;
1056     fgStructure.CurrentWindow->State.Height = height;
1057 }
1058
1059 /*
1060  * Change the current window's position
1061  */
1062 void FGAPIENTRY glutPositionWindow( int x, int y )
1063 {
1064     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPositionWindow" );
1065     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPositionWindow" );
1066
1067 #if TARGET_HOST_POSIX_X11
1068
1069     XMoveWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle,
1070                  x, y );
1071     XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1072
1073 #elif TARGET_HOST_MS_WINDOWS
1074
1075     {
1076         RECT winRect;
1077
1078         /* "GetWindowRect" returns the pixel coordinates of the outside of the window */
1079         GetWindowRect( fgStructure.CurrentWindow->Window.Handle, &winRect );
1080         MoveWindow(
1081             fgStructure.CurrentWindow->Window.Handle,
1082             x,
1083             y,
1084             winRect.right - winRect.left,
1085             winRect.bottom - winRect.top,
1086             TRUE
1087         );
1088     }
1089
1090 #endif
1091 }
1092
1093 /*
1094  * Lowers the current window (by Z order change)
1095  */
1096 void FGAPIENTRY glutPushWindow( void )
1097 {
1098     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPushWindow" );
1099     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPushWindow" );
1100
1101 #if TARGET_HOST_POSIX_X11
1102
1103     XLowerWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1104
1105 #elif TARGET_HOST_MS_WINDOWS
1106
1107     SetWindowPos(
1108         fgStructure.CurrentWindow->Window.Handle,
1109         HWND_BOTTOM,
1110         0, 0, 0, 0,
1111         SWP_NOSIZE | SWP_NOMOVE
1112     );
1113
1114 #endif
1115 }
1116
1117 /*
1118  * Raises the current window (by Z order change)
1119  */
1120 void FGAPIENTRY glutPopWindow( void )
1121 {
1122     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutPopWindow" );
1123     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutPopWindow" );
1124
1125 #if TARGET_HOST_POSIX_X11
1126
1127     XRaiseWindow( fgDisplay.Display, fgStructure.CurrentWindow->Window.Handle );
1128
1129 #elif TARGET_HOST_MS_WINDOWS
1130
1131     SetWindowPos(
1132         fgStructure.CurrentWindow->Window.Handle,
1133         HWND_TOP,
1134         0, 0, 0, 0,
1135         SWP_NOSIZE | SWP_NOMOVE
1136     );
1137
1138 #endif
1139 }
1140
1141 /*
1142  * Resize the current window so that it fits the whole screen
1143  */
1144 void FGAPIENTRY glutFullScreen( void )
1145 {
1146     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutFullScreen" );
1147     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutFullScreen" );
1148
1149     {
1150 #if TARGET_HOST_POSIX_X11
1151         int x, y;
1152         Window w;
1153
1154         XMoveResizeWindow(
1155             fgDisplay.Display,
1156             fgStructure.CurrentWindow->Window.Handle,
1157             0, 0,
1158             fgDisplay.ScreenWidth,
1159             fgDisplay.ScreenHeight
1160         );
1161
1162         XFlush( fgDisplay.Display ); /* This is needed */
1163
1164         XTranslateCoordinates(
1165             fgDisplay.Display,
1166             fgStructure.CurrentWindow->Window.Handle,
1167             fgDisplay.RootWindow,
1168             0, 0, &x, &y, &w
1169         );
1170
1171         if (x || y)
1172         {
1173             XMoveWindow(
1174                 fgDisplay.Display,
1175                 fgStructure.CurrentWindow->Window.Handle,
1176                 -x, -y
1177             );
1178             XFlush( fgDisplay.Display ); /* XXX Shouldn't need this */
1179         }
1180 #elif TARGET_HOST_MS_WINDOWS && !defined(_WIN32_WCE) /* FIXME: what about WinCE */
1181         RECT rect;
1182
1183         /* For fullscreen mode, force the top-left corner to 0,0
1184          * and adjust the window rectangle so that the client area
1185          * covers the whole screen.
1186          */
1187
1188         rect.left   = 0;
1189         rect.top    = 0;
1190         rect.right  = fgDisplay.ScreenWidth;
1191         rect.bottom = fgDisplay.ScreenHeight;
1192
1193         AdjustWindowRect ( &rect, WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS |
1194                                   WS_CLIPCHILDREN, FALSE );
1195
1196         /*
1197          * SWP_NOACTIVATE     Do not activate the window
1198          * SWP_NOOWNERZORDER  Do not change position in z-order
1199          * SWP_NOSENDCHANGING Supress WM_WINDOWPOSCHANGING message
1200          * SWP_NOZORDER       Retains the current Z order (ignore 2nd param)
1201          */
1202
1203         SetWindowPos( fgStructure.CurrentWindow->Window.Handle,
1204                       HWND_TOP,
1205                       rect.left,
1206                       rect.top,
1207                       rect.right  - rect.left,
1208                       rect.bottom - rect.top,
1209                       SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING |
1210                       SWP_NOZORDER
1211                     );
1212 #endif
1213     }
1214 }
1215
1216 /*
1217  * A.Donev: Set and retrieve the window's user data
1218  */
1219 void* FGAPIENTRY glutGetWindowData( void )
1220 {
1221     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutGetWindowData" );
1222     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutGetWindowData" );
1223     return fgStructure.CurrentWindow->UserData;
1224 }
1225
1226 void FGAPIENTRY glutSetWindowData(void* data)
1227 {
1228     FREEGLUT_EXIT_IF_NOT_INITIALISED ( "glutSetWindowData" );
1229     FREEGLUT_EXIT_IF_NO_WINDOW ( "glutSetWindowData" );
1230     fgStructure.CurrentWindow->UserData = data;
1231 }
1232
1233 /*** END OF FILE ***/