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