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