Fix for a deinitialization related crash.
[freeglut] / src / freeglut_structure.c
1 /*
2  * freeglut_structure.c
3  *
4  * Windows and menus need tree structure
5  *
6  * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
7  * Written by Pawel W. Olszta, <olszta@sourceforge.net>
8  * Creation date: Sat Dec 18 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 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #define  G_LOG_DOMAIN  "freeglut-structure"
33
34 #include "../include/GL/freeglut.h"
35 #include "freeglut_internal.h"
36
37
38 /* -- GLOBAL EXPORTS ------------------------------------------------------- */
39
40 /*
41  * The SFG_Structure container holds information about windows and menus
42  * created between glutInit() and glutMainLoop() return.
43  */
44
45 SFG_Structure fgStructure = { { NULL, NULL },  /* The list of windows       */
46                               { NULL, NULL },  /* The list of menus         */
47                               NULL,            /* The current window        */
48                               NULL,            /* The current menu          */
49                               NULL,            /* The menu OpenGL context   */
50                               NULL,            /* The game mode window      */
51                               0,               /* The current new window ID */
52                               0 };             /* The current new menu ID   */
53
54
55 /* -- PRIVATE FUNCTIONS ---------------------------------------------------- */
56
57 /*
58  * This private function creates, opens and adds to the hierarchy
59  * a freeglut window complete with OpenGL context and stuff...
60  *
61  * If parent is set to NULL, the window created will be a topmost one.
62  */
63 SFG_Window* fgCreateWindow( SFG_Window* parent, const char* title, int x, int y, int w, int h, GLboolean gameMode )
64 {
65     /*
66      * Have the window object created
67      */
68     SFG_Window *window = (SFG_Window *)calloc( sizeof(SFG_Window), 1 );
69     int fakeArgc = 0;
70
71     /*
72      * If the freeglut internals haven't been initialized yet,
73      * do it now. Hack's idea courtesy of Chris Purnell...
74      */
75     if( !fgState.Time.Set )
76         glutInit( &fakeArgc, NULL );
77
78     /*
79      * Initialize the object properties
80      */
81     window->ID = ++fgStructure.WindowID;
82
83     /*
84      * Initialize the children list
85      */
86     fgListInit( &window->Children );
87
88     /*
89      * Does this window have a parent?
90      */
91     if( parent != NULL )
92     {
93         /*
94          * That's quite right, attach this windows as a child window
95          */
96         fgListAppend( &parent->Children, &window->Node );
97         window->Parent = parent;
98     }
99     else
100     {
101         /*
102          * Otherwise add the newly created window to the topmost windows list
103          */
104         fgListAppend( &fgStructure.Windows, &window->Node );
105     }
106
107     /*
108      * Set the default mouse cursor and reset the modifiers value
109      */
110     window->State.Cursor    = GLUT_CURSOR_INHERIT;
111     window->State.Modifiers = 0xffffffff;
112
113     /*
114      * If this window is a menu, set IsMenu in the structure
115      */
116     window->IsMenu = fgState.BuildingAMenu ;
117
118     /*
119      * Open the window now. The fgOpenWindow() function is system
120      * dependant, and resides in freeglut_window.c. Uses fgState.
121      */
122     fgOpenWindow( window, title, x, y, w, h, gameMode, (parent != NULL) ? TRUE : FALSE );
123
124     /*
125      * Return a pointer to the newly created window
126      */
127     return( window );
128 }
129
130 /*
131  * This private function creates a menu and adds it to the menus list
132  */
133 SFG_Menu* fgCreateMenu( FGCBmenu menuCallback )
134 {
135   int x = 100, y = 100, w = 100, h = 100 ;
136   SFG_Window *current_window = fgStructure.Window ;
137
138     /*
139      * Have the menu object created
140      */
141     SFG_Menu* menu = (SFG_Menu *)calloc( sizeof(SFG_Menu), 1 );
142     int fakeArgc = 0;
143
144     /*
145      * If the freeglut internals haven't been initialized yet,
146      * do it now. Hack's idea courtesy of Chris Purnell...
147      */
148     if( !fgState.Time.Set )
149         glutInit( &fakeArgc, NULL );
150
151     menu->ParentWindow = fgStructure.Window ;
152
153     /*
154      * Create a window for the menu to reside in.  Set the
155      * global variable BuildingAMenu to true so we can ensure
156      * it is created without decorations.
157      */
158     fgState.BuildingAMenu = TRUE ;
159
160     fgCreateWindow ( NULL, NULL, x, y, w, h, FALSE ) ;
161     menu->Window = fgStructure.Window ;
162     glutDisplayFunc ( fgDisplayMenu ) ;
163
164     /*
165      * While BuildingAMenu is true, all windows built have no decorations.  That's
166      * not a good default behavior, so let's set it false again.
167      */
168     fgState.BuildingAMenu = FALSE ;
169
170     glutHideWindow () ;  /* Hide the window for now */
171     fgSetWindow ( current_window ) ;
172
173     /*
174      * Initialize the object properties:
175      */
176     menu->ID       = ++fgStructure.MenuID;
177     menu->Callback = menuCallback;
178     menu->ActiveEntry = NULL ;
179
180     /*
181      * Initialize the entries list
182      */
183     fgListInit( &menu->Entries );
184
185     /*
186      * Add it to the menu structure hierarchy
187      */
188     fgListAppend( &fgStructure.Menus, &menu->Node );
189
190     /*
191      * Newly created menus implicitly become current ones
192      */
193     fgStructure.Menu = menu;
194
195     /*
196      * Return the result to the caller
197      */
198     return( menu );
199 }
200
201 /*
202  * Linked list of windows to destroy ... this is so we don't destroy a window from the middle of
203  * its callback.  Some C compilers take an extremely dim view of this.
204  */
205
206 static SFG_WindowList* WindowsToDestroy = (SFG_WindowList*)NULL ;
207
208 /*
209  * Function to add a window to the linked list of windows to destroy.  Subwindows are automatically
210  * added because they hang from the window structure.
211  */
212 void fgAddToWindowDestroyList ( SFG_Window* window, GLboolean needToClose )
213 {
214   SFG_WindowList *new_list_entry = (SFG_WindowList*)malloc ( sizeof(SFG_WindowList) ) ;
215   new_list_entry->window = window ;
216   new_list_entry->needToClose = needToClose ;
217   new_list_entry->next = WindowsToDestroy ;
218   WindowsToDestroy = new_list_entry ;
219
220   /*
221    * Check if the window is the current one...
222    */
223   if ( fgStructure.Window == window )
224     fgStructure.Window = NULL;
225
226   /*
227    * If the destroyed window has the highest window ID number, decrement the window ID number
228    */
229   if ( window->ID == fgStructure.WindowID ) fgStructure.WindowID-- ;
230
231   /*
232    * Check the execution state.  If this has been called from "glutDestroyWindow",
233    * a statement in that function will reset the "ExecState" after this function returns.
234    */
235   if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
236   {
237     /*
238      * Set the execution state flag to drop out of the main loop.
239      */
240     if ( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
241       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
242   }
243 }
244
245 /*
246  * Function to close down all the windows in the "WindowsToDestroy" list
247  */
248 void fgCloseWindows ()
249 {
250   SFG_WindowList *window_ptr = WindowsToDestroy ;
251   WindowsToDestroy = (SFG_WindowList*)NULL ;  /* In case the destroy callbacks cause more windows to be closed */
252
253   while ( window_ptr )
254   {
255     SFG_WindowList *next = window_ptr->next ;
256     fgDestroyWindow ( window_ptr->window, window_ptr->needToClose ) ;
257     free ( window_ptr ) ;
258     window_ptr = next ;
259
260     if ( !window_ptr )
261     {
262       window_ptr = WindowsToDestroy ;
263       WindowsToDestroy = (SFG_WindowList*)NULL ;
264     }
265   }
266 }
267
268 /*
269  * This function destroys a window and all of its subwindows. Actually,
270  * another function, defined in freeglut_window.c is called, but this is
271  * a whole different story...
272  */
273 void fgDestroyWindow( SFG_Window* window, GLboolean needToClose )
274 {
275     SFG_Window* subWindow;
276
277     assert( window != NULL );
278     freeglut_assert_ready;
279
280     /*
281      * Does this window have any subwindows?
282      */
283     while ( (subWindow = (SFG_Window *)window->Children.First) != NULL )
284     {
285         /*
286          * Destroy the first window in the list (possibly destroying
287          * its subwindows too). This is not very effective, but works
288          */
289         fgDestroyWindow( subWindow, needToClose );
290     }
291
292     /*
293      * If the programmer defined a destroy callback, call it
294      * A. Donev: But first make this the active window
295      */
296     if ( window->Callbacks.Destroy != NULL )
297     {
298       SFG_Window *activeWindow = fgStructure.Window ;
299       fgSetWindow ( window ) ;
300       window->Callbacks.Destroy () ;
301       fgSetWindow ( activeWindow ) ;
302     }
303
304     /*
305      * Now we should remove the reference to this window from its parent
306      */
307     if ( window->Parent != NULL )
308         fgListRemove( &window->Parent->Children, &window->Node );
309     else
310         fgListRemove( &fgStructure.Windows, &window->Node );
311
312     /*
313      * OK, this window seems disconnected from the structure enough
314      * in order to be closed without any bigger risks...
315      */
316     if( needToClose == TRUE )
317         fgCloseWindow( window );
318
319     /*
320      * Finally, we can delete the window's object. It hopefully does
321      * have everything inside it freed and we do not have to care...
322      */
323     free( window );
324     if ( fgStructure.Window == window ) fgStructure.Window = NULL ;
325 }
326
327 /*
328  * This is a helper static function that removes a menu (given its pointer)
329  * from any windows that can be accessed from a given parent...
330  */
331 static void fghRemoveMenuFromWindow( SFG_Window* window, SFG_Menu* menu )
332 {
333     SFG_Window *subWindow;
334     int i;
335
336     /*
337      * Check if the menu is attached to the current window,
338      * if so, have it detached (by overwriting with a NULL):
339      */
340     for( i=0; i<3; i++ )
341     {
342         if( window->Menu[ i ] == menu )
343             window->Menu[ i ] = NULL;
344     }
345
346     /*
347      * Call this function for all of the window's children recursively:
348      */
349     for( subWindow = (SFG_Window *)window->Children.First; subWindow;
350          subWindow = (SFG_Window *)subWindow->Node.Next)
351     {
352         fghRemoveMenuFromWindow( subWindow, menu );
353     }
354 }
355
356 /*
357  * This is a static helper function that removes menu references
358  * from another menu, given two pointers to them...
359  */
360 static void fghRemoveMenuFromMenu( SFG_Menu* from, SFG_Menu* menu )
361 {
362   SFG_MenuEntry *entry;
363
364   for( entry = (SFG_MenuEntry *)from->Entries.First; entry; entry = (SFG_MenuEntry *)entry->Node.Next )
365   {
366     if (entry->SubMenu == menu)
367     {
368       entry->SubMenu = NULL;
369     }
370   }
371 }
372
373 /*
374  * This function destroys a menu specified by the parameter. All menus
375  * and windows are updated to make sure no ill pointers hang around.
376  */
377 void fgDestroyMenu( SFG_Menu* menu )
378 {
379   SFG_Window *window;
380   SFG_Menu *from;
381   SFG_MenuEntry *entry;
382
383   assert( menu != NULL );
384   freeglut_assert_ready;
385
386   /*
387    * First of all, have all references to this menu removed from all windows:
388    */
389   for( window = (SFG_Window *)fgStructure.Windows.First; window; window = (SFG_Window *)window->Node.Next )
390   {
391     fghRemoveMenuFromWindow( window, menu );
392   }
393
394   /*
395    * Now proceed with removing menu entries that lead to this menu
396    */
397   for( from = (SFG_Menu *)fgStructure.Menus.First; from; from = (SFG_Menu *)from->Node.Next )
398   {
399     fghRemoveMenuFromMenu( from, menu );
400   }
401
402   /*
403    * If the programmer defined a destroy callback, call it
404    * A. Donev: But first make this the active menu
405    */    
406   if ( menu->Destroy != NULL )
407   {
408     SFG_Menu *activeMenu=fgStructure.Menu;
409     fgStructure.Menu = menu;    
410     menu->Destroy () ;  
411     fgStructure.Menu = activeMenu;     
412   }        
413
414   /*
415    * Now we are pretty sure the menu is not used anywhere
416    * and that we can remove all of its entries
417    */
418   while( (entry = (SFG_MenuEntry *)menu->Entries.First) != NULL )
419   {
420     fgListRemove(&menu->Entries, &entry->Node);
421
422     /*
423      * There might be a string allocated, have it freed:
424      */
425     free( entry->Text );
426
427     /*
428      * Deallocate the entry itself:
429      */
430     free( entry );
431   }
432
433   /*
434    * Destroy the window associated with the menu
435    */
436   if ( fgStructure.Window == menu->Window )
437     fgSetWindow ( menu->ParentWindow ) ;
438
439   fgDestroyWindow ( menu->Window, TRUE ) ;
440
441   /*
442    * Remove the menu from the menus list
443    */
444   fgListRemove( &fgStructure.Menus, &menu->Node );
445
446   /*
447    * If that menu was the current one...
448    */
449   if( fgStructure.Menu == menu )
450     fgStructure.Menu = NULL;
451
452   /*
453    * Have the menu structure freed
454    */
455   free( menu );
456 }
457
458 /*
459  * This function should be called on glutInit(). It will prepare the internal
460  * structure of freeglut to be used in the application. The structure will be
461  * destroyed using fgDestroyStructure() on glutMainLoop() return. In that
462  * case further use of freeglut should be preceeded with a glutInit() call.
463  */
464 void fgCreateStructure( void )
465 {
466   /*
467    * We will be needing two lists: the first containing windows,
468    * and the second containing the user-defined menus.
469    * Also, no current window/menu is set, as none has been created yet.
470    */
471
472   fgListInit(&fgStructure.Windows);
473   fgListInit(&fgStructure.Menus);
474 }
475
476 /*
477  * This function is automatically called on glutMainLoop() return. It should deallocate 
478  * and destroy all remnants of previous glutInit()-enforced structure initialization...
479  */
480 void fgDestroyStructure( void )
481 {
482   SFG_Window *window;
483   SFG_Menu *menu;
484
485   /*
486    * Just make sure we are not called in vain...
487    */
488   freeglut_assert_ready;
489
490   /*
491    * Make sure all windows and menus have been deallocated
492    */
493   while( (menu = (SFG_Menu *)fgStructure.Menus.First) != NULL )
494     fgDestroyMenu( menu );
495
496   while( (window = (SFG_Window *)fgStructure.Windows.First) != NULL )
497     fgDestroyWindow( window, TRUE );
498 }
499
500 /*
501  * Helper function to enumerate through all registered top-level windows
502  */
503 void fgEnumWindows( FGCBenumerator enumCallback, SFG_Enumerator* enumerator )
504 {
505   SFG_Window *window;
506
507   assert( (enumCallback != NULL) && (enumerator != NULL) );
508   freeglut_assert_ready;
509
510   /*
511    * Check every of the top-level windows
512    */
513   for( window = (SFG_Window *)fgStructure.Windows.First; window;
514        window = (SFG_Window *)window->Node.Next )
515   {
516     /*
517      * Execute the callback...
518      */
519     enumCallback( window, enumerator );
520
521     /*
522      * If it has been marked as 'found', stop searching
523      */
524     if( enumerator->found == TRUE )
525       return;
526   }
527 }
528
529 /*
530  * Helper function to enumerate through all a window's subwindows (single level descent)
531  */
532 void fgEnumSubWindows( SFG_Window* window, FGCBenumerator enumCallback, SFG_Enumerator* enumerator )
533 {
534   SFG_Window *child;
535
536   assert( (enumCallback != NULL) && (enumerator != NULL) );
537   freeglut_assert_ready;
538
539   /*
540    * Check every of the window's children:
541    */
542   for( child = (SFG_Window *)window->Children.First; child; child = (SFG_Window *)child->Node.Next )
543   {
544     /*
545      * Execute the callback...
546      */
547     enumCallback( child, enumerator );
548
549     /*
550      * If it has been marked as 'found', stop searching
551      */
552     if( enumerator->found == TRUE )
553       return;
554   }
555 }
556
557 /*
558  * A static helper function to look for a window given its handle
559  */
560 static void fghcbWindowByHandle( SFG_Window *window, SFG_Enumerator *enumerator )
561 {
562     /*
563      * Make sure we do not overwrite our precious results...
564      */
565     freeglut_return_if_fail( enumerator->found == FALSE );
566
567 #if TARGET_HOST_UNIX_X11
568     #define WBHANDLE (Window)
569 #elif TARGET_HOST_WIN32
570     #define WBHANDLE (HWND)
571 #endif
572
573     /*
574      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
575      */
576     if( window->Window.Handle == WBHANDLE (enumerator->data) )
577     {
578         enumerator->found = TRUE;
579         enumerator->data = window;
580
581         return;
582     }
583
584     /*
585      * Otherwise, check this window's children
586      */
587     fgEnumSubWindows( window, fghcbWindowByHandle, enumerator );
588
589 #undef WBHANDLE
590 }
591
592 /*
593  * fgWindowByHandle returns a (SFG_Window *) value pointing to the
594  * first window in the queue matching the specified window handle.
595  * The function is defined in freeglut_structure.c file.
596  */
597 SFG_Window* fgWindowByHandle
598 #if TARGET_HOST_UNIX_X11
599 ( Window hWindow )
600 #elif TARGET_HOST_WIN32
601 ( HWND hWindow )
602 #endif
603 {
604     SFG_Enumerator enumerator;
605
606     /*
607      * This is easy and makes use of the windows enumeration defined above
608      */
609     enumerator.found = FALSE;
610     enumerator.data = (void *)hWindow;
611
612     /*
613      * Start the enumeration now:
614      */
615     fgEnumWindows( fghcbWindowByHandle, &enumerator );
616
617     /*
618      * Check if the window has been found or not:
619      */
620     if( enumerator.found == TRUE )
621         return( (SFG_Window *) enumerator.data );
622
623     /*
624      * Otherwise return NULL to mark the failure
625      */
626     return( NULL );
627 }
628
629 /*
630  * A static helper function to look for a window given its ID
631  */
632 static void fghcbWindowByID( SFG_Window *window, SFG_Enumerator *enumerator )
633 {
634     /*
635      * Make sure we do not overwrite our precious results...
636      */
637     freeglut_return_if_fail( enumerator->found == FALSE );
638
639     /*
640      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
641      */
642     if( window->ID == (int) (enumerator->data) )
643     {
644         enumerator->found = TRUE;
645         enumerator->data = window;
646
647         return;
648     }
649
650     /*
651      * Otherwise, check this window's children
652      */
653     fgEnumSubWindows( window, fghcbWindowByID, enumerator );
654 }
655
656 /*
657  * This function is similiar to the previous one, except it is
658  * looking for a specified (sub)window identifier. The function
659  * is defined in freeglut_structure.c file.
660  */
661 SFG_Window* fgWindowByID( int windowID )
662 {
663     SFG_Enumerator enumerator;
664
665     /*
666      * Uses a method very similiar for fgWindowByHandle...
667      */
668     enumerator.found = FALSE;
669     enumerator.data = (void *) windowID;
670
671     /*
672      * Start the enumeration now:
673      */
674     fgEnumWindows( fghcbWindowByID, &enumerator );
675
676     /*
677      * Check if the window has been found or not:
678      */
679     if( enumerator.found == TRUE )
680         return( (SFG_Window *) enumerator.data );
681
682     /*
683      * Otherwise return NULL to mark the failure
684      */
685     return( NULL );
686 }
687
688 /*
689  * Looks up a menu given its ID. This is easier that fgWindowByXXX
690  * as all menus are placed in a single doubly linked list...
691  */
692 SFG_Menu* fgMenuByID( int menuID )
693 {
694     SFG_Menu *menu = NULL;
695
696     freeglut_assert_ready;
697
698     /*
699      * It's enough to check all entries in fgStructure.Menus...
700      */
701     for( menu = (SFG_Menu *)fgStructure.Menus.First; menu; menu = (SFG_Menu *)menu->Node.Next )
702     {
703         /*
704          * Does the ID number match?
705          */
706         if( menu->ID == menuID )
707             return( menu );
708     }
709
710     /*
711      * We have not found the requested menu ID
712      */
713     return( NULL );
714 }
715
716 /*
717  * List functions...
718  */
719 void fgListInit(SFG_List *list)
720 {
721     list->First = NULL;
722     list->Last = NULL;
723 }
724
725 void fgListAppend(SFG_List *list, SFG_Node *node)
726 {
727     SFG_Node *ln;
728
729     if ( (ln = (SFG_Node *)list->Last) != NULL )
730     {
731         ln->Next = node;
732         node->Prev = ln;
733     }
734     else
735     {
736         node->Prev = NULL;
737         list->First = node;
738     }
739
740     node->Next = NULL;
741     list->Last = node;
742 }
743
744 void fgListRemove(SFG_List *list, SFG_Node *node)
745 {
746     SFG_Node *ln;
747
748     if ( (ln = (SFG_Node *)node->Next) != NULL )
749         ln->Prev = node->Prev;
750     if ( (ln = (SFG_Node *)node->Prev) != NULL )
751         ln->Next = node->Next;
752     if ( (ln = (SFG_Node *)list->First) == node )
753         list->First = node->Next;
754     if ( (ln = (SFG_Node *)list->Last) == node )
755         list->Last = node->Prev;
756 }
757
758 int fgListLength(SFG_List *list)
759 {
760     SFG_Node *node;
761     int length = 0;
762
763     for( node = (SFG_Node *)list->First; node; node = (SFG_Node *)node->Next )
764         ++length;
765
766     return( length );
767 }
768
769 /*** END OF FILE ***/