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