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