Added fgInitCallBacks() to freeglut_structure.c. (The function takes
[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 fgInitCallBacks( 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     fgInitCallBacks( 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    * If the destroyed window has the highest window ID number, decrement
209    * the window ID number.
210    *
211    * XXX Do we REALLY want to *ever* recycle window IDs?  Integers are
212    * XXX plentiful, and clients may rely upon the implied promise in
213    * XXX the GLUT docs to not recycle these.  (I can't remember if it
214    * XXX is explicit.)
215    *
216    * XXX If we *do* want to do this, we should actually recompute the
217    * XXX highest window-ID; the new highest may not in fact be one less
218    * XXX than what we have just deleted.
219    */
220   if ( window->ID == fgStructure.WindowID )
221       fgStructure.WindowID-- ;
222
223   /*
224    * Check the execution state.  If this has been called from
225    * "glutDestroyWindow", a statement in that function will reset the
226    * "ExecState" after this function returns.
227    */
228   if ( fgState.ActionOnWindowClose != GLUT_ACTION_CONTINUE_EXECUTION )
229   {
230     /*
231      * Set the execution state flag to drop out of the main loop.
232      */
233     if ( fgState.ActionOnWindowClose == GLUT_ACTION_EXIT )
234       fgState.ExecState = GLUT_EXEC_STATE_STOP ;
235   }
236 }
237
238 /*
239  * Function to close down all the windows in the "WindowsToDestroy" list
240  */
241 void fgCloseWindows ()
242 {
243   SFG_WindowList *window_ptr = WindowsToDestroy ;
244   WindowsToDestroy = (SFG_WindowList*)NULL ;
245   /* In case the destroy callbacks cause more windows to be closed */
246
247   while ( window_ptr )
248   {
249     SFG_WindowList *next = window_ptr->next ;
250     fgDestroyWindow ( window_ptr->window, window_ptr->needToClose ) ;
251     free ( window_ptr ) ;
252     window_ptr = next ;
253
254     if ( !window_ptr )
255     {
256       window_ptr = WindowsToDestroy ;
257       WindowsToDestroy = (SFG_WindowList*)NULL ;
258     }
259   }
260 }
261
262 /*
263  * This function destroys a window and all of its subwindows. Actually,
264  * another function, defined in freeglut_window.c is called, but this is
265  * a whole different story...
266  */
267 void fgDestroyWindow( SFG_Window* window, GLboolean needToClose )
268 {
269     SFG_Window* subWindow;
270     int menu_index ;
271
272     assert( window != NULL );
273     freeglut_assert_ready;
274
275     while ( (subWindow = (SFG_Window *)window->Children.First) != NULL )
276         fgDestroyWindow( subWindow, needToClose );
277
278     /*
279      * XXX Since INVOKE_WCB() tests the function pointer, why not make
280      * XXX this unconditional?  Overhead is close to nil, and it would
281      * XXX clarify the code by omitting a conditional test.
282      */
283     if ( FETCH_WCB( *window, Destroy ) )
284     {
285       SFG_Window *activeWindow = fgStructure.Window ;
286       INVOKE_WCB( *window, Destroy, ( ) );
287       fgSetWindow ( activeWindow ) ;
288     }
289
290     if ( window->Parent != NULL )
291         fgListRemove( &window->Parent->Children, &window->Node );
292     else
293         fgListRemove( &fgStructure.Windows, &window->Node );
294
295     if ( window->ActiveMenu != NULL )
296       fgDeactivateMenu ( window ) ;
297
298     for ( menu_index = 0; menu_index < 3; menu_index ++ )
299     {
300       if ( window->Menu[menu_index] != NULL )
301         window->Menu[menu_index]->ParentWindow = NULL ;
302     }
303
304     if( needToClose == TRUE )
305         fgCloseWindow( window );
306     free( window );
307     if ( fgStructure.Window == window )
308         fgStructure.Window = NULL ;
309 }
310
311 /*
312  * This is a helper static function that removes a menu (given its pointer)
313  * from any windows that can be accessed from a given parent...
314  */
315 static void fghRemoveMenuFromWindow( SFG_Window* window, SFG_Menu* menu )
316 {
317     SFG_Window *subWindow;
318     int i;
319
320     /*
321      * Check if the menu is attached to the current window,
322      * if so, have it detached (by overwriting with a NULL):
323      */
324     for( i=0; i<3; i++ )
325         if( window->Menu[ i ] == menu )
326             window->Menu[ i ] = NULL;
327
328     /*
329      * Call this function for all of the window's children recursively:
330      */
331     for( subWindow = (SFG_Window *)window->Children.First; subWindow;
332          subWindow = (SFG_Window *)subWindow->Node.Next)
333         fghRemoveMenuFromWindow( subWindow, menu );
334 }
335
336 /*
337  * This is a static helper function that removes menu references
338  * from another menu, given two pointers to them...
339  */
340 static void fghRemoveMenuFromMenu( SFG_Menu* from, SFG_Menu* menu )
341 {
342   SFG_MenuEntry *entry;
343
344   for( entry = (SFG_MenuEntry *)from->Entries.First;
345        entry;
346        entry = (SFG_MenuEntry *)entry->Node.Next )
347     if (entry->SubMenu == menu)
348       entry->SubMenu = NULL;
349 }
350
351 /*
352  * This function destroys a menu specified by the parameter. All menus
353  * and windows are updated to make sure no ill pointers hang around.
354  */
355 void fgDestroyMenu( SFG_Menu* menu )
356 {
357   SFG_Window *window;
358   SFG_Menu *from;
359   SFG_MenuEntry *entry;
360
361   assert( menu != NULL );
362   freeglut_assert_ready;
363
364   /*
365    * First of all, have all references to this menu removed from all windows:
366    */
367   for( window = (SFG_Window *)fgStructure.Windows.First;
368        window;
369        window = (SFG_Window *)window->Node.Next )
370     fghRemoveMenuFromWindow( window, menu );
371
372   /*
373    * Now proceed with removing menu entries that lead to this menu
374    */
375   for( from = (SFG_Menu *)fgStructure.Menus.First;
376        from;
377        from = (SFG_Menu *)from->Node.Next )
378     fghRemoveMenuFromMenu( from, menu );
379
380   /*
381    * If the programmer defined a destroy callback, call it
382    * A. Donev: But first make this the active menu
383    */    
384   if ( menu->Destroy != NULL )
385   {
386     SFG_Menu *activeMenu=fgStructure.Menu;
387     fgStructure.Menu = menu;    
388     menu->Destroy () ;  
389     fgStructure.Menu = activeMenu;     
390   }        
391
392   /*
393    * Now we are pretty sure the menu is not used anywhere
394    * and that we can remove all of its entries
395    */
396   while( (entry = (SFG_MenuEntry *)menu->Entries.First) != NULL )
397   {
398     fgListRemove(&menu->Entries, &entry->Node);
399
400     if( entry->Text )
401         free( entry->Text );
402     entry->Text = NULL;
403     
404     free( entry );
405     entry = NULL;
406   }
407
408   if ( fgStructure.Window == menu->Window )
409     fgSetWindow ( menu->ParentWindow ) ;
410   fgDestroyWindow ( menu->Window, TRUE ) ;
411   fgListRemove( &fgStructure.Menus, &menu->Node );
412   if( fgStructure.Menu == menu )
413     fgStructure.Menu = NULL;
414
415   free( menu );
416 }
417
418 /*
419  * This function should be called on glutInit(). It will prepare the internal
420  * structure of freeglut to be used in the application. The structure will be
421  * destroyed using fgDestroyStructure() on glutMainLoop() return. In that
422  * case further use of freeglut should be preceeded with a glutInit() call.
423  */
424 void fgCreateStructure( void )
425 {
426   /*
427    * We will be needing two lists: the first containing windows,
428    * and the second containing the user-defined menus.
429    * Also, no current window/menu is set, as none has been created yet.
430    */
431
432   fgListInit(&fgStructure.Windows);
433   fgListInit(&fgStructure.Menus);
434 }
435
436 /*
437  * This function is automatically called on glutMainLoop() return.
438  * It should deallocate and destroy all remnants of previous
439  * glutInit()-enforced structure initialization...
440  */
441 void fgDestroyStructure( void )
442 {
443   SFG_Window *window;
444   SFG_Menu *menu;
445
446   freeglut_assert_ready;
447
448   /*
449    * Make sure all windows and menus have been deallocated
450    */
451   while( (menu = (SFG_Menu *)fgStructure.Menus.First) != NULL )
452     fgDestroyMenu( menu );
453
454   while( (window = (SFG_Window *)fgStructure.Windows.First) != NULL )
455     fgDestroyWindow( window, TRUE );
456 }
457
458 /*
459  * Helper function to enumerate through all registered top-level windows
460  */
461 void fgEnumWindows( FGCBenumerator enumCallback, SFG_Enumerator* enumerator )
462 {
463   SFG_Window *window;
464
465   assert( (enumCallback != NULL) && (enumerator != NULL) );
466   freeglut_assert_ready;
467
468   /*
469    * Check every of the top-level windows
470    */
471   for( window = (SFG_Window *)fgStructure.Windows.First;
472        window;
473        window = (SFG_Window *)window->Node.Next )
474   {
475     enumCallback( window, enumerator );
476     if( enumerator->found == TRUE )
477       return;
478   }
479 }
480
481 /*
482  * Helper function to enumerate through all a window's subwindows
483  * (single level descent)
484  */
485 void fgEnumSubWindows( SFG_Window* window, FGCBenumerator enumCallback,
486                        SFG_Enumerator* enumerator )
487 {
488   SFG_Window *child;
489
490   assert( (enumCallback != NULL) && (enumerator != NULL) );
491   freeglut_assert_ready;
492
493   for( child = (SFG_Window *)window->Children.First;
494        child;
495        child = (SFG_Window *)child->Node.Next )
496   {
497     enumCallback( child, enumerator );
498     if( enumerator->found == TRUE )
499       return;
500   }
501 }
502
503 /*
504  * A static helper function to look for a window given its handle
505  */
506 static void fghcbWindowByHandle( SFG_Window *window,
507                                  SFG_Enumerator *enumerator )
508 {
509     freeglut_return_if_fail( enumerator->found == FALSE );
510
511 #if TARGET_HOST_UNIX_X11
512     #define WBHANDLE (Window)
513 #elif TARGET_HOST_WIN32
514     #define WBHANDLE (HWND)
515 #endif
516
517     /*
518      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
519      */
520     if( window->Window.Handle == WBHANDLE (enumerator->data) )
521     {
522         enumerator->found = TRUE;
523         enumerator->data = window;
524
525         return;
526     }
527
528     /*
529      * Otherwise, check this window's children
530      */
531     fgEnumSubWindows( window, fghcbWindowByHandle, enumerator );
532
533 #undef WBHANDLE
534 }
535
536 /*
537  * fgWindowByHandle returns a (SFG_Window *) value pointing to the
538  * first window in the queue matching the specified window handle.
539  * The function is defined in freeglut_structure.c file.
540  */
541 SFG_Window* fgWindowByHandle
542 #if TARGET_HOST_UNIX_X11
543 ( Window hWindow )
544 #elif TARGET_HOST_WIN32
545 ( HWND hWindow )
546 #endif
547 {
548     SFG_Enumerator enumerator;
549
550     /*
551      * This is easy and makes use of the windows enumeration defined above
552      */
553     enumerator.found = FALSE;
554     enumerator.data = (void *)hWindow;
555     fgEnumWindows( fghcbWindowByHandle, &enumerator );
556
557     if( enumerator.found == TRUE )
558         return( SFG_Window *) enumerator.data;
559     return NULL;
560 }
561
562 /*
563  * A static helper function to look for a window given its ID
564  */
565 static void fghcbWindowByID( SFG_Window *window, SFG_Enumerator *enumerator )
566 {
567     /*
568      * Make sure we do not overwrite our precious results...
569      */
570     freeglut_return_if_fail( enumerator->found == FALSE );
571
572     /*
573      * Check the window's handle. Hope this works. Looks ugly. That's for sure.
574      */
575     if( window->ID == (int) (enumerator->data) ) /* XXX int/ptr conversion! */
576     {
577         enumerator->found = TRUE;
578         enumerator->data = window;
579
580         return;
581     }
582
583     /*
584      * Otherwise, check this window's children
585      */
586     fgEnumSubWindows( window, fghcbWindowByID, enumerator );
587 }
588
589 /*
590  * This function is similiar to the previous one, except it is
591  * looking for a specified (sub)window identifier. The function
592  * is defined in freeglut_structure.c file.
593  */
594 SFG_Window* fgWindowByID( int windowID )
595 {
596     SFG_Enumerator enumerator;
597
598     /*
599      * Uses a method very similiar for fgWindowByHandle...
600      */
601     enumerator.found = FALSE;
602     enumerator.data = (void *) windowID; /* XXX int/pointer conversion! */
603     fgEnumWindows( fghcbWindowByID, &enumerator );
604     if( enumerator.found == TRUE )
605         return( SFG_Window *) enumerator.data;
606     return NULL;
607 }
608
609 /*
610  * Looks up a menu given its ID. This is easier that fgWindowByXXX
611  * as all menus are placed in a single doubly linked list...
612  */
613 SFG_Menu* fgMenuByID( int menuID )
614 {
615     SFG_Menu *menu = NULL;
616
617     freeglut_assert_ready;
618
619     /*
620      * It's enough to check all entries in fgStructure.Menus...
621      */
622     for( menu = (SFG_Menu *)fgStructure.Menus.First;
623          menu;
624          menu = (SFG_Menu *)menu->Node.Next )
625         if( menu->ID == menuID )
626             return menu;
627     return NULL;
628 }
629
630 /*
631  * List functions...
632  */
633 void fgListInit(SFG_List *list)
634 {
635     list->First = NULL;
636     list->Last = NULL;
637 }
638
639 void fgListAppend(SFG_List *list, SFG_Node *node)
640 {
641     SFG_Node *ln;
642
643     if ( (ln = (SFG_Node *)list->Last) != NULL )
644     {
645         ln->Next = node;
646         node->Prev = ln;
647     }
648     else
649     {
650         node->Prev = NULL;
651         list->First = node;
652     }
653
654     node->Next = NULL;
655     list->Last = node;
656 }
657
658 void fgListRemove(SFG_List *list, SFG_Node *node)
659 {
660     SFG_Node *ln;
661
662     if ( (ln = (SFG_Node *)node->Next) != NULL )
663         ln->Prev = node->Prev;
664     if ( (ln = (SFG_Node *)node->Prev) != NULL )
665         ln->Next = node->Next;
666     if ( (ln = (SFG_Node *)list->First) == node )
667         list->First = node->Next;
668     if ( (ln = (SFG_Node *)list->Last) == node )
669         list->Last = node->Prev;
670 }
671
672 int fgListLength(SFG_List *list)
673 {
674     SFG_Node *node;
675     int length = 0;
676
677     for( node = (SFG_Node *)list->First; node; node = (SFG_Node *)node->Next )
678         ++length;
679
680     return length;
681 }
682
683 /*** END OF FILE ***/