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