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