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