Played around with nitfol build process, adding rules to generate the
[rodin/chimara.git] / libchimara / chimara-glk.c
1 /* licensing and copyright information here */
2
3 #include <math.h>
4 #include <gtk/gtk.h>
5 #include <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(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 };
933
934 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
935 static gpointer
936 glk_enter(struct StartupData *startup)
937 {
938     extern ChimaraGlkPrivate *glk_data;
939         
940         /* Run startup function */
941         if(startup->glkunix_startup_code) {
942                 glk_data->in_startup = TRUE;
943                 int result = startup->glkunix_startup_code(&startup->args);
944                 glk_data->in_startup = FALSE;
945                 
946                 int i = 0;
947                 while(i < startup->args.argc)
948                         g_free(startup->args.argv[i++]);
949                 g_free(startup->args.argv);
950                 
951                 if(!result)
952                         return NULL;
953         }
954         
955         /* Run main function */
956     g_signal_emit_by_name(glk_data->self, "started");
957         (startup->glk_main)();
958         g_slice_free(struct StartupData, startup);      
959         g_signal_emit_by_name(glk_data->self, "stopped");
960         return NULL;
961 }
962
963 /**
964  * chimara_glk_run:
965  * @glk: a #ChimaraGlk widget
966  * @plugin: path to a plugin module compiled with <filename 
967  * class="header">glk.h</filename>
968  * @argc: Number of command line arguments in @argv
969  * @argv: Array of command line arguments to pass to the plugin
970  * @error: location to store a <link linkend="glib-GError">GError</link>, or 
971  * %NULL
972  *
973  * Opens a Glk program compiled as a plugin. Sorts out its command line
974  * arguments from #glkunix_arguments, calls its startup function
975  * glkunix_startup_code(), and then calls its main function glk_main() in
976  * a separate thread. On failure, returns %FALSE and sets @error.
977  *
978  * The plugin must at least export a glk_main() function; #glkunix_arguments and
979  * glkunix_startup_code() are optional.
980  *
981  * Return value: %TRUE if the Glk program was started successfully.
982  */
983 gboolean
984 chimara_glk_run(ChimaraGlk *glk, gchar *plugin, int argc, char *argv[], GError **error)
985 {
986     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
987     g_return_val_if_fail(plugin, FALSE);
988     
989     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
990         struct StartupData *startup = g_slice_new0(struct StartupData);
991     
992     /* Open the module to run */
993     g_assert( g_module_supported() );
994     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
995     
996     if(!priv->program)
997     {
998         g_warning( "Error opening module: %s", g_module_error() );
999         return FALSE;
1000     }
1001     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
1002     {
1003         g_warning( "Error finding glk_main(): %s", g_module_error() );
1004         return FALSE;
1005     }
1006
1007     if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
1008     {
1009                 glkunix_argumentlist_t *glkunix_arguments;
1010
1011                 if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
1012                           && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
1013                 {
1014                         /* arguments could not be parsed, so create data ourselves */
1015                         startup->args.argc = 1;
1016                         startup->args.argv = g_new0(gchar *, 1);
1017                 }
1018
1019                 /* Set the program name */
1020                 startup->args.argv[0] = g_strdup(plugin);
1021     }
1022
1023         extern ChimaraGlkPrivate *glk_data;
1024     /* Set the thread's private data */
1025     /* TODO: Do this with a GPrivate */
1026     glk_data = priv;
1027         
1028     /* Run in a separate thread */
1029         priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
1030         
1031         return !(priv->thread == NULL);
1032 }
1033
1034 /**
1035  * chimara_glk_stop:
1036  * @glk: a #ChimaraGlk widget
1037  *
1038  * Signals the Glk program running in @glk to abort. Note that if the program is
1039  * caught in an infinite loop in which glk_tick() is not called, this may not
1040  * work.
1041  */
1042 void
1043 chimara_glk_stop(ChimaraGlk *glk)
1044 {
1045     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1046     /* TODO: check if glk is actually running a program */
1047         signal_abort();
1048 }
1049
1050 /**
1051  * chimara_glk_wait:
1052  * @glk: a #ChimaraGlk widget
1053  *
1054  * Holds up the main thread and waits for the Glk program running in @glk to 
1055  * finish.
1056  */
1057 void
1058 chimara_glk_wait(ChimaraGlk *glk)
1059 {
1060     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1061     
1062     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1063     g_thread_join(priv->thread);
1064 }