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