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