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