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