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