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