Added some error-checking (particularly w.r.t. strdup()).
[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     int menu_index ;
277
278     assert( window != NULL );
279     freeglut_assert_ready;
280
281     /*
282      * Does this window have any subwindows?
283      */
284     while ( (subWindow = (SFG_Window *)window->Children.First) != NULL )
285     {
286         /*
287          * Destroy the first window in the list (possibly destroying
288          * its subwindows too). This is not very effective, but works
289          */
290         fgDestroyWindow( subWindow, needToClose );
291     }
292
293     /*
294      * If the programmer defined a destroy callback, call it
295      * A. Donev: But first make this the active window
296      */
297     if ( window->Callbacks.Destroy != NULL )
298     {
299       SFG_Window *activeWindow = fgStructure.Window ;
300       fgSetWindow ( window ) ;
301       window->Callbacks.Destroy () ;
302       fgSetWindow ( activeWindow ) ;
303     }
304
305     /*
306      * Now we should remove the reference to this window from its parent
307      */
308     if ( window->Parent != NULL )
309         fgListRemove( &window->Parent->Children, &window->Node );
310     else
311         fgListRemove( &fgStructure.Windows, &window->Node );
312
313     if ( window->ActiveMenu != NULL )
314       fgDeactivateMenu ( window ) ;
315
316     for ( menu_index = 0; menu_index < 3; menu_index ++ )
317     {
318       if ( window->Menu[menu_index] != NULL )
319         window->Menu[menu_index]->ParentWindow = NULL ;
320     }
321
322     /*
323      * OK, this window seems disconnected from the structure enough
324      * in order to be closed without any bigger risks...
325      */
326     if( needToClose == TRUE )
327         fgCloseWindow( window );
328
329     /*
330      * Finally, we can delete the window's object. It hopefully does
331      * have everything inside it freed and we do not have to care...
332      */
333     free( window );
334     if ( fgStructure.Window == window ) fgStructure.Window = NULL ;
335 }
336
337 /*
338  * This is a helper static function that removes a menu (given its pointer)
339  * from any windows that can be accessed from a given parent...
340  */
341 static void fghRemoveMenuFromWindow( SFG_Window* window, SFG_Menu* menu )
342 {
343     SFG_Window *subWindow;
344     int i;
345
346     /*
347      * Check if the menu is attached to the current window,
348      * if so, have it detached (by overwriting with a NULL):
349      */
350     for( i=0; i<3; i++ )
351     {
352         if( window->Menu[ i ] == menu )
353             window->Menu[ i ] = NULL;
354     }
355
356     /*
357      * Call this function for all of the window's children recursively:
358      */
359     for( subWindow = (SFG_Window *)window->Children.First; subWindow;
360          subWindow = (SFG_Window *)subWindow->Node.Next)
361     {
362         fghRemoveMenuFromWindow( subWindow, menu );
363     }
364 }
365
366 /*
367  * This is a static helper function that removes menu references
368  * from another menu, given two pointers to them...
369  */
370 static void fghRemoveMenuFromMenu( SFG_Menu* from, SFG_Menu* menu )
371 {
372   SFG_MenuEntry *entry;
373
374   for( entry = (SFG_MenuEntry *)from->Entries.First; entry; entry = (SFG_MenuEntry *)entry->Node.Next )
375   {
376     if (entry->SubMenu == menu)
377     {
378       entry->SubMenu = NULL;
379     }
380   }
381 }
382
383 /*
384  * This function destroys a menu specified by the parameter. All menus
385  * and windows are updated to make sure no ill pointers hang around.
386  */
387 void fgDestroyMenu( SFG_Menu* menu )
388 {
389   SFG_Window *window;
390   SFG_Menu *from;
391   SFG_MenuEntry *entry;
392
393   assert( menu != NULL );
394   freeglut_assert_ready;
395
396   /*
397    * First of all, have all references to this menu removed from all windows:
398    */
399   for( window = (SFG_Window *)fgStructure.Windows.First; window; window = (SFG_Window *)window->Node.Next )
400   {
401     fghRemoveMenuFromWindow( window, menu );
402   }
403
404   /*
405    * Now proceed with removing menu entries that lead to this menu
406    */
407   for( from = (SFG_Menu *)fgStructure.Menus.First; from; from = (SFG_Menu *)from->Node.Next )
408   {
409     fghRemoveMenuFromMenu( from, menu );
410   }
411
412   /*
413    * If the programmer defined a destroy callback, call it
414    * A. Donev: But first make this the active menu
415    */    
416   if ( menu->Destroy != NULL )
417   {
418     SFG_Menu *activeMenu=fgStructure.Menu;
419     fgStructure.Menu = menu;    
420     menu->Destroy () ;  
421     fgStructure.Menu = activeMenu;     
422   }        
423
424   /*
425    * Now we are pretty sure the menu is not used anywhere
426    * and that we can remove all of its entries
427    */
428   while( (entry = (SFG_MenuEntry *)menu->Entries.First) != NULL )
429   {
430     fgListRemove(&menu->Entries, &entry->Node);
431
432     /*
433      * There might be a string allocated, have it freed:
434      */
435     free( entry->Text );
436
437     /*
438      * Deallocate the entry itself:
439      */
440     free( entry );
441   }
442
443   /*
444    * Destroy the window associated with the menu
445    */
446   if ( fgStructure.Window == menu->Window )
447     fgSetWindow ( menu->ParentWindow ) ;
448
449   fgDestroyWindow ( menu->Window, TRUE ) ;
450
451   /*
452    * Remove the menu from the menus list
453    */
454   fgListRemove( &fgStructure.Menus, &menu->Node );
455
456   /*
457    * If that menu was the current one...
458    */
459   if( fgStructure.Menu == menu )
460     fgStructure.Menu = NULL;
461
462   /*
463    * Have the menu structure freed
464    */
465   free( menu );
466 }
467
468 /*
469  * This function should be called on glutInit(). It will prepare the internal
470  * structure of freeglut to be used in the application. The structure will be
471  * destroyed using fgDestroyStructure() on glutMainLoop() return. In that
472  * case further use of freeglut should be preceeded with a glutInit() call.
473  */
474 void fgCreateStructure( void )
475 {
476   /*
477    * We will be needing two lists: the first containing windows,
478    * and the second containing the user-defined menus.
479    * Also, no current window/menu is set, as none has been created yet.
480    */
481
482   fgListInit(&fgStructure.Windows);
483   fgListInit(&fgStructure.Menus);
484 }
485
486 /*
487  * This function is automatically called on glutMainLoop() return. It should deallocate 
488  * and destroy all remnants of previous glutInit()-enforced structure initialization...
489  */
490 void fgDestroyStructure( void )
491 {
492   SFG_Window *window;
493   SFG_Menu *menu;
494
495   /*
496    * Just make sure we are not called in vain...
497    */
498   freeglut_assert_ready;
499
500   /*
501    * Make sure all windows and menus have been deallocated
502    */
503   while( (menu = (SFG_Menu *)fgStructure.Menus.First) != NULL )
504     fgDestroyMenu( menu );
505
506   while( (window = (SFG_Window *)fgStructure.Windows.First) != NULL )
507     fgDestroyWindow( window, TRUE );
508 }
509
510 /*
511  * Helper function to enumerate through all registered top-level windows
512  */
513 void fgEnumWindows( FGCBenumerator enumCallback, SFG_Enumerator* enumerator )
514 {
515   SFG_Window *window;
516
517   assert( (enumCallback != NULL) && (enumerator != NULL) );
518   freeglut_assert_ready;
519
520   /*
521    * Check every of the top-level windows
522    */
523   for( window = (SFG_Window *)fgStructure.Windows.First; window;
524        window = (SFG_Window *)window->Node.Next )
525   {
526     /*
527      * Execute the callback...
528      */
529     enumCallback( window, enumerator );
530
531     /*
532      * If it has been marked as 'found', stop searching
533      */
534     if( enumerator->found == TRUE )
535       return;
536   }
537 }
538
539 /*
540  * Helper function to enumerate through all a window's subwindows (single level descent)
541  */
542 void fgEnumSubWindows( SFG_Window* window, FGCBenumerator enumCallback, SFG_Enumerator* enumerator )
543 {
544   SFG_Window *child;
545
546   assert( (enumCallback != NULL) && (enumerator != NULL) );
547   freeglut_assert_ready;
548
549   /*
550    * Check every of the window's children:
551    */
552   for( child = (SFG_Window *)window->Children.First; child; child = (SFG_Window *)child->Node.Next )
553   {
554     /*
555      * Execute the callback...
556      */
557     enumCallback( child, enumerator );
558
559     /*
560      * If it has been marked as 'found', stop searching
561      */
562     if( enumerator->found == TRUE )
563       return;
564   }
565 }
566
567 /*
568  * A static helper function to look for a window given its handle
569  */
570 static void fghcbWindowByHandle( SFG_Window *window, SFG_Enumerator *enumerator )
571 {
572     /*
573      * Make sure we do not overwrite our precious results...
574      */
575     freeglut_return_if_fail( enumerator->found == FALSE );
576
577 #if TARGET_HOST_UNIX_X11
578     #define WBHANDLE (Window)
579 #elif TARGET_HOST_WIN32
580     #define WBHANDLE (HWND)
581 #endif
582
583     /*
584      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
585      */
586     if( window->Window.Handle == WBHANDLE (enumerator->data) )
587     {
588         enumerator->found = TRUE;
589         enumerator->data = window;
590
591         return;
592     }
593
594     /*
595      * Otherwise, check this window's children
596      */
597     fgEnumSubWindows( window, fghcbWindowByHandle, enumerator );
598
599 #undef WBHANDLE
600 }
601
602 /*
603  * fgWindowByHandle returns a (SFG_Window *) value pointing to the
604  * first window in the queue matching the specified window handle.
605  * The function is defined in freeglut_structure.c file.
606  */
607 SFG_Window* fgWindowByHandle
608 #if TARGET_HOST_UNIX_X11
609 ( Window hWindow )
610 #elif TARGET_HOST_WIN32
611 ( HWND hWindow )
612 #endif
613 {
614     SFG_Enumerator enumerator;
615
616     /*
617      * This is easy and makes use of the windows enumeration defined above
618      */
619     enumerator.found = FALSE;
620     enumerator.data = (void *)hWindow;
621
622     /*
623      * Start the enumeration now:
624      */
625     fgEnumWindows( fghcbWindowByHandle, &enumerator );
626
627     /*
628      * Check if the window has been found or not:
629      */
630     if( enumerator.found == TRUE )
631         return( (SFG_Window *) enumerator.data );
632
633     /*
634      * Otherwise return NULL to mark the failure
635      */
636     return( NULL );
637 }
638
639 /*
640  * A static helper function to look for a window given its ID
641  */
642 static void fghcbWindowByID( SFG_Window *window, SFG_Enumerator *enumerator )
643 {
644     /*
645      * Make sure we do not overwrite our precious results...
646      */
647     freeglut_return_if_fail( enumerator->found == FALSE );
648
649     /*
650      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
651      */
652     if( window->ID == (int) (enumerator->data) )
653     {
654         enumerator->found = TRUE;
655         enumerator->data = window;
656
657         return;
658     }
659
660     /*
661      * Otherwise, check this window's children
662      */
663     fgEnumSubWindows( window, fghcbWindowByID, enumerator );
664 }
665
666 /*
667  * This function is similiar to the previous one, except it is
668  * looking for a specified (sub)window identifier. The function
669  * is defined in freeglut_structure.c file.
670  */
671 SFG_Window* fgWindowByID( int windowID )
672 {
673     SFG_Enumerator enumerator;
674
675     /*
676      * Uses a method very similiar for fgWindowByHandle...
677      */
678     enumerator.found = FALSE;
679     enumerator.data = (void *) windowID;
680
681     /*
682      * Start the enumeration now:
683      */
684     fgEnumWindows( fghcbWindowByID, &enumerator );
685
686     /*
687      * Check if the window has been found or not:
688      */
689     if( enumerator.found == TRUE )
690         return( (SFG_Window *) enumerator.data );
691
692     /*
693      * Otherwise return NULL to mark the failure
694      */
695     return( NULL );
696 }
697
698 /*
699  * Looks up a menu given its ID. This is easier that fgWindowByXXX
700  * as all menus are placed in a single doubly linked list...
701  */
702 SFG_Menu* fgMenuByID( int menuID )
703 {
704     SFG_Menu *menu = NULL;
705
706     freeglut_assert_ready;
707
708     /*
709      * It's enough to check all entries in fgStructure.Menus...
710      */
711     for( menu = (SFG_Menu *)fgStructure.Menus.First; menu; menu = (SFG_Menu *)menu->Node.Next )
712     {
713         /*
714          * Does the ID number match?
715          */
716         if( menu->ID == menuID )
717             return( menu );
718     }
719
720     /*
721      * We have not found the requested menu ID
722      */
723     return( NULL );
724 }
725
726 /*
727  * List functions...
728  */
729 void fgListInit(SFG_List *list)
730 {
731     list->First = NULL;
732     list->Last = NULL;
733 }
734
735 void fgListAppend(SFG_List *list, SFG_Node *node)
736 {
737     SFG_Node *ln;
738
739     if ( (ln = (SFG_Node *)list->Last) != NULL )
740     {
741         ln->Next = node;
742         node->Prev = ln;
743     }
744     else
745     {
746         node->Prev = NULL;
747         list->First = node;
748     }
749
750     node->Next = NULL;
751     list->Last = node;
752 }
753
754 void fgListRemove(SFG_List *list, SFG_Node *node)
755 {
756     SFG_Node *ln;
757
758     if ( (ln = (SFG_Node *)node->Next) != NULL )
759         ln->Prev = node->Prev;
760     if ( (ln = (SFG_Node *)node->Prev) != NULL )
761         ln->Next = node->Next;
762     if ( (ln = (SFG_Node *)list->First) == node )
763         list->First = node->Next;
764     if ( (ln = (SFG_Node *)list->Last) == node )
765         list->Last = node->Prev;
766 }
767
768 int fgListLength(SFG_List *list)
769 {
770     SFG_Node *node;
771     int length = 0;
772
773     for( node = (SFG_Node *)list->First; node; node = (SFG_Node *)node->Next )
774         ++length;
775
776     return( length );
777 }
778
779 /*** END OF FILE ***/