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