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