Brought documentation up to date
[rodin/chimara.git] / libchimara / chimara-glk.c
index 00cc8b4c6b11e191957b5277a60b3bcc48aa8542..63849189a1788347e3427795e4e5b140599a869c 100644 (file)
@@ -1,17 +1,27 @@
 /* licensing and copyright information here */
 
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
 #include <math.h>
 #include <gtk/gtk.h>
-#include <glib/gi18n.h>
+#include <config.h>
+#include <glib/gi18n-lib.h>
 #include <gmodule.h>
 #include <pango/pango.h>
 #include "chimara-glk.h"
 #include "chimara-glk-private.h"
+#include "chimara-marshallers.h"
 #include "glk.h"
 #include "abort.h"
+#include "stream.h"
 #include "window.h"
 #include "glkstart.h"
 #include "glkunix.h"
+#include "init.h"
+#include "magic.h"
 
 #define CHIMARA_GLK_MIN_WIDTH 0
 #define CHIMARA_GLK_MIN_HEIGHT 0
@@ -22,7 +32,7 @@
  * @stability: Unstable
  * @include: chimara/chimara-glk.h
  * 
- * The ChimaraGlk widget opens and runs a Glk program. The program must be
+ * The #ChimaraGlk widget opens and runs a Glk program. The program must be
  * compiled as a plugin module, with a function <function>glk_main()</function>
  * that the Glk library can hook into.
  *
@@ -48,14 +58,16 @@ enum {
     PROP_0,
     PROP_INTERACTIVE,
     PROP_PROTECT,
-       PROP_DEFAULT_FONT_DESCRIPTION,
-       PROP_MONOSPACE_FONT_DESCRIPTION,
-       PROP_SPACING
+       PROP_SPACING,
 };
 
 enum {
        STOPPED,
        STARTED,
+       WAITING,
+       CHAR_INPUT,
+       LINE_INPUT,
+       TEXT_BUFFER_OUTPUT,
 
        LAST_SIGNAL
 };
@@ -74,21 +86,33 @@ chimara_glk_init(ChimaraGlk *self)
     priv->self = self;
     priv->interactive = TRUE;
     priv->protect = FALSE;
-       priv->default_font_desc = pango_font_description_from_string("Sans");
-       priv->monospace_font_desc = pango_font_description_from_string("Monospace");
+       priv->default_styles = g_new0(StyleSet,1);
+       priv->current_styles = g_new0(StyleSet,1);
+       priv->pager_attr_list = pango_attr_list_new();
+       priv->final_message = g_strdup("[ The game has finished ]");
+       priv->running = FALSE;
     priv->program = NULL;
     priv->thread = NULL;
-    priv->event_queue = NULL;
-    priv->event_lock = NULL;
-    priv->event_queue_not_empty = NULL;
-    priv->event_queue_not_full = NULL;
-    priv->abort_lock = NULL;
+    priv->event_queue = g_queue_new();
+    priv->event_lock = g_mutex_new();
+    priv->event_queue_not_empty = g_cond_new();
+    priv->event_queue_not_full = g_cond_new();
+    priv->abort_lock = g_mutex_new();
     priv->abort_signalled = FALSE;
-       priv->arrange_lock = NULL;
-       priv->rearranged = NULL;
+       priv->shutdown_lock = g_mutex_new();
+       priv->shutdown_key_pressed = g_cond_new();
+       priv->arrange_lock = g_mutex_new();
+       priv->rearranged = g_cond_new();
        priv->needs_rearrange = FALSE;
        priv->ignore_next_arrange_event = FALSE;
-    priv->interrupt_handler = NULL;
+       priv->char_input_queue = g_async_queue_new();
+       priv->line_input_queue = g_async_queue_new();
+       /* Should be g_async_queue_new_full(g_free); but only in GTK >= 2.16 */
+       priv->resource_lock = g_mutex_new();
+       priv->resource_loaded = g_cond_new();
+       priv->resource_info_available = g_cond_new();
+       priv->image_cache = NULL;
+       priv->interrupt_handler = NULL;
     priv->root_window = NULL;
     priv->fileref_list = NULL;
     priv->current_stream = NULL;
@@ -96,6 +120,8 @@ chimara_glk_init(ChimaraGlk *self)
        priv->timer_id = 0;
        priv->in_startup = FALSE;
        priv->current_dir = NULL;
+
+       style_init(self);
 }
 
 static void
