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