Adding "glutFullScreenToggle" for X11 -- still needs implementation in Windows (e...
[freeglut] / src / freeglut_init.c
1 /*
2  * freeglut_init.c
3  *
4  * Various freeglut initialization functions.
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Thu Dec 2 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_POSIX_X11
32 #include <limits.h>  /* LONG_MAX */
33 #endif
34
35 /*
36  * TODO BEFORE THE STABLE RELEASE:
37  *
38  *  fgDeinitialize()        -- Win32's OK, X11 needs the OS-specific
39  *                             deinitialization done
40  *  glutInitDisplayString() -- display mode string parsing
41  *
42  * Wouldn't it be cool to use gettext() for error messages? I just love
43  * bash saying  "nie znaleziono pliku" instead of "file not found" :)
44  * Is gettext easily portable?
45  */
46
47 /* -- GLOBAL VARIABLES ----------------------------------------------------- */
48
49 /*
50  * A structure pointed by g_pDisplay holds all information
51  * regarding the display, screen, root window etc.
52  */
53 SFG_Display fgDisplay;
54
55 /*
56  * The settings for the current freeglut session
57  */
58 SFG_State fgState = { { -1, -1, GL_FALSE },  /* Position */
59                       { 300, 300, GL_TRUE }, /* Size */
60                       GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH,  /* DisplayMode */
61                       GL_FALSE,              /* Initialised */
62                       GLUT_TRY_DIRECT_CONTEXT,  /* DirectContext */
63                       GL_FALSE,              /* ForceIconic */
64                       GL_FALSE,              /* UseCurrentContext */
65                       GL_FALSE,              /* GLDebugSwitch */
66                       GL_FALSE,              /* XSyncSwitch */
67                       GLUT_KEY_REPEAT_ON,    /* KeyRepeat */
68                       INVALID_MODIFIERS,     /* Modifiers */
69                       0,                     /* FPSInterval */
70                       0,                     /* SwapCount */
71                       0,                     /* SwapTime */
72                       0,                     /* Time */
73                       { NULL, NULL },         /* Timers */
74                       { NULL, NULL },         /* FreeTimers */
75                       NULL,                   /* IdleCallback */
76                       0,                      /* ActiveMenus */
77                       NULL,                   /* MenuStateCallback */
78                       NULL,                   /* MenuStatusCallback */
79                       { 640, 480, GL_TRUE },  /* GameModeSize */
80                       16,                     /* GameModeDepth */
81                       72,                     /* GameModeRefresh */
82                       GLUT_ACTION_EXIT,       /* ActionOnWindowClose */
83                       GLUT_EXEC_STATE_INIT,   /* ExecState */
84                       NULL,                   /* ProgramName */
85                       GL_FALSE,               /* JoysticksInitialised */
86                       GL_FALSE,               /* InputDevsInitialised */
87                       0,                      /* AuxiliaryBufferNumber */
88                       0                       /* SampleNumber */
89 };
90
91
92 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
93
94 #if TARGET_HOST_POSIX_X11
95
96 /* Return the atom associated with "name". */
97 static Atom fghGetAtom(const char * name)
98 {
99   return XInternAtom(fgDisplay.Display, name, False);
100 }
101
102 /*
103  * Check if "property" is set on "window".  The property's values are returned
104  * through "data".  If the property is set and is of type "type", return the
105  * number of elements in "data".  Return zero otherwise.  In both cases, use
106  * "Xfree()" to free "data".
107  */
108 static int fghGetWindowProperty(Window window,
109                                 Atom property,
110                                 Atom type,
111                                 unsigned char ** data)
112 {
113   /*
114    * Caller always has to use "Xfree()" to free "data", since
115    * "XGetWindowProperty() always allocates one extra byte in prop_return
116    * [i.e. "data"] (even if the property is zero length) [..]".
117    */
118
119   int status;  /*  Returned by "XGetWindowProperty". */
120
121   Atom          type_returned;
122   int           temp_format;             /*  Not used. */
123   unsigned long number_of_elements;
124   unsigned long temp_bytes_after;        /*  Not used. */
125
126
127   status = XGetWindowProperty(fgDisplay.Display,
128                               window,
129                               property,
130                               0,
131                               LONG_MAX,
132                               False,
133                               type,
134                               &type_returned,
135                               &temp_format,
136                               &number_of_elements,
137                               &temp_bytes_after,
138                               data);
139
140   FREEGLUT_INTERNAL_ERROR_EXIT(status == Success,
141                                "XGetWindowProperty failled",
142                                "fghGetWindowProperty");
143
144   if (type_returned != type)
145     {
146       number_of_elements = 0;
147     }
148
149   return number_of_elements;
150 }
151
152 /*  Check if the window manager is NET WM compliant. */
153 static int fghNetWMSupported(void)
154 {
155   Atom wm_check;
156   Window ** window_ptr_1;
157
158   int number_of_windows;
159   int net_wm_supported;
160
161
162   net_wm_supported = 0;
163
164   wm_check = fghGetAtom("_NET_SUPPORTING_WM_CHECK");
165   window_ptr_1 = malloc(sizeof(Window *));
166
167   /*
168    * Check that the window manager has set this property on the root window.
169    * The property must be the ID of a child window.
170    */
171   number_of_windows = fghGetWindowProperty(fgDisplay.RootWindow,
172                                            wm_check,
173                                            XA_WINDOW,
174                                            (unsigned char **) window_ptr_1);
175   if (number_of_windows == 1)
176     {
177       Window ** window_ptr_2;
178
179       window_ptr_2 = malloc(sizeof(Window *));
180
181       /* Check that the window has the same property set to the same value. */
182       number_of_windows = fghGetWindowProperty(**window_ptr_1,
183                                                wm_check,
184                                                XA_WINDOW,
185                                                (unsigned char **) window_ptr_2);
186       if ((number_of_windows == 1) && (**window_ptr_1 == **window_ptr_2))
187       {
188         /* NET WM compliant */
189         net_wm_supported = 1;
190       }
191
192       XFree(*window_ptr_2);
193       free(window_ptr_2);
194     }
195
196         XFree(*window_ptr_1);
197         free(window_ptr_1);
198
199         return net_wm_supported;
200 }
201
202 /*  Check if "hint" is present in "property" for "window". */
203 int fgHintPresent(Window window, Atom property, Atom hint)
204 {
205   Atom ** atoms_ptr;
206   int number_of_atoms;
207   int supported;
208   int i;
209
210   supported = 0;
211
212   atoms_ptr = malloc(sizeof(Atom *));
213   number_of_atoms = fghGetWindowProperty(window,
214                                          property,
215                                          XA_ATOM,
216                                          (unsigned char **) atoms_ptr);
217   for (i = 0; i < number_of_atoms; i++)
218     {
219       if ((*atoms_ptr)[i] == hint)
220       {
221           supported = 1;
222           break;
223       }
224     }
225
226   return supported;
227 }
228
229 #endif /*  TARGET_HOST_POSIX_X11  */
230
231
232 /*
233  * A call to this function should initialize all the display stuff...
234  */
235 static void fghInitialize( const char* displayName )
236 {
237 #if TARGET_HOST_POSIX_X11
238     fgDisplay.Display = XOpenDisplay( displayName );
239
240     if( fgDisplay.Display == NULL )
241         fgError( "failed to open display '%s'", XDisplayName( displayName ) );
242
243     if( !glXQueryExtension( fgDisplay.Display, NULL, NULL ) )
244         fgError( "OpenGL GLX extension not supported by display '%s'",
245             XDisplayName( displayName ) );
246
247     fgDisplay.Screen = DefaultScreen( fgDisplay.Display );
248     fgDisplay.RootWindow = RootWindow(
249         fgDisplay.Display,
250         fgDisplay.Screen
251     );
252
253     fgDisplay.ScreenWidth  = DisplayWidth(
254         fgDisplay.Display,
255         fgDisplay.Screen
256     );
257     fgDisplay.ScreenHeight = DisplayHeight(
258         fgDisplay.Display,
259         fgDisplay.Screen
260     );
261
262     fgDisplay.ScreenWidthMM = DisplayWidthMM(
263         fgDisplay.Display,
264         fgDisplay.Screen
265     );
266     fgDisplay.ScreenHeightMM = DisplayHeightMM(
267         fgDisplay.Display,
268         fgDisplay.Screen
269     );
270
271     fgDisplay.Connection = ConnectionNumber( fgDisplay.Display );
272
273     /* Create the window deletion atom */
274     fgDisplay.DeleteWindow = fghGetAtom("WM_DELETE_WINDOW");
275
276     /* Create the state and full screen atoms */
277     fgDisplay.State           = None;
278     fgDisplay.StateFullScreen = None;
279
280     if (fghNetWMSupported())
281     {
282       const Atom supported = fghGetAtom("_NET_SUPPORTED");
283       const Atom state     = fghGetAtom("_NET_WM_STATE");
284       
285       /* Check if the state hint is supported. */
286       if (fgHintPresent(fgDisplay.RootWindow, supported, state))
287       {
288         const Atom full_screen = fghGetAtom("_NET_WM_STATE_FULLSCREEN");
289         
290         fgDisplay.State = state;
291         
292         /* Check if the window manager supports full screen. */
293         /**  Check "_NET_WM_ALLOWED_ACTIONS" on our window instead? **/
294         if (fgHintPresent(fgDisplay.RootWindow, supported, full_screen))
295         {
296           fgDisplay.StateFullScreen = full_screen;
297         }
298       }
299     }
300
301 #elif TARGET_HOST_MS_WINDOWS
302
303     WNDCLASS wc;
304     ATOM atom;
305
306     /* What we need to do is to initialize the fgDisplay global structure here. */
307     fgDisplay.Instance = GetModuleHandle( NULL );
308
309     atom = GetClassInfo( fgDisplay.Instance, _T("FREEGLUT"), &wc );
310
311     if( atom == 0 )
312     {
313         ZeroMemory( &wc, sizeof(WNDCLASS) );
314
315         /*
316          * Each of the windows should have its own device context, and we
317          * want redraw events during Vertical and Horizontal Resizes by
318          * the user.
319          *
320          * XXX Old code had "| CS_DBCLCKS" commented out.  Plans for the
321          * XXX future?  Dead-end idea?
322          */
323         wc.lpfnWndProc    = fgWindowProc;
324         wc.cbClsExtra     = 0;
325         wc.cbWndExtra     = 0;
326         wc.hInstance      = fgDisplay.Instance;
327         wc.hIcon          = LoadIcon( fgDisplay.Instance, _T("GLUT_ICON") );
328
329 #if defined(_WIN32_WCE)
330         wc.style          = CS_HREDRAW | CS_VREDRAW;
331 #else
332         wc.style          = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
333         if (!wc.hIcon)
334           wc.hIcon        = LoadIcon( NULL, IDI_WINLOGO );
335 #endif
336
337         wc.hCursor        = LoadCursor( NULL, IDC_ARROW );
338         wc.hbrBackground  = NULL;
339         wc.lpszMenuName   = NULL;
340         wc.lpszClassName  = _T("FREEGLUT");
341
342         /* Register the window class */
343         atom = RegisterClass( &wc );
344         FREEGLUT_INTERNAL_ERROR_EXIT ( atom, "Window Class Not Registered", "fghInitialize" );
345     }
346
347     /* The screen dimensions can be obtained via GetSystemMetrics() calls */
348     fgDisplay.ScreenWidth  = GetSystemMetrics( SM_CXSCREEN );
349     fgDisplay.ScreenHeight = GetSystemMetrics( SM_CYSCREEN );
350
351     {
352         HWND desktop = GetDesktopWindow( );
353         HDC  context = GetDC( desktop );
354
355         fgDisplay.ScreenWidthMM  = GetDeviceCaps( context, HORZSIZE );
356         fgDisplay.ScreenHeightMM = GetDeviceCaps( context, VERTSIZE );
357
358         ReleaseDC( desktop, context );
359     }
360
361     /* Set the timer granularity to 1 ms */
362     timeBeginPeriod ( 1 );
363
364 #endif
365
366     fgState.Initialised = GL_TRUE;
367
368     /* InputDevice uses GlutTimerFunc(), so fgState.Initialised must be TRUE */
369     fgInitialiseInputDevices();
370 }
371
372 /*
373  * Perform the freeglut deinitialization...
374  */
375 void fgDeinitialize( void )
376 {
377     SFG_Timer *timer;
378
379     if( !fgState.Initialised )
380     {
381         fgWarning( "fgDeinitialize(): "
382                    "no valid initialization has been performed" );
383         return;
384     }
385
386     /* If there was a menu created, destroy the rendering context */
387     if( fgStructure.MenuContext )
388     {
389 #if TARGET_HOST_POSIX_X11
390         /* Note that the MVisualInfo is not owned by the MenuContext! */
391         glXDestroyContext( fgDisplay.Display, fgStructure.MenuContext->MContext );
392 #endif
393         free( fgStructure.MenuContext );
394         fgStructure.MenuContext = NULL;
395     }
396
397     fgDestroyStructure( );
398
399     while( ( timer = fgState.Timers.First) )
400     {
401         fgListRemove( &fgState.Timers, &timer->Node );
402         free( timer );
403     }
404
405     while( ( timer = fgState.FreeTimers.First) )
406     {
407         fgListRemove( &fgState.FreeTimers, &timer->Node );
408         free( timer );
409     }
410
411 #if !defined(_WIN32_WCE)
412     if ( fgState.JoysticksInitialised )
413         fgJoystickClose( );
414
415     if ( fgState.InputDevsInitialised )
416         fgInputDeviceClose( );
417 #endif /* !defined(_WIN32_WCE) */
418     fgState.JoysticksInitialised = GL_FALSE;
419     fgState.InputDevsInitialised = GL_FALSE;
420
421     fgState.Initialised = GL_FALSE;
422
423     fgState.Position.X = -1;
424     fgState.Position.Y = -1;
425     fgState.Position.Use = GL_FALSE;
426
427     fgState.Size.X = 300;
428     fgState.Size.Y = 300;
429     fgState.Size.Use = GL_TRUE;
430
431     fgState.DisplayMode = GLUT_RGBA | GLUT_SINGLE | GLUT_DEPTH;
432
433     fgState.DirectContext  = GLUT_TRY_DIRECT_CONTEXT;
434     fgState.ForceIconic         = GL_FALSE;
435     fgState.UseCurrentContext   = GL_FALSE;
436     fgState.GLDebugSwitch       = GL_FALSE;
437     fgState.XSyncSwitch         = GL_FALSE;
438     fgState.ActionOnWindowClose = GLUT_ACTION_EXIT;
439     fgState.ExecState           = GLUT_EXEC_STATE_INIT;
440
441     fgState.KeyRepeat       = GLUT_KEY_REPEAT_ON;
442     fgState.Modifiers       = INVALID_MODIFIERS;
443
444     fgState.GameModeSize.X  = 640;
445     fgState.GameModeSize.Y  = 480;
446     fgState.GameModeDepth   =  16;
447     fgState.GameModeRefresh =  72;
448
449     fgListInit( &fgState.Timers );
450     fgListInit( &fgState.FreeTimers );
451
452     fgState.IdleCallback = NULL;
453     fgState.MenuStateCallback = ( FGCBMenuState )NULL;
454     fgState.MenuStatusCallback = ( FGCBMenuStatus )NULL;
455
456     fgState.SwapCount   = 0;
457     fgState.SwapTime    = 0;
458     fgState.FPSInterval = 0;
459
460     if( fgState.ProgramName )
461     {
462         free( fgState.ProgramName );
463         fgState.ProgramName = NULL;
464     }
465
466 #if TARGET_HOST_POSIX_X11
467
468     /*
469      * Make sure all X-client data we have created will be destroyed on
470      * display closing
471      */
472     XSetCloseDownMode( fgDisplay.Display, DestroyAll );
473
474     /*
475      * Close the display connection, destroying all windows we have
476      * created so far
477      */
478     XCloseDisplay( fgDisplay.Display );
479
480 #elif TARGET_HOST_MS_WINDOWS
481
482     /* Reset the timer granularity */
483     timeEndPeriod ( 1 );
484
485 #endif
486
487     fgState.Initialised = GL_FALSE;
488 }
489
490 /*
491  * Everything inside the following #ifndef is copied from the X sources.
492  */
493
494 #if TARGET_HOST_MS_WINDOWS
495
496 /*
497
498 Copyright 1985, 1986, 1987,1998  The Open Group
499
500 Permission to use, copy, modify, distribute, and sell this software and its
501 documentation for any purpose is hereby granted without fee, provided that
502 the above copyright notice appear in all copies and that both that
503 copyright notice and this permission notice appear in supporting
504 documentation.
505
506 The above copyright notice and this permission notice shall be included
507 in all copies or substantial portions of the Software.
508
509 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
510 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
511 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
512 IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
513 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
514 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
515 OTHER DEALINGS IN THE SOFTWARE.
516
517 Except as contained in this notice, the name of The Open Group shall
518 not be used in advertising or otherwise to promote the sale, use or
519 other dealings in this Software without prior written authorization
520 from The Open Group.
521
522 */
523
524 #define NoValue         0x0000
525 #define XValue          0x0001
526 #define YValue          0x0002
527 #define WidthValue      0x0004
528 #define HeightValue     0x0008
529 #define AllValues       0x000F
530 #define XNegative       0x0010
531 #define YNegative       0x0020
532
533 /*
534  *    XParseGeometry parses strings of the form
535  *   "=<width>x<height>{+-}<xoffset>{+-}<yoffset>", where
536  *   width, height, xoffset, and yoffset are unsigned integers.
537  *   Example:  "=80x24+300-49"
538  *   The equal sign is optional.
539  *   It returns a bitmask that indicates which of the four values
540  *   were actually found in the string.  For each value found,
541  *   the corresponding argument is updated;  for each value
542  *   not found, the corresponding argument is left unchanged.
543  */
544
545 static int
546 ReadInteger(char *string, char **NextString)
547 {
548     register int Result = 0;
549     int Sign = 1;
550
551     if (*string == '+')
552         string++;
553     else if (*string == '-')
554     {
555         string++;
556         Sign = -1;
557     }
558     for (; (*string >= '0') && (*string <= '9'); string++)
559     {
560         Result = (Result * 10) + (*string - '0');
561     }
562     *NextString = string;
563     if (Sign >= 0)
564         return Result;
565     else
566         return -Result;
567 }
568
569 static int XParseGeometry (
570     const char *string,
571     int *x,
572     int *y,
573     unsigned int *width,    /* RETURN */
574     unsigned int *height)    /* RETURN */
575 {
576     int mask = NoValue;
577     register char *strind;
578     unsigned int tempWidth = 0, tempHeight = 0;
579     int tempX = 0, tempY = 0;
580     char *nextCharacter;
581
582     if ( (string == NULL) || (*string == '\0'))
583       return mask;
584     if (*string == '=')
585         string++;  /* ignore possible '=' at beg of geometry spec */
586
587     strind = (char *)string;
588     if (*strind != '+' && *strind != '-' && *strind != 'x') {
589         tempWidth = ReadInteger(strind, &nextCharacter);
590         if (strind == nextCharacter)
591             return 0;
592         strind = nextCharacter;
593         mask |= WidthValue;
594     }
595
596     if (*strind == 'x' || *strind == 'X') {
597         strind++;
598         tempHeight = ReadInteger(strind, &nextCharacter);
599         if (strind == nextCharacter)
600             return 0;
601         strind = nextCharacter;
602         mask |= HeightValue;
603     }
604
605     if ((*strind == '+') || (*strind == '-')) {
606         if (*strind == '-') {
607             strind++;
608             tempX = -ReadInteger(strind, &nextCharacter);
609             if (strind == nextCharacter)
610                 return 0;
611             strind = nextCharacter;
612             mask |= XNegative;
613         }
614         else
615         {
616             strind++;
617             tempX = ReadInteger(strind, &nextCharacter);
618             if (strind == nextCharacter)
619                 return 0;
620             strind = nextCharacter;
621         }
622         mask |= XValue;
623         if ((*strind == '+') || (*strind == '-')) {
624             if (*strind == '-') {
625                 strind++;
626                 tempY = -ReadInteger(strind, &nextCharacter);
627                 if (strind == nextCharacter)
628                     return 0;
629                 strind = nextCharacter;
630                 mask |= YNegative;
631             }
632             else
633             {
634                 strind++;
635                 tempY = ReadInteger(strind, &nextCharacter);
636                 if (strind == nextCharacter)
637                     return 0;
638                 strind = nextCharacter;
639             }
640             mask |= YValue;
641         }
642     }
643
644     /* If strind isn't at the end of the string the it's an invalid
645        geometry specification. */
646
647     if (*strind != '\0') return 0;
648
649     if (mask & XValue)
650         *x = tempX;
651     if (mask & YValue)
652         *y = tempY;
653     if (mask & WidthValue)
654         *width = tempWidth;
655     if (mask & HeightValue)
656         *height = tempHeight;
657     return mask;
658 }
659 #endif
660
661 /* -- INTERFACE FUNCTIONS -------------------------------------------------- */
662
663 /*
664  * Perform initialization. This usually happens on the program startup
665  * and restarting after glutMainLoop termination...
666  */
667 void FGAPIENTRY glutInit( int* pargc, char** argv )
668 {
669     char* displayName = NULL;
670     char* geometry = NULL;
671     int i, j, argc = *pargc;
672
673     if( fgState.Initialised )
674         fgError( "illegal glutInit() reinitialization attempt" );
675
676     if (pargc && *pargc && argv && *argv && **argv)
677     {
678         fgState.ProgramName = strdup (*argv);
679
680         if( !fgState.ProgramName )
681             fgError ("Could not allocate space for the program's name.");
682     }
683
684     fgCreateStructure( );
685
686     /* Get start time */
687     fgState.Time = fgSystemTime();
688
689     /* check if GLUT_FPS env var is set */
690 #ifndef _WIN32_WCE
691     {
692         const char *fps = getenv( "GLUT_FPS" );
693         if( fps )
694         {
695             int interval;
696             sscanf( fps, "%d", &interval );
697
698             if( interval <= 0 )
699                 fgState.FPSInterval = 5000;  /* 5000 millisecond default */
700             else
701                 fgState.FPSInterval = interval;
702         }
703     }
704
705     displayName = getenv( "DISPLAY");
706
707     for( i = 1; i < argc; i++ )
708     {
709         if( strcmp( argv[ i ], "-display" ) == 0 )
710         {
711             if( ++i >= argc )
712                 fgError( "-display parameter must be followed by display name" );
713
714             displayName = argv[ i ];
715
716             argv[ i - 1 ] = NULL;
717             argv[ i     ] = NULL;
718             ( *pargc ) -= 2;
719         }
720         else if( strcmp( argv[ i ], "-geometry" ) == 0 )
721         {
722             if( ++i >= argc )
723                 fgError( "-geometry parameter must be followed by window "
724                          "geometry settings" );
725
726             geometry = argv[ i ];
727
728             argv[ i - 1 ] = NULL;
729             argv[ i     ] = NULL;
730             ( *pargc ) -= 2;
731         }
732         else if( strcmp( argv[ i ], "-direct" ) == 0)
733         {
734             if( fgState.DirectContext == GLUT_FORCE_INDIRECT_CONTEXT )
735                 fgError( "parameters ambiguity, -direct and -indirect "
736                     "cannot be both specified" );
737
738             fgState.DirectContext = GLUT_FORCE_DIRECT_CONTEXT;
739             argv[ i ] = NULL;
740             ( *pargc )--;
741         }
742         else if( strcmp( argv[ i ], "-indirect" ) == 0 )
743         {
744             if( fgState.DirectContext == GLUT_FORCE_DIRECT_CONTEXT )
745                 fgError( "parameters ambiguity, -direct and -indirect "
746                     "cannot be both specified" );
747
748             fgState.DirectContext = GLUT_FORCE_INDIRECT_CONTEXT;
749             argv[ i ] = NULL;
750             (*pargc)--;
751         }
752         else if( strcmp( argv[ i ], "-iconic" ) == 0 )
753         {
754             fgState.ForceIconic = GL_TRUE;
755             argv[ i ] = NULL;
756             ( *pargc )--;
757         }
758         else if( strcmp( argv[ i ], "-gldebug" ) == 0 )
759         {
760             fgState.GLDebugSwitch = GL_TRUE;
761             argv[ i ] = NULL;
762             ( *pargc )--;
763         }
764         else if( strcmp( argv[ i ], "-sync" ) == 0 )
765         {
766             fgState.XSyncSwitch = GL_TRUE;
767             argv[ i ] = NULL;
768             ( *pargc )--;
769         }
770     }
771
772     /* Compact {argv}. */
773     for( i = j = 1; i < *pargc; i++, j++ )
774     {
775         /* Guaranteed to end because there are "*pargc" arguments left */
776         while ( argv[ j ] == NULL )
777             j++;
778         if ( i != j )
779             argv[ i ] = argv[ j ];
780     }
781
782 #endif /* _WIN32_WCE */
783
784     /*
785      * Have the display created now. If there wasn't a "-display"
786      * in the program arguments, we will use the DISPLAY environment
787      * variable for opening the X display (see code above):
788      */
789     fghInitialize( displayName );
790
791     /*
792      * Geometry parsing deffered until here because we may need the screen
793      * size.
794      */
795
796     if (geometry )
797     {
798         unsigned int parsedWidth, parsedHeight;
799         int mask = XParseGeometry( geometry,
800                                    &fgState.Position.X, &fgState.Position.Y,
801                                    &parsedWidth, &parsedHeight );
802         /* TODO: Check for overflow? */
803         fgState.Size.X = parsedWidth;
804         fgState.Size.Y = parsedHeight;
805
806         if( (mask & (WidthValue|HeightValue)) == (WidthValue|HeightValue) )
807             fgState.Size.Use = GL_TRUE;
808
809         if( mask & XNegative )
810             fgState.Position.X += fgDisplay.ScreenWidth - fgState.Size.X;
811
812         if( mask & YNegative )
813             fgState.Position.Y += fgDisplay.ScreenHeight - fgState.Size.Y;
814
815         if( (mask & (XValue|YValue)) == (XValue|YValue) )
816             fgState.Position.Use = GL_TRUE;
817     }
818 }
819
820 /*
821  * Undoes all the "glutInit" stuff
822  */
823 void FGAPIENTRY glutExit ( void )
824 {
825   fgDeinitialize ();
826 }
827
828 /*
829  * Sets the default initial window position for new windows
830  */
831 void FGAPIENTRY glutInitWindowPosition( int x, int y )
832 {
833     fgState.Position.X = x;
834     fgState.Position.Y = y;
835
836     if( ( x >= 0 ) && ( y >= 0 ) )
837         fgState.Position.Use = GL_TRUE;
838     else
839         fgState.Position.Use = GL_FALSE;
840 }
841
842 /*
843  * Sets the default initial window size for new windows
844  */
845 void FGAPIENTRY glutInitWindowSize( int width, int height )
846 {
847     fgState.Size.X = width;
848     fgState.Size.Y = height;
849
850     if( ( width > 0 ) && ( height > 0 ) )
851         fgState.Size.Use = GL_TRUE;
852     else
853         fgState.Size.Use = GL_FALSE;
854 }
855
856 /*
857  * Sets the default display mode for all new windows
858  */
859 void FGAPIENTRY glutInitDisplayMode( unsigned int displayMode )
860 {
861     /* We will make use of this value when creating a new OpenGL context... */
862     fgState.DisplayMode = displayMode;
863 }
864
865
866 /* -- INIT DISPLAY STRING PARSING ------------------------------------------ */
867
868 static char* Tokens[] =
869 {
870     "alpha", "acca", "acc", "blue", "buffer", "conformant", "depth", "double",
871     "green", "index", "num", "red", "rgba", "rgb", "luminance", "stencil",
872     "single", "stereo", "samples", "slow", "win32pdf", "win32pfd", "xvisual",
873     "xstaticgray", "xgrayscale", "xstaticcolor", "xpseudocolor",
874     "xtruecolor", "xdirectcolor",
875     "xstaticgrey", "xgreyscale", "xstaticcolour", "xpseudocolour",
876     "xtruecolour", "xdirectcolour", "borderless", "aux"
877 };
878 #define NUM_TOKENS             (sizeof(Tokens) / sizeof(*Tokens))
879
880 void FGAPIENTRY glutInitDisplayString( const char* displayMode )
881 {
882     int glut_state_flag = 0 ;
883     /*
884      * Unpack a lot of options from a character string.  The options are
885      * delimited by blanks or tabs.
886      */
887     char *token ;
888     size_t len = strlen ( displayMode );
889     char *buffer = (char *)malloc ( (len+1) * sizeof(char) );
890     memcpy ( buffer, displayMode, len );
891     buffer[len] = '\0';
892
893     token = strtok ( buffer, " \t" );
894     while ( token )
895     {
896         /* Process this token */
897         int i ;
898
899         /* Temporary fix:  Ignore any length specifications and at least
900          * process the basic token
901          * TODO:  Fix this permanently
902          */
903         size_t cleanlength = strcspn ( token, "=<>~!" );
904
905         for ( i = 0; i < NUM_TOKENS; i++ )
906         {
907             if ( strncmp ( token, Tokens[i], cleanlength ) == 0 ) break ;
908         }
909
910         switch ( i )
911         {
912         case 0 :  /* "alpha":  Alpha color buffer precision in bits */
913             glut_state_flag |= GLUT_ALPHA ;  /* Somebody fix this for me! */
914             break ;
915
916         case 1 :  /* "acca":  Red, green, blue, and alpha accumulation buffer
917                      precision in bits */
918             break ;
919
920         case 2 :  /* "acc":  Red, green, and blue accumulation buffer precision
921                      in bits with zero bits alpha */
922             glut_state_flag |= GLUT_ACCUM ;  /* Somebody fix this for me! */
923             break ;
924
925         case 3 :  /* "blue":  Blue color buffer precision in bits */
926             break ;
927
928         case 4 :  /* "buffer":  Number of bits in the color index color buffer
929                    */
930             break ;
931
932         case 5 :  /* "conformant":  Boolean indicating if the frame buffer
933                      configuration is conformant or not */
934             break ;
935
936         case 6 : /* "depth":  Number of bits of precsion in the depth buffer */
937             glut_state_flag |= GLUT_DEPTH ;  /* Somebody fix this for me! */
938             break ;
939
940         case 7 :  /* "double":  Boolean indicating if the color buffer is
941                      double buffered */
942             glut_state_flag |= GLUT_DOUBLE ;
943             break ;
944
945         case 8 :  /* "green":  Green color buffer precision in bits */
946             break ;
947
948         case 9 :  /* "index":  Boolean if the color model is color index or not
949                    */
950             glut_state_flag |= GLUT_INDEX ;
951             break ;
952
953         case 10 :  /* "num":  A special capability  name indicating where the
954                       value represents the Nth frame buffer configuration
955                       matching the description string */
956             break ;
957
958         case 11 :  /* "red":  Red color buffer precision in bits */
959             break ;
960
961         case 12 :  /* "rgba":  Number of bits of red, green, blue, and alpha in
962                       the RGBA color buffer */
963             glut_state_flag |= GLUT_RGBA ;  /* Somebody fix this for me! */
964             break ;
965
966         case 13 :  /* "rgb":  Number of bits of red, green, and blue in the
967                       RGBA color buffer with zero bits alpha */
968             glut_state_flag |= GLUT_RGB ;  /* Somebody fix this for me! */
969             break ;
970
971         case 14 :  /* "luminance":  Number of bits of red in the RGBA and zero
972                       bits of green, blue (alpha not specified) of color buffer
973                       precision */
974             glut_state_flag |= GLUT_LUMINANCE ; /* Somebody fix this for me! */
975             break ;
976
977         case 15 :  /* "stencil":  Number of bits in the stencil buffer */
978             glut_state_flag |= GLUT_STENCIL;  /* Somebody fix this for me! */
979             break ;
980
981         case 16 :  /* "single":  Boolean indicate the color buffer is single
982                       buffered */
983             glut_state_flag |= GLUT_SINGLE ;
984             break ;
985
986         case 17 :  /* "stereo":  Boolean indicating the color buffer supports
987                       OpenGL-style stereo */
988             glut_state_flag |= GLUT_STEREO ;
989             break ;
990
991         case 18 :  /* "samples":  Indicates the number of multisamples to use
992                       based on GLX's SGIS_multisample extension (for
993                       antialiasing) */
994             glut_state_flag |= GLUT_MULTISAMPLE ; /*Somebody fix this for me!*/
995             break ;
996
997         case 19 :  /* "slow":  Boolean indicating if the frame buffer
998                       configuration is slow or not */
999             break ;
1000
1001         case 20 :  /* "win32pdf": (incorrect spelling but was there before */
1002         case 21 :  /* "win32pfd":  matches the Win32 Pixel Format Descriptor by
1003                       number */
1004 #if TARGET_HOST_MS_WINDOWS
1005 #endif
1006             break ;
1007
1008         case 22 :  /* "xvisual":  matches the X visual ID by number */
1009 #if TARGET_HOST_POSIX_X11
1010 #endif
1011             break ;
1012
1013         case 23 :  /* "xstaticgray": */
1014         case 29 :  /* "xstaticgrey":  boolean indicating if the frame buffer
1015                       configuration's X visual is of type StaticGray */
1016 #if TARGET_HOST_POSIX_X11
1017 #endif
1018             break ;
1019
1020         case 24 :  /* "xgrayscale": */
1021         case 30 :  /* "xgreyscale":  boolean indicating if the frame buffer
1022                       configuration's X visual is of type GrayScale */
1023 #if TARGET_HOST_POSIX_X11
1024 #endif
1025             break ;
1026
1027         case 25 :  /* "xstaticcolor": */
1028         case 31 :  /* "xstaticcolour":  boolean indicating if the frame buffer
1029                       configuration's X visual is of type StaticColor */
1030 #if TARGET_HOST_POSIX_X11
1031 #endif
1032             break ;
1033
1034         case 26 :  /* "xpseudocolor": */
1035         case 32 :  /* "xpseudocolour":  boolean indicating if the frame buffer
1036                       configuration's X visual is of type PseudoColor */
1037 #if TARGET_HOST_POSIX_X11
1038 #endif
1039             break ;
1040
1041         case 27 :  /* "xtruecolor": */
1042         case 33 :  /* "xtruecolour":  boolean indicating if the frame buffer
1043                       configuration's X visual is of type TrueColor */
1044 #if TARGET_HOST_POSIX_X11
1045 #endif
1046             break ;
1047
1048         case 28 :  /* "xdirectcolor": */
1049         case 34 :  /* "xdirectcolour":  boolean indicating if the frame buffer
1050                       configuration's X visual is of type DirectColor */
1051 #if TARGET_HOST_POSIX_X11
1052 #endif
1053             break ;
1054
1055         case 35 :  /* "borderless":  windows should not have borders */
1056 #if TARGET_HOST_POSIX_X11
1057 #endif
1058             break ;
1059
1060         case 36 :  /* "aux":  some number of aux buffers */
1061             glut_state_flag |= GLUT_AUX;
1062             break ;
1063
1064         case 37 :  /* Unrecognized */
1065             fgWarning ( "WARNING - Display string token not recognized:  %s",
1066                         token );
1067             break ;
1068         }
1069
1070         token = strtok ( NULL, " \t" );
1071     }
1072
1073     free ( buffer );
1074
1075     /* We will make use of this value when creating a new OpenGL context... */
1076     fgState.DisplayMode = glut_state_flag;
1077 }
1078
1079 /*** END OF FILE ***/