@@ -111,12 +137,6 @@ chimara_glk_set_property(GObject *object, guint prop_id, const GValue *value, GP
         case PROP_PROTECT:
             chimara_glk_set_protect( glk, g_value_get_boolean(value) );
             break;
-               case PROP_DEFAULT_FONT_DESCRIPTION:
-                       chimara_glk_set_default_font_description( glk, (PangoFontDescription *)g_value_get_pointer(value) );
-                       break;
-               case PROP_MONOSPACE_FONT_DESCRIPTION:
-                       chimara_glk_set_monospace_font_description( glk, (PangoFontDescription *)g_value_get_pointer(value) );
-                       break;
                case PROP_SPACING:
                        chimara_glk_set_spacing( glk, g_value_get_uint(value) );
                        break;
@@ -138,12 +158,6 @@ chimara_glk_get_property(GObject *object, guint prop_id, GValue *value, GParamSp
         case PROP_PROTECT:
             g_value_set_boolean(value, priv->protect);
             break;
-               case PROP_DEFAULT_FONT_DESCRIPTION:
-                       g_value_set_pointer(value, priv->default_font_desc);
-                       break;
-               case PROP_MONOSPACE_FONT_DESCRIPTION:
-                       g_value_set_pointer(value, priv->monospace_font_desc);
-                       break;
                case PROP_SPACING:
                        g_value_set_uint(value, priv->spacing);
                        break;
@@ -156,8 +170,17 @@ static void
 chimara_glk_finalize(GObject *object)
 {
     ChimaraGlk *self = CHIMARA_GLK(object);
-    ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
-    
+       CHIMARA_GLK_USE_PRIVATE(self, priv);
+
+       /* Free widget properties */
+       g_free(priv->final_message);
+       /* Free styles */
+       g_hash_table_destroy(priv->default_styles->text_buffer);
+       g_hash_table_destroy(priv->default_styles->text_grid);
+       g_hash_table_destroy(priv->current_styles->text_buffer);
+       g_hash_table_destroy(priv->current_styles->text_grid);
+       pango_attr_list_unref(priv->pager_attr_list);
+       
     /* Free the event queue */
     g_mutex_lock(priv->event_lock);
        g_queue_foreach(priv->event_queue, (GFunc)g_free, NULL);
@@ -167,26 +190,38 @@ chimara_glk_finalize(GObject *object)
        priv->event_queue = NULL;
        g_mutex_unlock(priv->event_lock);
        g_mutex_free(priv->event_lock);
-       
-       /* Free the abort signalling mechanism */
+    /* Free the abort signaling mechanism */
        g_mutex_lock(priv->abort_lock);
        /* Make sure no other thread is busy with this */
        g_mutex_unlock(priv->abort_lock);
        g_mutex_free(priv->abort_lock);
        priv->abort_lock = NULL;
-
-       /* Free the window arrangement signalling */
+       /* Free the shutdown keypress signaling mechanism */
+       g_mutex_lock(priv->shutdown_lock);
+       g_cond_free(priv->shutdown_key_pressed);
+       g_mutex_unlock(priv->shutdown_lock);
+       priv->shutdown_lock = NULL;
+       /* Free the window arrangement signaling */
        g_mutex_lock(priv->arrange_lock);
        g_cond_free(priv->rearranged);
        g_mutex_unlock(priv->arrange_lock);
        g_mutex_free(priv->arrange_lock);
        priv->arrange_lock = NULL;
+       g_mutex_lock(priv->resource_lock);
+       g_cond_free(priv->resource_loaded);
+       g_cond_free(priv->resource_info_available);
+       g_mutex_unlock(priv->resource_lock);
+       g_mutex_free(priv->resource_lock);
+       g_slist_foreach(priv->image_cache, (GFunc)clear_image_cache, NULL);
+       g_slist_free(priv->image_cache);
+       /* Unref input queues (this should destroy them since any Glk thread has stopped by now */
+       g_async_queue_unref(priv->char_input_queue);
+       g_async_queue_unref(priv->line_input_queue);
        
-       /* Free private data */
-       pango_font_description_free(priv->default_font_desc);
-       pango_font_description_free(priv->monospace_font_desc);
+       /* Free other stuff */
        g_free(priv->current_dir);
-       
+
+       /* Chain up to parent */
     G_OBJECT_CLASS(chimara_glk_parent_class)->finalize(object);
 }
 
@@ -200,11 +235,14 @@ request_recurse(winid_t win, GtkRequisition *requisition, guint spacing)
                GtkRequisition child1, child2;
                request_recurse(win->window_node->children->data, &child1, spacing);
                request_recurse(win->window_node->children->next->data, &child2, spacing);
+
+               glui32 division = win->split_method & winmethod_DivisionMask;
+               glui32 direction = win->split_method & winmethod_DirMask;
                
                /* If the split is fixed, get the size of the fixed child */
-               if((win->split_method & winmethod_DivisionMask) == winmethod_Fixed)
+               if(division == winmethod_Fixed)
                {
-                       switch(win->split_method & winmethod_DirMask)
+                       switch(direction)
                        {
                                case winmethod_Left:
                                        child1.width = win->key_window?
@@ -230,7 +268,7 @@ request_recurse(winid_t win, GtkRequisition *requisition, guint spacing)
                }
                
                /* Add the children's requests */
-               switch(win->split_method & winmethod_DirMask)
+               switch(direction)
                {
                        case winmethod_Left:
                        case winmethod_Right:
@@ -282,15 +320,24 @@ allocate_recurse(winid_t win, GtkAllocation *allocation, guint spacing)
 {
        if(win->type == wintype_Pair)
        {
+               glui32 division = win->split_method & winmethod_DivisionMask;
+               glui32 direction = win->split_method & winmethod_DirMask;
+
+               /* If the space gets too small to honor the spacing property, then just 
+                ignore spacing in this window and below. */
+               if( (spacing > allocation->width && (direction == winmethod_Left || direction == winmethod_Right))
+                  || (spacing > allocation->height && (direction == winmethod_Above || direction == winmethod_Below)) )
+                       spacing = 0;
+               
                GtkAllocation child1, child2;
                child1.x = allocation->x;
                child1.y = allocation->y;
                
-               if((win->split_method & winmethod_DivisionMask) == winmethod_Fixed)
+               if(division == winmethod_Fixed)
                {
                        /* If the key window has been closed, then default to 0; otherwise
                         use the key window to determine the size */
-                       switch(win->split_method & winmethod_DirMask)
+                       switch(direction)
                        {
                                case winmethod_Left:
                                        child1.width = win->key_window? 
@@ -317,46 +364,46 @@ allocate_recurse(winid_t win, GtkAllocation *allocation, guint spacing)
                else /* proportional */
                {
                        gdouble fraction = win->constraint_size / 100.0;
-                       switch(win->split_method & winmethod_DirMask)
+                       switch(direction)
                        {
                                case winmethod_Left:
-                                       child1.width = (glui32) ceil( fraction * (allocation->width - spacing) );
+                                       child1.width = MAX(0, (gint)ceil(fraction * (allocation->width - spacing)) );
                                        break;
                                case winmethod_Right:
-                                       child2.width = (glui32) ceil( fraction * (allocation->width - spacing) );
+                                       child2.width = MAX(0, (gint)ceil(fraction * (allocation->width - spacing)) );
                                        break;
                                case winmethod_Above:
-                                       child1.height = (glui32) ceil( fraction * (allocation->height - spacing) );
+                                       child1.height = MAX(0, (gint)ceil(fraction * (allocation->height - spacing)) );
                                        break;
                                case winmethod_Below:
-                                       child2.height = (glui32) ceil( fraction * (allocation->height - spacing) );
+                                       child2.height = MAX(0, (gint)ceil(fraction * (allocation->height - spacing)) );
                                        break;
                        }
                }
                
                /* Fill in the rest of the size requisitions according to the child specified above */
-               switch(win->split_method & winmethod_DirMask)
+               switch(direction)
                {
                        case winmethod_Left:
-                               child2.width = allocation->width - spacing - child1.width;
+                               child2.width = MAX(0, allocation->width - spacing - child1.width);
                                child2.x = child1.x + child1.width + spacing;
                                child2.y = child1.y;
                                child1.height = child2.height = allocation->height;
                                break;
                        case winmethod_Right:
-                               child1.width = allocation->width - spacing - child2.width;
+                               child1.width = MAX(0, allocation->width - spacing - child2.width);
                                child2.x = child1.x + child1.width + spacing;
                                child2.y = child1.y;
                                child1.height = child2.height = allocation->height;
                                break;
                        case winmethod_Above:
-                               child2.height = allocation->height - spacing - child1.height;
+                               child2.height = MAX(0, allocation->height - spacing - child1.height);
                                child2.x = child1.x;
                                child2.y = child1.y + child1.height + spacing;
                                child1.width = child2.width = allocation->width;
                                break;
                        case winmethod_Below:
-                               child1.height = allocation->height - spacing - child2.height;
+                               child1.height = MAX(0, allocation->height - spacing - child2.height);
                                child2.x = child1.x;
                                child2.y = child1.y + child1.height + spacing;
                                child1.width = child2.width = allocation->width;
@@ -472,7 +519,7 @@ chimara_glk_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
                if(!priv->ignore_next_arrange_event)
                {
                        if(arrange)
-                               event_throw(evtype_Arrange, arrange == priv->root_window->data? NULL : arrange, 0, 0);
+                               event_throw(CHIMARA_GLK(widget), evtype_Arrange, arrange == priv->root_window->data? NULL : arrange, 0, 0);
                }
                else
                        priv->ignore_next_arrange_event = FALSE;
@@ -515,22 +562,51 @@ chimara_glk_forall(GtkContainer *container, gboolean include_internals, GtkCallb
 static void
 chimara_glk_stopped(ChimaraGlk *self)
 {
-    ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
-
-    /* Free the plugin */
-       if( priv->program && !g_module_close(priv->program) )
-           g_warning( "Error closing module: %s", g_module_error() );
+    CHIMARA_GLK_USE_PRIVATE(self, priv);
+    priv->running = FALSE;
 }
 
 static void
 chimara_glk_started(ChimaraGlk *self)
 {
-       /* TODO: Add default signal handler implementation here */
+       CHIMARA_GLK_USE_PRIVATE(self, priv);
+       priv->running = TRUE;
 }
 
-/* G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
+static void
+chimara_glk_waiting(ChimaraGlk *self)
+{
+       /* Default signal handler */
+}
+
+static void
+chimara_glk_char_input(ChimaraGlk *self, guint window_rock, guint keysym)
+{
+       /* Default signal handler */
+}
+
+static void
+chimara_glk_line_input(ChimaraGlk *self, guint window_rock, gchar *text)
+{
+       /* Default signal handler */
+}
+
+static void
+chimara_glk_text_buffer_output(ChimaraGlk *self, guint window_rock, gchar *text)
+{
+       /* Default signal handler */
+}
+
+/* COMPAT: G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
 #ifndef G_PARAM_STATIC_STRINGS
+
+/* COMPAT: G_PARAM_STATIC_NAME and friends only appeared in GTK 2.8 */
+#if GTK_CHECK_VERSION(2,8,0)
 #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
+#else
+#define G_PARAM_STATIC_STRINGS (0)
+#endif
+
 #endif
 
 static void
@@ -552,28 +628,85 @@ chimara_glk_class_init(ChimaraGlkClass *klass)
     /* Signals */
     klass->stopped = chimara_glk_stopped;
     klass->started = chimara_glk_started;
+    klass->waiting = chimara_glk_waiting;
+    klass->char_input = chimara_glk_char_input;
+    klass->line_input = chimara_glk_line_input;
+    klass->text_buffer_output = chimara_glk_text_buffer_output;
     /**
      * ChimaraGlk::stopped:
      * @glk: The widget that received the signal
      *
-     * The ::stopped signal is emitted when the a Glk program finishes
-     * executing in the widget, whether it ended normally, or was interrupted.
+     * Emitted when the a Glk program finishes executing in the widget, whether
+     * it ended normally, or was interrupted.
      */ 
     chimara_glk_signals[STOPPED] = g_signal_new("stopped", 
-        G_OBJECT_CLASS_TYPE(klass), 0, 
+        G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST, 
+        /* FIXME: Should be G_SIGNAL_RUN_CLEANUP but that segfaults??! */
         G_STRUCT_OFFSET(ChimaraGlkClass, stopped), NULL, NULL,
                g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
        /**
         * ChimaraGlk::started:
         * @glk: The widget that received the signal
         *
-        * The ::started signal is emitted when a Glk program starts executing in
-        * the widget.
+        * Emitted when a Glk program starts executing in the widget.
         */
        chimara_glk_signals[STARTED] = g_signal_new ("started",
-               G_OBJECT_CLASS_TYPE (klass), 0,
+               G_OBJECT_CLASS_TYPE(klass), G_SIGNAL_RUN_FIRST,
                G_STRUCT_OFFSET(ChimaraGlkClass, started), NULL, NULL,
                g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
+       /**
+        * ChimaraGlk::waiting:
+        * @glk: The widget that received the signal
+        * 
+        * Emitted when glk_select() is called by the Glk program and the event
+        * queue is empty, which means that the widget is waiting for input.
+        */
+       chimara_glk_signals[WAITING] = g_signal_new("waiting",
+               G_OBJECT_CLASS_TYPE(klass), 0,
+               G_STRUCT_OFFSET(ChimaraGlkClass, waiting), NULL, NULL,
+               g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
+       /**
+        * ChimaraGlk::char-input:
+        * @glk: The widget that received the signal
+        * @window_rock: The rock value of the window that received character input
+        * (see <link linkend="chimara-Rocks">Rocks</link>)
+        * @keysym: The key that was typed, in the form of a key symbol from 
+        * <filename class="headerfile">gdk/gdkkeysyms.h</filename>
+        * 
+        * Emitted when a Glk window receives character input.
+        */
+       chimara_glk_signals[CHAR_INPUT] = g_signal_new("char-input",
+               G_OBJECT_CLASS_TYPE(klass), 0,
+               G_STRUCT_OFFSET(ChimaraGlkClass, char_input), NULL, NULL,
+               chimara_marshal_VOID__UINT_UINT,
+               G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_UINT);
+       /**
+        * ChimaraGlk::line-input:
+        * @glk: The widget that received the signal
+        * @window_rock: The rock value of the window that received line input (see
+        * <link linkend="chimara-Rocks">Rocks</link>)
+        * @text: The text that was typed
+        * 
+        * Emitted when a Glk window receives line input.
+        */
+       chimara_glk_signals[LINE_INPUT] = g_signal_new("line-input",
+               G_OBJECT_CLASS_TYPE(klass), 0,
+               G_STRUCT_OFFSET(ChimaraGlkClass, line_input), NULL, NULL,
+               chimara_marshal_VOID__UINT_STRING,
+               G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
+       /**
+        * ChimaraGlk::text-buffer-output:
+        * @glk: The widget that received the signal
+        * @window_rock: The rock value of the window that was printed to (see <link
+        * linkend="chimara-Rocks">Rocks</link>)
+        * 
+        * Emitted when text is printed to a text buffer window.
+        */
+       chimara_glk_signals[TEXT_BUFFER_OUTPUT] = g_signal_new("text-buffer-output",
+               G_OBJECT_CLASS_TYPE(klass), 0,
+               G_STRUCT_OFFSET(ChimaraGlkClass, text_buffer_output), NULL, NULL,
+               chimara_marshal_VOID__UINT_STRING,
+               G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_STRING);
 
     /* Properties */
     /**
@@ -604,36 +737,6 @@ chimara_glk_class_init(ChimaraGlkClass *klass)
         FALSE,
         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
 
-       /* We can't use G_PARAM_CONSTRUCT on these because then the constructor will
-        initialize them with NULL */
-       /**
-        * ChimaraGlk:default-font-description:
-        * 
-        * Pointer to a #PangoFontDescription describing the default proportional 
-        * font, to be used in text buffer windows for example.
-        *
-        * Default value: font description created from the string 
-        * <quote>Sans</quote>
-        */
-       g_object_class_install_property(object_class, PROP_DEFAULT_FONT_DESCRIPTION, 
-               g_param_spec_pointer("default-font-description", _("Default Font"),
-               _("Font description of the default proportional font"),
-               G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
-
-       /**
-        * ChimaraGlk:monospace-font-description:
-        *
-        * Pointer to a #PangoFontDescription describing the default monospace font,
-        * to be used in text grid windows and %style_Preformatted, for example.
-        *
-        * Default value: font description created from the string 
-        * <quote>Monospace</quote>
-        */
-       g_object_class_install_property(object_class, PROP_MONOSPACE_FONT_DESCRIPTION, 
-               g_param_spec_pointer("monospace-font-description", _("Monospace Font"),
-               _("Font description of the default monospace font"),
-               G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
-
        /**
         * ChimaraGlk:spacing:
         *
@@ -651,6 +754,21 @@ chimara_glk_class_init(ChimaraGlkClass *klass)
 
 /* PUBLIC FUNCTIONS */
 
+/**
+ * chimara_error_quark:
+ *
+ * The error domain for errors from Chimara widgets.
+ *
+ * Returns: The string <quote>chimara-error-quark</quote> as a <link 
+ * linkend="GQuark">GQuark</link>.
+ */
+GQuark
+chimara_error_quark(void)
+{
+       chimara_init(); /* This is a library entry point */
+       return g_quark_from_static_string("chimara-error-quark");
+}
+
 /**
  * chimara_glk_new:
  *
@@ -661,18 +779,10 @@ chimara_glk_class_init(ChimaraGlkClass *klass)
 GtkWidget *
 chimara_glk_new(void)
 {
-    ChimaraGlk *self = CHIMARA_GLK(g_object_new(CHIMARA_TYPE_GLK, NULL));
-    ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
-    
-    priv->event_queue = g_queue_new();
-    priv->event_lock = g_mutex_new();
-    priv->event_queue_not_empty = g_cond_new();
-    priv->event_queue_not_full = g_cond_new();
-    priv->abort_lock = g_mutex_new();
-       priv->arrange_lock = g_mutex_new();
-       priv->rearranged = g_cond_new();
-    
-    return GTK_WIDGET(self);
+       /* This is a library entry point; initialize the library */
+       chimara_init();
+
+    return GTK_WIDGET(g_object_new(CHIMARA_TYPE_GLK, NULL));
 }
 
 /**
@@ -689,6 +799,7 @@ chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
     
     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
     priv->interactive = interactive;
+    g_object_notify(G_OBJECT(glk), "interactive");
 }
 
 /**
@@ -725,6 +836,7 @@ chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
     
     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
     priv->protect = protect;
+    g_object_notify(G_OBJECT(glk), "protect");
 }
 
 /**
@@ -746,137 +858,90 @@ chimara_glk_get_protect(ChimaraGlk *glk)
 }
 
 /**
- * chimara_glk_set_default_font_description:
+ * chimara_glk_set_css_to_default:
  * @glk: a #ChimaraGlk widget
- * @font: a #PangoFontDescription
  *
- * Sets @glk's default proportional font. See 
- * #ChimaraGlk:default-font-description.
+ * Resets the styles for text buffer and text grid windows to their defaults.
+ * <para><warning>
+ *   This function is not implemented yet.
+ * </warning></para>
  */
-void 
-chimara_glk_set_default_font_description(ChimaraGlk *glk, PangoFontDescription *font)
+void
+chimara_glk_set_css_to_default(ChimaraGlk *glk)
 {
-       g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-       g_return_if_fail(font);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       pango_font_description_free(priv->default_font_desc);
-       priv->default_font_desc = pango_font_description_copy(font);
-       
-       /* TODO: Apply the font description to all the windows and recalculate the sizes */
+       reset_default_styles(glk);
 }
 
 /**
- * chimara_glk_set_default_font_string:
+ * chimara_glk_set_css_from_file:
  * @glk: a #ChimaraGlk widget
- * @font: string representation of a font description
+ * @filename: path to a CSS file, or %NULL
+ * @error: location to store a <link linkend="glib-GError">GError</link>, or 
+ * %NULL
  *
- * Sets @glk's default proportional font according to the string @font, which
- * must be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
- * [<replaceable>STYLE-OPTIONS</replaceable>] 
- * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Charter,Utopia 
- * Italic 12</quote> or <quote>Sans</quote>. See 
- * #ChimaraGlk:default-font-description.
- */
-void 
-chimara_glk_set_default_font_string(ChimaraGlk *glk, const gchar *font)
-{
-       g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-       g_return_if_fail(font || *font);
-       
-       PangoFontDescription *fontdesc = pango_font_description_from_string(font);
-       g_return_if_fail(fontdesc);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       pango_font_description_free(priv->default_font_desc);
-       priv->default_font_desc = fontdesc;
-       
-       /* TODO: Apply the font description to all the windows and recalculate the sizes */
-}
-       
-/**
- * chimara_glk_get_default_font_description:
- * @glk: a #ChimaraGlk widget
- * 
- * Returns @glk's default proportional font.
+ * Sets the styles for text buffer and text grid windows according to the CSS
+ * file @filename. Note that the styles are set cumulatively on top of whatever
+ * the styles are at the time this function is called; to reset the styles to
+ * their defaults, use chimara_glk_set_css_to_default().
  *
- * Return value: a newly-allocated #PangoFontDescription which must be freed
- * using pango_font_description_free(), or %NULL on error.
+ * Returns: %TRUE on success, %FALSE if an error occurred, in which case @error
+ * will be set.
  */
-PangoFontDescription *
-chimara_glk_get_default_font_description(ChimaraGlk *glk)
+gboolean 
+chimara_glk_set_css_from_file(ChimaraGlk *glk, const gchar *filename, GError **error)
 {
-       g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       return pango_font_description_copy(priv->default_font_desc);
-}
+       g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
+       g_return_val_if_fail(filename, FALSE);
+       g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
 
-/**
- * chimara_glk_set_monospace_font_description:
- * @glk: a #ChimaraGlk widget
- * @font: a #PangoFontDescription
- *
- * Sets @glk's default monospace font. See 
- * #ChimaraGlk:monospace-font-description.
- */
-void 
-chimara_glk_set_monospace_font_description(ChimaraGlk *glk, PangoFontDescription *font)
-{
-       g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-       g_return_if_fail(font);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       pango_font_description_free(priv->monospace_font_desc);
-       priv->monospace_font_desc = pango_font_description_copy(font);
+       int fd = open(filename, O_RDONLY);
+       if(fd == -1) {
+               *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno), 
+                   _("Error opening file \"%s\": %s"), filename, g_strerror(errno));
+               return FALSE;
+       }
+
+       GScanner *scanner = create_css_file_scanner();
+       g_scanner_input_file(scanner, fd);
+       scanner->input_name = filename;
+       scan_css_file(scanner, glk);
+
+       /* Set the current style to a copy of the default style */
+       /* FIXME this is not correct */
+       copy_default_styles_to_current_styles(glk);
        
-       /* TODO: Apply the font description to all the windows and recalculate the sizes */
+       if(close(fd) == -1) {
+               *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno),
+                   _("Error closing file \"%s\": %s"), filename, g_strerror(errno));
+               return FALSE;
+       }
+       return TRUE;
 }
 
 /**
- * chimara_glk_set_monospace_font_string:
+ * chimara_glk_set_css_from_string:
  * @glk: a #ChimaraGlk widget
- * @font: string representation of a font description
+ * @filename: a string containing CSS code
  *
- * Sets @glk's default monospace font according to the string @font, which must
- * be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
- * [<replaceable>STYLE-OPTIONS</replaceable>] 
- * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Courier 
- * Bold 12</quote> or <quote>Monospace</quote>. See 
- * #ChimaraGlk:monospace-font-description.
+ * Sets the styles for text buffer and text grid windows according to the CSS
+ * code @css. Note that the styles are set cumulatively on top of whatever the 
+ * styles are at the time this function is called; to reset the styles to their
+ * defaults, use chimara_glk_set_css_to_default().
  */
 void 
-chimara_glk_set_monospace_font_string(ChimaraGlk *glk, const gchar *font)
+chimara_glk_set_css_from_string(ChimaraGlk *glk, const gchar *css)
 {
        g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-       g_return_if_fail(font || *font);
-       
-       PangoFontDescription *fontdesc = pango_font_description_from_string(font);
-       g_return_if_fail(fontdesc);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       pango_font_description_free(priv->monospace_font_desc);
-       priv->monospace_font_desc = fontdesc;
+       g_return_if_fail(css || *css);
        
-       /* TODO: Apply the font description to all the windows and recalculate the sizes */
-}
-       
-/**
- * chimara_glk_get_monospace_font_description:
- * @glk: a #ChimaraGlk widget
- * 
- * Returns @glk's default monospace font.
- *
- * Return value: a newly-allocated #PangoFontDescription which must be freed
- * using pango_font_description_free(), or %NULL on error.
- */
-PangoFontDescription *
-chimara_glk_get_monospace_font_description(ChimaraGlk *glk)
-{
-       g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
-       
-       ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-       return pango_font_description_copy(priv->monospace_font_desc);
+       GScanner *scanner = create_css_file_scanner();
+       g_scanner_input_text(scanner, css, strlen(css));
+       scanner->input_name = "<string>";
+       scan_css_file(scanner, glk);
+
+       /* Set the current style to a copy of the default style */
+       /* FIXME this is not correct */
+       copy_default_styles_to_current_styles(glk);
 }
 
 /**
@@ -894,6 +959,7 @@ chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
        
        ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
        priv->spacing = spacing;
+       g_object_notify(G_OBJECT(glk), "spacing");
 }
 
 /**
@@ -913,16 +979,49 @@ chimara_glk_get_spacing(ChimaraGlk *glk)
        return priv->spacing;
 }
 
+struct StartupData {
+       glk_main_t glk_main;
+       glkunix_startup_code_t glkunix_startup_code;
+       glkunix_startup_t args;
+       ChimaraGlkPrivate *glk_data;
+};
+
 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
 static gpointer
-glk_enter(gpointer glk_main)
+glk_enter(struct StartupData *startup)
 {
-    extern ChimaraGlkPrivate *glk_data;
-
-    g_signal_emit_by_name(glk_data->self, "started");
-       ((glk_main_t)glk_main)();
-       g_signal_emit_by_name(glk_data->self, "stopped");
-       return NULL;
+       extern GPrivate *glk_data_key;
+       g_private_set(glk_data_key, startup->glk_data);
+       
+       /* Acquire the Glk thread's references to the input queues */
+       g_async_queue_ref(startup->glk_data->char_input_queue);
+       g_async_queue_ref(startup->glk_data->line_input_queue);
+       
+       /* Run startup function */
+       if(startup->glkunix_startup_code) {
+               startup->glk_data->in_startup = TRUE;
+               int result = startup->glkunix_startup_code(&startup->args);
+               startup->glk_data->in_startup = FALSE;
+               
+               int i = 0;
+               while(i < startup->args.argc)
+                       g_free(startup->args.argv[i++]);
+               g_free(startup->args.argv);
+               
+               if(!result)
+                       return NULL;
+       }
+       
+       /* Run main function */
+       glk_main_t glk_main = startup->glk_main;
+       
+       /* COMPAT: avoid usage of slices */
+       g_free(startup);
+    g_signal_emit_by_name(startup->glk_data->self, "started");
+       glk_main();
+       glk_exit(); /* Run shutdown code in glk_exit() even if glk_main() returns normally */
+       g_assert_not_reached(); /* because glk_exit() calls g_thread_exit() */
+       return NULL; 
 }
 
 /**
@@ -946,69 +1045,60 @@ glk_enter(gpointer glk_main)
  * Return value: %TRUE if the Glk program was started successfully.
  */
 gboolean
-chimara_glk_run(ChimaraGlk *glk, gchar *plugin, int argc, char *argv[], GError **error)
+chimara_glk_run(ChimaraGlk *glk, const gchar *plugin, int argc, char *argv[], GError **error)
 {
     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
     g_return_val_if_fail(plugin, FALSE);
+       g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
+       
+       if(chimara_glk_get_running(glk)) {
+               g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_ALREADY_RUNNING, _("There was already a plugin running."));
+               return FALSE;
+       }
     
     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
-    
-    /* Open the module to run */
-    glk_main_t glk_main;
-       glkunix_startup_code_t glkunix_startup_code;
+
+       /* COMPAT: avoid usage of slices */
+       struct StartupData *startup = g_new0(struct StartupData,1);
+       
     g_assert( g_module_supported() );
+       /* If there is already a module loaded, free it first -- you see, we want to
+        * keep modules loaded as long as possible to avoid crashes in stack unwinding */
+       if( priv->program && !g_module_close(priv->program) )
+               g_warning( "Error closing module :%s", g_module_error() );
+       /* Open the module to run */
     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
     
     if(!priv->program)
     {
-        g_warning( "Error opening module: %s", g_module_error() );
+       g_set_error(error, CHIMARA_ERROR, CHIMARA_LOAD_MODULE_ERROR, _("Error opening module: %s"), g_module_error());
         return FALSE;
     }
-    if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &glk_main) )
+    if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
     {
-        g_warning( "Error finding glk_main(): %s", g_module_error() );
+       g_set_error(error, CHIMARA_ERROR, CHIMARA_NO_GLK_MAIN, _("Error finding glk_main(): %s"), g_module_error());
         return FALSE;
     }
 
-       extern ChimaraGlkPrivate *glk_data;
-    /* Set the thread's private data */
-    /* TODO: Do this with a GPrivate */
-    glk_data = priv;
-       
-    if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &glkunix_startup_code) )
+    if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
     {
-               glkunix_startup_t data;
                glkunix_argumentlist_t *glkunix_arguments;
-               gboolean startup_succeeded;
 
-               if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) && parse_command_line(glkunix_arguments, argc, argv, &data)) )
+               if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
+                         && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
                {
                        /* arguments could not be parsed, so create data ourselves */
-                       data.argc = 1;
-                       data.argv = g_new0(gchar *, 1);
+                       startup->args.argc = 1;
+                       startup->args.argv = g_new0(gchar *, 1);
                }
 
                /* Set the program name */
-               data.argv[0] = g_strdup(plugin);
-               
-               priv->in_startup = TRUE;
-               startup_succeeded = glkunix_startup_code(&data);
-               priv->in_startup = FALSE;
-               
-               gchar **ptr = data.argv;
-               while(*ptr++)
-                       g_free(*ptr);
-               g_free(data.argv);
-               
-               if(!startup_succeeded)
-               {
-                       chimara_glk_stopped(glk);
-                       return FALSE;
-               }
+               startup->args.argv[0] = g_strdup(plugin);
     }
+       startup->glk_data = priv;
        
     /* Run in a separate thread */
-       priv->thread = g_thread_create(glk_enter, glk_main, TRUE, error);
+       priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
        
        return !(priv->thread == NULL);
 }
@@ -1025,8 +1115,23 @@ void
 chimara_glk_stop(ChimaraGlk *glk)
 {
     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-    /* TODO: check if glk is actually running a program */
-    signal_abort();
+    CHIMARA_GLK_USE_PRIVATE(glk, priv);
+
+    /* Don't do anything if not running a program */
+    if(!priv->running)
+       return;
+    
+       if(priv->abort_lock) {
+               g_mutex_lock(priv->abort_lock);
+               priv->abort_signalled = TRUE;
+               g_mutex_unlock(priv->abort_lock);
+               /* Stop blocking on the event queue condition */
+               event_throw(glk, evtype_Abort, NULL, 0, 0);
+               /* Stop blocking on the shutdown key press condition */
+               g_mutex_lock(priv->shutdown_lock);
+               g_cond_signal(priv->shutdown_key_pressed);
+               g_mutex_unlock(priv->shutdown_lock);
+       }
 }
 
 /**
@@ -1040,7 +1145,73 @@ void
 chimara_glk_wait(ChimaraGlk *glk)
 {
     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
-    
-    ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
+    CHIMARA_GLK_USE_PRIVATE(glk, priv);
+    /* Don't do anything if not running a program */
+    if(!priv->running)
+       return;
+       /* Unlock GDK mutex, because the Glk program might need to use it for shutdown */
+       gdk_threads_leave();
     g_thread_join(priv->thread);
+       gdk_threads_enter();
+}
+
+/**
+ * chimara_glk_get_running:
+ * @glk: a #ChimaraGlk widget
+ * 
+ * Use this function to tell whether a program is currently running in the
+ * widget.
+ * 
+ * Returns: %TRUE if @glk is executing a Glk program, %FALSE otherwise.
+ */
+gboolean
+chimara_glk_get_running(ChimaraGlk *glk)
+{
+       g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
+       CHIMARA_GLK_USE_PRIVATE(glk, priv);
+       return priv->running;
+}
+
+/**
+ * chimara_glk_feed_char_input:
+ * @glk: a #ChimaraGlk widget
+ * @keyval: a key symbol as defined in <filename 
+ * class="headerfile">gdk/gdkkeysyms.h</filename>
+ * 
+ * Pretend that a key was pressed in the Glk program as a response to a 
+ * character input request. You can call this function even when no window has
+ * requested character input, in which case the key will be saved for the 
+ * following window that requests character input. This has the disadvantage 
+ * that if more than one window has requested character input, it is arbitrary 
+ * which one gets the key press.
+ */
+void 
+chimara_glk_feed_char_input(ChimaraGlk *glk, guint keyval)
+{
+       g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
+       CHIMARA_GLK_USE_PRIVATE(glk, priv);
+       g_async_queue_push(priv->char_input_queue, GUINT_TO_POINTER(keyval));
+       event_throw(glk, evtype_ForcedCharInput, NULL, 0, 0);
+}
+
+/**
+ * chimara_glk_feed_line_input:
+ * @glk: a #ChimaraGlk widget
+ * @text: text to pass to the next line input request
+ * 
+ * Pretend that @text was typed in the Glk program as a response to a line input
+ * request. @text does not need to end with a newline. You can call this 
+ * function even when no window has requested line input, in which case the text
+ * will be saved for the following window that requests line input. This has the 
+ * disadvantage that if more than one window has requested character input, it 
+ * is arbitrary which one gets the text.
+ */
+void 
+chimara_glk_feed_line_input(ChimaraGlk *glk, const gchar *text)
+{
+       g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
+       g_return_if_fail(text);
+       CHIMARA_GLK_USE_PRIVATE(glk, priv);
+       g_async_queue_push(priv->line_input_queue, g_strdup(text));
+       event_throw(glk, evtype_ForcedLineInput, NULL, 0, 0);
 }