Added a browser view with fake library data
[projects/chimara/chimara.git] / libchimara / chimara-glk.c
1 /* licensing and copyright information here */
2
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <fcntl.h>
6 #include <unistd.h>
7 #include <errno.h>
8 #include <math.h>
9 #include <gtk/gtk.h>
10 #include <config.h>
11 #include <glib/gi18n-lib.h>
12 #include <gmodule.h>
13 #include <pango/pango.h>
14 #include <gio/gio.h>
15 #include "chimara-glk.h"
16 #include "chimara-glk-private.h"
17 #include "chimara-marshallers.h"
18 #include "glk.h"
19 #include "abort.h"
20 #include "stream.h"
21 #include "window.h"
22 #include "glkstart.h"
23 #include "glkunix.h"
24 #include "init.h"
25 #include "magic.h"
26 #include "style.h"
27
28 #define CHIMARA_GLK_MIN_WIDTH 0
29 #define CHIMARA_GLK_MIN_HEIGHT 0
30
31 /* Substitute functions for compiling on iLiad */
32
33 #if !GTK_CHECK_VERSION(2, 18, 0)
34 #define gtk_widget_get_allocation(w, a) \
35         G_STMT_START { \
36                 (a)->x = (w)->allocation.x; \
37                 (a)->y = (w)->allocation.y; \
38                 (a)->width = (w)->allocation.width; \
39                 (a)->height = (w)->allocation.height; \
40         } G_STMT_END
41 #define gtk_widget_set_allocation(w, a) \
42         G_STMT_START { (w)->allocation = *(a); } G_STMT_END
43 #define gtk_widget_set_has_window(w, f) \
44         G_STMT_START { \
45                 if(f) \
46                         GTK_WIDGET_UNSET_FLAGS((w), GTK_NO_WINDOW); \
47                 else \
48                         GTK_WIDGET_SET_FLAGS((w), GTK_NO_WINDOW); \
49         } G_STMT_END
50 #endif /* GTK 2.18 */
51
52 /**
53  * SECTION:chimara-glk
54  * @short_description: Widget which executes a Glk program
55  * @stability: Unstable
56  * 
57  * The #ChimaraGlk widget opens and runs a Glk program. The program must be
58  * compiled as a plugin module, with a function <function>glk_main()</function>
59  * that the Glk library can hook into.
60  *
61  * On Linux systems, this is a file with a name like 
62  * <filename>plugin.so</filename>. For portability, you can use libtool and 
63  * automake:
64  * |[
65  * pkglib_LTLIBRARIES = plugin.la
66  * plugin_la_SOURCES = plugin.c foo.c bar.c
67  * plugin_la_LDFLAGS = -module -shared -avoid-version -export-symbols-regex "^glk_main$$"
68  * ]|
69  * This will produce <filename>plugin.la</filename> which is a text file 
70  * containing the correct plugin file to open (see the relevant section of the
71  * <ulink 
72  * url="http://www.gnu.org/software/libtool/manual/html_node/Finding-the-dlname.html">
73  * Libtool manual</ulink>).
74  *
75  * You need to initialize multithreading in any program you use a #ChimaraGlk
76  * widget in. This means including the following incantation at the beginning
77  * of your program:
78  * |[
79  * if(!g_thread_supported())
80  *     g_thread_init(NULL);
81  * gdk_threads_init();
82  * ]|
83  * This initialization must take place <emphasis>before</emphasis> the call to
84  * gtk_init(). In addition to this, you must also protect your call to 
85  * gtk_main() by calling gdk_threads_enter() right before it, and 
86  * gdk_threads_leave() right after it.
87  *
88  * The following sample program shows how to initialize and construct a simple 
89  * GTK window that runs a Glk program:
90  * |[
91  * #include <glib.h>
92  * #include <gtk/gtk.h>
93  * #include <libchimara/chimara-glk.h>
94  *
95  * int
96  * main(int argc, char *argv[])
97  * {
98  *     GtkWidget *window, *glk;
99  *     GError *error = NULL;
100  *     gchar *plugin_argv[] = { "plugin.so", "-option" };
101  *
102  *     /<!---->* Initialize threads and GTK *<!---->/
103  *     if(!g_thread_supported())
104  *         g_thread_init(NULL);
105  *     gdk_threads_init();
106  *     gtk_init(&argc, &argv);
107  *     
108  *     /<!---->* Construct the window and its contents. We quit the GTK main loop
109  *      * when the window's close button is clicked. *<!---->/
110  *     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
111  *     g_signal_connect(window, "delete-event", G_CALLBACK(gtk_main_quit), NULL);
112  *     glk = chimara_glk_new();
113  *     gtk_container_add(GTK_CONTAINER(window), glk);
114  *     gtk_widget_show_all(window);
115  *
116  *     /<!---->* Add a reference to the ChimaraGlk widget, since we want it to
117  *      * persist after the window's delete-event -- otherwise it will be destroyed
118  *      * with the window. *<!---->/
119  *     g_object_ref(glk);
120  *     
121  *     /<!---->* Start the Glk program in a separate thread *<!---->/
122  *     if(!chimara_glk_run(CHIMARA_GLK(glk), "./plugin.so", 2, plugin_argv, &error))
123  *         g_error("Error starting Glk library: %s\n", error->message);
124  *     
125  *     /<!---->* Start the GTK main loop *<!---->/
126  *     gdk_threads_enter();
127  *     gtk_main();
128  *     gdk_threads_leave();
129  *
130  *     /<!---->* After the GTK main loop exits, signal the Glk program to shut down if
131  *      * it is still running, and wait for it to exit. *<!---->/
132  *     chimara_glk_stop(CHIMARA_GLK(glk));
133  *     chimara_glk_wait(CHIMARA_GLK(glk));
134  *     g_object_unref(glk);
135  *
136  *     return 0;
137  * }
138  * ]|
139  */
140
141 typedef void (* glk_main_t) (void);
142 typedef int (* glkunix_startup_code_t) (glkunix_startup_t*);
143
144 enum {
145     PROP_0,
146     PROP_INTERACTIVE,
147     PROP_PROTECT,
148         PROP_SPACING,
149         PROP_PROGRAM_NAME,
150         PROP_PROGRAM_INFO,
151         PROP_STORY_NAME
152 };
153
154 enum {
155         STOPPED,
156         STARTED,
157         WAITING,
158         CHAR_INPUT,
159         LINE_INPUT,
160         TEXT_BUFFER_OUTPUT,
161         ILIAD_SCREEN_UPDATE,
162
163         LAST_SIGNAL
164 };
165
166 static guint chimara_glk_signals[LAST_SIGNAL] = { 0 };
167
168 G_DEFINE_TYPE(ChimaraGlk, chimara_glk, GTK_TYPE_CONTAINER);
169
170 static void
171 chimara_glk_init(ChimaraGlk *self)
172 {
173     gtk_widget_set_has_window(GTK_WIDGET(self), FALSE);
174
175     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
176     
177     priv->self = self;
178     priv->interactive = TRUE;
179     priv->protect = FALSE;
180         priv->styles = g_new0(StyleSet,1);
181         priv->glk_styles = g_new0(StyleSet,1);
182         priv->pager_attr_list = pango_attr_list_new();
183         priv->final_message = g_strdup("[ The game has finished ]");
184         priv->running = FALSE;
185     priv->program = NULL;
186     priv->thread = NULL;
187     priv->event_queue = g_queue_new();
188     priv->event_lock = g_mutex_new();
189     priv->event_queue_not_empty = g_cond_new();
190     priv->event_queue_not_full = g_cond_new();
191     priv->abort_lock = g_mutex_new();
192     priv->abort_signalled = FALSE;
193         priv->shutdown_lock = g_mutex_new();
194         priv->shutdown_key_pressed = g_cond_new();
195         priv->arrange_lock = g_mutex_new();
196         priv->rearranged = g_cond_new();
197         priv->needs_rearrange = FALSE;
198         priv->ignore_next_arrange_event = FALSE;
199         priv->char_input_queue = g_async_queue_new();
200         priv->line_input_queue = g_async_queue_new();
201         /* FIXME Should be g_async_queue_new_full(g_free); but only in GTK >= 2.16 */
202         priv->resource_map = NULL;
203         priv->resource_lock = g_mutex_new();
204         priv->resource_loaded = g_cond_new();
205         priv->resource_info_available = g_cond_new();
206         priv->resource_load_callback = NULL;
207         priv->resource_load_callback_data = NULL;
208         priv->image_cache = NULL;
209         priv->program_name = NULL;
210         priv->program_info = NULL;
211         priv->story_name = NULL;
212         priv->interrupt_handler = NULL;
213     priv->root_window = NULL;
214     priv->fileref_list = NULL;
215     priv->current_stream = NULL;
216     priv->stream_list = NULL;
217         priv->timer_id = 0;
218         priv->in_startup = FALSE;
219         priv->current_dir = NULL;
220
221         style_init(self);
222 }
223
224 static void
225 chimara_glk_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
226 {
227     ChimaraGlk *glk = CHIMARA_GLK(object);
228     
229     switch(prop_id) 
230     {
231         case PROP_INTERACTIVE:
232             chimara_glk_set_interactive( glk, g_value_get_boolean(value) );
233             break;
234         case PROP_PROTECT:
235             chimara_glk_set_protect( glk, g_value_get_boolean(value) );
236             break;
237                 case PROP_SPACING:
238                         chimara_glk_set_spacing( glk, g_value_get_uint(value) );
239                         break;
240         default:
241             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
242     }
243 }
244
245 static void
246 chimara_glk_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
247 {
248     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(object);
249     
250     switch(prop_id)
251     {
252         case PROP_INTERACTIVE:
253             g_value_set_boolean(value, priv->interactive);
254             break;
255         case PROP_PROTECT:
256             g_value_set_boolean(value, priv->protect);
257             break;
258                 case PROP_SPACING:
259                         g_value_set_uint(value, priv->spacing);
260                         break;
261                 case PROP_PROGRAM_NAME:
262                         g_value_set_string(value, priv->program_name);
263                         break;
264                 case PROP_PROGRAM_INFO:
265                         g_value_set_string(value, priv->program_info);
266                         break;
267                 case PROP_STORY_NAME:
268                         g_value_set_string(value, priv->story_name);
269                         break;
270                 default:
271             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
272     }
273 }
274
275 static void
276 chimara_glk_finalize(GObject *object)
277 {
278     ChimaraGlk *self = CHIMARA_GLK(object);
279         CHIMARA_GLK_USE_PRIVATE(self, priv);
280
281         /* Free widget properties */
282         g_free(priv->final_message);
283         /* Free styles */
284         g_hash_table_destroy(priv->styles->text_buffer);
285         g_hash_table_destroy(priv->styles->text_grid);
286         g_hash_table_destroy(priv->glk_styles->text_buffer);
287         g_hash_table_destroy(priv->glk_styles->text_grid);
288         pango_attr_list_unref(priv->pager_attr_list);
289         
290     /* Free the event queue */
291     g_mutex_lock(priv->event_lock);
292         g_queue_foreach(priv->event_queue, (GFunc)g_free, NULL);
293         g_queue_free(priv->event_queue);
294         g_cond_free(priv->event_queue_not_empty);
295         g_cond_free(priv->event_queue_not_full);
296         priv->event_queue = NULL;
297         g_mutex_unlock(priv->event_lock);
298         g_mutex_free(priv->event_lock);
299     /* Free the abort signaling mechanism */
300         g_mutex_lock(priv->abort_lock);
301         /* Make sure no other thread is busy with this */
302         g_mutex_unlock(priv->abort_lock);
303         g_mutex_free(priv->abort_lock);
304         priv->abort_lock = NULL;
305         /* Free the shutdown keypress signaling mechanism */
306         g_mutex_lock(priv->shutdown_lock);
307         g_cond_free(priv->shutdown_key_pressed);
308         g_mutex_unlock(priv->shutdown_lock);
309         priv->shutdown_lock = NULL;
310         /* Free the window arrangement signaling */
311         g_mutex_lock(priv->arrange_lock);
312         g_cond_free(priv->rearranged);
313         g_mutex_unlock(priv->arrange_lock);
314         g_mutex_free(priv->arrange_lock);
315         priv->arrange_lock = NULL;
316         g_mutex_lock(priv->resource_lock);
317         g_cond_free(priv->resource_loaded);
318         g_cond_free(priv->resource_info_available);
319         g_mutex_unlock(priv->resource_lock);
320         g_mutex_free(priv->resource_lock);
321         g_slist_foreach(priv->image_cache, (GFunc)clear_image_cache, NULL);
322         g_slist_free(priv->image_cache);
323         /* Unref input queues (this should destroy them since any Glk thread has stopped by now */
324         g_async_queue_unref(priv->char_input_queue);
325         g_async_queue_unref(priv->line_input_queue);
326         /* Destroy callback data if ownership retained */
327         if(priv->resource_load_callback_destroy_data)
328                 priv->resource_load_callback_destroy_data(priv->resource_load_callback_data);
329         
330         /* Free other stuff */
331         g_free(priv->current_dir);
332         g_free(priv->program_name);
333         g_free(priv->program_info);
334         g_free(priv->story_name);
335         g_free(priv->styles);
336         g_free(priv->glk_styles);
337
338         /* Chain up to parent */
339     G_OBJECT_CLASS(chimara_glk_parent_class)->finalize(object);
340 }
341
342 /* Internal function: Recursively get the Glk window tree's size request */
343 static void
344 request_recurse(winid_t win, GtkRequisition *requisition, guint spacing)
345 {
346         if(win->type == wintype_Pair)
347         {
348                 /* Get children's size requests */
349                 GtkRequisition child1, child2;
350                 request_recurse(win->window_node->children->data, &child1, spacing);
351                 request_recurse(win->window_node->children->next->data, &child2, spacing);
352
353                 glui32 division = win->split_method & winmethod_DivisionMask;
354                 glui32 direction = win->split_method & winmethod_DirMask;
355                 unsigned border = ((win->split_method & winmethod_BorderMask) == winmethod_NoBorder)? 0 : spacing;
356
357                 /* If the split is fixed, get the size of the fixed child */
358                 if(division == winmethod_Fixed)
359                 {
360                         switch(direction)
361                         {
362                                 case winmethod_Left:
363                                         child1.width = win->key_window?
364                                                 win->constraint_size * win->key_window->unit_width
365                                                 : 0;
366                                         break;
367                                 case winmethod_Right:
368                                         child2.width = win->key_window?
369                                                 win->constraint_size * win->key_window->unit_width
370                                                 : 0;
371                                         break;
372                                 case winmethod_Above:
373                                         child1.height = win->key_window?
374                                                 win->constraint_size * win->key_window->unit_height
375                                                 : 0;
376                                         break;
377                                 case winmethod_Below:
378                                         child2.height = win->key_window?
379                                                 win->constraint_size * win->key_window->unit_height
380                                                 : 0;
381                                         break;
382                         }
383                 }
384                 
385                 /* Add the children's requests */
386                 switch(direction)
387                 {
388                         case winmethod_Left:
389                         case winmethod_Right:
390                                 requisition->width = child1.width + child2.width + border;
391                                 requisition->height = MAX(child1.height, child2.height);
392                                 break;
393                         case winmethod_Above:
394                         case winmethod_Below:
395                                 requisition->width = MAX(child1.width, child2.width);
396                                 requisition->height = child1.height + child2.height + border;
397                                 break;
398                 }
399         }
400         
401         /* For non-pair windows, just use the size that GTK requests */
402         else
403                 gtk_widget_size_request(win->frame, requisition);
404 }
405
406 /* Overrides gtk_widget_size_request */
407 static void
408 chimara_glk_size_request(GtkWidget *widget, GtkRequisition *requisition)
409 {
410     g_return_if_fail(widget);
411     g_return_if_fail(requisition);
412     g_return_if_fail(CHIMARA_IS_GLK(widget));
413     
414     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
415     
416     guint border_width = gtk_container_get_border_width(GTK_CONTAINER(widget));
417     /* For now, just pass the size request on to the root Glk window */
418     if(priv->root_window) 
419         {
420                 request_recurse(priv->root_window->data, requisition, priv->spacing);
421                 requisition->width += 2 * border_width;
422                 requisition->height += 2 * border_width;
423         } 
424         else 
425         {
426         requisition->width = CHIMARA_GLK_MIN_WIDTH + 2 * border_width;
427         requisition->height = CHIMARA_GLK_MIN_HEIGHT + 2 * border_width;
428     }
429 }
430
431 /* Recursively give the Glk windows their allocated space. Returns a window
432  containing all children of this window that must be redrawn, or NULL if there 
433  are no children that require redrawing. */
434 static winid_t
435 allocate_recurse(winid_t win, GtkAllocation *allocation, guint spacing)
436 {
437         if(win->type == wintype_Pair)
438         {
439                 glui32 division = win->split_method & winmethod_DivisionMask;
440                 glui32 direction = win->split_method & winmethod_DirMask;
441                 unsigned border = ((win->split_method & winmethod_BorderMask) == winmethod_NoBorder)? 0 : spacing;
442
443                 /* If the space gets too small to honor the spacing property, then just 
444                  ignore spacing in this window and below. */
445                 if( (border > allocation->width && (direction == winmethod_Left || direction == winmethod_Right))
446                    || (border > allocation->height && (direction == winmethod_Above || direction == winmethod_Below)) )
447                         border = 0;
448                 
449                 GtkAllocation child1, child2;
450                 child1.x = allocation->x;
451                 child1.y = allocation->y;
452                 
453                 if(division == winmethod_Fixed)
454                 {
455                         /* If the key window has been closed, then default to 0; otherwise
456                          use the key window to determine the size */
457                         switch(direction)
458                         {
459                                 case winmethod_Left:
460                                         child1.width = win->key_window? 
461                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - border) 
462                                                 : 0;
463                                         break;
464                                 case winmethod_Right:
465                                         child2.width = win->key_window? 
466                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - border)
467                                                 : 0;
468                                         break;
469                                 case winmethod_Above:
470                                         child1.height = win->key_window? 
471                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - border)
472                                                 : 0;
473                                         break;
474                                 case winmethod_Below:
475                                         child2.height = win->key_window?
476                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - border)
477                                                 : 0;
478                                         break;
479                         }
480                 }
481                 else /* proportional */
482                 {
483                         gdouble fraction = win->constraint_size / 100.0;
484                         switch(direction)
485                         {
486                                 case winmethod_Left:
487                                         child1.width = MAX(0, (gint)ceil(fraction * (allocation->width - border)) );
488                                         break;
489                                 case winmethod_Right:
490                                         child2.width = MAX(0, (gint)ceil(fraction * (allocation->width - border)) );
491                                         break;
492                                 case winmethod_Above:
493                                         child1.height = MAX(0, (gint)ceil(fraction * (allocation->height - border)) );
494                                         break;
495                                 case winmethod_Below:
496                                         child2.height = MAX(0, (gint)ceil(fraction * (allocation->height - border)) );
497                                         break;
498                         }
499                 }
500                 
501                 /* Fill in the rest of the size requisitions according to the child specified above */
502                 switch(direction)
503                 {
504                         case winmethod_Left:
505                                 child2.width = MAX(0, allocation->width - border - child1.width);
506                                 child2.x = child1.x + child1.width + border;
507                                 child2.y = child1.y;
508                                 child1.height = child2.height = allocation->height;
509                                 break;
510                         case winmethod_Right:
511                                 child1.width = MAX(0, allocation->width - border - child2.width);
512                                 child2.x = child1.x + child1.width + border;
513                                 child2.y = child1.y;
514                                 child1.height = child2.height = allocation->height;
515                                 break;
516                         case winmethod_Above:
517                                 child2.height = MAX(0, allocation->height - border - child1.height);
518                                 child2.x = child1.x;
519                                 child2.y = child1.y + child1.height + border;
520                                 child1.width = child2.width = allocation->width;
521                                 break;
522                         case winmethod_Below:
523                                 child1.height = MAX(0, allocation->height - border - child2.height);
524                                 child2.x = child1.x;
525                                 child2.y = child1.y + child1.height + border;
526                                 child1.width = child2.width = allocation->width;
527                                 break;
528                 }
529                 
530                 /* Recurse */
531                 winid_t arrange1 = allocate_recurse(win->window_node->children->data, &child1, spacing);
532                 winid_t arrange2 = allocate_recurse(win->window_node->children->next->data, &child2, spacing);
533                 if(arrange1 == NULL)
534                         return arrange2;
535                 if(arrange2 == NULL)
536                         return arrange1;
537                 return win;
538         }
539         
540         else if(win->type == wintype_TextGrid)
541         {
542                 /* Pass the size allocation on to the framing widget */
543                 gtk_widget_size_allocate(win->frame, allocation);
544                 /* It says in the spec that when a text grid window is resized smaller,
545                  the bottom or right area is thrown away; when it is resized larger, the
546                  bottom or right area is filled with blanks. */
547                 GtkAllocation widget_allocation;
548                 gtk_widget_get_allocation(win->widget, &widget_allocation);
549                 glui32 newwidth = (glui32)(widget_allocation.width / win->unit_width);
550                 glui32 newheight = (glui32)(widget_allocation.height / win->unit_height);
551                 gint line;
552                 GtkTextBuffer *textbuffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
553                 GtkTextIter start, end;
554         
555                 for(line = 0; line < win->height; line++)
556                 {
557                         gtk_text_buffer_get_iter_at_line(textbuffer, &start, line);
558                         /* If this line is going to fall off the bottom, delete it */
559                         if(line >= newheight)
560                         {
561                                 end = start;
562                                 gtk_text_iter_forward_to_line_end(&end);
563                                 gtk_text_iter_forward_char(&end);
564                                 gtk_text_buffer_delete(textbuffer, &start, &end);
565                                 break;
566                         }
567                         /* If this line is not long enough, add spaces on the end */
568                         if(newwidth > win->width)
569                         {
570                                 gchar *spaces = g_strnfill(newwidth - win->width, ' ');
571                                 gtk_text_iter_forward_to_line_end(&start);
572                                 gtk_text_buffer_insert(textbuffer, &start, spaces, -1);
573                                 g_free(spaces);
574                         }
575                         /* But if it's too long, delete characters from the end */
576                         else if(newwidth < win->width)
577                         {
578                                 end = start;
579                                 gtk_text_iter_forward_chars(&start, newwidth);
580                                 gtk_text_iter_forward_to_line_end(&end);
581                                 gtk_text_buffer_delete(textbuffer, &start, &end);
582                         }
583                         /* Note: if the widths are equal, do nothing */
584                 }
585                 /* Add blank lines if there aren't enough lines to fit the new size */
586                 if(newheight > win->height)
587                 {
588                         gchar *blanks = g_strnfill(win->width, ' ');
589                     gchar **blanklines = g_new0(gchar *, (newheight - win->height) + 1);
590                     int count;
591                     for(count = 0; count < newheight - win->height; count++)
592                         blanklines[count] = blanks;
593                     blanklines[newheight - win->height] = NULL;
594                     gchar *text = g_strjoinv("\n", blanklines);
595                     g_free(blanklines); /* not g_strfreev() */
596                     g_free(blanks);
597                     
598                         gtk_text_buffer_get_end_iter(textbuffer, &start);
599                         gtk_text_buffer_insert(textbuffer, &start, "\n", -1);
600                     gtk_text_buffer_insert(textbuffer, &start, text, -1);
601                     g_free(text);
602                 }
603         
604                 gboolean arrange = !(win->width == newwidth && win->height == newheight);
605                 win->width = newwidth;
606                 win->height = newheight;
607                 return arrange? win : NULL;
608         }
609         
610         /* For non-pair, non-text-grid windows, just give them the size */
611         gtk_widget_size_allocate(win->frame, allocation);
612         return NULL;
613 }
614
615 /* Overrides gtk_widget_size_allocate */
616 static void
617 chimara_glk_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
618 {
619     g_return_if_fail(widget);
620     g_return_if_fail(allocation);
621     g_return_if_fail(CHIMARA_IS_GLK(widget));
622     
623     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
624     
625     gtk_widget_set_allocation(widget, allocation);
626             
627     if(priv->root_window) {
628                 GtkAllocation child;
629                 guint border_width = gtk_container_get_border_width(GTK_CONTAINER(widget));
630                 child.x = allocation->x + border_width;
631                 child.y = allocation->y + border_width;
632                 child.width = CLAMP(allocation->width - 2 * border_width, 0, allocation->width);
633                 child.height = CLAMP(allocation->height - 2 * border_width, 0, allocation->height);
634                 winid_t arrange = allocate_recurse(priv->root_window->data, &child, priv->spacing);
635                 
636                 /* arrange points to a window that contains all text grid and graphics
637                  windows which have been resized */
638                 g_mutex_lock(priv->arrange_lock);
639                 if(!priv->ignore_next_arrange_event)
640                 {
641                         if(arrange)
642                                 event_throw(CHIMARA_GLK(widget), evtype_Arrange, arrange == priv->root_window->data? NULL : arrange, 0, 0);
643                 }
644                 else
645                         priv->ignore_next_arrange_event = FALSE;
646                 priv->needs_rearrange = FALSE;
647                 g_cond_signal(priv->rearranged);
648                 g_mutex_unlock(priv->arrange_lock);
649         }
650 }
651
652 /* Recursively invoke callback() on the GtkWidget of each non-pair window in the tree */
653 static void
654 forall_recurse(winid_t win, GtkCallback callback, gpointer callback_data)
655 {
656         if(win->type == wintype_Pair)
657         {
658                 forall_recurse(win->window_node->children->data, callback, callback_data);
659                 forall_recurse(win->window_node->children->next->data, callback, callback_data);
660         }
661         else
662                 (*callback)(win->frame, callback_data);
663 }
664
665 /* Overrides gtk_container_forall */
666 static void
667 chimara_glk_forall(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data)
668 {
669     g_return_if_fail(container);
670     g_return_if_fail(CHIMARA_IS_GLK(container));
671     
672     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(container);
673     
674         /* All the children are "internal" */
675         if(!include_internals)
676                 return;
677         
678     if(priv->root_window)
679                 forall_recurse(priv->root_window->data, callback, callback_data);
680 }
681
682 static void
683 chimara_glk_stopped(ChimaraGlk *self)
684 {
685     CHIMARA_GLK_USE_PRIVATE(self, priv);
686     priv->running = FALSE;
687     priv->program_name = NULL;
688     g_object_notify(G_OBJECT(self), "program-name");
689     priv->program_info = NULL;
690     g_object_notify(G_OBJECT(self), "program-info");
691     priv->story_name = NULL;
692     g_object_notify(G_OBJECT(self), "story-name");
693 }
694
695 static void
696 chimara_glk_started(ChimaraGlk *self)
697 {
698         CHIMARA_GLK_USE_PRIVATE(self, priv);
699         priv->running = TRUE;
700 }
701
702 static void
703 chimara_glk_waiting(ChimaraGlk *self)
704 {
705         /* Default signal handler */
706 }
707
708 static void
709 chimara_glk_char_input(ChimaraGlk *self, guint window_rock, guint keysym)
710 {
711         /* Default signal handler */
712 }
713
714 static void
715 chimara_glk_line_input(ChimaraGlk *self, guint window_rock, gchar *text)
716 {
717         /* Default signal handler */
718 }
719
720 static void
721 chimara_glk_text_buffer_output(ChimaraGlk *self, guint window_rock, gchar *text)
722 {
723         /* Default signal handler */
724 }
725
726 static void
727 chimara_glk_iliad_screen_update(ChimaraGlk *self, gboolean typing)
728 {
729         /* Default signal handler */
730 }
731
732 /* COMPAT: G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
733 #ifndef G_PARAM_STATIC_STRINGS
734
735 /* COMPAT: G_PARAM_STATIC_NAME and friends only appeared in GTK 2.8 */
736 #if GTK_CHECK_VERSION(2,8,0)
737 #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
738 #else
739 #define G_PARAM_STATIC_STRINGS (0)
740 #endif
741
742 #endif
743
744 static void
745 chimara_glk_class_init(ChimaraGlkClass *klass)
746 {
747     /* Override methods of parent classes */
748     GObjectClass *object_class = G_OBJECT_CLASS(klass);
749     object_class->set_property = chimara_glk_set_property;
750     object_class->get_property = chimara_glk_get_property;
751     object_class->finalize = chimara_glk_finalize;
752     
753     GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
754     widget_class->size_request = chimara_glk_size_request;
755     widget_class->size_allocate = chimara_glk_size_allocate;
756
757     GtkContainerClass *container_class = GTK_CONTAINER_CLASS(klass);
758     container_class->forall = chimara_glk_forall;
759
760     /* Signals */
761     klass->stopped = chimara_glk_stopped;
762     klass->started = chimara_glk_started;
763     klass->waiting = chimara_glk_waiting;
764     klass->char_input = chimara_glk_char_input;
765     klass->line_input = chimara_glk_line_input;
766     klass->text_buffer_output = chimara_glk_text_buffer_output;
767     klass->iliad_screen_update = chimara_glk_iliad_screen_update;
768
769     /**
770      * ChimaraGlk::stopped:
771      * @glk: The widget that received the signal
772      *
773      * Emitted when the a Glk program finishes executing in the widget, whether
774      * it ended normally, or was interrupted.
775      */ 
776     chimara_glk_signals[STOPPED] = g_signal_new("stopped", 
777         G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST, 
778         /* FIXME: Should be G_SIGNAL_RUN_CLEANUP but that segfaults??! */
779         G_STRUCT_OFFSET(ChimaraGlkClass, stopped), NULL, NULL,
780                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
781         /**
782          * ChimaraGlk::started:
783          * @glk: The widget that received the signal
784          *
785          * Emitted when a Glk program starts executing in the widget.
786          */
787         chimara_glk_signals[STARTED] = g_signal_new ("started",
788                 G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST,
789                 G_STRUCT_OFFSET(ChimaraGlkClass, started), NULL, NULL,
790                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
791         /**
792          * ChimaraGlk::waiting:
793          * @glk: The widget that received the signal
794          * 
795          * Emitted when glk_select() is called by the Glk program and the event
796          * queue is empty, which means that the widget is waiting for input.
797          */
798         chimara_glk_signals[WAITING] = g_signal_new("waiting",
799                 G_OBJECT_CLASS_TYPE(klass), 0,
800                 G_STRUCT_OFFSET(ChimaraGlkClass, waiting), NULL, NULL,
801                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
802         /**
803          * ChimaraGlk::char-input:
804          * @glk: The widget that received the signal
805          * @window_rock: The rock value of the window that received character input
806          * (see <link linkend="chimara-Rocks">Rocks</link>)
807          * @keysym: The key that was typed, in the form of a key symbol from 
808          * <filename class="headerfile">gdk/gdkkeysyms.h</filename>
809          * 
810          * Emitted when a Glk window receives character input.
811          */
812         chimara_glk_signals[CHAR_INPUT] = g_signal_new("char-input",
813                 G_OBJECT_CLASS_TYPE(klass), 0,
814                 G_STRUCT_OFFSET(ChimaraGlkClass, char_input), NULL, NULL,
815                 _chimara_marshal_VOID__UINT_UINT,
816                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
817         /**
818          * ChimaraGlk::line-input:
819          * @glk: The widget that received the signal
820          * @window_rock: The rock value of the window that received line input (see
821          * <link linkend="chimara-Rocks">Rocks</link>)
822          * @text: The text that was typed
823          * 
824          * Emitted when a Glk window receives line input.
825          */
826         chimara_glk_signals[LINE_INPUT] = g_signal_new("line-input",
827                 G_OBJECT_CLASS_TYPE(klass), 0,
828                 G_STRUCT_OFFSET(ChimaraGlkClass, line_input), NULL, NULL,
829                 _chimara_marshal_VOID__UINT_STRING,
830                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
831         /**
832          * ChimaraGlk::text-buffer-output:
833          * @glk: The widget that received the signal
834          * @window_rock: The rock value of the window that was printed to (see <link
835          * linkend="chimara-Rocks">Rocks</link>)
836          * 
837          * Emitted when text is printed to a text buffer window.
838          */
839         chimara_glk_signals[TEXT_BUFFER_OUTPUT] = g_signal_new("text-buffer-output",
840                 G_OBJECT_CLASS_TYPE(klass), 0,
841                 G_STRUCT_OFFSET(ChimaraGlkClass, text_buffer_output), NULL, NULL,
842                 _chimara_marshal_VOID__UINT_STRING,
843                 G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
844         /**
845          * ChimaraGlk::iliad-screen-update:
846          * @self: The widget that received the signal
847          * @typing: Whether to perform a typing or full screen update
848          *
849          * Iliad specific signal which is emitted whenever the screen needs to be updated.
850          * Since iliad screen updates are very slow, updating should only be done when
851          * necessary.
852          */
853         chimara_glk_signals[ILIAD_SCREEN_UPDATE] = g_signal_new("iliad-screen-update",
854                 G_OBJECT_CLASS_TYPE(klass), 0,
855                 G_STRUCT_OFFSET(ChimaraGlkClass, iliad_screen_update), NULL, NULL,
856                 _chimara_marshal_VOID__BOOLEAN,
857                 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
858
859     /* Properties */
860     /**
861      * ChimaraGlk:interactive:
862      *
863      * Sets whether the widget is interactive. A Glk widget is normally 
864      * interactive, but in non-interactive mode, keyboard and mouse input are 
865      * ignored and the Glk program is controlled by 
866      * chimara_glk_feed_char_input() and chimara_glk_feed_line_input(). 
867      * <quote>More</quote> prompts when a lot of text is printed to a text 
868          * buffer are also disabled. This is typically used when you wish to control
869          * an interpreter program by feeding it a predefined list of commands.
870      */
871     g_object_class_install_property( object_class, PROP_INTERACTIVE, 
872                 g_param_spec_boolean("interactive", _("Interactive"),
873         _("Whether user input is expected in the Glk program"),
874         TRUE,
875         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
876
877         /**
878      * ChimaraGlk:protect:
879      *
880      * Sets whether the Glk program is allowed to do file operations. In protect
881      * mode, all file operations will fail.
882      */
883     g_object_class_install_property(object_class, PROP_PROTECT, 
884                 g_param_spec_boolean("protect", _("Protected"),
885         _("Whether the Glk program is barred from doing file operations"),
886         FALSE,
887         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
888
889         /**
890          * ChimaraGlk:spacing:
891          *
892          * The amount of space between the Glk windows. This space forms a visible
893          * border between windows; however, if you open a window using the
894          * %winmethod_NoBorder flag, there will be no spacing between it and its
895          * sibling window, no matter what the value of this property is.
896          */
897         g_object_class_install_property(object_class, PROP_SPACING,
898                 g_param_spec_uint("spacing", _("Spacing"),
899                 _("The amount of space between Glk windows"),
900                 0, G_MAXUINT, 0,
901                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
902         
903         /**
904          * ChimaraGlk:program-name:
905          *
906          * The name of the currently running Glk program. You cannot set this 
907          * property yourself. It is set to the filename of the plugin when you call
908          * chimara_glk_run(), but the plugin can change it by calling 
909          * garglk_set_program_name(). To find out when this information changes,
910          * for example to put the program name in the title bar of a window, connect
911          * to the <code>::notify::program-name</code> signal.
912          */
913         g_object_class_install_property(object_class, PROP_PROGRAM_NAME,
914                 g_param_spec_string("program-name", _("Program name"),
915                 _("Name of the currently running program"),
916                 NULL,
917                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
918                 
919         /**
920          * ChimaraGlk:program-info:
921          *
922          * Information about the currently running Glk program. You cannot set this
923          * property yourself. The plugin can change it by calling
924          * garglk_set_program_info(). See also #ChimaraGlk:program-name.
925          */
926         g_object_class_install_property(object_class, PROP_PROGRAM_INFO,
927                 g_param_spec_string("program-info", _("Program info"),
928                 _("Information about the currently running program"),
929                 NULL,
930                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
931         
932         /**
933          * ChimaraGlk:story-name:
934          *
935          * The name of the story currently running in the Glk interpreter. You
936          * cannot set this property yourself. It is set to the story filename when
937          * you call chimara_if_run_game(), but the plugin can change it by calling
938          * garglk_set_story_name().
939          *
940          * Strictly speaking, this should be a property of #ChimaraIF, but it is
941          * legal for any Glk program to call garglk_set_story_name(), even if it is
942          * not an interpreter and does not load story files.
943          */
944         g_object_class_install_property(object_class, PROP_STORY_NAME,
945                 g_param_spec_string("story-name", _("Story name"),
946                 _("Name of the story currently loaded in the interpreter"),
947                 NULL,
948                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS) );
949         
950         /* Private data */
951     g_type_class_add_private(klass, sizeof(ChimaraGlkPrivate));
952 }
953
954 /* PUBLIC FUNCTIONS */
955
956 /**
957  * chimara_error_quark:
958  *
959  * The error domain for errors from Chimara widgets.
960  *
961  * Returns: The string <quote>chimara-error-quark</quote> as a <link 
962  * linkend="GQuark">GQuark</link>.
963  */
964 GQuark
965 chimara_error_quark(void)
966 {
967         chimara_init(); /* This is a library entry point */
968         return g_quark_from_static_string("chimara-error-quark");
969 }
970
971 /**
972  * chimara_glk_new:
973  *
974  * Creates and initializes a new #ChimaraGlk widget.
975  *
976  * Return value: a #ChimaraGlk widget, with a floating reference.
977  */
978 GtkWidget *
979 chimara_glk_new(void)
980 {
981         /* This is a library entry point; initialize the library */
982         chimara_init();
983
984     return GTK_WIDGET(g_object_new(CHIMARA_TYPE_GLK, NULL));
985 }
986
987 /**
988  * chimara_glk_set_interactive:
989  * @glk: a #ChimaraGlk widget
990  * @interactive: whether the widget should expect user input
991  *
992  * Sets the #ChimaraGlk:interactive property of @glk. 
993  */
994 void 
995 chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
996 {
997     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
998     
999     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1000     priv->interactive = interactive;
1001     g_object_notify(G_OBJECT(glk), "interactive");
1002 }
1003
1004 /**
1005  * chimara_glk_get_interactive:
1006  * @glk: a #ChimaraGlk widget
1007  *
1008  * Returns whether @glk is interactive (expecting user input). See 
1009  * #ChimaraGlk:interactive.
1010  *
1011  * Return value: %TRUE if @glk is interactive.
1012  */
1013 gboolean 
1014 chimara_glk_get_interactive(ChimaraGlk *glk)
1015 {
1016     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1017     
1018     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1019     return priv->interactive;
1020 }
1021
1022 /**
1023  * chimara_glk_set_protect:
1024  * @glk: a #ChimaraGlk widget
1025  * @protect: whether the widget should allow the Glk program to do file 
1026  * operations
1027  *
1028  * Sets the #ChimaraGlk:protect property of @glk. In protect mode, the Glk 
1029  * program is not allowed to do file operations.
1030  */
1031 void 
1032 chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
1033 {
1034     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1035     
1036     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1037     priv->protect = protect;
1038     g_object_notify(G_OBJECT(glk), "protect");
1039 }
1040
1041 /**
1042  * chimara_glk_get_protect:
1043  * @glk: a #ChimaraGlk widget
1044  *
1045  * Returns whether @glk is in protect mode (banned from doing file operations).
1046  * See #ChimaraGlk:protect.
1047  *
1048  * Return value: %TRUE if @glk is in protect mode.
1049  */
1050 gboolean 
1051 chimara_glk_get_protect(ChimaraGlk *glk)
1052 {
1053     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1054     
1055     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1056     return priv->protect;
1057 }
1058
1059 /**
1060  * chimara_glk_set_css_to_default:
1061  * @glk: a #ChimaraGlk widget
1062  *
1063  * Resets the styles for text buffer and text grid windows to their defaults.
1064  * <para><warning>
1065  *   This function is not implemented yet.
1066  * </warning></para>
1067  */
1068 void
1069 chimara_glk_set_css_to_default(ChimaraGlk *glk)
1070 {
1071         reset_default_styles(glk);
1072 }
1073
1074 /**
1075  * chimara_glk_set_css_from_file:
1076  * @glk: a #ChimaraGlk widget
1077  * @filename: path to a CSS file, or %NULL
1078  * @error: location to store a <link 
1079  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1080  *
1081  * Sets the styles for text buffer and text grid windows according to the CSS
1082  * file @filename. Note that the styles are set cumulatively on top of whatever
1083  * the styles are at the time this function is called; to reset the styles to
1084  * their defaults, use chimara_glk_set_css_to_default().
1085  *
1086  * Returns: %TRUE on success, %FALSE if an error occurred, in which case @error
1087  * will be set.
1088  */
1089 gboolean 
1090 chimara_glk_set_css_from_file(ChimaraGlk *glk, const gchar *filename, GError **error)
1091 {
1092         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1093         g_return_val_if_fail(filename, FALSE);
1094         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1095
1096         int fd = open(filename, O_RDONLY);
1097         if(fd == -1) {
1098                 if(error)
1099                         *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno), 
1100                                 _("Error opening file \"%s\": %s"), filename, g_strerror(errno));
1101                 return FALSE;
1102         }
1103
1104         GScanner *scanner = create_css_file_scanner();
1105         g_scanner_input_file(scanner, fd);
1106         scanner->input_name = filename;
1107         scan_css_file(scanner, glk);
1108
1109         if(close(fd) == -1) {
1110                 if(error)
1111                         *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno),
1112                                 _("Error closing file \"%s\": %s"), filename, g_strerror(errno));
1113                 return FALSE;
1114         }
1115         return TRUE;
1116 }
1117
1118 /**
1119  * chimara_glk_set_css_from_string:
1120  * @glk: a #ChimaraGlk widget
1121  * @css: a string containing CSS code
1122  *
1123  * Sets the styles for text buffer and text grid windows according to the CSS
1124  * code @css. Note that the styles are set cumulatively on top of whatever the 
1125  * styles are at the time this function is called; to reset the styles to their
1126  * defaults, use chimara_glk_set_css_to_default().
1127  */
1128 void 
1129 chimara_glk_set_css_from_string(ChimaraGlk *glk, const gchar *css)
1130 {
1131         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1132         g_return_if_fail(css || *css);
1133         
1134         GScanner *scanner = create_css_file_scanner();
1135         g_scanner_input_text(scanner, css, strlen(css));
1136         scanner->input_name = "<string>";
1137         scan_css_file(scanner, glk);
1138 }
1139
1140 /**
1141  * chimara_glk_set_spacing:
1142  * @glk: a #ChimaraGlk widget
1143  * @spacing: the number of pixels to put between Glk windows
1144  *
1145  * Sets the #ChimaraGlk:spacing property of @glk, which is the border width in
1146  * pixels between Glk windows.
1147  */
1148 void 
1149 chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
1150 {
1151         g_return_if_fail( glk || CHIMARA_IS_GLK(glk) );
1152         
1153         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1154         priv->spacing = spacing;
1155         g_object_notify(G_OBJECT(glk), "spacing");
1156 }
1157
1158 /**
1159  * chimara_glk_get_spacing:
1160  * @glk: a #ChimaraGlk widget
1161  *
1162  * Gets the value set by chimara_glk_set_spacing().
1163  *
1164  * Return value: pixels of spacing between Glk windows
1165  */
1166 guint 
1167 chimara_glk_get_spacing(ChimaraGlk *glk)
1168 {
1169         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), 0);
1170         
1171         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1172         return priv->spacing;
1173 }
1174
1175 struct StartupData {
1176         glk_main_t glk_main;
1177         glkunix_startup_code_t glkunix_startup_code;
1178         glkunix_startup_t args;
1179         ChimaraGlkPrivate *glk_data;
1180 };
1181
1182 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
1183 static gpointer
1184 glk_enter(struct StartupData *startup)
1185 {
1186         extern GPrivate *glk_data_key;
1187         g_private_set(glk_data_key, startup->glk_data);
1188         
1189         /* Acquire the Glk thread's references to the input queues */
1190         g_async_queue_ref(startup->glk_data->char_input_queue);
1191         g_async_queue_ref(startup->glk_data->line_input_queue);
1192         
1193         /* Run startup function */
1194         if(startup->glkunix_startup_code) {
1195                 startup->glk_data->in_startup = TRUE;
1196                 int result = startup->glkunix_startup_code(&startup->args);
1197                 startup->glk_data->in_startup = FALSE;
1198                 
1199                 int i = 0;
1200                 while(i < startup->args.argc)
1201                         g_free(startup->args.argv[i++]);
1202                 g_free(startup->args.argv);
1203                 
1204                 if(!result)
1205                         return NULL;
1206         }
1207         
1208         /* Run main function */
1209         glk_main_t glk_main = startup->glk_main;
1210         
1211         /* COMPAT: avoid usage of slices */
1212         g_free(startup);
1213     g_signal_emit_by_name(startup->glk_data->self, "started");
1214         glk_main();
1215         glk_exit(); /* Run shutdown code in glk_exit() even if glk_main() returns normally */
1216         g_assert_not_reached(); /* because glk_exit() calls g_thread_exit() */
1217         return NULL; 
1218 }
1219
1220 /**
1221  * chimara_glk_run:
1222  * @glk: a #ChimaraGlk widget
1223  * @plugin: path to a plugin module compiled with <filename 
1224  * class="header">glk.h</filename>
1225  * @argc: Number of command line arguments in @argv
1226  * @argv: Array of command line arguments to pass to the plugin
1227  * @error: location to store a <link 
1228  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1229  *
1230  * Opens a Glk program compiled as a plugin. Sorts out its command line
1231  * arguments from #glkunix_arguments, calls its startup function
1232  * glkunix_startup_code(), and then calls its main function glk_main() in
1233  * a separate thread. On failure, returns %FALSE and sets @error.
1234  *
1235  * The plugin must at least export a glk_main() function; #glkunix_arguments and
1236  * glkunix_startup_code() are optional.
1237  *
1238  * Return value: %TRUE if the Glk program was started successfully.
1239  */
1240 gboolean
1241 chimara_glk_run(ChimaraGlk *glk, const gchar *plugin, int argc, char *argv[], GError **error)
1242 {
1243     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1244     g_return_val_if_fail(plugin, FALSE);
1245         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1246         
1247         if(chimara_glk_get_running(glk)) {
1248                 g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_ALREADY_RUNNING, _("There was already a plugin running."));
1249                 return FALSE;
1250         }
1251     
1252     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1253
1254         /* COMPAT: avoid usage of slices */
1255         struct StartupData *startup = g_new0(struct StartupData,1);
1256         
1257     g_assert( g_module_supported() );
1258         /* If there is already a module loaded, free it first -- you see, we want to
1259          * keep modules loaded as long as possible to avoid crashes in stack unwinding */
1260         if( priv->program && !g_module_close(priv->program) )
1261                 g_warning( "Error closing module :%s", g_module_error() );
1262         /* Open the module to run */
1263     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
1264     
1265     if(!priv->program)
1266     {
1267         g_set_error(error, CHIMARA_ERROR, CHIMARA_LOAD_MODULE_ERROR, _("Error opening module: %s"), g_module_error());
1268         return FALSE;
1269     }
1270     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
1271     {
1272         g_set_error(error, CHIMARA_ERROR, CHIMARA_NO_GLK_MAIN, _("Error finding glk_main(): %s"), g_module_error());
1273         return FALSE;
1274     }
1275
1276     if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
1277     {
1278                 glkunix_argumentlist_t *glkunix_arguments;
1279
1280                 if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
1281                           && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
1282                 {
1283                         /* arguments could not be parsed, so create data ourselves */
1284                         startup->args.argc = 1;
1285                         startup->args.argv = g_new0(gchar *, 1);
1286                 }
1287
1288                 /* Set the program invocation name */
1289                 startup->args.argv[0] = g_strdup(plugin);
1290     }
1291         startup->glk_data = priv;
1292         
1293         /* Set the program name */
1294         priv->program_name = g_path_get_basename(plugin);
1295         g_object_notify(G_OBJECT(glk), "program-name");
1296         
1297     /* Run in a separate thread */
1298         priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
1299         
1300         return !(priv->thread == NULL);
1301 }
1302
1303 /**
1304  * chimara_glk_stop:
1305  * @glk: a #ChimaraGlk widget
1306  *
1307  * Signals the Glk program running in @glk to abort. Note that if the program is
1308  * caught in an infinite loop in which glk_tick() is not called, this may not
1309  * work.
1310  */
1311 void
1312 chimara_glk_stop(ChimaraGlk *glk)
1313 {
1314     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1315     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1316
1317     /* Don't do anything if not running a program */
1318     if(!priv->running)
1319         return;
1320     
1321         if(priv->abort_lock) {
1322                 g_mutex_lock(priv->abort_lock);
1323                 priv->abort_signalled = TRUE;
1324                 g_mutex_unlock(priv->abort_lock);
1325                 /* Stop blocking on the event queue condition */
1326                 event_throw(glk, evtype_Abort, NULL, 0, 0);
1327                 /* Stop blocking on the shutdown key press condition */
1328                 g_mutex_lock(priv->shutdown_lock);
1329                 g_cond_signal(priv->shutdown_key_pressed);
1330                 g_mutex_unlock(priv->shutdown_lock);
1331         }
1332 }
1333
1334 /**
1335  * chimara_glk_wait:
1336  * @glk: a #ChimaraGlk widget
1337  *
1338  * Holds up the main thread and waits for the Glk program running in @glk to 
1339  * finish.
1340  */
1341 void
1342 chimara_glk_wait(ChimaraGlk *glk)
1343 {
1344     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1345     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1346     /* Don't do anything if not running a program */
1347     if(!priv->running)
1348         return;
1349         /* Unlock GDK mutex, because the Glk program might need to use it for shutdown */
1350         gdk_threads_leave();
1351     g_thread_join(priv->thread);
1352         gdk_threads_enter();
1353 }
1354
1355 /**
1356  * chimara_glk_get_running:
1357  * @glk: a #ChimaraGlk widget
1358  * 
1359  * Use this function to tell whether a program is currently running in the
1360  * widget.
1361  * 
1362  * Returns: %TRUE if @glk is executing a Glk program, %FALSE otherwise.
1363  */
1364 gboolean
1365 chimara_glk_get_running(ChimaraGlk *glk)
1366 {
1367         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1368         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1369         return priv->running;
1370 }
1371
1372 /**
1373  * chimara_glk_feed_char_input:
1374  * @glk: a #ChimaraGlk widget
1375  * @keyval: a key symbol as defined in <filename 
1376  * class="headerfile">gdk/gdkkeysyms.h</filename>
1377  * 
1378  * Pretend that a key was pressed in the Glk program as a response to a 
1379  * character input request. You can call this function even when no window has
1380  * requested character input, in which case the key will be saved for the 
1381  * following window that requests character input. This has the disadvantage 
1382  * that if more than one window has requested character input, it is arbitrary 
1383  * which one gets the key press.
1384  */
1385 void 
1386 chimara_glk_feed_char_input(ChimaraGlk *glk, guint keyval)
1387 {
1388         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1389         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1390         g_async_queue_push(priv->char_input_queue, GUINT_TO_POINTER(keyval));
1391         event_throw(glk, evtype_ForcedCharInput, NULL, 0, 0);
1392 }
1393
1394 /**
1395  * chimara_glk_feed_line_input:
1396  * @glk: a #ChimaraGlk widget
1397  * @text: text to pass to the next line input request
1398  * 
1399  * Pretend that @text was typed in the Glk program as a response to a line input
1400  * request. @text does not need to end with a newline. You can call this 
1401  * function even when no window has requested line input, in which case the text
1402  * will be saved for the following window that requests line input. This has the 
1403  * disadvantage that if more than one window has requested line input, it is
1404  * arbitrary which one gets the text.
1405  */
1406 void 
1407 chimara_glk_feed_line_input(ChimaraGlk *glk, const gchar *text)
1408 {
1409         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1410         g_return_if_fail(text);
1411         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1412         g_async_queue_push(priv->line_input_queue, g_strdup(text));
1413         event_throw(glk, evtype_ForcedLineInput, NULL, 0, 0);
1414 }
1415
1416 /**
1417  * chimara_glk_is_char_input_pending:
1418  * @glk: a #ChimaraGlk widget
1419  *
1420  * Use this function to tell if character input forced by 
1421  * chimara_glk_feed_char_input() has been passed to an input request or not.
1422  *
1423  * Returns: %TRUE if forced character input is pending, %FALSE otherwise.
1424  */
1425 gboolean
1426 chimara_glk_is_char_input_pending(ChimaraGlk *glk)
1427 {
1428         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1429         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1430         return g_async_queue_length(priv->char_input_queue) > 0;
1431 }
1432
1433 /**
1434  * chimara_glk_is_line_input_pending:
1435  * @glk: a #ChimaraGlk widget
1436  *
1437  * Use this function to tell if line input forced by 
1438  * chimara_glk_feed_line_input() has been passed to an input request or not.
1439  *
1440  * Returns: %TRUE if forced line input is pending, %FALSE otherwise.
1441  */
1442 gboolean
1443 chimara_glk_is_line_input_pending(ChimaraGlk *glk)
1444 {
1445         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1446         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1447         return g_async_queue_length(priv->line_input_queue) > 0;
1448 }
1449
1450 /**
1451  * chimara_glk_get_tag:
1452  * @glk: a #ChimaraGlk widget
1453  * @window: The type of window to retrieve the tag for
1454  * @name: The name of the tag to retrieve
1455  *
1456  * Use this function to get a #GtkTextTag so style properties can be changed.
1457  * See also chimara_glk_set_css_from_string().
1458  *
1459  * The layout of the text in Chimara is controlled by two sets of tags: one set
1460  * describing the style in text buffers and one for text grids. See also the
1461  * Glk specification for the difference between the two. The main narrative of
1462  * a game is usually rendered in text buffers, whereas text grids are mostly
1463  * used for status bars and in game menus.
1464  *
1465  * The following tag names are supported:
1466  * <itemizedlist>
1467  *      <listitem><para>normal</para></listitem>
1468  *      <listitem><para>emphasized</para></listitem>
1469  *      <listitem><para>preformatted</para></listitem>
1470  *      <listitem><para>header</para></listitem>
1471  *      <listitem><para>subheader</para></listitem>
1472  *      <listitem><para>alert</para></listitem>
1473  *      <listitem><para>note</para></listitem>
1474  *      <listitem><para>block-quote</para></listitem>
1475  *      <listitem><para>input</para></listitem>
1476  *      <listitem><para>user1</para></listitem>
1477  *      <listitem><para>user2</para></listitem>
1478  *      <listitem><para>hyperlink</para></listitem>
1479  *      <listitem><para>pager</para></listitem>
1480  * </itemizedlist>
1481  *
1482  * Returns: (transfer none): The #GtkTextTag corresponding to @name in the
1483  * styles of @window.
1484  */
1485 GtkTextTag *
1486 chimara_glk_get_tag(ChimaraGlk *glk, ChimaraGlkWindowType window, const gchar *name)
1487 {
1488         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1489
1490         switch(window) {
1491         case CHIMARA_GLK_TEXT_BUFFER:
1492                 return GTK_TEXT_TAG( g_hash_table_lookup(priv->styles->text_buffer, name) );
1493                 break;
1494         case CHIMARA_GLK_TEXT_GRID:
1495                 return GTK_TEXT_TAG( g_hash_table_lookup(priv->styles->text_grid, name) );
1496                 break;
1497         default:
1498                 ILLEGAL_PARAM("Unknown window type: %u", window);
1499                 return NULL;
1500         }
1501 }
1502
1503 /**
1504  * chimara_glk_get_tag_names:
1505  * @num_tags: Return location for the number of tag names retrieved.
1506  *
1507  * Class method. Retrieves the possible tag names to use in
1508  * chimara_glk_get_tag().
1509  *
1510  * Returns: (transfer none) (array length=num_tags) (element-type utf8):
1511  * Array of strings containing the tag names. This array is owned by Chimara,
1512  * do not free it.
1513  */
1514 const gchar **
1515 chimara_glk_get_tag_names(unsigned int *num_tags)
1516 {
1517         g_return_val_if_fail(num_tags != NULL, NULL);
1518
1519         *num_tags = CHIMARA_NUM_STYLES;
1520         return style_get_tag_names();
1521 }
1522
1523 /**
1524  * chimara_glk_update_style:
1525  * @glk: a #ChimaraGlk widget
1526  *
1527  * Processes style updates and updates the widget to reflect the new style.
1528  * Call this every time you change a property of a #GtkTextTag retrieved by
1529  * chimara_glk_get_tag().
1530  */
1531 void
1532 chimara_glk_update_style(ChimaraGlk *glk)
1533 {
1534         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1535         style_update(glk);
1536
1537         /* Schedule a redraw */
1538         g_mutex_lock(priv->arrange_lock);
1539         priv->needs_rearrange = TRUE;
1540         priv->ignore_next_arrange_event = TRUE;
1541         g_mutex_unlock(priv->arrange_lock);
1542         gtk_widget_queue_resize( GTK_WIDGET(priv->self) );
1543 }
1544
1545 /**
1546  * chimara_glk_set_resource_load_callback:
1547  * @glk: a #ChimaraGlk widget
1548  * @func: a function to call for loading resources, or %NULL
1549  * @user_data: user data to pass to @func, or %NULL
1550  * @destroy_user_data: a function to call for freeing @user_data, or %NULL
1551  *
1552  * Sometimes it is preferable to load image and sound resources from somewhere
1553  * else than a Blorb file, for example while developing a game. Section 14 of
1554  * the <ulink url="http://eblong.com/zarf/blorb/blorb.html#s14">Blorb
1555  * specification</ulink> allows for this possibility. This function sets @func
1556  * to be called when the Glk program requests loading an image or sound without
1557  * a Blorb resource map having been loaded, optionally passing @user_data as an 
1558  * extra parameter.
1559  *
1560  * Note that @func is only called if no Blorb resource map has been set; having
1561  * a resource map in place overrides this function.
1562  *
1563  * If you pass non-%NULL for @destroy_user_data, then @glk takes ownership of
1564  * @user_data. When it is not needed anymore, it will be freed by calling
1565  * @destroy_user_data on it. If you wish to retain ownership of @user_data, pass
1566  * %NULL for @destroy_user_data.
1567  *
1568  * To deactivate the callback, call this function with @func set to %NULL.
1569  */
1570 void
1571 chimara_glk_set_resource_load_callback(ChimaraGlk *glk, ChimaraResourceLoadFunc func, gpointer user_data, GDestroyNotify destroy_user_data)
1572 {
1573         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1574
1575         if(priv->resource_load_callback == func
1576                 && priv->resource_load_callback_data == user_data
1577                 && priv->resource_load_callback_destroy_data == destroy_user_data)
1578                 return;
1579
1580         if(priv->resource_load_callback_destroy_data)
1581                 priv->resource_load_callback_destroy_data(priv->resource_load_callback_data);
1582
1583         priv->resource_load_callback = func;
1584         priv->resource_load_callback_data = user_data;
1585         priv->resource_load_callback_destroy_data = destroy_user_data;
1586 }