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