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