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