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