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