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