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