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