Iliad port
[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 /* COMPAT: G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
621 #ifndef G_PARAM_STATIC_STRINGS
622
623 /* COMPAT: G_PARAM_STATIC_NAME and friends only appeared in GTK 2.8 */
624 #if GTK_CHECK_VERSION(2,8,0)
625 #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
626 #else
627 #define G_PARAM_STATIC_STRINGS (0)
628 #endif
629
630 #endif
631
632 static void
633 chimara_glk_class_init(ChimaraGlkClass *klass)
634 {
635     /* Override methods of parent classes */
636     GObjectClass *object_class = G_OBJECT_CLASS(klass);
637     object_class->set_property = chimara_glk_set_property;
638     object_class->get_property = chimara_glk_get_property;
639     object_class->finalize = chimara_glk_finalize;
640     
641     GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
642     widget_class->size_request = chimara_glk_size_request;
643     widget_class->size_allocate = chimara_glk_size_allocate;
644
645     GtkContainerClass *container_class = GTK_CONTAINER_CLASS(klass);
646     container_class->forall = chimara_glk_forall;
647
648     /* Signals */
649     klass->stopped = chimara_glk_stopped;
650     klass->started = chimara_glk_started;
651     klass->waiting = chimara_glk_waiting;
652     klass->char_input = chimara_glk_char_input;
653     klass->line_input = chimara_glk_line_input;
654     klass->text_buffer_output = chimara_glk_text_buffer_output;
655     /**
656      * ChimaraGlk::stopped:
657      * @glk: The widget that received the signal
658      *
659      * Emitted when the a Glk program finishes executing in the widget, whether
660      * it ended normally, or was interrupted.
661      */ 
662     chimara_glk_signals[STOPPED] = g_signal_new("stopped", 
663         G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST, 
664         /* FIXME: Should be G_SIGNAL_RUN_CLEANUP but that segfaults??! */
665         G_STRUCT_OFFSET(ChimaraGlkClass, stopped), NULL, NULL,
666                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
667         /**
668          * ChimaraGlk::started:
669          * @glk: The widget that received the signal
670          *
671          * Emitted when a Glk program starts executing in the widget.
672          */
673         chimara_glk_signals[STARTED] = g_signal_new ("started",
674                 G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST,
675                 G_STRUCT_OFFSET(ChimaraGlkClass, started), NULL, NULL,
676                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
677         /**
678          * ChimaraGlk::waiting:
679          * @glk: The widget that received the signal
680          * 
681          * Emitted when glk_select() is called by the Glk program and the event
682          * queue is empty, which means that the widget is waiting for input.
683          */
684         chimara_glk_signals[WAITING] = g_signal_new("waiting",
685                 G_OBJECT_CLASS_TYPE(klass), 0,
686                 G_STRUCT_OFFSET(ChimaraGlkClass, waiting), NULL, NULL,
687                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
688         /**
689          * ChimaraGlk::char-input:
690          * @glk: The widget that received the signal
691          * @window_rock: The rock value of the window that received character input
692          * (see <link linkend="chimara-Rocks">Rocks</link>)
693          * @keysym: The key that was typed, in the form of a key symbol from 
694          * <filename class="headerfile">gdk/gdkkeysyms.h</filename>
695          * 
696          * Emitted when a Glk window receives character input.
697          */
698         chimara_glk_signals[CHAR_INPUT] = g_signal_new("char-input",
699                 G_OBJECT_CLASS_TYPE(klass), 0,
700                 G_STRUCT_OFFSET(ChimaraGlkClass, char_input), NULL, NULL,
701                 chimara_marshal_VOID__UINT_UINT,
702                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
703         /**
704          * ChimaraGlk::line-input:
705          * @glk: The widget that received the signal
706          * @window_rock: The rock value of the window that received line input (see
707          * <link linkend="chimara-Rocks">Rocks</link>)
708          * @text: The text that was typed
709          * 
710          * Emitted when a Glk window receives line input.
711          */
712         chimara_glk_signals[LINE_INPUT] = g_signal_new("line-input",
713                 G_OBJECT_CLASS_TYPE(klass), 0,
714                 G_STRUCT_OFFSET(ChimaraGlkClass, line_input), NULL, NULL,
715                 chimara_marshal_VOID__UINT_STRING,
716                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
717         /**
718          * ChimaraGlk::text-buffer-output:
719          * @glk: The widget that received the signal
720          * @window_rock: The rock value of the window that was printed to (see <link
721          * linkend="chimara-Rocks">Rocks</link>)
722          * 
723          * Emitted when text is printed to a text buffer window.
724          */
725         chimara_glk_signals[TEXT_BUFFER_OUTPUT] = g_signal_new("text-buffer-output",
726                 G_OBJECT_CLASS_TYPE(klass), 0,
727                 G_STRUCT_OFFSET(ChimaraGlkClass, text_buffer_output), NULL, NULL,
728                 chimara_marshal_VOID__UINT_STRING,
729                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
730
731     /* Properties */
732     /**
733      * ChimaraGlk:interactive:
734      *
735      * Sets whether the widget is interactive. A Glk widget is normally 
736      * interactive, but in non-interactive mode, keyboard and mouse input are 
737      * ignored and the Glk program is controlled by chimara_glk_feed_text(). 
738      * <quote>More</quote> prompts when a lot of text is printed to a text 
739          * buffer are also disabled. This is typically used when you wish to control
740          * an interpreter program by feeding it a predefined list of commands.
741      */
742     g_object_class_install_property( object_class, PROP_INTERACTIVE, 
743                 g_param_spec_boolean("interactive", _("Interactive"),
744         _("Whether user input is expected in the Glk program"),
745         TRUE,
746         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
747
748         /**
749      * ChimaraGlk:protect:
750      *
751      * Sets whether the Glk program is allowed to do file operations. In protect
752      * mode, all file operations will fail.
753      */
754     g_object_class_install_property(object_class, PROP_PROTECT, 
755                 g_param_spec_boolean("protect", _("Protected"),
756         _("Whether the Glk program is barred from doing file operations"),
757         FALSE,
758         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
759
760         /* We can't use G_PARAM_CONSTRUCT on these because then the constructor will
761          initialize them with NULL */
762         /**
763          * ChimaraGlk:default-font-description:
764          * 
765          * Pointer to a #PangoFontDescription describing the default proportional 
766          * font, to be used in text buffer windows for example.
767          *
768          * Default value: font description created from the string 
769          * <quote>Sans</quote>
770          */
771         g_object_class_install_property(object_class, PROP_DEFAULT_FONT_DESCRIPTION, 
772                 g_param_spec_pointer("default-font-description", _("Default Font"),
773                 _("Font description of the default proportional font"),
774                 G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
775
776         /**
777          * ChimaraGlk:monospace-font-description:
778          *
779          * Pointer to a #PangoFontDescription describing the default monospace font,
780          * to be used in text grid windows and %style_Preformatted, for example.
781          *
782          * Default value: font description created from the string 
783          * <quote>Monospace</quote>
784          */
785         g_object_class_install_property(object_class, PROP_MONOSPACE_FONT_DESCRIPTION, 
786                 g_param_spec_pointer("monospace-font-description", _("Monospace Font"),
787                 _("Font description of the default monospace font"),
788                 G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
789
790         /**
791          * ChimaraGlk:spacing:
792          *
793          * The amount of space between the Glk windows.
794          */
795         g_object_class_install_property(object_class, PROP_SPACING,
796                 g_param_spec_uint("spacing", _("Spacing"),
797                 _("The amount of space between Glk windows"),
798                 0, G_MAXUINT, 0,
799                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
800         
801     /* Private data */
802     g_type_class_add_private(klass, sizeof(ChimaraGlkPrivate));
803 }
804
805 /* PUBLIC FUNCTIONS */
806
807 /**
808  * chimara_error_quark:
809  *
810  * The error domain for errors from Chimara widgets.
811  *
812  * Returns: The string <quote>chimara-error-quark</quote> as a <link 
813  * linkend="GQuark">GQuark</link>.
814  */
815 GQuark
816 chimara_error_quark(void)
817 {
818         chimara_init(); /* This is a library entry point */
819         return g_quark_from_static_string("chimara-error-quark");
820 }
821
822 /**
823  * chimara_glk_new:
824  *
825  * Creates and initializes a new #ChimaraGlk widget.
826  *
827  * Return value: a #ChimaraGlk widget, with a floating reference.
828  */
829 GtkWidget *
830 chimara_glk_new(void)
831 {
832         /* This is a library entry point; initialize the library */
833         chimara_init();
834
835     return GTK_WIDGET(g_object_new(CHIMARA_TYPE_GLK, NULL));
836 }
837
838 /**
839  * chimara_glk_set_interactive:
840  * @glk: a #ChimaraGlk widget
841  * @interactive: whether the widget should expect user input
842  *
843  * Sets the #ChimaraGlk:interactive property of @glk. 
844  */
845 void 
846 chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
847 {
848     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
849     
850     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
851     priv->interactive = interactive;
852     g_object_notify(G_OBJECT(glk), "interactive");
853 }
854
855 /**
856  * chimara_glk_get_interactive:
857  * @glk: a #ChimaraGlk widget
858  *
859  * Returns whether @glk is interactive (expecting user input). See 
860  * #ChimaraGlk:interactive.
861  *
862  * Return value: %TRUE if @glk is interactive.
863  */
864 gboolean 
865 chimara_glk_get_interactive(ChimaraGlk *glk)
866 {
867     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
868     
869     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
870     return priv->interactive;
871 }
872
873 /**
874  * chimara_glk_set_protect:
875  * @glk: a #ChimaraGlk widget
876  * @protect: whether the widget should allow the Glk program to do file 
877  * operations
878  *
879  * Sets the #ChimaraGlk:protect property of @glk. In protect mode, the Glk 
880  * program is not allowed to do file operations.
881  */
882 void 
883 chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
884 {
885     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
886     
887     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
888     priv->protect = protect;
889     g_object_notify(G_OBJECT(glk), "protect");
890 }
891
892 /**
893  * chimara_glk_get_protect:
894  * @glk: a #ChimaraGlk widget
895  *
896  * Returns whether @glk is in protect mode (banned from doing file operations).
897  * See #ChimaraGlk:protect.
898  *
899  * Return value: %TRUE if @glk is in protect mode.
900  */
901 gboolean 
902 chimara_glk_get_protect(ChimaraGlk *glk)
903 {
904     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
905     
906     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
907     return priv->protect;
908 }
909
910 /**
911  * chimara_glk_set_default_font_description:
912  * @glk: a #ChimaraGlk widget
913  * @font: a #PangoFontDescription
914  *
915  * Sets @glk's default proportional font. See 
916  * #ChimaraGlk:default-font-description.
917  */
918 void 
919 chimara_glk_set_default_font_description(ChimaraGlk *glk, PangoFontDescription *font)
920 {
921         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
922         g_return_if_fail(font);
923         
924         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
925         pango_font_description_free(priv->default_font_desc);
926         priv->default_font_desc = pango_font_description_copy(font);
927         g_object_notify(G_OBJECT(glk), "default-font-description");
928         /* TODO: Apply the font description to all the windows and recalculate the sizes */
929 }
930
931 /**
932  * chimara_glk_set_default_font_string:
933  * @glk: a #ChimaraGlk widget
934  * @font: string representation of a font description
935  *
936  * Sets @glk's default proportional font according to the string @font, which
937  * must be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
938  * [<replaceable>STYLE-OPTIONS</replaceable>] 
939  * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Charter,Utopia 
940  * Italic 12</quote> or <quote>Sans</quote>. See 
941  * #ChimaraGlk:default-font-description.
942  */
943 void 
944 chimara_glk_set_default_font_string(ChimaraGlk *glk, const gchar *font)
945 {
946         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
947         g_return_if_fail(font || *font);
948         
949         PangoFontDescription *fontdesc = pango_font_description_from_string(font);
950         g_return_if_fail(fontdesc);
951         
952         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
953         pango_font_description_free(priv->default_font_desc);
954         priv->default_font_desc = fontdesc;
955         g_object_notify(G_OBJECT(glk), "default-font-description");
956         
957         /* TODO: Apply the font description to all the windows and recalculate the sizes */
958 }
959         
960 /**
961  * chimara_glk_get_default_font_description:
962  * @glk: a #ChimaraGlk widget
963  * 
964  * Returns @glk's default proportional font.
965  *
966  * Return value: a newly-allocated #PangoFontDescription which must be freed
967  * using pango_font_description_free(), or %NULL on error.
968  */
969 PangoFontDescription *
970 chimara_glk_get_default_font_description(ChimaraGlk *glk)
971 {
972         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
973         
974         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
975         return pango_font_description_copy(priv->default_font_desc);
976 }
977
978 /**
979  * chimara_glk_set_monospace_font_description:
980  * @glk: a #ChimaraGlk widget
981  * @font: a #PangoFontDescription
982  *
983  * Sets @glk's default monospace font. See 
984  * #ChimaraGlk:monospace-font-description.
985  */
986 void 
987 chimara_glk_set_monospace_font_description(ChimaraGlk *glk, PangoFontDescription *font)
988 {
989         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
990         g_return_if_fail(font);
991         
992         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
993         pango_font_description_free(priv->monospace_font_desc);
994         priv->monospace_font_desc = pango_font_description_copy(font);
995         g_object_notify(G_OBJECT(glk), "monospace-font-description");
996         
997         /* TODO: Apply the font description to all the windows and recalculate the sizes */
998 }
999
1000 /**
1001  * chimara_glk_set_monospace_font_string:
1002  * @glk: a #ChimaraGlk widget
1003  * @font: string representation of a font description
1004  *
1005  * Sets @glk's default monospace font according to the string @font, which must
1006  * be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
1007  * [<replaceable>STYLE-OPTIONS</replaceable>] 
1008  * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Courier 
1009  * Bold 12</quote> or <quote>Monospace</quote>. See 
1010  * #ChimaraGlk:monospace-font-description.
1011  */
1012 void 
1013 chimara_glk_set_monospace_font_string(ChimaraGlk *glk, const gchar *font)
1014 {
1015         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1016         g_return_if_fail(font || *font);
1017         
1018         PangoFontDescription *fontdesc = pango_font_description_from_string(font);
1019         g_return_if_fail(fontdesc);
1020         
1021         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1022         pango_font_description_free(priv->monospace_font_desc);
1023         priv->monospace_font_desc = fontdesc;
1024         g_object_notify(G_OBJECT(glk), "monospace-font-description");
1025         
1026         /* TODO: Apply the font description to all the windows and recalculate the sizes */
1027 }
1028         
1029 /**
1030  * chimara_glk_get_monospace_font_description:
1031  * @glk: a #ChimaraGlk widget
1032  * 
1033  * Returns @glk's default monospace font.
1034  *
1035  * Return value: a newly-allocated #PangoFontDescription which must be freed
1036  * using pango_font_description_free(), or %NULL on error.
1037  */
1038 PangoFontDescription *
1039 chimara_glk_get_monospace_font_description(ChimaraGlk *glk)
1040 {
1041         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
1042         
1043         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1044         return pango_font_description_copy(priv->monospace_font_desc);
1045 }
1046
1047 /**
1048  * chimara_glk_set_spacing:
1049  * @glk: a #ChimaraGlk widget
1050  * @spacing: the number of pixels to put between Glk windows
1051  *
1052  * Sets the #ChimaraGlk:spacing property of @glk, which is the border width in
1053  * pixels between Glk windows.
1054  */
1055 void 
1056 chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
1057 {
1058         g_return_if_fail( glk || CHIMARA_IS_GLK(glk) );
1059         
1060         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1061         priv->spacing = spacing;
1062         g_object_notify(G_OBJECT(glk), "spacing");
1063 }
1064
1065 /**
1066  * chimara_glk_get_spacing:
1067  * @glk: a #ChimaraGlk widget
1068  *
1069  * Gets the value set by chimara_glk_set_spacing().
1070  *
1071  * Return value: pixels of spacing between Glk windows
1072  */
1073 guint 
1074 chimara_glk_get_spacing(ChimaraGlk *glk)
1075 {
1076         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), 0);
1077         
1078         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1079         return priv->spacing;
1080 }
1081
1082 struct StartupData {
1083         glk_main_t glk_main;
1084         glkunix_startup_code_t glkunix_startup_code;
1085         glkunix_startup_t args;
1086         ChimaraGlkPrivate *glk_data;
1087 };
1088
1089 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
1090 static gpointer
1091 glk_enter(struct StartupData *startup)
1092 {
1093         extern GPrivate *glk_data_key;
1094         g_private_set(glk_data_key, startup->glk_data);
1095         
1096         /* Acquire the Glk thread's references to the input queues */
1097         g_async_queue_ref(startup->glk_data->char_input_queue);
1098         g_async_queue_ref(startup->glk_data->line_input_queue);
1099         
1100         /* Run startup function */
1101         if(startup->glkunix_startup_code) {
1102                 startup->glk_data->in_startup = TRUE;
1103                 int result = startup->glkunix_startup_code(&startup->args);
1104                 startup->glk_data->in_startup = FALSE;
1105                 
1106                 int i = 0;
1107                 while(i < startup->args.argc)
1108                         g_free(startup->args.argv[i++]);
1109                 g_free(startup->args.argv);
1110                 
1111                 if(!result)
1112                         return NULL;
1113         }
1114         
1115         /* Run main function */
1116         glk_main_t glk_main = startup->glk_main;
1117         
1118         /* COMPAT: avoid usage of slices */
1119         g_free(startup);
1120     g_signal_emit_by_name(startup->glk_data->self, "started");
1121         glk_main();
1122         glk_exit(); /* Run shutdown code in glk_exit() even if glk_main() returns normally */
1123         g_assert_not_reached(); /* because glk_exit() calls g_thread_exit() */
1124         return NULL; 
1125 }
1126
1127 /**
1128  * chimara_glk_run:
1129  * @glk: a #ChimaraGlk widget
1130  * @plugin: path to a plugin module compiled with <filename 
1131  * class="header">glk.h</filename>
1132  * @argc: Number of command line arguments in @argv
1133  * @argv: Array of command line arguments to pass to the plugin
1134  * @error: location to store a <link linkend="glib-GError">GError</link>, or 
1135  * %NULL
1136  *
1137  * Opens a Glk program compiled as a plugin. Sorts out its command line
1138  * arguments from #glkunix_arguments, calls its startup function
1139  * glkunix_startup_code(), and then calls its main function glk_main() in
1140  * a separate thread. On failure, returns %FALSE and sets @error.
1141  *
1142  * The plugin must at least export a glk_main() function; #glkunix_arguments and
1143  * glkunix_startup_code() are optional.
1144  *
1145  * Return value: %TRUE if the Glk program was started successfully.
1146  */
1147 gboolean
1148 chimara_glk_run(ChimaraGlk *glk, const gchar *plugin, int argc, char *argv[], GError **error)
1149 {
1150     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1151     g_return_val_if_fail(plugin, FALSE);
1152         if(chimara_glk_get_running(glk)) {
1153                 g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_ALREADY_RUNNING, _("There was already a plugin running."));
1154                 return FALSE;
1155         }
1156     
1157     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1158
1159         /* COMPAT: avoid usage of slices */
1160         struct StartupData *startup = g_new0(struct StartupData,1);
1161         
1162     /* Open the module to run */
1163     g_assert( g_module_supported() );
1164     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
1165     
1166     if(!priv->program)
1167     {
1168         g_set_error(error, CHIMARA_ERROR, CHIMARA_LOAD_MODULE_ERROR, _("Error opening module: %s"), g_module_error());
1169         return FALSE;
1170     }
1171     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
1172     {
1173         g_set_error(error, CHIMARA_ERROR, CHIMARA_NO_GLK_MAIN, _("Error finding glk_main(): %s"), g_module_error());
1174         return FALSE;
1175     }
1176
1177     if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
1178     {
1179                 glkunix_argumentlist_t *glkunix_arguments;
1180
1181                 if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
1182                           && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
1183                 {
1184                         /* arguments could not be parsed, so create data ourselves */
1185                         startup->args.argc = 1;
1186                         startup->args.argv = g_new0(gchar *, 1);
1187                 }
1188
1189                 /* Set the program name */
1190                 startup->args.argv[0] = g_strdup(plugin);
1191     }
1192         startup->glk_data = priv;
1193         
1194     /* Run in a separate thread */
1195         priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
1196         
1197         return !(priv->thread == NULL);
1198 }
1199
1200 /**
1201  * chimara_glk_stop:
1202  * @glk: a #ChimaraGlk widget
1203  *
1204  * Signals the Glk program running in @glk to abort. Note that if the program is
1205  * caught in an infinite loop in which glk_tick() is not called, this may not
1206  * work.
1207  */
1208 void
1209 chimara_glk_stop(ChimaraGlk *glk)
1210 {
1211     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1212     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1213
1214     /* Don't do anything if not running a program */
1215     if(!priv->running)
1216         return;
1217     
1218         if(priv->abort_lock) {
1219                 g_mutex_lock(priv->abort_lock);
1220                 priv->abort_signalled = TRUE;
1221                 g_mutex_unlock(priv->abort_lock);
1222                 /* Stop blocking on the event queue condition */
1223                 event_throw(glk, evtype_Abort, NULL, 0, 0);
1224                 /* Stop blocking on the shutdown key press condition */
1225                 g_mutex_lock(priv->shutdown_lock);
1226                 g_cond_signal(priv->shutdown_key_pressed);
1227                 g_mutex_unlock(priv->shutdown_lock);
1228         }
1229 }
1230
1231 /**
1232  * chimara_glk_wait:
1233  * @glk: a #ChimaraGlk widget
1234  *
1235  * Holds up the main thread and waits for the Glk program running in @glk to 
1236  * finish.
1237  */
1238 void
1239 chimara_glk_wait(ChimaraGlk *glk)
1240 {
1241     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1242     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1243     /* Don't do anything if not running a program */
1244     if(!priv->running)
1245         return;
1246         /* Unlock GDK mutex, because the Glk program might need to use it for shutdown */
1247         gdk_threads_leave();
1248     g_thread_join(priv->thread);
1249         gdk_threads_enter();
1250 }
1251
1252 /**
1253  * chimara_glk_get_running:
1254  * @glk: a #ChimaraGlk widget
1255  * 
1256  * Use this function to tell whether a program is currently running in the
1257  * widget.
1258  * 
1259  * Returns: %TRUE if @glk is executing a Glk program, %FALSE otherwise.
1260  */
1261 gboolean
1262 chimara_glk_get_running(ChimaraGlk *glk)
1263 {
1264         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1265         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1266         return priv->running;
1267 }
1268
1269 /**
1270  * chimara_glk_feed_char_input:
1271  * @glk: a #ChimaraGlk widget
1272  * @keyval: a key symbol as defined in <filename 
1273  * class="headerfile">gdk/gdkkeysyms.h</filename>
1274  * 
1275  * Pretend that a key was pressed in the Glk program as a response to a 
1276  * character input request. You can call this function even when no window has
1277  * requested character input, in which case the key will be saved for the 
1278  * following window that requests character input. This has the disadvantage 
1279  * that if more than one window has requested character input, it is arbitrary 
1280  * which one gets the key press.
1281  */
1282 void 
1283 chimara_glk_feed_char_input(ChimaraGlk *glk, guint keyval)
1284 {
1285         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1286         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1287         g_async_queue_push(priv->char_input_queue, GUINT_TO_POINTER(keyval));
1288         event_throw(glk, evtype_ForcedCharInput, NULL, 0, 0);
1289 }
1290
1291 /**
1292  * chimara_glk_feed_line_input:
1293  * @glk: a #ChimaraGlk widget
1294  * @text: text to pass to the next line input request
1295  * 
1296  * Pretend that @text was typed in the Glk program as a response to a line input
1297  * request. @text does not need to end with a newline. You can call this 
1298  * function even when no window has requested line input, in which case the text
1299  * will be saved for the following window that requests line input. This has the 
1300  * disadvantage that if more than one window has requested character input, it 
1301  * is arbitrary which one gets the text.
1302  */
1303 void 
1304 chimara_glk_feed_line_input(ChimaraGlk *glk, const gchar *text)
1305 {
1306         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1307         g_return_if_fail(text);
1308         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1309         g_async_queue_push(priv->line_input_queue, g_strdup(text));
1310         event_throw(glk, evtype_ForcedLineInput, NULL, 0, 0);
1311 }