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