Identified two more entry points
[projects/chimara/chimara.git] / libchimara / chimara-glk.c
1 /* licensing and copyright information here */
2
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <errno.h>
8 #include <math.h>
9 #include <gtk/gtk.h>
10 #include <config.h>
11 #include <glib/gi18n-lib.h>
12 #include <gmodule.h>
13 #include <pango/pango.h>
14 #include <gio/gio.h>
15 #include "chimara-glk.h"
16 #include "chimara-glk-private.h"
17 #include "chimara-marshallers.h"
18 #include "glk.h"
19 #include "abort.h"
20 #include "stream.h"
21 #include "window.h"
22 #include "glkstart.h"
23 #include "glkunix.h"
24 #include "init.h"
25 #include "magic.h"
26 #include "style.h"
27
28 #define CHIMARA_GLK_MIN_WIDTH 0
29 #define CHIMARA_GLK_MIN_HEIGHT 0
30
31 /* Substitute functions for compiling on iLiad */
32
33 #if !GTK_CHECK_VERSION(2, 18, 0)
34 #define gtk_widget_get_allocation(w, a) \
35         G_STMT_START { \
36                 (a)->x = (w)->allocation.x; \
37                 (a)->y = (w)->allocation.y; \
38                 (a)->width = (w)->allocation.width; \
39                 (a)->height = (w)->allocation.height; \
40         } G_STMT_END
41 #define gtk_widget_set_allocation(w, a) \
42         G_STMT_START { (w)->allocation = *(a); } G_STMT_END
43 #define gtk_widget_set_has_window(w, f) \
44         G_STMT_START { \
45                 if(f) \
46                         GTK_WIDGET_UNSET_FLAGS((w), GTK_NO_WINDOW); \
47                 else \
48                         GTK_WIDGET_SET_FLAGS((w), GTK_NO_WINDOW); \
49         } G_STMT_END
50 #endif /* GTK 2.18 */
51
52 /**
53  * SECTION:chimara-glk
54  * @short_description: Widget which executes a Glk program
55  * @stability: Unstable
56  * 
57  * The #ChimaraGlk widget opens and runs a Glk program. The program must be
58  * compiled as a plugin module, with a function <function>glk_main()</function>
59  * that the Glk library can hook into.
60  *
61  * On Linux systems, this is a file with a name like 
62  * <filename>plugin.so</filename>. For portability, you can use libtool and 
63  * automake:
64  * |[
65  * pkglib_LTLIBRARIES = plugin.la
66  * plugin_la_SOURCES = plugin.c foo.c bar.c
67  * plugin_la_LDFLAGS = -module -shared -avoid-version -export-symbols-regex "^glk_main$$"
68  * ]|
69  * This will produce <filename>plugin.la</filename> which is a text file 
70  * containing the correct plugin file to open (see the relevant section of the
71  * <ulink 
72  * url="http://www.gnu.org/software/libtool/manual/html_node/Finding-the-dlname.html">
73  * Libtool manual</ulink>).
74  *
75  * You need to initialize multithreading in any program you use a #ChimaraGlk
76  * widget in. This means including the following incantation at the beginning
77  * of your program:
78  * |[
79  * if(!g_thread_supported())
80  *     g_thread_init(NULL);
81  * gdk_threads_init();
82  * ]|
83  * This initialization must take place <emphasis>before</emphasis> the call to
84  * gtk_init(). In addition to this, you must also protect your call to 
85  * gtk_main() by calling gdk_threads_enter() right before it, and 
86  * gdk_threads_leave() right after it.
87  *
88  * The following sample program shows how to initialize and construct a simple 
89  * GTK window that runs a Glk program:
90  * |[
91  * #include <glib.h>
92  * #include <gtk/gtk.h>
93  * #include <libchimara/chimara-glk.h>
94  *
95  * int
96  * main(int argc, char *argv[])
97  * {
98  *     GtkWidget *window, *glk;
99  *     GError *error = NULL;
100  *     gchar *plugin_argv[] = { "plugin.so", "-option" };
101  *
102  *     /<!---->* Initialize threads and GTK *<!---->/
103  *     if(!g_thread_supported())
104  *         g_thread_init(NULL);
105  *     gdk_threads_init();
106  *     gtk_init(&argc, &argv);
107  *     
108  *     /<!---->* Construct the window and its contents. We quit the GTK main loop
109  *      * when the window's close button is clicked. *<!---->/
110  *     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
111  *     g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
112  *     glk = chimara_glk_new();
113  *     gtk_container_add(GTK_CONTAINER(window), glk);
114  *     gtk_widget_show_all(window);
115  *
116  *     /<!---->* Add a reference to the ChimaraGlk widget, since we want it to
117  *      * persist after the window's delete-event -- otherwise it will be destroyed
118  *      * with the window. *<!---->/
119  *     g_object_ref(glk);
120  *     
121  *     /<!---->* Start the Glk program in a separate thread *<!---->/
122  *     if(!chimara_glk_run(CHIMARA_GLK(glk), "./plugin.so", 2, plugin_argv, &error))
123  *         g_error("Error starting Glk library: %s\n", error->message);
124  *     
125  *     /<!---->* Start the GTK main loop *<!---->/
126  *     gdk_threads_enter();
127  *     gtk_main();
128  *     gdk_threads_leave();
129  *
130  *     /<!---->* After the GTK main loop exits, signal the Glk program to shut down if
131  *      * it is still running, and wait for it to exit. *<!---->/
132  *     chimara_glk_stop(CHIMARA_GLK(glk));
133  *     chimara_glk_wait(CHIMARA_GLK(glk));
134  *     g_object_unref(glk);
135  *
136  *     return 0;
137  * }
138  * ]|
139  */
140
141 typedef void (* glk_main_t) (void);
142 typedef int (* glkunix_startup_code_t) (glkunix_startup_t*);
143
144 enum {
145     PROP_0,
146     PROP_INTERACTIVE,
147     PROP_PROTECT,
148         PROP_SPACING,
149         PROP_PROGRAM_NAME,
150         PROP_PROGRAM_INFO,
151         PROP_STORY_NAME
152 };
153
154 enum {
155         STOPPED,
156         STARTED,
157         WAITING,
158         CHAR_INPUT,
159         LINE_INPUT,
160         TEXT_BUFFER_OUTPUT,
161         ILIAD_SCREEN_UPDATE,
162
163         LAST_SIGNAL
164 };
165
166 static guint chimara_glk_signals[LAST_SIGNAL] = { 0 };
167
168 G_DEFINE_TYPE(ChimaraGlk, chimara_glk, GTK_TYPE_CONTAINER);
169
170 static void
171 chimara_glk_init(ChimaraGlk *self)
172 {
173         chimara_init(); /* This is a library entry point */
174
175     gtk_widget_set_has_window(GTK_WIDGET(self), FALSE);
176
177     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
178     
179     priv->self = self;
180     priv->interactive = TRUE;
181     priv->protect = FALSE;
182         priv->styles = g_new0(StyleSet,1);
183         priv->glk_styles = g_new0(StyleSet,1);
184         priv->pager_attr_list = pango_attr_list_new();
185         priv->final_message = g_strdup("[ The game has finished ]");
186         priv->running = FALSE;
187     priv->program = NULL;
188     priv->thread = NULL;
189     priv->event_queue = g_queue_new();
190     priv->event_lock = g_mutex_new();
191     priv->event_queue_not_empty = g_cond_new();
192     priv->event_queue_not_full = g_cond_new();
193     priv->abort_lock = g_mutex_new();
194     priv->abort_signalled = FALSE;
195         priv->shutdown_lock = g_mutex_new();
196         priv->shutdown_key_pressed = g_cond_new();
197         priv->arrange_lock = g_mutex_new();
198         priv->rearranged = g_cond_new();
199         priv->needs_rearrange = FALSE;
200         priv->ignore_next_arrange_event = FALSE;
201         priv->char_input_queue = g_async_queue_new();
202         priv->line_input_queue = g_async_queue_new();
203         /* FIXME Should be g_async_queue_new_full(g_free); but only in GTK >= 2.16 */
204         priv->resource_map = NULL;
205         priv->resource_lock = g_mutex_new();
206         priv->resource_loaded = g_cond_new();
207         priv->resource_info_available = g_cond_new();
208         priv->resource_load_callback = NULL;
209         priv->resource_load_callback_data = NULL;
210         priv->image_cache = NULL;
211         priv->program_name = NULL;
212         priv->program_info = NULL;
213         priv->story_name = NULL;
214         priv->interrupt_handler = NULL;
215     priv->root_window = NULL;
216     priv->fileref_list = NULL;
217     priv->current_stream = NULL;
218     priv->stream_list = NULL;
219         priv->timer_id = 0;
220         priv->in_startup = FALSE;
221         priv->current_dir = NULL;
222
223         style_init(self);
224 }
225
226 static void
227 chimara_glk_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
228 {
229     ChimaraGlk *glk = CHIMARA_GLK(object);
230     
231     switch(prop_id) 
232     {
233         case PROP_INTERACTIVE:
234             chimara_glk_set_interactive( glk, g_value_get_boolean(value) );
235             break;
236         case PROP_PROTECT:
237             chimara_glk_set_protect( glk, g_value_get_boolean(value) );
238             break;
239                 case PROP_SPACING:
240                         chimara_glk_set_spacing( glk, g_value_get_uint(value) );
241                         break;
242         default:
243             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
244     }
245 }
246
247 static void
248 chimara_glk_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
249 {
250     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(object);
251     
252     switch(prop_id)
253     {
254         case PROP_INTERACTIVE:
255             g_value_set_boolean(value, priv->interactive);
256             break;
257         case PROP_PROTECT:
258             g_value_set_boolean(value, priv->protect);
259             break;
260                 case PROP_SPACING:
261                         g_value_set_uint(value, priv->spacing);
262                         break;
263                 case PROP_PROGRAM_NAME:
264                         g_value_set_string(value, priv->program_name);
265                         break;
266                 case PROP_PROGRAM_INFO:
267                         g_value_set_string(value, priv->program_info);
268                         break;
269                 case PROP_STORY_NAME:
270                         g_value_set_string(value, priv->story_name);
271                         break;
272                 default:
273             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
274     }
275 }
276
277 static void
278 chimara_glk_finalize(GObject *object)
279 {
280     ChimaraGlk *self = CHIMARA_GLK(object);
281         CHIMARA_GLK_USE_PRIVATE(self, priv);
282
283         /* Free widget properties */
284         g_free(priv->final_message);
285         /* Free styles */
286         g_hash_table_destroy(priv->styles->text_buffer);
287         g_hash_table_destroy(priv->styles->text_grid);
288         g_hash_table_destroy(priv->glk_styles->text_buffer);
289         g_hash_table_destroy(priv->glk_styles->text_grid);
290         pango_attr_list_unref(priv->pager_attr_list);
291         
292     /* Free the event queue */
293     g_mutex_lock(priv->event_lock);
294         g_queue_foreach(priv->event_queue, (GFunc)g_free, NULL);
295         g_queue_free(priv->event_queue);
296         g_cond_free(priv->event_queue_not_empty);
297         g_cond_free(priv->event_queue_not_full);
298         priv->event_queue = NULL;
299         g_mutex_unlock(priv->event_lock);
300         g_mutex_free(priv->event_lock);
301     /* Free the abort signaling mechanism */
302         g_mutex_lock(priv->abort_lock);
303         /* Make sure no other thread is busy with this */
304         g_mutex_unlock(priv->abort_lock);
305         g_mutex_free(priv->abort_lock);
306         priv->abort_lock = NULL;
307         /* Free the shutdown keypress signaling mechanism */
308         g_mutex_lock(priv->shutdown_lock);
309         g_cond_free(priv->shutdown_key_pressed);
310         g_mutex_unlock(priv->shutdown_lock);
311         priv->shutdown_lock = NULL;
312         /* Free the window arrangement signaling */
313         g_mutex_lock(priv->arrange_lock);
314         g_cond_free(priv->rearranged);
315         g_mutex_unlock(priv->arrange_lock);
316         g_mutex_free(priv->arrange_lock);
317         priv->arrange_lock = NULL;
318         g_mutex_lock(priv->resource_lock);
319         g_cond_free(priv->resource_loaded);
320         g_cond_free(priv->resource_info_available);
321         g_mutex_unlock(priv->resource_lock);
322         g_mutex_free(priv->resource_lock);
323         g_slist_foreach(priv->image_cache, (GFunc)clear_image_cache, NULL);
324         g_slist_free(priv->image_cache);
325         /* Unref input queues (this should destroy them since any Glk thread has stopped by now */
326         g_async_queue_unref(priv->char_input_queue);
327         g_async_queue_unref(priv->line_input_queue);
328         /* Destroy callback data if ownership retained */
329         if(priv->resource_load_callback_destroy_data)
330                 priv->resource_load_callback_destroy_data(priv->resource_load_callback_data);
331         
332         /* Free other stuff */
333         g_free(priv->current_dir);
334         g_free(priv->program_name);
335         g_free(priv->program_info);
336         g_free(priv->story_name);
337         g_free(priv->styles);
338         g_free(priv->glk_styles);
339
340         /* Chain up to parent */
341     G_OBJECT_CLASS(chimara_glk_parent_class)->finalize(object);
342 }
343
344 /* Internal function: Recursively get the Glk window tree's size request */
345 static void
346 request_recurse(winid_t win, GtkRequisition *requisition, guint spacing)
347 {
348         if(win->type == wintype_Pair)
349         {
350                 /* Get children's size requests */
351                 GtkRequisition child1, child2;
352                 request_recurse(win->window_node->children->data, &child1, spacing);
353                 request_recurse(win->window_node->children->next->data, &child2, spacing);
354
355                 glui32 division = win->split_method & winmethod_DivisionMask;
356                 glui32 direction = win->split_method & winmethod_DirMask;
357                 unsigned border = ((win->split_method & winmethod_BorderMask) == winmethod_NoBorder)? 0 : spacing;
358
359                 /* If the split is fixed, get the size of the fixed child */
360                 if(division == winmethod_Fixed)
361                 {
362                         switch(direction)
363                         {
364                                 case winmethod_Left:
365                                         child1.width = win->key_window?
366                                                 win->constraint_size * win->key_window->unit_width
367                                                 : 0;
368                                         break;
369                                 case winmethod_Right:
370                                         child2.width = win->key_window?
371                                                 win->constraint_size * win->key_window->unit_width
372                                                 : 0;
373                                         break;
374                                 case winmethod_Above:
375                                         child1.height = win->key_window?
376                                                 win->constraint_size * win->key_window->unit_height
377                                                 : 0;
378                                         break;
379                                 case winmethod_Below:
380                                         child2.height = win->key_window?
381                                                 win->constraint_size * win->key_window->unit_height
382                                                 : 0;
383                                         break;
384                         }
385                 }
386                 
387                 /* Add the children's requests */
388                 switch(direction)
389                 {
390                         case winmethod_Left:
391                         case winmethod_Right:
392                                 requisition->width = child1.width + child2.width + border;
393                                 requisition->height = MAX(child1.height, child2.height);
394                                 break;
395                         case winmethod_Above:
396                         case winmethod_Below:
397                                 requisition->width = MAX(child1.width, child2.width);
398                                 requisition->height = child1.height + child2.height + border;
399                                 break;
400                 }
401         }
402         
403         /* For non-pair windows, just use the size that GTK requests */
404         else
405                 gtk_widget_size_request(win->frame, requisition);
406 }
407
408 /* Overrides gtk_widget_size_request */
409 static void
410 chimara_glk_size_request(GtkWidget *widget, GtkRequisition *requisition)
411 {
412     g_return_if_fail(widget);
413     g_return_if_fail(requisition);
414     g_return_if_fail(CHIMARA_IS_GLK(widget));
415     
416     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
417     
418     guint border_width = gtk_container_get_border_width(GTK_CONTAINER(widget));
419     /* For now, just pass the size request on to the root Glk window */
420     if(priv->root_window) 
421         {
422                 request_recurse(priv->root_window->data, requisition, priv->spacing);
423                 requisition->width += 2 * border_width;
424                 requisition->height += 2 * border_width;
425         } 
426         else 
427         {
428         requisition->width = CHIMARA_GLK_MIN_WIDTH + 2 * border_width;
429         requisition->height = CHIMARA_GLK_MIN_HEIGHT + 2 * border_width;
430     }
431 }
432
433 /* Recursively give the Glk windows their allocated space. Returns a window
434  containing all children of this window that must be redrawn, or NULL if there 
435  are no children that require redrawing. */
436 static winid_t
437 allocate_recurse(winid_t win, GtkAllocation *allocation, guint spacing)
438 {
439         if(win->type == wintype_Pair)
440         {
441                 glui32 division = win->split_method & winmethod_DivisionMask;
442                 glui32 direction = win->split_method & winmethod_DirMask;
443                 unsigned border = ((win->split_method & winmethod_BorderMask) == winmethod_NoBorder)? 0 : spacing;
444
445                 /* If the space gets too small to honor the spacing property, then just 
446                  ignore spacing in this window and below. */
447                 if( (border > allocation->width && (direction == winmethod_Left || direction == winmethod_Right))
448                    || (border > allocation->height && (direction == winmethod_Above || direction == winmethod_Below)) )
449                         border = 0;
450                 
451                 GtkAllocation child1, child2;
452                 child1.x = allocation->x;
453                 child1.y = allocation->y;
454                 
455                 if(division == winmethod_Fixed)
456                 {
457                         /* If the key window has been closed, then default to 0; otherwise
458                          use the key window to determine the size */
459                         switch(direction)
460                         {
461                                 case winmethod_Left:
462                                         child1.width = win->key_window? 
463                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - border) 
464                                                 : 0;
465                                         break;
466                                 case winmethod_Right:
467                                         child2.width = win->key_window? 
468                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - border)
469                                                 : 0;
470                                         break;
471                                 case winmethod_Above:
472                                         child1.height = win->key_window? 
473                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - border)
474                                                 : 0;
475                                         break;
476                                 case winmethod_Below:
477                                         child2.height = win->key_window?
478                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - border)
479                                                 : 0;
480                                         break;
481                         }
482                 }
483                 else /* proportional */
484                 {
485                         gdouble fraction = win->constraint_size / 100.0;
486                         switch(direction)
487                         {
488                                 case winmethod_Left:
489                                         child1.width = MAX(0, (gint)ceil(fraction * (allocation->width - border)) );
490                                         break;
491                                 case winmethod_Right:
492                                         child2.width = MAX(0, (gint)ceil(fraction * (allocation->width - border)) );
493                                         break;
494                                 case winmethod_Above:
495                                         child1.height = MAX(0, (gint)ceil(fraction * (allocation->height - border)) );
496                                         break;
497                                 case winmethod_Below:
498                                         child2.height = MAX(0, (gint)ceil(fraction * (allocation->height - border)) );
499                                         break;
500                         }
501                 }
502                 
503                 /* Fill in the rest of the size requisitions according to the child specified above */
504                 switch(direction)
505                 {
506                         case winmethod_Left:
507                                 child2.width = MAX(0, allocation->width - border - child1.width);
508                                 child2.x = child1.x + child1.width + border;
509                                 child2.y = child1.y;
510                                 child1.height = child2.height = allocation->height;
511                                 break;
512                         case winmethod_Right:
513                                 child1.width = MAX(0, allocation->width - border - child2.width);
514                                 child2.x = child1.x + child1.width + border;
515                                 child2.y = child1.y;
516                                 child1.height = child2.height = allocation->height;
517                                 break;
518                         case winmethod_Above:
519                                 child2.height = MAX(0, allocation->height - border - child1.height);
520                                 child2.x = child1.x;
521                                 child2.y = child1.y + child1.height + border;
522                                 child1.width = child2.width = allocation->width;
523                                 break;
524                         case winmethod_Below:
525                                 child1.height = MAX(0, allocation->height - border - child2.height);
526                                 child2.x = child1.x;
527                                 child2.y = child1.y + child1.height + border;
528                                 child1.width = child2.width = allocation->width;
529                                 break;
530                 }
531                 
532                 /* Recurse */
533                 winid_t arrange1 = allocate_recurse(win->window_node->children->data, &child1, spacing);
534                 winid_t arrange2 = allocate_recurse(win->window_node->children->next->data, &child2, spacing);
535                 if(arrange1 == NULL)
536                         return arrange2;
537                 if(arrange2 == NULL)
538                         return arrange1;
539                 return win;
540         }
541         
542         else if(win->type == wintype_TextGrid)
543         {
544                 /* Pass the size allocation on to the framing widget */
545                 gtk_widget_size_allocate(win->frame, allocation);
546                 /* It says in the spec that when a text grid window is resized smaller,
547                  the bottom or right area is thrown away; when it is resized larger, the
548                  bottom or right area is filled with blanks. */
549                 GtkAllocation widget_allocation;
550                 gtk_widget_get_allocation(win->widget, &widget_allocation);
551                 glui32 newwidth = (glui32)(widget_allocation.width / win->unit_width);
552                 glui32 newheight = (glui32)(widget_allocation.height / win->unit_height);
553                 gint line;
554                 GtkTextBuffer *textbuffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
555                 GtkTextIter start, end;
556         
557                 for(line = 0; line < win->height; line++)
558                 {
559                         gtk_text_buffer_get_iter_at_line(textbuffer, &start, line);
560                         /* If this line is going to fall off the bottom, delete it */
561                         if(line >= newheight)
562                         {
563                                 end = start;
564                                 gtk_text_iter_forward_to_line_end(&end);
565                                 gtk_text_iter_forward_char(&end);
566                                 gtk_text_buffer_delete(textbuffer, &start, &end);
567                                 break;
568                         }
569                         /* If this line is not long enough, add spaces on the end */
570                         if(newwidth > win->width)
571                         {
572                                 gchar *spaces = g_strnfill(newwidth - win->width, ' ');
573                                 gtk_text_iter_forward_to_line_end(&start);
574                                 gtk_text_buffer_insert(textbuffer, &start, spaces, -1);
575                                 g_free(spaces);
576                         }
577                         /* But if it's too long, delete characters from the end */
578                         else if(newwidth < win->width)
579                         {
580                                 end = start;
581                                 gtk_text_iter_forward_chars(&start, newwidth);
582                                 gtk_text_iter_forward_to_line_end(&end);
583                                 gtk_text_buffer_delete(textbuffer, &start, &end);
584                         }
585                         /* Note: if the widths are equal, do nothing */
586                 }
587                 /* Add blank lines if there aren't enough lines to fit the new size */
588                 if(newheight > win->height)
589                 {
590                         gchar *blanks = g_strnfill(win->width, ' ');
591                     gchar **blanklines = g_new0(gchar *, (newheight - win->height) + 1);
592                     int count;
593                     for(count = 0; count < newheight - win->height; count++)
594                         blanklines[count] = blanks;
595                     blanklines[newheight - win->height] = NULL;
596                     gchar *text = g_strjoinv("\n", blanklines);
597                     g_free(blanklines); /* not g_strfreev() */
598                     g_free(blanks);
599                     
600                         gtk_text_buffer_get_end_iter(textbuffer, &start);
601                         gtk_text_buffer_insert(textbuffer, &start, "\n", -1);
602                     gtk_text_buffer_insert(textbuffer, &start, text, -1);
603                     g_free(text);
604                 }
605         
606                 gboolean arrange = !(win->width == newwidth && win->height == newheight);
607                 win->width = newwidth;
608                 win->height = newheight;
609                 return arrange? win : NULL;
610         }
611         
612         /* For non-pair, non-text-grid windows, just give them the size */
613         gtk_widget_size_allocate(win->frame, allocation);
614         return NULL;
615 }
616
617 /* Overrides gtk_widget_size_allocate */
618 static void
619 chimara_glk_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
620 {
621     g_return_if_fail(widget);
622     g_return_if_fail(allocation);
623     g_return_if_fail(CHIMARA_IS_GLK(widget));
624     
625     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
626     
627     gtk_widget_set_allocation(widget, allocation);
628             
629     if(priv->root_window) {
630                 GtkAllocation child;
631                 guint border_width = gtk_container_get_border_width(GTK_CONTAINER(widget));
632                 child.x = allocation->x + border_width;
633                 child.y = allocation->y + border_width;
634                 child.width = CLAMP(allocation->width - 2 * border_width, 0, allocation->width);
635                 child.height = CLAMP(allocation->height - 2 * border_width, 0, allocation->height);
636                 winid_t arrange = allocate_recurse(priv->root_window->data, &child, priv->spacing);
637                 
638                 /* arrange points to a window that contains all text grid and graphics
639                  windows which have been resized */
640                 g_mutex_lock(priv->arrange_lock);
641                 if(!priv->ignore_next_arrange_event)
642                 {
643                         if(arrange)
644                                 event_throw(CHIMARA_GLK(widget), evtype_Arrange, arrange == priv->root_window->data? NULL : arrange, 0, 0);
645                 }
646                 else
647                         priv->ignore_next_arrange_event = FALSE;
648                 priv->needs_rearrange = FALSE;
649                 g_cond_signal(priv->rearranged);
650                 g_mutex_unlock(priv->arrange_lock);
651         }
652 }
653
654 /* Recursively invoke callback() on the GtkWidget of each non-pair window in the tree */
655 static void
656 forall_recurse(winid_t win, GtkCallback callback, gpointer callback_data)
657 {
658         if(win->type == wintype_Pair)
659         {
660                 forall_recurse(win->window_node->children->data, callback, callback_data);
661                 forall_recurse(win->window_node->children->next->data, callback, callback_data);
662         }
663         else
664                 (*callback)(win->frame, callback_data);
665 }
666
667 /* Overrides gtk_container_forall */
668 static void
669 chimara_glk_forall(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data)
670 {
671     g_return_if_fail(container);
672     g_return_if_fail(CHIMARA_IS_GLK(container));
673     
674     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(container);
675     
676         /* All the children are "internal" */
677         if(!include_internals)
678                 return;
679         
680     if(priv->root_window)
681                 forall_recurse(priv->root_window->data, callback, callback_data);
682 }
683
684 static void
685 chimara_glk_stopped(ChimaraGlk *self)
686 {
687     CHIMARA_GLK_USE_PRIVATE(self, priv);
688     priv->running = FALSE;
689     priv->program_name = NULL;
690     g_object_notify(G_OBJECT(self), "program-name");
691     priv->program_info = NULL;
692     g_object_notify(G_OBJECT(self), "program-info");
693     priv->story_name = NULL;
694     g_object_notify(G_OBJECT(self), "story-name");
695 }
696
697 static void
698 chimara_glk_started(ChimaraGlk *self)
699 {
700         CHIMARA_GLK_USE_PRIVATE(self, priv);
701         priv->running = TRUE;
702 }
703
704 static void
705 chimara_glk_waiting(ChimaraGlk *self)
706 {
707         /* Default signal handler */
708 }
709
710 static void
711 chimara_glk_char_input(ChimaraGlk *self, guint window_rock, guint keysym)
712 {
713         /* Default signal handler */
714 }
715
716 static void
717 chimara_glk_line_input(ChimaraGlk *self, guint window_rock, gchar *text)
718 {
719         /* Default signal handler */
720 }
721
722 static void
723 chimara_glk_text_buffer_output(ChimaraGlk *self, guint window_rock, gchar *text)
724 {
725         /* Default signal handler */
726 }
727
728 static void
729 chimara_glk_iliad_screen_update(ChimaraGlk *self, gboolean typing)
730 {
731         /* Default signal handler */
732 }
733
734 /* COMPAT: G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
735 #ifndef G_PARAM_STATIC_STRINGS
736
737 /* COMPAT: G_PARAM_STATIC_NAME and friends only appeared in GTK 2.8 */
738 #if GTK_CHECK_VERSION(2,8,0)
739 #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
740 #else
741 #define G_PARAM_STATIC_STRINGS (0)
742 #endif
743
744 #endif
745
746 static void
747 chimara_glk_class_init(ChimaraGlkClass *klass)
748 {
749     /* Override methods of parent classes */
750     GObjectClass *object_class = G_OBJECT_CLASS(klass);
751     object_class->set_property = chimara_glk_set_property;
752     object_class->get_property = chimara_glk_get_property;
753     object_class->finalize = chimara_glk_finalize;
754     
755     GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
756     widget_class->size_request = chimara_glk_size_request;
757     widget_class->size_allocate = chimara_glk_size_allocate;
758
759     GtkContainerClass *container_class = GTK_CONTAINER_CLASS(klass);
760     container_class->forall = chimara_glk_forall;
761
762     /* Signals */
763     klass->stopped = chimara_glk_stopped;
764     klass->started = chimara_glk_started;
765     klass->waiting = chimara_glk_waiting;
766     klass->char_input = chimara_glk_char_input;
767     klass->line_input = chimara_glk_line_input;
768     klass->text_buffer_output = chimara_glk_text_buffer_output;
769     klass->iliad_screen_update = chimara_glk_iliad_screen_update;
770
771     /**
772      * ChimaraGlk::stopped:
773      * @glk: The widget that received the signal
774      *
775      * Emitted when the a Glk program finishes executing in the widget, whether
776      * it ended normally, or was interrupted.
777      */ 
778     chimara_glk_signals[STOPPED] = g_signal_new("stopped", 
779         G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST, 
780         /* FIXME: Should be G_SIGNAL_RUN_CLEANUP but that segfaults??! */
781         G_STRUCT_OFFSET(ChimaraGlkClass, stopped), NULL, NULL,
782                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
783         /**
784          * ChimaraGlk::started:
785          * @glk: The widget that received the signal
786          *
787          * Emitted when a Glk program starts executing in the widget.
788          */
789         chimara_glk_signals[STARTED] = g_signal_new ("started",
790                 G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST,
791                 G_STRUCT_OFFSET(ChimaraGlkClass, started), NULL, NULL,
792                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
793         /**
794          * ChimaraGlk::waiting:
795          * @glk: The widget that received the signal
796          * 
797          * Emitted when glk_select() is called by the Glk program and the event
798          * queue is empty, which means that the widget is waiting for input.
799          */
800         chimara_glk_signals[WAITING] = g_signal_new("waiting",
801                 G_OBJECT_CLASS_TYPE(klass), 0,
802                 G_STRUCT_OFFSET(ChimaraGlkClass, waiting), NULL, NULL,
803                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
804         /**
805          * ChimaraGlk::char-input:
806          * @glk: The widget that received the signal
807          * @window_rock: The rock value of the window that received character input
808          * (see <link linkend="chimara-Rocks">Rocks</link>)
809          * @keysym: The key that was typed, in the form of a key symbol from 
810          * <filename class="headerfile">gdk/gdkkeysyms.h</filename>
811          * 
812          * Emitted when a Glk window receives character input.
813          */
814         chimara_glk_signals[CHAR_INPUT] = g_signal_new("char-input",
815                 G_OBJECT_CLASS_TYPE(klass), 0,
816                 G_STRUCT_OFFSET(ChimaraGlkClass, char_input), NULL, NULL,
817                 _chimara_marshal_VOID__UINT_UINT,
818                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
819         /**
820          * ChimaraGlk::line-input:
821          * @glk: The widget that received the signal
822          * @window_rock: The rock value of the window that received line input (see
823          * <link linkend="chimara-Rocks">Rocks</link>)
824          * @text: The text that was typed
825          * 
826          * Emitted when a Glk window receives line input.
827          */
828         chimara_glk_signals[LINE_INPUT] = g_signal_new("line-input",
829                 G_OBJECT_CLASS_TYPE(klass), 0,
830                 G_STRUCT_OFFSET(ChimaraGlkClass, line_input), NULL, NULL,
831                 _chimara_marshal_VOID__UINT_STRING,
832                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
833         /**
834          * ChimaraGlk::text-buffer-output:
835          * @glk: The widget that received the signal
836          * @window_rock: The rock value of the window that was printed to (see <link
837          * linkend="chimara-Rocks">Rocks</link>)
838          * 
839          * Emitted when text is printed to a text buffer window.
840          */
841         chimara_glk_signals[TEXT_BUFFER_OUTPUT] = g_signal_new("text-buffer-output",
842                 G_OBJECT_CLASS_TYPE(klass), 0,
843                 G_STRUCT_OFFSET(ChimaraGlkClass, text_buffer_output), NULL, NULL,
844                 _chimara_marshal_VOID__UINT_STRING,
845                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
846         /**
847          * ChimaraGlk::iliad-screen-update:
848          * @self: The widget that received the signal
849          * @typing: Whether to perform a typing or full screen update
850          *
851          * Iliad specific signal which is emitted whenever the screen needs to be updated.
852          * Since iliad screen updates are very slow, updating should only be done when
853          * necessary.
854          */
855         chimara_glk_signals[ILIAD_SCREEN_UPDATE] = g_signal_new("iliad-screen-update",
856                 G_OBJECT_CLASS_TYPE(klass), 0,
857                 G_STRUCT_OFFSET(ChimaraGlkClass, iliad_screen_update), NULL, NULL,
858                 _chimara_marshal_VOID__BOOLEAN,
859                 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
860
861     /* Properties */
862     /**
863      * ChimaraGlk:interactive:
864      *
865      * Sets whether the widget is interactive. A Glk widget is normally 
866      * interactive, but in non-interactive mode, keyboard and mouse input are 
867      * ignored and the Glk program is controlled by 
868      * chimara_glk_feed_char_input() and chimara_glk_feed_line_input(). 
869      * <quote>More</quote> prompts when a lot of text is printed to a text 
870          * buffer are also disabled. This is typically used when you wish to control
871          * an interpreter program by feeding it a predefined list of commands.
872      */
873     g_object_class_install_property( object_class, PROP_INTERACTIVE, 
874                 g_param_spec_boolean("interactive", _("Interactive"),
875         _("Whether user input is expected in the Glk program"),
876         TRUE,
877         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
878
879         /**
880      * ChimaraGlk:protect:
881      *
882      * Sets whether the Glk program is allowed to do file operations. In protect
883      * mode, all file operations will fail.
884      */
885     g_object_class_install_property(object_class, PROP_PROTECT, 
886                 g_param_spec_boolean("protect", _("Protected"),
887         _("Whether the Glk program is barred from doing file operations"),
888         FALSE,
889         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
890
891         /**
892          * ChimaraGlk:spacing:
893          *
894          * The amount of space between the Glk windows. This space forms a visible
895          * border between windows; however, if you open a window using the
896          * %winmethod_NoBorder flag, there will be no spacing between it and its
897          * sibling window, no matter what the value of this property is.
898          */
899         g_object_class_install_property(object_class, PROP_SPACING,
900                 g_param_spec_uint("spacing", _("Spacing"),
901                 _("The amount of space between Glk windows"),
902                 0, G_MAXUINT, 0,
903                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
904         
905         /**
906          * ChimaraGlk:program-name:
907          *
908          * The name of the currently running Glk program. You cannot set this 
909          * property yourself. It is set to the filename of the plugin when you call
910          * chimara_glk_run(), but the plugin can change it by calling 
911          * garglk_set_program_name(). To find out when this information changes,
912          * for example to put the program name in the title bar of a window, connect
913          * to the <code>::notify::program-name</code> signal.
914          */
915         g_object_class_install_property(object_class, PROP_PROGRAM_NAME,
916                 g_param_spec_string("program-name", _("Program name"),
917                 _("Name of the currently running program"),
918                 NULL,
919                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
920                 
921         /**
922          * ChimaraGlk:program-info:
923          *
924          * Information about the currently running Glk program. You cannot set this
925          * property yourself. The plugin can change it by calling
926          * garglk_set_program_info(). See also #ChimaraGlk:program-name.
927          */
928         g_object_class_install_property(object_class, PROP_PROGRAM_INFO,
929                 g_param_spec_string("program-info", _("Program info"),
930                 _("Information about the currently running program"),
931                 NULL,
932                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
933         
934         /**
935          * ChimaraGlk:story-name:
936          *
937          * The name of the story currently running in the Glk interpreter. You
938          * cannot set this property yourself. It is set to the story filename when
939          * you call chimara_if_run_game(), but the plugin can change it by calling
940          * garglk_set_story_name().
941          *
942          * Strictly speaking, this should be a property of #ChimaraIF, but it is
943          * legal for any Glk program to call garglk_set_story_name(), even if it is
944          * not an interpreter and does not load story files.
945          */
946         g_object_class_install_property(object_class, PROP_STORY_NAME,
947                 g_param_spec_string("story-name", _("Story name"),
948                 _("Name of the story currently loaded in the interpreter"),
949                 NULL,
950                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
951         
952         /* Private data */
953     g_type_class_add_private(klass, sizeof(ChimaraGlkPrivate));
954 }
955
956 /* PUBLIC FUNCTIONS */
957
958 /**
959  * chimara_error_quark:
960  *
961  * The error domain for errors from Chimara widgets.
962  *
963  * Returns: The string <quote>chimara-error-quark</quote> as a <link 
964  * linkend="GQuark">GQuark</link>.
965  */
966 GQuark
967 chimara_error_quark(void)
968 {
969         chimara_init(); /* This is a library entry point */
970         return g_quark_from_static_string("chimara-error-quark");
971 }
972
973 /**
974  * chimara_glk_new:
975  *
976  * Creates and initializes a new #ChimaraGlk widget.
977  *
978  * Return value: a #ChimaraGlk widget, with a floating reference.
979  */
980 GtkWidget *
981 chimara_glk_new(void)
982 {
983         /* This is a library entry point; initialize the library */
984         chimara_init();
985
986     return GTK_WIDGET(g_object_new(CHIMARA_TYPE_GLK, NULL));
987 }
988
989 /**
990  * chimara_glk_set_interactive:
991  * @glk: a #ChimaraGlk widget
992  * @interactive: whether the widget should expect user input
993  *
994  * Sets the #ChimaraGlk:interactive property of @glk. 
995  */
996 void 
997 chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
998 {
999     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1000     
1001     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1002     priv->interactive = interactive;
1003     g_object_notify(G_OBJECT(glk), "interactive");
1004 }
1005
1006 /**
1007  * chimara_glk_get_interactive:
1008  * @glk: a #ChimaraGlk widget
1009  *
1010  * Returns whether @glk is interactive (expecting user input). See 
1011  * #ChimaraGlk:interactive.
1012  *
1013  * Return value: %TRUE if @glk is interactive.
1014  */
1015 gboolean 
1016 chimara_glk_get_interactive(ChimaraGlk *glk)
1017 {
1018     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1019     
1020     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1021     return priv->interactive;
1022 }
1023
1024 /**
1025  * chimara_glk_set_protect:
1026  * @glk: a #ChimaraGlk widget
1027  * @protect: whether the widget should allow the Glk program to do file 
1028  * operations
1029  *
1030  * Sets the #ChimaraGlk:protect property of @glk. In protect mode, the Glk 
1031  * program is not allowed to do file operations.
1032  */
1033 void 
1034 chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
1035 {
1036     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1037     
1038     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1039     priv->protect = protect;
1040     g_object_notify(G_OBJECT(glk), "protect");
1041 }
1042
1043 /**
1044  * chimara_glk_get_protect:
1045  * @glk: a #ChimaraGlk widget
1046  *
1047  * Returns whether @glk is in protect mode (banned from doing file operations).
1048  * See #ChimaraGlk:protect.
1049  *
1050  * Return value: %TRUE if @glk is in protect mode.
1051  */
1052 gboolean 
1053 chimara_glk_get_protect(ChimaraGlk *glk)
1054 {
1055     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1056     
1057     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1058     return priv->protect;
1059 }
1060
1061 /**
1062  * chimara_glk_set_css_to_default:
1063  * @glk: a #ChimaraGlk widget
1064  *
1065  * Resets the styles for text buffer and text grid windows to their defaults.
1066  * <para><warning>
1067  *   This function is not implemented yet.
1068  * </warning></para>
1069  */
1070 void
1071 chimara_glk_set_css_to_default(ChimaraGlk *glk)
1072 {
1073         reset_default_styles(glk);
1074 }
1075
1076 /**
1077  * chimara_glk_set_css_from_file:
1078  * @glk: a #ChimaraGlk widget
1079  * @filename: path to a CSS file, or %NULL
1080  * @error: location to store a <link 
1081  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1082  *
1083  * Sets the styles for text buffer and text grid windows according to the CSS
1084  * file @filename. Note that the styles are set cumulatively on top of whatever
1085  * the styles are at the time this function is called; to reset the styles to
1086  * their defaults, use chimara_glk_set_css_to_default().
1087  *
1088  * Returns: %TRUE on success, %FALSE if an error occurred, in which case @error
1089  * will be set.
1090  */
1091 gboolean 
1092 chimara_glk_set_css_from_file(ChimaraGlk *glk, const gchar *filename, GError **error)
1093 {
1094         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1095         g_return_val_if_fail(filename, FALSE);
1096         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1097
1098         int fd = open(filename, O_RDONLY);
1099         if(fd == -1) {
1100                 if(error)
1101                         *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno), 
1102                                 _("Error opening file \"%s\": %s"), filename, g_strerror(errno));
1103                 return FALSE;
1104         }
1105
1106         GScanner *scanner = create_css_file_scanner();
1107         g_scanner_input_file(scanner, fd);
1108         scanner->input_name = filename;
1109         scan_css_file(scanner, glk);
1110
1111         if(close(fd) == -1) {
1112                 if(error)
1113                         *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno),
1114                                 _("Error closing file \"%s\": %s"), filename, g_strerror(errno));
1115                 return FALSE;
1116         }
1117         return TRUE;
1118 }
1119
1120 /**
1121  * chimara_glk_set_css_from_string:
1122  * @glk: a #ChimaraGlk widget
1123  * @css: a string containing CSS code
1124  *
1125  * Sets the styles for text buffer and text grid windows according to the CSS
1126  * code @css. Note that the styles are set cumulatively on top of whatever the 
1127  * styles are at the time this function is called; to reset the styles to their
1128  * defaults, use chimara_glk_set_css_to_default().
1129  */
1130 void 
1131 chimara_glk_set_css_from_string(ChimaraGlk *glk, const gchar *css)
1132 {
1133         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1134         g_return_if_fail(css || *css);
1135         
1136         GScanner *scanner = create_css_file_scanner();
1137         g_scanner_input_text(scanner, css, strlen(css));
1138         scanner->input_name = "<string>";
1139         scan_css_file(scanner, glk);
1140 }
1141
1142 /**
1143  * chimara_glk_set_spacing:
1144  * @glk: a #ChimaraGlk widget
1145  * @spacing: the number of pixels to put between Glk windows
1146  *
1147  * Sets the #ChimaraGlk:spacing property of @glk, which is the border width in
1148  * pixels between Glk windows.
1149  */
1150 void 
1151 chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
1152 {
1153         g_return_if_fail( glk || CHIMARA_IS_GLK(glk) );
1154         
1155         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1156         priv->spacing = spacing;
1157         g_object_notify(G_OBJECT(glk), "spacing");
1158 }
1159
1160 /**
1161  * chimara_glk_get_spacing:
1162  * @glk: a #ChimaraGlk widget
1163  *
1164  * Gets the value set by chimara_glk_set_spacing().
1165  *
1166  * Return value: pixels of spacing between Glk windows
1167  */
1168 guint 
1169 chimara_glk_get_spacing(ChimaraGlk *glk)
1170 {
1171         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), 0);
1172         
1173         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1174         return priv->spacing;
1175 }
1176
1177 struct StartupData {
1178         glk_main_t glk_main;
1179         glkunix_startup_code_t glkunix_startup_code;
1180         glkunix_startup_t args;
1181         ChimaraGlkPrivate *glk_data;
1182 };
1183
1184 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
1185 static gpointer
1186 glk_enter(struct StartupData *startup)
1187 {
1188         extern GPrivate *glk_data_key;
1189         g_private_set(glk_data_key, startup->glk_data);
1190         
1191         /* Acquire the Glk thread's references to the input queues */
1192         g_async_queue_ref(startup->glk_data->char_input_queue);
1193         g_async_queue_ref(startup->glk_data->line_input_queue);
1194         
1195         /* Run startup function */
1196         if(startup->glkunix_startup_code) {
1197                 startup->glk_data->in_startup = TRUE;
1198                 int result = startup->glkunix_startup_code(&startup->args);
1199                 startup->glk_data->in_startup = FALSE;
1200                 
1201                 int i = 0;
1202                 while(i < startup->args.argc)
1203                         g_free(startup->args.argv[i++]);
1204                 g_free(startup->args.argv);
1205                 
1206                 if(!result)
1207                         return NULL;
1208         }
1209         
1210         /* Run main function */
1211         glk_main_t glk_main = startup->glk_main;
1212         
1213         /* COMPAT: avoid usage of slices */
1214         g_free(startup);
1215     g_signal_emit_by_name(startup->glk_data->self, "started");
1216         glk_main();
1217         glk_exit(); /* Run shutdown code in glk_exit() even if glk_main() returns normally */
1218         g_assert_not_reached(); /* because glk_exit() calls g_thread_exit() */
1219         return NULL; 
1220 }
1221
1222 /**
1223  * chimara_glk_run:
1224  * @glk: a #ChimaraGlk widget
1225  * @plugin: path to a plugin module compiled with <filename 
1226  * class="header">glk.h</filename>
1227  * @argc: Number of command line arguments in @argv
1228  * @argv: Array of command line arguments to pass to the plugin
1229  * @error: location to store a <link 
1230  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1231  *
1232  * Opens a Glk program compiled as a plugin. Sorts out its command line
1233  * arguments from #glkunix_arguments, calls its startup function
1234  * glkunix_startup_code(), and then calls its main function glk_main() in
1235  * a separate thread. On failure, returns %FALSE and sets @error.
1236  *
1237  * The plugin must at least export a glk_main() function; #glkunix_arguments and
1238  * glkunix_startup_code() are optional.
1239  *
1240  * Return value: %TRUE if the Glk program was started successfully.
1241  */
1242 gboolean
1243 chimara_glk_run(ChimaraGlk *glk, const gchar *plugin, int argc, char *argv[], GError **error)
1244 {
1245     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1246     g_return_val_if_fail(plugin, FALSE);
1247         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1248         
1249         if(chimara_glk_get_running(glk)) {
1250                 g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_ALREADY_RUNNING, _("There was already a plugin running."));
1251                 return FALSE;
1252         }
1253     
1254     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1255
1256         /* COMPAT: avoid usage of slices */
1257         struct StartupData *startup = g_new0(struct StartupData,1);
1258         
1259     g_assert( g_module_supported() );
1260         /* If there is already a module loaded, free it first -- you see, we want to
1261          * keep modules loaded as long as possible to avoid crashes in stack unwinding */
1262         chimara_glk_unload_plugin(glk);
1263         /* Open the module to run */
1264     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
1265     
1266     if(!priv->program)
1267     {
1268         g_set_error(error, CHIMARA_ERROR, CHIMARA_LOAD_MODULE_ERROR, _("Error opening module: %s"), g_module_error());
1269         return FALSE;
1270     }
1271     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
1272     {
1273         g_set_error(error, CHIMARA_ERROR, CHIMARA_NO_GLK_MAIN, _("Error finding glk_main(): %s"), g_module_error());
1274         return FALSE;
1275     }
1276
1277     if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
1278     {
1279                 glkunix_argumentlist_t *glkunix_arguments;
1280
1281                 if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
1282                           && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
1283                 {
1284                         /* arguments could not be parsed, so create data ourselves */
1285                         startup->args.argc = 1;
1286                         startup->args.argv = g_new0(gchar *, 1);
1287                 }
1288
1289                 /* Set the program invocation name */
1290                 startup->args.argv[0] = g_strdup(plugin);
1291     }
1292         startup->glk_data = priv;
1293         
1294         /* Set the program name */
1295         priv->program_name = g_path_get_basename(plugin);
1296         g_object_notify(G_OBJECT(glk), "program-name");
1297         
1298     /* Run in a separate thread */
1299         priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
1300         
1301         return !(priv->thread == NULL);
1302 }
1303
1304 /**
1305  * chimara_glk_run_file:
1306  * @self: a #ChimaraGlk widget
1307  * @plugin_file: a #GFile pointing to a plugin module compiled with <filename
1308  * class="header">glk.h</filename>
1309  * @argc: Number of command line arguments in @argv
1310  * @argv: Array of command line arguments to pass to the plugin
1311  * @error: location to store a <link
1312  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1313  *
1314  * Opens a Glk program compiled as a plugin, from a #GFile. See
1315  * chimara_glk_run() for details.
1316  *
1317  * Return value: %TRUE if the Glk program was started successfully.
1318  */
1319 gboolean
1320 chimara_glk_run_file(ChimaraGlk *self, GFile *plugin_file, int argc, char *argv[], GError **error)
1321 {
1322         g_return_val_if_fail(self || CHIMARA_IS_GLK(self), FALSE);
1323         g_return_val_if_fail(plugin_file || G_IS_FILE(plugin_file), FALSE);
1324         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1325
1326         char *path = g_file_get_path(plugin_file);
1327         gboolean retval = chimara_glk_run(self, path, argc, argv, error);
1328         g_free(path);
1329
1330         return retval;
1331 }
1332
1333 /**
1334  * chimara_glk_stop:
1335  * @glk: a #ChimaraGlk widget
1336  *
1337  * Signals the Glk program running in @glk to abort. Note that if the program is
1338  * caught in an infinite loop in which glk_tick() is not called, this may not
1339  * work.
1340  *
1341  * This function does nothing if no Glk program is running.
1342  */
1343 void
1344 chimara_glk_stop(ChimaraGlk *glk)
1345 {
1346     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1347     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1348
1349     /* Don't do anything if not running a program */
1350     if(!priv->running)
1351         return;
1352     
1353         if(priv->abort_lock) {
1354                 g_mutex_lock(priv->abort_lock);
1355                 priv->abort_signalled = TRUE;
1356                 g_mutex_unlock(priv->abort_lock);
1357                 /* Stop blocking on the event queue condition */
1358                 event_throw(glk, evtype_Abort, NULL, 0, 0);
1359                 /* Stop blocking on the shutdown key press condition */
1360                 g_mutex_lock(priv->shutdown_lock);
1361                 g_cond_signal(priv->shutdown_key_pressed);
1362                 g_mutex_unlock(priv->shutdown_lock);
1363         }
1364 }
1365
1366 /**
1367  * chimara_glk_wait:
1368  * @glk: a #ChimaraGlk widget
1369  *
1370  * Holds up the main thread and waits for the Glk program running in @glk to 
1371  * finish.
1372  *
1373  * This function does nothing if no Glk program is running.
1374  */
1375 void
1376 chimara_glk_wait(ChimaraGlk *glk)
1377 {
1378     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1379     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1380     /* Don't do anything if not running a program */
1381     if(!priv->running)
1382         return;
1383         /* Unlock GDK mutex, because the Glk program might need to use it for shutdown */
1384         gdk_threads_leave();
1385     g_thread_join(priv->thread);
1386         gdk_threads_enter();
1387 }
1388
1389 /**
1390  * chimara_glk_unload_plugin:
1391  * @glk: a #ChimaraGlk widget
1392  *
1393  * The plugin containing the Glk program is unloaded as late as possible before
1394  * loading a new plugin, in order to prevent crashes while printing stack
1395  * backtraces during debugging. Sometimes this behavior is not desirable. This
1396  * function forces @glk to unload the plugin running in it.
1397  *
1398  * This function does nothing if there is no plugin loaded.
1399  */
1400 void
1401 chimara_glk_unload_plugin(ChimaraGlk *glk)
1402 {
1403         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1404     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1405         if( priv->program && !g_module_close(priv->program) )
1406                 g_warning( "Error closing module :%s", g_module_error() );
1407 }
1408
1409 /**
1410  * chimara_glk_get_running:
1411  * @glk: a #ChimaraGlk widget
1412  * 
1413  * Use this function to tell whether a program is currently running in the
1414  * widget.
1415  * 
1416  * Returns: %TRUE if @glk is executing a Glk program, %FALSE otherwise.
1417  */
1418 gboolean
1419 chimara_glk_get_running(ChimaraGlk *glk)
1420 {
1421         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1422         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1423         return priv->running;
1424 }
1425
1426 /**
1427  * chimara_glk_feed_char_input:
1428  * @glk: a #ChimaraGlk widget
1429  * @keyval: a key symbol as defined in <filename 
1430  * class="headerfile">gdk/gdkkeysyms.h</filename>
1431  * 
1432  * Pretend that a key was pressed in the Glk program as a response to a 
1433  * character input request. You can call this function even when no window has
1434  * requested character input, in which case the key will be saved for the 
1435  * following window that requests character input. This has the disadvantage 
1436  * that if more than one window has requested character input, it is arbitrary 
1437  * which one gets the key press.
1438  */
1439 void 
1440 chimara_glk_feed_char_input(ChimaraGlk *glk, guint keyval)
1441 {
1442         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1443         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1444         g_async_queue_push(priv->char_input_queue, GUINT_TO_POINTER(keyval));
1445         event_throw(glk, evtype_ForcedCharInput, NULL, 0, 0);
1446 }
1447
1448 /**
1449  * chimara_glk_feed_line_input:
1450  * @glk: a #ChimaraGlk widget
1451  * @text: text to pass to the next line input request
1452  * 
1453  * Pretend that @text was typed in the Glk program as a response to a line input
1454  * request. @text does not need to end with a newline. You can call this 
1455  * function even when no window has requested line input, in which case the text
1456  * will be saved for the following window that requests line input. This has the 
1457  * disadvantage that if more than one window has requested line input, it is
1458  * arbitrary which one gets the text.
1459  */
1460 void 
1461 chimara_glk_feed_line_input(ChimaraGlk *glk, const gchar *text)
1462 {
1463         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1464         g_return_if_fail(text);
1465         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1466         g_async_queue_push(priv->line_input_queue, g_strdup(text));
1467         event_throw(glk, evtype_ForcedLineInput, NULL, 0, 0);
1468 }
1469
1470 /**
1471  * chimara_glk_is_char_input_pending:
1472  * @glk: a #ChimaraGlk widget
1473  *
1474  * Use this function to tell if character input forced by 
1475  * chimara_glk_feed_char_input() has been passed to an input request or not.
1476  *
1477  * Returns: %TRUE if forced character input is pending, %FALSE otherwise.
1478  */
1479 gboolean
1480 chimara_glk_is_char_input_pending(ChimaraGlk *glk)
1481 {
1482         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1483         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1484         return g_async_queue_length(priv->char_input_queue) > 0;
1485 }
1486
1487 /**
1488  * chimara_glk_is_line_input_pending:
1489  * @glk: a #ChimaraGlk widget
1490  *
1491  * Use this function to tell if line input forced by 
1492  * chimara_glk_feed_line_input() has been passed to an input request or not.
1493  *
1494  * Returns: %TRUE if forced line input is pending, %FALSE otherwise.
1495  */
1496 gboolean
1497 chimara_glk_is_line_input_pending(ChimaraGlk *glk)
1498 {
1499         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1500         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1501         return g_async_queue_length(priv->line_input_queue) > 0;
1502 }
1503
1504 /**
1505  * chimara_glk_get_tag:
1506  * @glk: a #ChimaraGlk widget
1507  * @window: The type of window to retrieve the tag for
1508  * @name: The name of the tag to retrieve
1509  *
1510  * Use this function to get a #GtkTextTag so style properties can be changed.
1511  * See also chimara_glk_set_css_from_string().
1512  *
1513  * The layout of the text in Chimara is controlled by two sets of tags: one set
1514  * describing the style in text buffers and one for text grids. See also the
1515  * Glk specification for the difference between the two. The main narrative of
1516  * a game is usually rendered in text buffers, whereas text grids are mostly
1517  * used for status bars and in game menus.
1518  *
1519  * The following tag names are supported:
1520  * <itemizedlist>
1521  *      <listitem><para>normal</para></listitem>
1522  *      <listitem><para>emphasized</para></listitem>
1523  *      <listitem><para>preformatted</para></listitem>
1524  *      <listitem><para>header</para></listitem>
1525  *      <listitem><para>subheader</para></listitem>
1526  *      <listitem><para>alert</para></listitem>
1527  *      <listitem><para>note</para></listitem>
1528  *      <listitem><para>block-quote</para></listitem>
1529  *      <listitem><para>input</para></listitem>
1530  *      <listitem><para>user1</para></listitem>
1531  *      <listitem><para>user2</para></listitem>
1532  *      <listitem><para>hyperlink</para></listitem>
1533  *      <listitem><para>pager</para></listitem>
1534  * </itemizedlist>
1535  *
1536  * Returns: (transfer none): The #GtkTextTag corresponding to @name in the
1537  * styles of @window.
1538  */
1539 GtkTextTag *
1540 chimara_glk_get_tag(ChimaraGlk *glk, ChimaraGlkWindowType window, const gchar *name)
1541 {
1542         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1543
1544         switch(window) {
1545         case CHIMARA_GLK_TEXT_BUFFER:
1546                 return GTK_TEXT_TAG( g_hash_table_lookup(priv->styles->text_buffer, name) );
1547                 break;
1548         case CHIMARA_GLK_TEXT_GRID:
1549                 return GTK_TEXT_TAG( g_hash_table_lookup(priv->styles->text_grid, name) );
1550                 break;
1551         default:
1552                 ILLEGAL_PARAM("Unknown window type: %u", window);
1553                 return NULL;
1554         }
1555 }
1556
1557 /**
1558  * chimara_glk_get_tag_names:
1559  * @glk: a #ChimaraGlk widget
1560  * @num_tags: Return location for the number of tag names retrieved.
1561  *
1562  * Retrieves the possible tag names to use in chimara_glk_get_tag().
1563  *
1564  * Returns: (transfer none) (array length=num_tags) (element-type utf8):
1565  * Array of strings containing the tag names. This array is owned by Chimara,
1566  * do not free it.
1567  */
1568 const gchar **
1569 chimara_glk_get_tag_names(ChimaraGlk *glk, unsigned int *num_tags)
1570 {
1571         g_return_val_if_fail(num_tags != NULL, NULL);
1572
1573         *num_tags = CHIMARA_NUM_STYLES;
1574         return style_get_tag_names();
1575 }
1576
1577 /**
1578  * chimara_glk_update_style:
1579  * @glk: a #ChimaraGlk widget
1580  *
1581  * Processes style updates and updates the widget to reflect the new style.
1582  * Call this every time you change a property of a #GtkTextTag retrieved by
1583  * chimara_glk_get_tag().
1584  */
1585 void
1586 chimara_glk_update_style(ChimaraGlk *glk)
1587 {
1588         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1589         style_update(glk);
1590
1591         /* Schedule a redraw */
1592         g_mutex_lock(priv->arrange_lock);
1593         priv->needs_rearrange = TRUE;
1594         priv->ignore_next_arrange_event = TRUE;
1595         g_mutex_unlock(priv->arrange_lock);
1596         gtk_widget_queue_resize( GTK_WIDGET(priv->self) );
1597 }
1598
1599 /**
1600  * chimara_glk_set_resource_load_callback:
1601  * @glk: a #ChimaraGlk widget
1602  * @func: a function to call for loading resources, or %NULL
1603  * @user_data: user data to pass to @func, or %NULL
1604  * @destroy_user_data: a function to call for freeing @user_data, or %NULL
1605  *
1606  * Sometimes it is preferable to load image and sound resources from somewhere
1607  * else than a Blorb file, for example while developing a game. Section 14 of
1608  * the <ulink url="http://eblong.com/zarf/blorb/blorb.html#s14">Blorb
1609  * specification</ulink> allows for this possibility. This function sets @func
1610  * to be called when the Glk program requests loading an image or sound without
1611  * a Blorb resource map having been loaded, optionally passing @user_data as an 
1612  * extra parameter.
1613  *
1614  * Note that @func is only called if no Blorb resource map has been set; having
1615  * a resource map in place overrides this function.
1616  *
1617  * If you pass non-%NULL for @destroy_user_data, then @glk takes ownership of
1618  * @user_data. When it is not needed anymore, it will be freed by calling
1619  * @destroy_user_data on it. If you wish to retain ownership of @user_data, pass
1620  * %NULL for @destroy_user_data.
1621  *
1622  * To deactivate the callback, call this function with @func set to %NULL.
1623  */
1624 void
1625 chimara_glk_set_resource_load_callback(ChimaraGlk *glk, ChimaraResourceLoadFunc func, gpointer user_data, GDestroyNotify destroy_user_data)
1626 {
1627         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1628
1629         if(priv->resource_load_callback == func
1630                 && priv->resource_load_callback_data == user_data
1631                 && priv->resource_load_callback_destroy_data == destroy_user_data)
1632                 return;
1633
1634         if(priv->resource_load_callback_destroy_data)
1635                 priv->resource_load_callback_destroy_data(priv->resource_load_callback_data);
1636
1637         priv->resource_load_callback = func;
1638         priv->resource_load_callback_data = user_data;
1639         priv->resource_load_callback_destroy_data = destroy_user_data;
1640 }