Fixed documentation to work with Gtk-Doc 1.14 and produce as few warnings as possible
[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 
718      * chimara_glk_feed_char_input() and chimara_glk_feed_line_input(). 
719      * <quote>More</quote> prompts when a lot of text is printed to a text 
720          * buffer are also disabled. This is typically used when you wish to control
721          * an interpreter program by feeding it a predefined list of commands.
722      */
723     g_object_class_install_property( object_class, PROP_INTERACTIVE, 
724                 g_param_spec_boolean("interactive", _("Interactive"),
725         _("Whether user input is expected in the Glk program"),
726         TRUE,
727         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
728
729         /**
730      * ChimaraGlk:protect:
731      *
732      * Sets whether the Glk program is allowed to do file operations. In protect
733      * mode, all file operations will fail.
734      */
735     g_object_class_install_property(object_class, PROP_PROTECT, 
736                 g_param_spec_boolean("protect", _("Protected"),
737         _("Whether the Glk program is barred from doing file operations"),
738         FALSE,
739         G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
740
741         /**
742          * ChimaraGlk:spacing:
743          *
744          * The amount of space between the Glk windows.
745          */
746         g_object_class_install_property(object_class, PROP_SPACING,
747                 g_param_spec_uint("spacing", _("Spacing"),
748                 _("The amount of space between Glk windows"),
749                 0, G_MAXUINT, 0,
750                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS) );
751         
752     /* Private data */
753     g_type_class_add_private(klass, sizeof(ChimaraGlkPrivate));
754 }
755
756 /* PUBLIC FUNCTIONS */
757
758 /**
759  * chimara_error_quark:
760  *
761  * The error domain for errors from Chimara widgets.
762  *
763  * Returns: The string <quote>chimara-error-quark</quote> as a <link 
764  * linkend="GQuark">GQuark</link>.
765  */
766 GQuark
767 chimara_error_quark(void)
768 {
769         chimara_init(); /* This is a library entry point */
770         return g_quark_from_static_string("chimara-error-quark");
771 }
772
773 /**
774  * chimara_glk_new:
775  *
776  * Creates and initializes a new #ChimaraGlk widget.
777  *
778  * Return value: a #ChimaraGlk widget, with a floating reference.
779  */
780 GtkWidget *
781 chimara_glk_new(void)
782 {
783         /* This is a library entry point; initialize the library */
784         chimara_init();
785
786     return GTK_WIDGET(g_object_new(CHIMARA_TYPE_GLK, NULL));
787 }
788
789 /**
790  * chimara_glk_set_interactive:
791  * @glk: a #ChimaraGlk widget
792  * @interactive: whether the widget should expect user input
793  *
794  * Sets the #ChimaraGlk:interactive property of @glk. 
795  */
796 void 
797 chimara_glk_set_interactive(ChimaraGlk *glk, gboolean interactive)
798 {
799     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
800     
801     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
802     priv->interactive = interactive;
803     g_object_notify(G_OBJECT(glk), "interactive");
804 }
805
806 /**
807  * chimara_glk_get_interactive:
808  * @glk: a #ChimaraGlk widget
809  *
810  * Returns whether @glk is interactive (expecting user input). See 
811  * #ChimaraGlk:interactive.
812  *
813  * Return value: %TRUE if @glk is interactive.
814  */
815 gboolean 
816 chimara_glk_get_interactive(ChimaraGlk *glk)
817 {
818     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
819     
820     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
821     return priv->interactive;
822 }
823
824 /**
825  * chimara_glk_set_protect:
826  * @glk: a #ChimaraGlk widget
827  * @protect: whether the widget should allow the Glk program to do file 
828  * operations
829  *
830  * Sets the #ChimaraGlk:protect property of @glk. In protect mode, the Glk 
831  * program is not allowed to do file operations.
832  */
833 void 
834 chimara_glk_set_protect(ChimaraGlk *glk, gboolean protect)
835 {
836     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
837     
838     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
839     priv->protect = protect;
840     g_object_notify(G_OBJECT(glk), "protect");
841 }
842
843 /**
844  * chimara_glk_get_protect:
845  * @glk: a #ChimaraGlk widget
846  *
847  * Returns whether @glk is in protect mode (banned from doing file operations).
848  * See #ChimaraGlk:protect.
849  *
850  * Return value: %TRUE if @glk is in protect mode.
851  */
852 gboolean 
853 chimara_glk_get_protect(ChimaraGlk *glk)
854 {
855     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
856     
857     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
858     return priv->protect;
859 }
860
861 /**
862  * chimara_glk_set_css_to_default:
863  * @glk: a #ChimaraGlk widget
864  *
865  * Resets the styles for text buffer and text grid windows to their defaults.
866  * <para><warning>
867  *   This function is not implemented yet.
868  * </warning></para>
869  */
870 void
871 chimara_glk_set_css_to_default(ChimaraGlk *glk)
872 {
873         reset_default_styles(glk);
874 }
875
876 /**
877  * chimara_glk_set_css_from_file:
878  * @glk: a #ChimaraGlk widget
879  * @filename: path to a CSS file, or %NULL
880  * @error: location to store a <link 
881  * linkend="glib-Error-Reporting">GError</link>, or %NULL
882  *
883  * Sets the styles for text buffer and text grid windows according to the CSS
884  * file @filename. Note that the styles are set cumulatively on top of whatever
885  * the styles are at the time this function is called; to reset the styles to
886  * their defaults, use chimara_glk_set_css_to_default().
887  *
888  * Returns: %TRUE on success, %FALSE if an error occurred, in which case @error
889  * will be set.
890  */
891 gboolean 
892 chimara_glk_set_css_from_file(ChimaraGlk *glk, const gchar *filename, GError **error)
893 {
894         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
895         g_return_val_if_fail(filename, FALSE);
896         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
897
898         int fd = open(filename, O_RDONLY);
899         if(fd == -1) {
900                 *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno), 
901                     _("Error opening file \"%s\": %s"), filename, g_strerror(errno));
902                 return FALSE;
903         }
904
905         GScanner *scanner = create_css_file_scanner();
906         g_scanner_input_file(scanner, fd);
907         scanner->input_name = filename;
908         scan_css_file(scanner, glk);
909
910         /* Set the current style to a copy of the default style */
911         /* FIXME this is not correct */
912         copy_default_styles_to_current_styles(glk);
913         
914         if(close(fd) == -1) {
915                 *error = g_error_new(G_IO_ERROR, g_io_error_from_errno(errno),
916                     _("Error closing file \"%s\": %s"), filename, g_strerror(errno));
917                 return FALSE;
918         }
919         return TRUE;
920 }
921
922 /**
923  * chimara_glk_set_css_from_string:
924  * @glk: a #ChimaraGlk widget
925  * @css: a string containing CSS code
926  *
927  * Sets the styles for text buffer and text grid windows according to the CSS
928  * code @css. Note that the styles are set cumulatively on top of whatever the 
929  * styles are at the time this function is called; to reset the styles to their
930  * defaults, use chimara_glk_set_css_to_default().
931  */
932 void 
933 chimara_glk_set_css_from_string(ChimaraGlk *glk, const gchar *css)
934 {
935         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
936         g_return_if_fail(css || *css);
937         
938         GScanner *scanner = create_css_file_scanner();
939         g_scanner_input_text(scanner, css, strlen(css));
940         scanner->input_name = "<string>";
941         scan_css_file(scanner, glk);
942
943         /* Set the current style to a copy of the default style */
944         /* FIXME this is not correct */
945         copy_default_styles_to_current_styles(glk);
946 }
947
948 /**
949  * chimara_glk_set_spacing:
950  * @glk: a #ChimaraGlk widget
951  * @spacing: the number of pixels to put between Glk windows
952  *
953  * Sets the #ChimaraGlk:spacing property of @glk, which is the border width in
954  * pixels between Glk windows.
955  */
956 void 
957 chimara_glk_set_spacing(ChimaraGlk *glk, guint spacing)
958 {
959         g_return_if_fail( glk || CHIMARA_IS_GLK(glk) );
960         
961         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
962         priv->spacing = spacing;
963         g_object_notify(G_OBJECT(glk), "spacing");
964 }
965
966 /**
967  * chimara_glk_get_spacing:
968  * @glk: a #ChimaraGlk widget
969  *
970  * Gets the value set by chimara_glk_set_spacing().
971  *
972  * Return value: pixels of spacing between Glk windows
973  */
974 guint 
975 chimara_glk_get_spacing(ChimaraGlk *glk)
976 {
977         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), 0);
978         
979         ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
980         return priv->spacing;
981 }
982
983 struct StartupData {
984         glk_main_t glk_main;
985         glkunix_startup_code_t glkunix_startup_code;
986         glkunix_startup_t args;
987         ChimaraGlkPrivate *glk_data;
988 };
989
990 /* glk_enter() is the actual function called in the new thread in which glk_main() runs.  */
991 static gpointer
992 glk_enter(struct StartupData *startup)
993 {
994         extern GPrivate *glk_data_key;
995         g_private_set(glk_data_key, startup->glk_data);
996         
997         /* Acquire the Glk thread's references to the input queues */
998         g_async_queue_ref(startup->glk_data->char_input_queue);
999         g_async_queue_ref(startup->glk_data->line_input_queue);
1000         
1001         /* Run startup function */
1002         if(startup->glkunix_startup_code) {
1003                 startup->glk_data->in_startup = TRUE;
1004                 int result = startup->glkunix_startup_code(&startup->args);
1005                 startup->glk_data->in_startup = FALSE;
1006                 
1007                 int i = 0;
1008                 while(i < startup->args.argc)
1009                         g_free(startup->args.argv[i++]);
1010                 g_free(startup->args.argv);
1011                 
1012                 if(!result)
1013                         return NULL;
1014         }
1015         
1016         /* Run main function */
1017         glk_main_t glk_main = startup->glk_main;
1018         
1019         /* COMPAT: avoid usage of slices */
1020         g_free(startup);
1021     g_signal_emit_by_name(startup->glk_data->self, "started");
1022         glk_main();
1023         glk_exit(); /* Run shutdown code in glk_exit() even if glk_main() returns normally */
1024         g_assert_not_reached(); /* because glk_exit() calls g_thread_exit() */
1025         return NULL; 
1026 }
1027
1028 /**
1029  * chimara_glk_run:
1030  * @glk: a #ChimaraGlk widget
1031  * @plugin: path to a plugin module compiled with <filename 
1032  * class="header">glk.h</filename>
1033  * @argc: Number of command line arguments in @argv
1034  * @argv: Array of command line arguments to pass to the plugin
1035  * @error: location to store a <link 
1036  * linkend="glib-Error-Reporting">GError</link>, or %NULL
1037  *
1038  * Opens a Glk program compiled as a plugin. Sorts out its command line
1039  * arguments from #glkunix_arguments, calls its startup function
1040  * glkunix_startup_code(), and then calls its main function glk_main() in
1041  * a separate thread. On failure, returns %FALSE and sets @error.
1042  *
1043  * The plugin must at least export a glk_main() function; #glkunix_arguments and
1044  * glkunix_startup_code() are optional.
1045  *
1046  * Return value: %TRUE if the Glk program was started successfully.
1047  */
1048 gboolean
1049 chimara_glk_run(ChimaraGlk *glk, const gchar *plugin, int argc, char *argv[], GError **error)
1050 {
1051     g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1052     g_return_val_if_fail(plugin, FALSE);
1053         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
1054         
1055         if(chimara_glk_get_running(glk)) {
1056                 g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_ALREADY_RUNNING, _("There was already a plugin running."));
1057                 return FALSE;
1058         }
1059     
1060     ChimaraGlkPrivate *priv = CHIMARA_GLK_PRIVATE(glk);
1061
1062         /* COMPAT: avoid usage of slices */
1063         struct StartupData *startup = g_new0(struct StartupData,1);
1064         
1065     g_assert( g_module_supported() );
1066         /* If there is already a module loaded, free it first -- you see, we want to
1067          * keep modules loaded as long as possible to avoid crashes in stack unwinding */
1068         if( priv->program && !g_module_close(priv->program) )
1069                 g_warning( "Error closing module :%s", g_module_error() );
1070         /* Open the module to run */
1071     priv->program = g_module_open(plugin, G_MODULE_BIND_LAZY);
1072     
1073     if(!priv->program)
1074     {
1075         g_set_error(error, CHIMARA_ERROR, CHIMARA_LOAD_MODULE_ERROR, _("Error opening module: %s"), g_module_error());
1076         return FALSE;
1077     }
1078     if( !g_module_symbol(priv->program, "glk_main", (gpointer *) &startup->glk_main) )
1079     {
1080         g_set_error(error, CHIMARA_ERROR, CHIMARA_NO_GLK_MAIN, _("Error finding glk_main(): %s"), g_module_error());
1081         return FALSE;
1082     }
1083
1084     if( g_module_symbol(priv->program, "glkunix_startup_code", (gpointer *) &startup->glkunix_startup_code) )
1085     {
1086                 glkunix_argumentlist_t *glkunix_arguments;
1087
1088                 if( !(g_module_symbol(priv->program, "glkunix_arguments", (gpointer *) &glkunix_arguments) 
1089                           && parse_command_line(glkunix_arguments, argc, argv, &startup->args)) )
1090                 {
1091                         /* arguments could not be parsed, so create data ourselves */
1092                         startup->args.argc = 1;
1093                         startup->args.argv = g_new0(gchar *, 1);
1094                 }
1095
1096                 /* Set the program name */
1097                 startup->args.argv[0] = g_strdup(plugin);
1098     }
1099         startup->glk_data = priv;
1100         
1101     /* Run in a separate thread */
1102         priv->thread = g_thread_create((GThreadFunc)glk_enter, startup, TRUE, error);
1103         
1104         return !(priv->thread == NULL);
1105 }
1106
1107 /**
1108  * chimara_glk_stop:
1109  * @glk: a #ChimaraGlk widget
1110  *
1111  * Signals the Glk program running in @glk to abort. Note that if the program is
1112  * caught in an infinite loop in which glk_tick() is not called, this may not
1113  * work.
1114  */
1115 void
1116 chimara_glk_stop(ChimaraGlk *glk)
1117 {
1118     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1119     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1120
1121     /* Don't do anything if not running a program */
1122     if(!priv->running)
1123         return;
1124     
1125         if(priv->abort_lock) {
1126                 g_mutex_lock(priv->abort_lock);
1127                 priv->abort_signalled = TRUE;
1128                 g_mutex_unlock(priv->abort_lock);
1129                 /* Stop blocking on the event queue condition */
1130                 event_throw(glk, evtype_Abort, NULL, 0, 0);
1131                 /* Stop blocking on the shutdown key press condition */
1132                 g_mutex_lock(priv->shutdown_lock);
1133                 g_cond_signal(priv->shutdown_key_pressed);
1134                 g_mutex_unlock(priv->shutdown_lock);
1135         }
1136 }
1137
1138 /**
1139  * chimara_glk_wait:
1140  * @glk: a #ChimaraGlk widget
1141  *
1142  * Holds up the main thread and waits for the Glk program running in @glk to 
1143  * finish.
1144  */
1145 void
1146 chimara_glk_wait(ChimaraGlk *glk)
1147 {
1148     g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1149     CHIMARA_GLK_USE_PRIVATE(glk, priv);
1150     /* Don't do anything if not running a program */
1151     if(!priv->running)
1152         return;
1153         /* Unlock GDK mutex, because the Glk program might need to use it for shutdown */
1154         gdk_threads_leave();
1155     g_thread_join(priv->thread);
1156         gdk_threads_enter();
1157 }
1158
1159 /**
1160  * chimara_glk_get_running:
1161  * @glk: a #ChimaraGlk widget
1162  * 
1163  * Use this function to tell whether a program is currently running in the
1164  * widget.
1165  * 
1166  * Returns: %TRUE if @glk is executing a Glk program, %FALSE otherwise.
1167  */
1168 gboolean
1169 chimara_glk_get_running(ChimaraGlk *glk)
1170 {
1171         g_return_val_if_fail(glk || CHIMARA_IS_GLK(glk), FALSE);
1172         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1173         return priv->running;
1174 }
1175
1176 /**
1177  * chimara_glk_feed_char_input:
1178  * @glk: a #ChimaraGlk widget
1179  * @keyval: a key symbol as defined in <filename 
1180  * class="headerfile">gdk/gdkkeysyms.h</filename>
1181  * 
1182  * Pretend that a key was pressed in the Glk program as a response to a 
1183  * character input request. You can call this function even when no window has
1184  * requested character input, in which case the key will be saved for the 
1185  * following window that requests character input. This has the disadvantage 
1186  * that if more than one window has requested character input, it is arbitrary 
1187  * which one gets the key press.
1188  */
1189 void 
1190 chimara_glk_feed_char_input(ChimaraGlk *glk, guint keyval)
1191 {
1192         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1193         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1194         g_async_queue_push(priv->char_input_queue, GUINT_TO_POINTER(keyval));
1195         event_throw(glk, evtype_ForcedCharInput, NULL, 0, 0);
1196 }
1197
1198 /**
1199  * chimara_glk_feed_line_input:
1200  * @glk: a #ChimaraGlk widget
1201  * @text: text to pass to the next line input request
1202  * 
1203  * Pretend that @text was typed in the Glk program as a response to a line input
1204  * request. @text does not need to end with a newline. You can call this 
1205  * function even when no window has requested line input, in which case the text
1206  * will be saved for the following window that requests line input. This has the 
1207  * disadvantage that if more than one window has requested character input, it 
1208  * is arbitrary which one gets the text.
1209  */
1210 void 
1211 chimara_glk_feed_line_input(ChimaraGlk *glk, const gchar *text)
1212 {
1213         g_return_if_fail(glk || CHIMARA_IS_GLK(glk));
1214         g_return_if_fail(text);
1215         CHIMARA_GLK_USE_PRIVATE(glk, priv);
1216         g_async_queue_push(priv->line_input_queue, g_strdup(text));
1217         event_throw(glk, evtype_ForcedLineInput, NULL, 0, 0);
1218 }