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