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