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