Separated library source code from testing code, fixing #6
[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 <glib/gi18n.h>
6 #include <gmodule.h>
7 #include <pango/pango.h>
8 #include "chimara-glk.h"
9 #include "chimara-glk-private.h"
10 #include "glk.h"
11 #include "abort.h"
12 #include "window.h"
13
14 #define CHIMARA_GLK_MIN_WIDTH 0
15 #define CHIMARA_GLK_MIN_HEIGHT 0
16
17 /**
18  * SECTION:chimara-glk
19  * @short_description: Widget which executes a Glk program
20  * @stability: Unstable
21  * @include: chimara/chimara-glk.h
22  * 
23  * The ChimaraGlk widget opens and runs a Glk program. The program must be
24  * compiled as a plugin module, with a function <function>glk_main()</function>
25  * that the Glk library can hook into.
26  *
27  * On Linux systems, this is a file with a name like 
28  * <filename>plugin.so</filename>. For portability, you can use libtool and 
29  * automake:
30  * |[
31  * pkglib_LTLIBRARIES = plugin.la
32  * plugin_la_SOURCES = plugin.c foo.c bar.c
33  * plugin_la_LDFLAGS = -module -shared -avoid-version -export-symbols-regex "^glk_main$$"
34  * ]|
35  * This will produce <filename>plugin.la</filename> which is a text file 
36  * containing the correct plugin file to open (see the relevant section of the
37  * <ulink 
38  * url="http://www.gnu.org/software/libtool/manual/html_node/Finding-the-dlname.html">
39  * Libtool manual</ulink>).
40  */
41
42 typedef void (* glk_main_t) (void);
43
44 enum {
45     PROP_0,
46     PROP_INTERACTIVE,
47     PROP_PROTECT,
48         PROP_DEFAULT_FONT_DESCRIPTION,
49         PROP_MONOSPACE_FONT_DESCRIPTION,
50         PROP_SPACING
51 };
52
53 enum {
54         STOPPED,
55         STARTED,
56
57         LAST_SIGNAL
58 };
59
60 static guint chimara_glk_signals[LAST_SIGNAL] = { 0 };
61
62 G_DEFINE_TYPE(ChimaraGlk, chimara_glk, GTK_TYPE_CONTAINER);
63
64 static void
65 chimara_glk_init(ChimaraGlk *self)
66 {
67     GTK_WIDGET_SET_FLAGS(GTK_WIDGET(self), GTK_NO_WINDOW);
68
69     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
70     
71     priv->self = self;
72     priv->interactive = TRUE;
73     priv->protect = FALSE;
74         priv->default_font_desc = pango_font_description_from_string("Sans");
75         priv->monospace_font_desc = pango_font_description_from_string("Monospace");
76     priv->program = NULL;
77     priv->thread = NULL;
78     priv->event_queue = NULL;
79     priv->event_lock = NULL;
80     priv->event_queue_not_empty = NULL;
81     priv->event_queue_not_full = NULL;
82     priv->abort_lock = NULL;
83     priv->abort_signalled = FALSE;
84     priv->interrupt_handler = NULL;
85     priv->root_window = NULL;
86     priv->fileref_list = NULL;
87     priv->current_stream = NULL;
88     priv->stream_list = NULL;
89         priv->timer_id = 0;
90 }
91
92 static void
93 chimara_glk_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
94 {
95     ChimaraGlk *glk = CHIMARA_GLK(object);
96     
97     switch(prop_id) 
98     {
99         case PROP_INTERACTIVE:
100             chimara_glk_set_interactive( glk, g_value_get_boolean(value) );
101             break;
102         case PROP_PROTECT:
103             chimara_glk_set_protect( glk, g_value_get_boolean(value) );
104             break;
105                 case PROP_DEFAULT_FONT_DESCRIPTION:
106                         chimara_glk_set_default_font_description( glk, (PangoFontDescription *)g_value_get_pointer(value) );
107                         break;
108                 case PROP_MONOSPACE_FONT_DESCRIPTION:
109                         chimara_glk_set_monospace_font_description( glk, (PangoFontDescription *)g_value_get_pointer(value) );
110                         break;
111                 case PROP_SPACING:
112                         chimara_glk_set_spacing( glk, g_value_get_uint(value) );
113                         break;
114         default:
115             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
116     }
117 }
118
119 static void
120 chimara_glk_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
121 {
122     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(object);
123     
124     switch(prop_id)
125     {
126         case PROP_INTERACTIVE:
127             g_value_set_boolean(value, priv->interactive);
128             break;
129         case PROP_PROTECT:
130             g_value_set_boolean(value, priv->protect);
131             break;
132                 case PROP_DEFAULT_FONT_DESCRIPTION:
133                         g_value_set_pointer(value, priv->default_font_desc);
134                         break;
135                 case PROP_MONOSPACE_FONT_DESCRIPTION:
136                         g_value_set_pointer(value, priv->monospace_font_desc);
137                         break;
138                 case PROP_SPACING:
139                         g_value_set_uint(value, priv->spacing);
140                         break;
141         default:
142             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
143     }
144 }
145
146 static void
147 chimara_glk_finalize(GObject *object)
148 {
149     ChimaraGlk *self = CHIMARA_GLK(object);
150     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
151     
152     /* Free the event queue */
153     g_mutex_lock(priv->event_lock);
154         g_queue_foreach(priv->event_queue, (GFunc)g_free, NULL);
155         g_queue_free(priv->event_queue);
156         g_cond_free(priv->event_queue_not_empty);
157         g_cond_free(priv->event_queue_not_full);
158         priv->event_queue = NULL;
159         g_mutex_unlock(priv->event_lock);
160         g_mutex_free(priv->event_lock);
161         
162         /* Free the abort signalling mechanism */
163         g_mutex_lock(priv->abort_lock);
164         /* Make sure no other thread is busy with this */
165         g_mutex_unlock(priv->abort_lock);
166         g_mutex_free(priv->abort_lock);
167         priv->abort_lock = NULL;
168
169         /* Free private data */
170         pango_font_description_free(priv->default_font_desc);
171         pango_font_description_free(priv->monospace_font_desc);
172         
173     G_OBJECT_CLASS(chimara_glk_parent_class)->finalize(object);
174 }
175
176 /* Internal function: Recursively get the Glk window tree's size request */
177 static void
178 request_recurse(winid_t win, GtkRequisition *requisition, guint spacing)
179 {
180         if(win->type == wintype_Pair)
181         {
182                 /* Get children's size requests */
183                 GtkRequisition child1, child2;
184                 request_recurse(win->window_node->children->data, &child1, spacing);
185                 request_recurse(win->window_node->children->next->data, &child2, spacing);
186                 
187                 /* If the split is fixed, get the size of the fixed child */
188                 if((win->split_method & winmethod_DivisionMask) == winmethod_Fixed)
189                 {
190                         switch(win->split_method & winmethod_DirMask)
191                         {
192                                 case winmethod_Left:
193                                         child1.width = win->key_window?
194                                                 win->constraint_size * win->key_window->unit_width
195                                                 : 0;
196                                         break;
197                                 case winmethod_Right:
198                                         child2.width = win->key_window?
199                                                 win->constraint_size * win->key_window->unit_width
200                                                 : 0;
201                                         break;
202                                 case winmethod_Above:
203                                         child1.height = win->key_window?
204                                                 win->constraint_size * win->key_window->unit_height
205                                                 : 0;
206                                         break;
207                                 case winmethod_Below:
208                                         child2.height = win->key_window?
209                                                 win->constraint_size * win->key_window->unit_height
210                                                 : 0;
211                                         break;
212                         }
213                 }
214                 
215                 /* Add the children's requests */
216                 switch(win->split_method & winmethod_DirMask)
217                 {
218                         case winmethod_Left:
219                         case winmethod_Right:
220                                 requisition->width = child1.width + child2.width + spacing;
221                                 requisition->height = MAX(child1.height, child2.height);
222                                 break;
223                         case winmethod_Above:
224                         case winmethod_Below:
225                                 requisition->width = MAX(child1.width, child2.width);
226                                 requisition->height = child1.height + child2.height + spacing;
227                                 break;
228                 }
229         }
230         
231         /* For non-pair windows, just use the size that GTK requests */
232         else
233                 gtk_widget_size_request(win->frame, requisition);
234 }
235
236 /* Overrides gtk_widget_size_request */
237 static void
238 chimara_glk_size_request(GtkWidget *widget, GtkRequisition *requisition)
239 {
240     g_return_if_fail(widget);
241     g_return_if_fail(requisition);
242     g_return_if_fail(CHIMARA_IS_GLK(widget));
243     
244     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
245     
246     /* For now, just pass the size request on to the root Glk window */
247     if(priv->root_window) 
248         {
249                 request_recurse(priv->root_window->data, requisition, priv->spacing);
250                 requisition->width += 2 * GTK_CONTAINER(widget)->border_width;
251                 requisition->height += 2 * GTK_CONTAINER(widget)->border_width;
252         } 
253         else 
254         {
255         requisition->width = CHIMARA_GLK_MIN_WIDTH + 2 * GTK_CONTAINER(widget)->border_width;
256         requisition->height = CHIMARA_GLK_MIN_HEIGHT + 2 * GTK_CONTAINER(widget)->border_width;
257     }
258 }
259
260 /* Recursively give the Glk windows their allocated space */
261 static void
262 allocate_recurse(winid_t win, GtkAllocation *allocation, guint spacing)
263 {
264         if(win->type == wintype_Pair)
265         {
266                 GtkAllocation child1, child2;
267                 child1.x = allocation->x;
268                 child1.y = allocation->y;
269                 
270                 if((win->split_method & winmethod_DivisionMask) == winmethod_Fixed)
271                 {
272                         /* If the key window has been closed, then default to 0; otherwise
273                          use the key window to determine the size */
274                         switch(win->split_method & winmethod_DirMask)
275                         {
276                                 case winmethod_Left:
277                                         child1.width = win->key_window? 
278                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - spacing) 
279                                                 : 0;
280                                         break;
281                                 case winmethod_Right:
282                                         child2.width = win->key_window? 
283                                                 CLAMP(win->constraint_size * win->key_window->unit_width, 0, allocation->width - spacing)
284                                                 : 0;
285                                         break;
286                                 case winmethod_Above:
287                                         child1.height = win->key_window? 
288                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - spacing)
289                                                 : 0;
290                                         break;
291                                 case winmethod_Below:
292                                         child2.height = win->key_window?
293                                                 CLAMP(win->constraint_size * win->key_window->unit_height, 0, allocation->height - spacing)
294                                                 : 0;
295                                         break;
296                         }
297                 }
298                 else /* proportional */
299                 {
300                         gdouble fraction = win->constraint_size / 100.0;
301                         switch(win->split_method & winmethod_DirMask)
302                         {
303                                 case winmethod_Left:
304                                         child1.width = (glui32) ceil( fraction * (allocation->width - spacing) );
305                                         break;
306                                 case winmethod_Right:
307                                         child2.width = (glui32) ceil( fraction * (allocation->width - spacing) );
308                                         break;
309                                 case winmethod_Above:
310                                         child1.height = (glui32) ceil( fraction * (allocation->height - spacing) );
311                                         break;
312                                 case winmethod_Below:
313                                         child2.height = (glui32) ceil( fraction * (allocation->height - spacing) );
314                                         break;
315                         }
316                 }
317                 
318                 /* Fill in the rest of the size requisitions according to the child specified above */
319                 switch(win->split_method & winmethod_DirMask)
320                 {
321                         case winmethod_Left:
322                                 child2.width = allocation->width - spacing - child1.width;
323                                 child2.x = child1.x + child1.width + spacing;
324                                 child2.y = child1.y;
325                                 child1.height = child2.height = allocation->height;
326                                 break;
327                         case winmethod_Right:
328                                 child1.width = allocation->width - spacing - child2.width;
329                                 child2.x = child1.x + child1.width + spacing;
330                                 child2.y = child1.y;
331                                 child1.height = child2.height = allocation->height;
332                                 break;
333                         case winmethod_Above:
334                                 child2.height = allocation->height - spacing - child1.height;
335                                 child2.x = child1.x;
336                                 child2.y = child1.y + child1.height + spacing;
337                                 child1.width = child2.width = allocation->width;
338                                 break;
339                         case winmethod_Below:
340                                 child1.height = allocation->height - spacing - child2.height;
341                                 child2.x = child1.x;
342                                 child2.y = child1.y + child1.height + spacing;
343                                 child1.width = child2.width = allocation->width;
344                                 break;
345                 }
346                 
347                 /* Recurse */
348                 allocate_recurse(win->window_node->children->data, &child1, spacing);
349                 allocate_recurse(win->window_node->children->next->data, &child2, spacing);
350         }
351         
352         else if(win->type == wintype_TextGrid)
353         {
354                 /* Pass the size allocation on to the framing widget */
355                 gtk_widget_size_allocate(win->frame, allocation);
356                 /* It says in the spec that when a text grid window is resized smaller,
357                  the bottom or right area is thrown away; when it is resized larger, the
358                  bottom or right area is filled with blanks. */
359                 glui32 newwidth = (glui32)(win->widget->allocation.width / win->unit_width);
360                 glui32 newheight = (glui32)(win->widget->allocation.height / win->unit_height);
361                 gint line;
362                 GtkTextBuffer *textbuffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
363                 GtkTextIter start, end;
364         
365                 for(line = 0; line < win->height; line++)
366                 {
367                         gtk_text_buffer_get_iter_at_line(textbuffer, &start, line);
368                         /* If this line is going to fall off the bottom, delete it */
369                         if(line >= newheight)
370                         {
371                                 end = start;
372                                 gtk_text_iter_forward_to_line_end(&end);
373                                 gtk_text_iter_forward_char(&end);
374                                 gtk_text_buffer_delete(textbuffer, &start, &end);
375                                 break;
376                         }
377                         /* If this line is not long enough, add spaces on the end */
378                         if(newwidth > win->width)
379                         {
380                                 gchar *spaces = g_strnfill(newwidth - win->width, ' ');
381                                 gtk_text_iter_forward_to_line_end(&start);
382                                 gtk_text_buffer_insert(textbuffer, &start, spaces, -1);
383                                 g_free(spaces);
384                         }
385                         /* But if it's too long, delete characters from the end */
386                         else if(newwidth < win->width)
387                         {
388                                 end = start;
389                                 gtk_text_iter_forward_chars(&start, newwidth);
390                                 gtk_text_iter_forward_to_line_end(&end);
391                                 gtk_text_buffer_delete(textbuffer, &start, &end);
392                         }
393                         /* Note: if the widths are equal, do nothing */
394                 }
395                 /* Add blank lines if there aren't enough lines to fit the new size */
396                 if(newheight > win->height)
397                 {
398                         gchar *blanks = g_strnfill(win->width, ' ');
399                     gchar **blanklines = g_new0(gchar *, (newheight - win->height) + 1);
400                     int count;
401                     for(count = 0; count < newheight - win->height; count++)
402                         blanklines[count] = blanks;
403                     blanklines[newheight - win->height] = NULL;
404                     gchar *text = g_strjoinv("\n", blanklines);
405                     g_free(blanklines); /* not g_strfreev() */
406                     g_free(blanks);
407                     
408                         gtk_text_buffer_get_end_iter(textbuffer, &start);
409                         gtk_text_buffer_insert(textbuffer, &start, "\n", -1);
410                     gtk_text_buffer_insert(textbuffer, &start, text, -1);
411                     g_free(text);
412                 }
413         
414                 win->width = newwidth;
415                 win->height = newheight;
416         }
417         
418         /* For non-pair, non-text-grid windows, just give them the size */
419         else
420                 gtk_widget_size_allocate(win->frame, allocation);
421 }
422
423 /* Overrides gtk_widget_size_allocate */
424 static void
425 chimara_glk_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
426 {
427     g_return_if_fail(widget);
428     g_return_if_fail(allocation);
429     g_return_if_fail(CHIMARA_IS_GLK(widget));
430     
431     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(widget);
432     
433     widget->allocation = *allocation;
434             
435     if(priv->root_window) {
436                 GtkAllocation child;
437                 child.x = allocation->x + GTK_CONTAINER(widget)->border_width;
438                 child.y = allocation->y + GTK_CONTAINER(widget)->border_width;
439                 child.width = CLAMP(allocation->width - 2 * GTK_CONTAINER(widget)->border_width, 0, allocation->width);
440                 child.height = CLAMP(allocation->height - 2 * GTK_CONTAINER(widget)->border_width, 0, allocation->height);
441                 allocate_recurse(priv->root_window->data, &child, priv->spacing);
442         }
443 }
444
445 /* Recursively invoke callback() on the GtkWidget of each non-pair window in the tree */
446 static void
447 forall_recurse(winid_t win, GtkCallback callback, gpointer callback_data)
448 {
449         if(win->type == wintype_Pair)
450         {
451                 forall_recurse(win->window_node->children->data, callback, callback_data);
452                 forall_recurse(win->window_node->children->next->data, callback, callback_data);
453         }
454         else
455                 (*callback)(win->frame, callback_data);
456 }
457
458 /* Overrides gtk_container_forall */
459 static void
460 chimara_glk_forall(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data)
461 {
462     g_return_if_fail(container);
463     g_return_if_fail(CHIMARA_IS_GLK(container));
464     
465     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(container);
466     
467         /* All the children are "internal" */
468         if(!include_internals)
469                 return;
470         
471     if(priv->root_window)
472                 forall_recurse(priv->root_window->data, callback, callback_data);
473 }
474
475 static void
476 chimara_glk_stopped(ChimaraGlk *self)
477 {
478     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
479
480     /* Free the plugin */
481         if( priv->program && !g_module_close(priv->program) )
482             g_warning( "Error closing module: %s", g_module_error() );
483 }
484
485 static void
486 chimara_glk_started(ChimaraGlk *self)
487 {
488         /* TODO: Add default signal handler implementation here */
489 }
490
491 /* G_PARAM_STATIC_STRINGS only appeared in GTK 2.13.0 */
492 #ifndef G_PARAM_STATIC_STRINGS
493 #define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
494 #endif
495
496 static void
497 chimara_glk_class_init(ChimaraGlkClass *klass)
498 {
499     /* Override methods of parent classes */
500     GObjectClass *object_class = G_OBJECT_CLASS(klass);
501     object_class->set_property = chimara_glk_set_property;
502     object_class->get_property = chimara_glk_get_property;
503     object_class->finalize = chimara_glk_finalize;
504     
505     GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass);
506     widget_class->size_request = chimara_glk_size_request;
507     widget_class->size_allocate = chimara_glk_size_allocate;
508
509     GtkContainerClass *container_class = GTK_CONTAINER_CLASS(klass);
510     container_class->forall = chimara_glk_forall;
511
512     /* Signals */
513     klass->stopped = chimara_glk_stopped;
514     klass->started = chimara_glk_started;
515     /**
516      * ChimaraGlk::stopped:
517      * @glk: The widget that received the signal
518      *
519      * The ::stopped signal is emitted when the a Glk program finishes
520      * executing in the widget, whether it ended normally, or was interrupted.
521      */ 
522     chimara_glk_signals[STOPPED] = g_signal_new("stopped", 
523         G_OBJECT_CLASS_TYPE(klass), 0, 
524         G_STRUCT_OFFSET(ChimaraGlkClass, stopped), NULL, NULL,
525                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
526         /**
527          * ChimaraGlk::started:
528          * @glk: The widget that received the signal
529          *
530          * The ::started signal is emitted when a Glk program starts executing in
531          * the widget.
532          */
533         chimara_glk_signals[STARTED] = g_signal_new ("started",
534                 G_OBJECT_CLASS_TYPE (klass), 0,
535                 G_STRUCT_OFFSET(ChimaraGlkClass, started), NULL, NULL,
536                 g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
537
538     /* Properties */
539     /**
540      * ChimaraGlk:interactive:
541      *
542      * Sets whether the widget is interactive. A Glk widget is normally 
543      * interactive, but in non-interactive mode, keyboard and mouse input are 
544      * ignored and the Glk program is controlled by chimara_glk_feed_text(). 
545      * <quote>More</quote> prompts when a lot of text is printed to a text 
546          * buffer are also disabled. This is typically used when you wish to control
547          * an interpreter program by feeding it a predefined list of commands.
548      */
549     g_object_class_install_property( object_class, PROP_INTERACTIVE, 
550                 g_param_spec_boolean("interactive", _("Interactive"),
551         _("Whether user input is expected in the Glk program"),
552         TRUE,
553         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
554
555         /**
556      * ChimaraGlk:protect:
557      *
558      * Sets whether the Glk program is allowed to do file operations. In protect
559      * mode, all file operations will fail.
560      */
561     g_object_class_install_property(object_class, PROP_PROTECT, 
562                 g_param_spec_boolean("protect", _("Protected"),
563         _("Whether the Glk program is barred from doing file operations"),
564         FALSE,
565         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
566
567         /* We can't use G_PARAM_CONSTRUCT on these because then the constructor will
568          initialize them with NULL */
569         /**
570          * ChimaraGlk:default-font-description:
571          * 
572          * Pointer to a #PangoFontDescription describing the default proportional 
573          * font, to be used in text buffer windows for example.
574          *
575          * Default value: font description created from the string 
576          * <quote>Sans</quote>
577          */
578         g_object_class_install_property(object_class, PROP_DEFAULT_FONT_DESCRIPTION, 
579                 g_param_spec_pointer("default-font-description", _("Default Font"),
580                 _("Font description of the default proportional font"),
581                 G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
582
583         /**
584          * ChimaraGlk:monospace-font-description:
585          *
586          * Pointer to a #PangoFontDescription describing the default monospace font,
587          * to be used in text grid windows and #style_Preformatted, for example.
588          *
589          * Default value: font description created from the string 
590          * <quote>Monospace</quote>
591          */
592         g_object_class_install_property(object_class, PROP_MONOSPACE_FONT_DESCRIPTION, 
593                 g_param_spec_pointer("monospace-font-description", _("Monospace Font"),
594                 _("Font description of the default monospace font"),
595                 G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
596
597         /**
598          * ChimaraGlk:spacing:
599          *
600          * The amount of space between the Glk windows.
601          */
602         g_object_class_install_property(object_class, PROP_SPACING,
603                 g_param_spec_uint("spacing", _("Spacing"),
604                 _("The amount of space between Glk windows"),
605                 0, G_MAXUINT, 0,
606                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
607         
608     /* Private data */
609     g_type_class_add_private(klass, sizeof(ChimaraGlkPrivate));
610 }
611
612 /* PUBLIC FUNCTIONS */
613
614 /**
615  * chimara_glk_new:
616  *
617  * Creates and initializes a new #ChimaraGlk widget.
618  *
619  * Return value: a #ChimaraGlk widget, with a floating reference.
620  */
621 GtkWidget *
622 chimara_glk_new(void)
623 {
624     ChimaraGlk *self = CHIMARA_GLK(g_object_new(CHIMARA_TYPE_GLK, NULL));
625     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(self);
626     
627     priv->event_queue = g_queue_new();
628     priv->event_lock = g_mutex_new();
629     priv->event_queue_not_empty = g_cond_new();
630     priv->event_queue_not_full = g_cond_new();
631     priv->abort_lock = g_mutex_new();
632     
633     return GTK_WIDGET(self);
634 }
635
636 /**
637  * chimara_glk_set_interactive:
638  * @glk: a #ChimaraGlk widget
639  * @interactive: whether the widget should expect user input
640  *
641  * Sets the #ChimaraGlk:interactive property of @glk. 
642  */
643 void 
644 chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
645 {
646     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
647     
648     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
649     priv->interactive = interactive;
650 }
651
652 /**
653  * chimara_glk_get_interactive:
654  * @glk: a #ChimaraGlk widget
655  *
656  * Returns whether @glk is interactive (expecting user input). See 
657  * #ChimaraGlk:interactive.
658  *
659  * Return value: %TRUE if @glk is interactive.
660  */
661 gboolean 
662 chimara_glk_get_interactive(ChimaraGlk *glk)
663 {
664     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
665     
666     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
667     return priv->interactive;
668 }
669
670 /**
671  * chimara_glk_set_protect:
672  * @glk: a #ChimaraGlk widget
673  * @protect: whether the widget should allow the Glk program to do file 
674  * operations
675  *
676  * Sets the #ChimaraGlk:protect property of @glk. In protect mode, the Glk 
677  * program is not allowed to do file operations.
678  */
679 void 
680 chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
681 {
682     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
683     
684     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
685     priv->protect = protect;
686 }
687
688 /**
689  * chimara_glk_get_protect:
690  * @glk: a #ChimaraGlk widget
691  *
692  * Returns whether @glk is in protect mode (banned from doing file operations).
693  * See #ChimaraGlk:protect.
694  *
695  * Return value: %TRUE if @glk is in protect mode.
696  */
697 gboolean 
698 chimara_glk_get_protect(ChimaraGlk *glk)
699 {
700     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
701     
702     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
703     return priv->protect;
704 }
705
706 /**
707  * chimara_glk_set_default_font_description:
708  * @glk: a #ChimaraGlk widget
709  * @font: a #PangoFontDescription
710  *
711  * Sets @glk's default proportional font. See 
712  * #ChimaraGlk:default-font-description.
713  */
714 void 
715 chimara_glk_set_default_font_description(ChimaraGlk *glk, PangoFontDescription *font)
716 {
717         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
718         g_return_if_fail(font);
719         
720         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
721         pango_font_description_free(priv->default_font_desc);
722         priv->default_font_desc = pango_font_description_copy(font);
723         
724         /* TODO: Apply the font description to all the windows and recalculate the sizes */
725 }
726
727 /**
728  * chimara_glk_set_default_font_string:
729  * @glk: a #ChimaraGlk widget
730  * @font: string representation of a font description
731  *
732  * Sets @glk's default proportional font according to the string @font, which
733  * must be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
734  * [<replaceable>STYLE-OPTIONS</replaceable>] 
735  * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Charter,Utopia 
736  * Italic 12</quote> or <quote>Sans</quote>. See 
737  * #ChimaraGlk:default-font-description.
738  */
739 void 
740 chimara_glk_set_default_font_string(ChimaraGlk *glk, const gchar *font)
741 {
742         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
743         g_return_if_fail(font || *font);
744         
745         PangoFontDescription *fontdesc = pango_font_description_from_string(font);
746         g_return_if_fail(fontdesc);
747         
748         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
749         pango_font_description_free(priv->default_font_desc);
750         priv->default_font_desc = fontdesc;
751         
752         /* TODO: Apply the font description to all the windows and recalculate the sizes */
753 }
754         
755 /**
756  * chimara_glk_get_default_font_description:
757  * @glk: a #ChimaraGlk widget
758  * 
759  * Returns @glk's default proportional font.
760  *
761  * Return value: a newly-allocated #PangoFontDescription which must be freed
762  * using pango_font_description_free(), or %NULL on error.
763  */
764 PangoFontDescription *
765 chimara_glk_get_default_font_description(ChimaraGlk *glk)
766 {
767         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
768         
769         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
770         return pango_font_description_copy(priv->default_font_desc);
771 }
772
773 /**
774  * chimara_glk_set_monospace_font_description:
775  * @glk: a #ChimaraGlk widget
776  * @font: a #PangoFontDescription
777  *
778  * Sets @glk's default monospace font. See 
779  * #ChimaraGlk:monospace-font-description.
780  */
781 void 
782 chimara_glk_set_monospace_font_description(ChimaraGlk *glk, PangoFontDescription *font)
783 {
784         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
785         g_return_if_fail(font);
786         
787         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
788         pango_font_description_free(priv->monospace_font_desc);
789         priv->monospace_font_desc = pango_font_description_copy(font);
790         
791         /* TODO: Apply the font description to all the windows and recalculate the sizes */
792 }
793
794 /**
795  * chimara_glk_set_monospace_font_string:
796  * @glk: a #ChimaraGlk widget
797  * @font: string representation of a font description
798  *
799  * Sets @glk's default monospace font according to the string @font, which must
800  * be a string in the form <quote><replaceable>FAMILY-LIST</replaceable> 
801  * [<replaceable>STYLE-OPTIONS</replaceable>] 
802  * [<replaceable>SIZE</replaceable>]</quote>, such as <quote>Courier 
803  * Bold 12</quote> or <quote>Monospace</quote>. See 
804  * #ChimaraGlk:monospace-font-description.
805  */
806 void 
807 chimara_glk_set_monospace_font_string(ChimaraGlk *glk, const gchar *font)
808 {
809         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
810         g_return_if_fail(font || *font);
811         
812         PangoFontDescription *fontdesc = pango_font_description_from_string(font);
813         g_return_if_fail(fontdesc);
814         
815         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
816         pango_font_description_free(priv->monospace_font_desc);
817         priv->monospace_font_desc = fontdesc;
818         
819         /* TODO: Apply the font description to all the windows and recalculate the sizes */
820 }
821         
822 /**
823  * chimara_glk_get_monospace_font_description:
824  * @glk: a #ChimaraGlk widget
825  * 
826  * Returns @glk's default monospace font.
827  *
828  * Return value: a newly-allocated #PangoFontDescription which must be freed
829  * using pango_font_description_free(), or %NULL on error.
830  */
831 PangoFontDescription *
832 chimara_glk_get_monospace_font_description(ChimaraGlk *glk)
833 {
834         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), NULL);
835         
836         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
837         return pango_font_description_copy(priv->monospace_font_desc);
838 }
839
840 /**
841  * chimara_glk_set_spacing:
842  * @glk: a #ChimaraGlk widget
843  * @spacing: the number of pixels to put between Glk windows
844  *
845  * Sets the #ChimaraGlk:spacing property of @glk, which is the border width in
846  * pixels between Glk windows.
847  */
848 void 
849 chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
850 {
851         g_return_if_fail( glk || CHIMARA_IS_GLK(glk) );
852         
853         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
854         priv->spacing = spacing;
855 }
856
857 /**
858  * chimara_glk_get_spacing:
859  * @glk: a #ChimaraGlk widget
860  *
861  * Gets the value set by chimara_glk_set_spacing().
862  *
863  * Return value: pixels of spacing between Glk windows
864  */
865 guint 
866 chimara_glk_get_spacing(ChimaraGlk *glk)
867 {
868         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), 0);
869         
870         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
871         return priv->spacing;
872 }
873
874 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
875 static gpointer
876 glk_enter(gpointer glk_main)
877 {
878     extern ChimaraGlkPrivate *glk_data;
879     g_signal_emit_by_name(glk_data->self, "started");
880         ((glk_main_t)glk_main)();
881         g_signal_emit_by_name(glk_data->self, "stopped");
882         return NULL;
883 }
884
885 /**
886  * chimara_glk_run:
887  * @glk: a #ChimaraGlk widget
888  * @plugin: path to a plugin module compiled with <filename 
889  * class="header">glk.h</filename>
890  * @error: location to store a <link linkend="glib-GError">GError</link>, or 
891  * %NULL
892  *
893  * Opens a Glk program compiled as a plugin and runs its glk_main() function in
894  * a separate thread. On failure, returns %FALSE and sets @error.
895  *
896  * Return value: %TRUE if the Glk program was started successfully.
897  */
898 gboolean
899 chimara_glk_run(ChimaraGlk *glk, gchar *plugin, GError **error)
900 {
901     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
902     g_return_val_if_fail(plugin, FALSE);
903     
904     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
905     
906     /* Open the module to run */
907     glk_main_t glk_main;
908     g_assert( g_module_supported() );
909     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
910     
911     if(!priv->program)
912     {
913         g_warning( "Error opening module: %s", g_module_error() );
914         return FALSE;
915     }
916     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &glk_main) )
917     {
918         g_warning( "Error finding glk_main(): %s", g_module_error() );
919         return FALSE;
920     }
921
922     extern ChimaraGlkPrivate *glk_data;
923     /* Set the thread's private data */
924     /* TODO: Do this with a GPrivate */
925     glk_data = priv;
926
927     /* Run in a separate thread */
928         priv->thread = g_thread_create(glk_enter, glk_main, TRUE, error);
929         
930         return !(priv->thread == NULL);
931 }
932
933 /**
934  * chimara_glk_stop:
935  * @glk: a #ChimaraGlk widget
936  *
937  * Signals the Glk program running in @glk to abort. Note that if the program is
938  * caught in an infinite loop in which glk_tick() is not called, this may not
939  * work.
940  */
941 void
942 chimara_glk_stop(ChimaraGlk *glk)
943 {
944     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
945     /* TODO: check if glk is actually running a program */
946     signal_abort();
947 }
948
949 /**
950  * chimara_glk_wait:
951  * @glk: a #ChimaraGlk widget
952  *
953  * Holds up the main thread and waits for the Glk program running in @glk to 
954  * finish.
955  */
956 void
957 chimara_glk_wait(ChimaraGlk *glk)
958 {
959     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
960     
961     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
962     g_thread_join(priv->thread);
963 }