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