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