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