Use g_cond_wait_until() instead of g_cond_timed_wait()
[projects/chimara/chimara.git] / libchimara / chimara-if.c
1 #include <errno.h>
2 #include <stdlib.h>
3 #include <glib.h>
4 #include <glib-object.h>
5 #include <config.h>
6 #include <glib/gi18n-lib.h>
7 #include "chimara-if.h"
8 #include "chimara-glk.h"
9 #include "chimara-glk-private.h"
10 #include "chimara-marshallers.h"
11 #include "init.h"
12
13 #ifndef PLUGINDIR
14 #define PLUGINDIR "."
15 #endif
16
17 /**
18  * SECTION:chimara-if
19  * @short_description: Widget which plays an interactive fiction game
20  * @stability: Unstable
21  *
22  * The #ChimaraIF widget, given an interactive fiction game file to run, selects
23  * an appropriate interpreter plugin and runs it. Interpreter options are set by
24  * setting properties on the widget.
25  *
26  * Using it in a GTK program is similar to using #ChimaraGlk (which see). 
27  * Threads must be initialized before using #ChimaraIF and the call to 
28  * gtk_main() must be bracketed between gdk_threads_enter() and 
29  * gdk_threads_leave(). Use chimara_if_run_game() to start playing an
30  * interactive fiction game.
31  */
32
33 static gboolean supported_formats[CHIMARA_IF_NUM_FORMATS][CHIMARA_IF_NUM_INTERPRETERS] = {
34         /* Frotz Nitfol Glulxe Git    Bocfel */
35         { TRUE,  TRUE,  FALSE, FALSE, TRUE  }, /* Z5 */
36         { TRUE,  TRUE,  FALSE, FALSE, TRUE  }, /* Z6 */
37         { TRUE,  TRUE,  FALSE, FALSE, TRUE  }, /* Z8 */
38         { TRUE,  TRUE,  FALSE, FALSE, TRUE  }, /* Zblorb */
39         { FALSE, FALSE, TRUE,  TRUE,  FALSE }, /* Glulx */
40         { FALSE, FALSE, TRUE,  TRUE,  FALSE }  /* Gblorb */
41 };
42 static gchar *format_names[CHIMARA_IF_NUM_FORMATS] = {
43         N_("Z-code version 5"),
44         N_("Z-code version 6"),
45         N_("Z-code version 8"),
46         N_("Blorbed Z-code"),
47         N_("Glulx"),
48         N_("Blorbed Glulx")
49 };
50 static gchar *interpreter_names[CHIMARA_IF_NUM_INTERPRETERS] = {
51         N_("Frotz"), N_("Nitfol"), N_("Glulxe"), N_("Git"), N_("Bocfel")
52 };
53 static gchar *plugin_names[CHIMARA_IF_NUM_INTERPRETERS] = {
54         "frotz", "nitfol", "glulxe", "git", "bocfel"
55 };
56
57 typedef enum _ChimaraIFFlags {
58         CHIMARA_IF_PIRACY_MODE = 1 << 0,
59         CHIMARA_IF_TANDY_BIT = 1 << 1,
60         CHIMARA_IF_EXPAND_ABBREVIATIONS = 1 << 2,
61         CHIMARA_IF_IGNORE_ERRORS = 1 << 3,
62         CHIMARA_IF_TYPO_CORRECTION = 1 << 4
63 } ChimaraIFFlags;
64
65 typedef struct _ChimaraIFPrivate {
66         ChimaraIFInterpreter preferred_interpreter[CHIMARA_IF_NUM_FORMATS];
67         ChimaraIFFormat format;
68         ChimaraIFInterpreter interpreter;
69         ChimaraIFFlags flags;
70         ChimaraIFZmachineVersion interpreter_number;
71         gint random_seed;
72         gboolean random_seed_set;
73         gchar *graphics_file;
74         /* Holding buffers for input and response */
75         gchar *input;
76         GString *response;
77 } ChimaraIFPrivate;
78
79 #define CHIMARA_IF_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE((o), CHIMARA_TYPE_IF, ChimaraIFPrivate))
80 #define CHIMARA_IF_USE_PRIVATE(o, n) ChimaraIFPrivate *n = CHIMARA_IF_PRIVATE(o)
81
82 enum {
83         PROP_0,
84         PROP_PIRACY_MODE,
85         PROP_TANDY_BIT,
86         PROP_EXPAND_ABBREVIATIONS,
87         PROP_IGNORE_ERRORS,
88         PROP_TYPO_CORRECTION,
89         PROP_INTERPRETER_NUMBER,
90         PROP_RANDOM_SEED,
91         PROP_RANDOM_SEED_SET,
92         PROP_GRAPHICS_FILE
93 };
94
95 enum {
96         COMMAND,
97         LAST_SIGNAL
98 };
99
100 static guint chimara_if_signals[LAST_SIGNAL] = { 0 };
101
102 G_DEFINE_TYPE(ChimaraIF, chimara_if, CHIMARA_TYPE_GLK);
103
104 static void
105 chimara_if_waiting(ChimaraGlk *glk)
106 {
107         CHIMARA_IF_USE_PRIVATE(glk, priv);
108
109         gchar *response = g_string_free(priv->response, FALSE);
110         priv->response = g_string_new("");
111
112         gdk_threads_enter();
113         g_signal_emit_by_name(glk, "command", priv->input, response);
114         gdk_threads_leave();
115
116         g_free(priv->input);
117         g_free(response);
118         priv->input = NULL;
119 }
120
121 static void
122 chimara_if_stopped(ChimaraGlk *glk)
123 {
124         CHIMARA_IF_USE_PRIVATE(glk, priv);
125
126         if(priv->input || priv->response->len > 0)
127                 chimara_if_waiting(glk); /* Send one last command signal */
128
129         priv->format = CHIMARA_IF_FORMAT_NONE;
130         priv->interpreter = CHIMARA_IF_INTERPRETER_NONE;
131 }
132
133 static void
134 chimara_if_char_input(ChimaraGlk *glk, guint32 win_rock, guint keysym)
135 {
136         CHIMARA_IF_USE_PRIVATE(glk, priv);
137         g_assert(priv->input == NULL);
138
139         gchar outbuf[6];
140         gint outbuflen = g_unichar_to_utf8(gdk_keyval_to_unicode(keysym), outbuf);
141         priv->input = g_strndup(outbuf, outbuflen);
142 }
143
144 static void
145 chimara_if_line_input(ChimaraGlk *glk, guint32 win_rock, gchar *input)
146 {
147         CHIMARA_IF_USE_PRIVATE(glk, priv);
148         g_assert(priv->input == NULL);
149         priv->input = g_strdup(input);
150 }
151
152 static void
153 chimara_if_text_buffer_output(ChimaraGlk *glk, guint32 win_rock, gchar *output)
154 {
155         CHIMARA_IF_USE_PRIVATE(glk, priv);
156         g_string_append(priv->response, output);
157 }
158
159 static void
160 chimara_if_init(ChimaraIF *self)
161 {
162         chimara_init(); /* This is a library entry point */
163
164         CHIMARA_IF_USE_PRIVATE(self, priv);
165         priv->preferred_interpreter[CHIMARA_IF_FORMAT_Z5] = CHIMARA_IF_INTERPRETER_FROTZ;
166         priv->preferred_interpreter[CHIMARA_IF_FORMAT_Z6] = CHIMARA_IF_INTERPRETER_NITFOL;
167         priv->preferred_interpreter[CHIMARA_IF_FORMAT_Z8] = CHIMARA_IF_INTERPRETER_FROTZ;
168         priv->preferred_interpreter[CHIMARA_IF_FORMAT_Z_BLORB] = CHIMARA_IF_INTERPRETER_FROTZ;
169         priv->preferred_interpreter[CHIMARA_IF_FORMAT_GLULX] = CHIMARA_IF_INTERPRETER_GLULXE;
170         priv->preferred_interpreter[CHIMARA_IF_FORMAT_GLULX_BLORB] = CHIMARA_IF_INTERPRETER_GLULXE;
171         priv->format = CHIMARA_IF_FORMAT_NONE;
172         priv->interpreter = CHIMARA_IF_INTERPRETER_NONE;
173         priv->flags = CHIMARA_IF_TYPO_CORRECTION;
174         priv->interpreter_number = CHIMARA_IF_ZMACHINE_DEFAULT;
175         priv->response = g_string_new("");
176
177         /* Connect to signals of ChimaraGlk parent */
178         g_signal_connect(self, "stopped", G_CALLBACK(chimara_if_stopped), NULL);
179         g_signal_connect(self, "waiting", G_CALLBACK(chimara_if_waiting), NULL);
180         g_signal_connect(self, "char-input", G_CALLBACK(chimara_if_char_input), NULL);
181         g_signal_connect(self, "line-input", G_CALLBACK(chimara_if_line_input), NULL);
182         g_signal_connect(self, "text-buffer-output", G_CALLBACK(chimara_if_text_buffer_output), NULL);
183 }
184
185 #define PROCESS_FLAG(flags, flag, val) (flags) = (val)? (flags) | (flag) : (flags) & ~(flag)
186
187 static void
188 chimara_if_set_property(GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
189 {
190         CHIMARA_IF_USE_PRIVATE(object, priv);
191     switch(prop_id)
192     {
193         case PROP_PIRACY_MODE:
194                 PROCESS_FLAG(priv->flags, CHIMARA_IF_PIRACY_MODE, g_value_get_boolean(value));
195                 g_object_notify(object, "piracy-mode");
196                 break;
197         case PROP_TANDY_BIT:
198                 PROCESS_FLAG(priv->flags, CHIMARA_IF_TANDY_BIT, g_value_get_boolean(value));
199                 g_object_notify(object, "tandy-bit");
200                 break;
201         case PROP_EXPAND_ABBREVIATIONS:
202                 PROCESS_FLAG(priv->flags, CHIMARA_IF_EXPAND_ABBREVIATIONS, g_value_get_boolean(value));
203                 g_object_notify(object, "expand-abbreviations");
204                 break;
205         case PROP_IGNORE_ERRORS:
206                 PROCESS_FLAG(priv->flags, CHIMARA_IF_IGNORE_ERRORS, g_value_get_boolean(value));
207                 g_object_notify(object, "ignore-errors");
208                 break;
209         case PROP_TYPO_CORRECTION:
210                 PROCESS_FLAG(priv->flags, CHIMARA_IF_TYPO_CORRECTION, g_value_get_boolean(value));
211                 g_object_notify(object, "typo-correction");
212                 break;
213         case PROP_INTERPRETER_NUMBER:
214                 priv->interpreter_number = g_value_get_uint(value);
215                 g_object_notify(object, "interpreter-number");
216                 break;
217         case PROP_RANDOM_SEED:
218                 priv->random_seed = g_value_get_int(value);
219                 g_object_notify(object, "random-seed");
220                 break;
221         case PROP_RANDOM_SEED_SET:
222                 priv->random_seed_set = g_value_get_boolean(value);
223                 g_object_notify(object, "random-seed-set");
224                 break;
225                 case PROP_GRAPHICS_FILE:
226                         priv->graphics_file = g_strdup(g_value_get_string(value));
227                         g_object_notify(object, "graphics-file");
228                         break;
229         default:
230             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
231     }
232 }
233
234 static void
235 chimara_if_get_property(GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
236 {
237         CHIMARA_IF_USE_PRIVATE(object, priv);
238     switch(prop_id)
239     {
240         case PROP_PIRACY_MODE:
241                 g_value_set_boolean(value, priv->flags & CHIMARA_IF_PIRACY_MODE);
242                 break;
243         case PROP_TANDY_BIT:
244                 g_value_set_boolean(value, priv->flags & CHIMARA_IF_TANDY_BIT);
245                 break;
246         case PROP_EXPAND_ABBREVIATIONS:
247                 g_value_set_boolean(value, priv->flags & CHIMARA_IF_EXPAND_ABBREVIATIONS);
248                 break;
249         case PROP_IGNORE_ERRORS:
250                 g_value_set_boolean(value, priv->flags & CHIMARA_IF_IGNORE_ERRORS);
251                 break;
252         case PROP_TYPO_CORRECTION:
253                 g_value_set_boolean(value, priv->flags & CHIMARA_IF_TYPO_CORRECTION);
254                 break;
255         case PROP_INTERPRETER_NUMBER:
256                 g_value_set_uint(value, priv->interpreter_number);
257                 break;
258         case PROP_RANDOM_SEED:
259                 g_value_set_int(value, priv->random_seed);
260                 break;
261         case PROP_RANDOM_SEED_SET:
262                 g_value_set_boolean(value, priv->random_seed_set);
263                 break;
264                 case PROP_GRAPHICS_FILE:
265                         g_value_set_string(value, priv->graphics_file);
266                         break;
267         default:
268             G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
269     }
270 }
271
272 static void
273 chimara_if_finalize(GObject *object)
274 {
275         CHIMARA_IF_USE_PRIVATE(object, priv);
276         g_free(priv->graphics_file);
277     G_OBJECT_CLASS(chimara_if_parent_class)->finalize(object);
278 }
279
280 static void
281 chimara_if_command(ChimaraIF *self, gchar *input, gchar *response)
282 {
283         /* Default signal handler */
284 }
285
286 static void
287 chimara_if_class_init(ChimaraIFClass *klass)
288 {
289         /* Override methods of parent classes */
290         GObjectClass *object_class = G_OBJECT_CLASS(klass);
291         object_class->set_property = chimara_if_set_property;
292         object_class->get_property = chimara_if_get_property;
293         object_class->finalize = chimara_if_finalize;
294
295         /* Signals */
296         klass->command = chimara_if_command;
297         /**
298          * ChimaraIF::command:
299          * @self: The widget that received the signal
300          * @input: The command typed into the game, or %NULL
301          * @response: The game's response to the command
302          *
303          * Emitted once for each input-response cycle of an interactive fiction
304          * game. Note that games with nontraditional input systems (i.e. not all
305          * taking place in the same text buffer window) may confuse this signal.
306          *
307          * It may happen that @input is %NULL, in which case @response is not due to
308          * a user command, but contains the text printed at the beginning of the
309          * game, up until the first prompt.
310          */
311         chimara_if_signals[COMMAND] = g_signal_new("command",
312                 G_OBJECT_CLASS_TYPE(klass), 0,
313                 G_STRUCT_OFFSET(ChimaraIFClass, command), NULL, NULL,
314                 _chimara_marshal_VOID__STRING_STRING,
315                 G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_STRING);
316
317         /* Properties */
318         /**
319          * ChimaraIF:piracy-mode:
320          *
321          * The Z-machine specification defines a facility for games to ask the
322          * interpreter they are running on whether this copy of the game is pirated.
323          * How the interpreter is supposed to magically determine that it is running
324          * pirate software is unclear, and so the majority of games and interpreters
325          * ignore this feature. Set this property to %TRUE if you want the
326          * interpreter to pretend it has detected a pirated game.
327          *
328          * Only affects Z-machine interpreters.
329          */
330         g_object_class_install_property(object_class, PROP_PIRACY_MODE,
331                 g_param_spec_boolean("piracy-mode", _("Piracy mode"),
332                 _("Pretend the game is pirated"), FALSE,
333                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
334         /**
335          * ChimaraIF:tandy-bit:
336          *
337          * Some early Infocom games were sold by the Tandy Corporation. Setting this
338          * property to %TRUE changes the wording of some Version 3 Infocom games
339          * slightly, so as to be less offensive. See <ulink
340          * url="http://www.ifarchive.org/if-archive/infocom/info/tandy_bits.html">
341          * http://www.ifarchive.org/if-archive/infocom/info/tandy_bits.html</ulink>.
342          *
343          * Only affects Z-machine interpreters.
344          */
345         g_object_class_install_property(object_class, PROP_TANDY_BIT,
346                 g_param_spec_boolean("tandy-bit", _("Tandy bit"),
347                 _("Censor certain Infocom games"), FALSE,
348                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
349         /**
350          * ChimaraIF:expand-abbreviations:
351          *
352          * Most Z-machine games, in particular ones compiled with the Inform
353          * library, support the following one-letter abbreviations:
354          * <simplelist>
355          * <member>D &mdash; Down</member>
356          * <member>E &mdash; East</member>
357          * <member>G &mdash; aGain</member>
358          * <member>I &mdash; Inventory</member>
359          * <member>L &mdash; Look</member>
360          * <member>N &mdash; North</member>
361          * <member>O &mdash; Oops</member>
362          * <member>Q &mdash; Quit</member>
363          * <member>S &mdash; South</member>
364          * <member>U &mdash; Up</member>
365          * <member>W &mdash; West</member>
366          * <member>X &mdash; eXamine</member>
367          * <member>Y &mdash; Yes</member>
368          * <member>Z &mdash; wait (ZZZZ...)</member>
369          * </simplelist>
370          * Some early Infocom games might not recognize these abbreviations. Setting
371          * this property to %TRUE will cause the interpreter to expand the
372          * abbreviations to the full words before passing the commands on to the
373          * game. Frotz only expands G, X, and Z; Nitfol expands all of the above
374          * plus the following nonstandard ones:
375          * <simplelist>
376          * <member>C &mdash; Close</member>
377          * <member>K &mdash; attacK</member>
378          * <member>P &mdash; oPen</member>
379          * <member>R &mdash; dRop</member>
380          * <member>T &mdash; Take</member>
381          * </simplelist>
382          *
383          * Only affects Z-machine interpreters. Behaves differently on Frotz and
384          * Nitfol.
385          */
386         g_object_class_install_property(object_class, PROP_EXPAND_ABBREVIATIONS,
387                 g_param_spec_boolean("expand-abbreviations", _("Expand abbreviations"),
388                 _("Expand abbreviations such as X for EXAMINE"), FALSE,
389                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
390         /**
391          * ChimaraIF:ignore-errors:
392          *
393          * Setting this property to %TRUE will cause the interpreter to ignore
394          * certain Z-machine runtime errors. Frotz will ignore any fatal errors.
395          * Nitfol by default warns about any shady behavior, and this property will
396          * turn those warnings off.
397          *
398          * Only affects Z-machine interpreters. Behaves differently on Frotz and
399          * Nitfol.
400          */
401         g_object_class_install_property(object_class, PROP_IGNORE_ERRORS,
402                 g_param_spec_boolean("ignore-errors", _("Ignore errors"),
403                 _("Do not warn the user about Z-machine errors"), FALSE,
404                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
405         /**
406          * ChimaraIF:typo-correction:
407          *
408          * Nitfol has an automatic typo-correction facility, where it searches the
409          * game dictionary for words which differ by one letter from any unknown
410          * input words. Set this property to %FALSE to turn this feature off.
411          *
412          * Only affects Nitfol.
413          */
414         g_object_class_install_property(object_class, PROP_TYPO_CORRECTION,
415                 g_param_spec_boolean("typo-correction", _("Typo correction"),
416                 _("Try to remedy typos if the interpreter supports it"), TRUE,
417                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
418         /**
419          * ChimaraIF:interpreter-number:
420          *
421          * Infocom gave each port of their interpreter a different number. The Frotz
422          * and Nitfol plugins can emulate any of these platforms. Some games behave
423          * slightly differently depending on what platform they are on. Set this
424          * property to a #ChimaraIFZmachineVersion value to emulate a certain
425          * platform.
426          *
427          * Note that Nitfol pretends to be an Apple IIe by default.
428          *
429          * Only affects Z-machine interpreters.
430          */
431         g_object_class_install_property(object_class, PROP_INTERPRETER_NUMBER,
432                 g_param_spec_uint("interpreter-number", _("Interpreter number"),
433                 _("Platform the Z-machine should pretend it is running on"),
434                 CHIMARA_IF_ZMACHINE_DEFAULT, CHIMARA_IF_ZMACHINE_MAXVAL, CHIMARA_IF_ZMACHINE_DEFAULT,
435                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
436         /**
437          * ChimaraIF:random-seed:
438          *
439          * If the #ChimaraIF:random-seed-set property is %TRUE, then the interpreter
440          * will use the value of this property as a seed for the random number
441          * generator. Use this feature to duplicate sequences of random numbers
442          * for testing games.
443          *
444          * Note that the value -1 is a valid random number seed for
445          * Nitfol, whereas it will cause Frotz to pick an arbitrary seed even when
446          * #ChimaraIF:random-seed-set is %TRUE.
447          *
448          * Only affects Z-machine interpreters. Behaves slightly differently on
449          * Frotz and Nitfol.
450          */
451         g_object_class_install_property(object_class, PROP_RANDOM_SEED,
452                 g_param_spec_int("random-seed", _("Random seed"),
453                 _("Seed for the random number generator"), G_MININT, G_MAXINT, 0,
454                 G_PARAM_READWRITE | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
455         /**
456          * ChimaraIF:random-seed-set:
457          *
458          * Whether to use or ignore the #ChimaraIF:random-seed property.
459          *
460          * Only affects Z-machine interpreters.
461          */
462         g_object_class_install_property(object_class, PROP_RANDOM_SEED_SET,
463                 g_param_spec_boolean("random-seed-set", _("Random seed set"),
464                 _("Whether the seed for the random number generator should be set manually"), FALSE,
465                 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
466         /**
467          * ChimaraIF:graphics-file:
468          *
469          * Some Z-machine interpreters accept an extra argument that indicates a
470          * separate Blorb file containing graphics and sound resources. The
471          * interpreter will check if the file specified in this property really
472          * exists, and if so, use it as a resource file. If this property is set to 
473          * %NULL, the interpreter will not look for an extra file.
474          *
475          * Only affects Frotz and Nitfol.
476          */
477         g_object_class_install_property(object_class, PROP_GRAPHICS_FILE,
478             g_param_spec_string("graphics-file", _("Graphics file"),
479             _("Location in which to look for a separate graphics Blorb file"), NULL,
480             G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_LAX_VALIDATION | G_PARAM_STATIC_STRINGS));
481         /* Private data */
482         g_type_class_add_private(klass, sizeof(ChimaraIFPrivate));
483 }
484
485 /* PUBLIC FUNCTIONS */
486
487 /**
488  * chimara_if_new:
489  *
490  * Creates and initializes a new #ChimaraIF widget.
491  *
492  * Return value: a #ChimaraIF widget, with a floating reference.
493  */
494 GtkWidget *
495 chimara_if_new(void)
496 {
497         /* This is a library entry point; initialize the library */
498         chimara_init();
499     return GTK_WIDGET(g_object_new(CHIMARA_TYPE_IF, NULL));
500 }
501
502 /**
503  * chimara_if_set_preferred_interpreter:
504  * @self: A #ChimaraIF widget.
505  * @format: The game format to set the preferred interpreter plugin for.
506  * @interpreter: The preferred interpreter plugin for @format.
507  *
508  * The function chimara_if_run_game() picks an appropriate interpreter for the
509  * type of game file it is given. This function sets which interpreter is picked
510  * for a certain game file format. Most formats, notably the Z-machine, have
511  * had many different interpreters written for them over the years, all with
512  * slightly different quirks and capabilities, so there is plenty of choice.
513  */
514 void
515 chimara_if_set_preferred_interpreter(ChimaraIF *self, ChimaraIFFormat format, ChimaraIFInterpreter interpreter)
516 {
517         g_return_if_fail(self && CHIMARA_IS_IF(self));
518         g_return_if_fail(format < CHIMARA_IF_NUM_FORMATS);
519         g_return_if_fail(interpreter < CHIMARA_IF_NUM_INTERPRETERS);
520
521         CHIMARA_IF_USE_PRIVATE(self, priv);
522
523         if(supported_formats[format][interpreter])
524                 priv->preferred_interpreter[format] = interpreter;
525         else
526                 g_warning("Format '%s' is not supported by interpreter '%s'", format_names[format], interpreter_names[interpreter]);
527 }
528
529 /**
530  * chimara_if_get_preferred_interpreter:
531  * @self: A #ChimaraIF widget.
532  * @format: The game format to query the preferred interpreter plugin for.
533  *
534  * Looks up the preferred interpreter for the game file format @format. See
535  * chimara_if_set_preferred_interpreter().
536  *
537  * Returns: a #ChimaraIFInterpreter value representing the preferred interpreter
538  * plugin for @format.
539  */
540 ChimaraIFInterpreter
541 chimara_if_get_preferred_interpreter(ChimaraIF *self, ChimaraIFFormat format)
542 {
543         g_return_val_if_fail(self && CHIMARA_IS_IF(self), -1);
544         g_return_val_if_fail(format < CHIMARA_IF_NUM_FORMATS, -1);
545         CHIMARA_IF_USE_PRIVATE(self, priv);
546         return priv->preferred_interpreter[format];
547 }
548
549 /**
550  * chimara_if_run_game:
551  * @self: A #ChimaraIF widget.
552  * @game_path: Path to an interactive fiction game file.
553  * @error: Return location for an error, or %NULL.
554  *
555  * Autodetects the type of a game file and runs it using an appropriate
556  * interpreter plugin. If there is more than one interpreter that supports the
557  * file format, the preferred one will be picked, according to
558  * chimara_if_set_preferred_interpreter().
559  *
560  * Returns: %TRUE if the game was started successfully, %FALSE if not, in which
561  * case @error is set.
562  */
563 gboolean
564 chimara_if_run_game(ChimaraIF *self, const char *game_path, GError **error)
565 {
566         g_return_val_if_fail(self && CHIMARA_IS_IF(self), FALSE);
567         g_return_val_if_fail(game_path, FALSE);
568         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
569
570         CHIMARA_IF_USE_PRIVATE(self, priv);
571
572         /* Find out what format the game is */
573         /* TODO: Look inside the file instead of just looking at the extension */
574         ChimaraIFFormat format = CHIMARA_IF_FORMAT_Z5;
575         if(g_str_has_suffix(game_path, ".z5"))
576                 format = CHIMARA_IF_FORMAT_Z5;
577         else if(g_str_has_suffix(game_path, ".z6"))
578                 format = CHIMARA_IF_FORMAT_Z6;
579         else if(g_str_has_suffix(game_path, ".z8"))
580                 format = CHIMARA_IF_FORMAT_Z8;
581         else if(g_str_has_suffix(game_path, ".zlb") || g_str_has_suffix(game_path, ".zblorb"))
582                 format = CHIMARA_IF_FORMAT_Z_BLORB;
583         else if(g_str_has_suffix(game_path, ".ulx"))
584                 format = CHIMARA_IF_FORMAT_GLULX;
585         else if(g_str_has_suffix(game_path, ".blb") || g_str_has_suffix(game_path, ".blorb") || g_str_has_suffix(game_path, ".glb") || g_str_has_suffix(game_path, ".gblorb"))
586                 format = CHIMARA_IF_FORMAT_GLULX_BLORB;
587
588         /* Now decide what interpreter to use */
589         ChimaraIFInterpreter interpreter = priv->preferred_interpreter[format];
590         gchar *pluginfile = g_strconcat(plugin_names[interpreter], "." G_MODULE_SUFFIX, NULL);
591
592         gchar *pluginpath;
593 #ifdef DEBUG
594 #ifndef LT_OBJDIR
595 #define LT_OBJDIR ".libs" /* Pre-2.2 libtool, so take a wild guess */
596 #endif /* LT_OBJDIR */
597         /* If there is a plugin in the source tree, use that */
598         pluginpath = g_build_filename(PLUGINSOURCEDIR, plugin_names[interpreter], LT_OBJDIR, pluginfile, NULL);
599         if( !g_file_test(pluginpath, G_FILE_TEST_EXISTS) )
600         {
601                 g_free(pluginpath);
602 #endif /* DEBUG */
603                 pluginpath = g_build_filename(PLUGINDIR, pluginfile, NULL);
604                 if( !g_file_test(pluginpath, G_FILE_TEST_EXISTS) )
605                 {
606                         g_free(pluginpath);
607                         g_free(pluginfile);
608                         g_set_error(error, CHIMARA_ERROR, CHIMARA_PLUGIN_NOT_FOUND, _("No appropriate %s interpreter plugin was found"), interpreter_names[interpreter]);
609                         return FALSE;
610                 }
611 #ifdef DEBUG
612         }
613 #endif
614         g_free(pluginfile);
615
616         /* Decide what arguments to pass to the interpreters; currently only the
617         Z-machine interpreters accept command line arguments other than the game */
618         GSList *args = NULL;
619         gchar *terpnumstr = NULL, *randomstr = NULL;
620         args = g_slist_prepend(args, pluginpath);
621         switch(interpreter)
622         {
623                 case CHIMARA_IF_INTERPRETER_FROTZ:
624                         if(priv->flags & CHIMARA_IF_PIRACY_MODE)
625                                 args = g_slist_prepend(args, "-P");
626                         if(priv->flags & CHIMARA_IF_TANDY_BIT)
627                                 args = g_slist_prepend(args, "-t");
628                         if(priv->flags & CHIMARA_IF_EXPAND_ABBREVIATIONS)
629                                 args = g_slist_prepend(args, "-x");
630                         if(priv->flags & CHIMARA_IF_IGNORE_ERRORS)
631                                 args = g_slist_prepend(args, "-i");
632                         if(priv->interpreter_number != CHIMARA_IF_ZMACHINE_DEFAULT)
633                         {
634                                 terpnumstr = g_strdup_printf("-I%u", priv->interpreter_number);
635                                 args = g_slist_prepend(args, terpnumstr);
636                         }
637                         if(priv->random_seed_set)
638                         {
639                                 randomstr = g_strdup_printf("-s%d", priv->random_seed);
640                                 args = g_slist_prepend(args, randomstr);
641                         }
642                         break;
643                 case CHIMARA_IF_INTERPRETER_NITFOL:
644                         if(priv->flags & CHIMARA_IF_PIRACY_MODE)
645                                 args = g_slist_prepend(args, "-pirate");
646                         if(priv->flags & CHIMARA_IF_TANDY_BIT)
647                                 args = g_slist_prepend(args, "-tandy");
648                         if(!(priv->flags & CHIMARA_IF_EXPAND_ABBREVIATIONS))
649                                 args = g_slist_prepend(args, "-no-expand");
650                         if(priv->flags & CHIMARA_IF_IGNORE_ERRORS)
651                                 args = g_slist_prepend(args, "-ignore");
652                         if(!(priv->flags & CHIMARA_IF_TYPO_CORRECTION))
653                                 args = g_slist_prepend(args, "-no-spell");
654                         if(priv->interpreter_number != CHIMARA_IF_ZMACHINE_DEFAULT)
655                         {
656                                 terpnumstr = g_strdup_printf("-terpnum%u", priv->interpreter_number);
657                                 args = g_slist_prepend(args, terpnumstr);
658                         }
659                         if(priv->random_seed_set)
660                         {
661                                 randomstr = g_strdup_printf("-random%d", priv->random_seed);
662                                 args = g_slist_prepend(args, randomstr);
663                         }
664                         break;
665                 default:
666                         ;
667         }
668
669         /* Game file and external blorb file */
670         args = g_slist_prepend(args, (gpointer)game_path);
671         if(priv->graphics_file
672                 && (interpreter == CHIMARA_IF_INTERPRETER_FROTZ || interpreter == CHIMARA_IF_INTERPRETER_NITFOL)
673             && g_file_test(priv->graphics_file, G_FILE_TEST_EXISTS)) {
674                 args = g_slist_prepend(args, priv->graphics_file);
675         }
676
677         /* Allocate argv to hold the arguments */
678         int argc = g_slist_length(args);
679         args = g_slist_prepend(args, NULL);
680         char **argv = g_new0(char *, argc + 1);
681
682         /* Fill argv */
683         args = g_slist_reverse(args);
684         int count;
685         GSList *ptr;
686         for(count = 0, ptr = args; ptr; count++, ptr = g_slist_next(ptr))
687                 argv[count] = g_strdup(ptr->data);
688
689         /* Set the story name */
690         /* We peek into ChimaraGlk's private data here, because GObject has no
691         equivalent to "protected" */
692         CHIMARA_GLK_USE_PRIVATE(self, glk_priv);
693         glk_priv->story_name = g_path_get_basename(game_path);
694         g_object_notify(G_OBJECT(self), "story-name");
695         
696         gboolean retval = chimara_glk_run(CHIMARA_GLK(self), pluginpath, argc, argv, error);
697         g_strfreev(argv);
698         if(terpnumstr)
699                 g_free(terpnumstr);
700         if(randomstr)
701                 g_free(randomstr);
702         g_free(pluginpath);
703
704         /* Set current format and interpreter if plugin was started successfully */
705         if(retval)
706         {
707                 priv->format = format;
708                 priv->interpreter = interpreter;
709         }
710         return retval;
711 }
712
713 /**
714  * chimara_if_run_game_file:
715  * @self: A #ChimaraIF widget.
716  * @game_file: a #GFile pointing to an interactive fiction game file.
717  * @error: Return location for an error, or %NULL.
718  *
719  * Autodetects the type of a game file and runs it using an appropriate
720  * interpreter plugin. See chimara_if_run_game() for more information.
721  *
722  * Returns: %TRUE if the game was started successfully, %FALSE if not, in which
723  * case @error is set.
724  */
725 gboolean
726 chimara_if_run_game_file(ChimaraIF *self, GFile *game_file, GError **error)
727 {
728         g_return_val_if_fail(self || CHIMARA_IS_IF(self), FALSE);
729         g_return_val_if_fail(game_file || G_IS_FILE(game_file), FALSE);
730         g_return_val_if_fail(error == NULL || *error == NULL, FALSE);
731
732         char *path = g_file_get_path(game_file);
733         gboolean retval = chimara_if_run_game(self, path, error);
734         g_free(path);
735         return retval;
736 }
737
738 /**
739  * chimara_if_get_format:
740  * @self: A #ChimaraIF widget.
741  *
742  * Returns the file format of the currently running game.
743  *
744  * Returns: a #ChimaraIFFormat constant.
745  */
746 ChimaraIFFormat
747 chimara_if_get_format(ChimaraIF *self)
748 {
749         g_return_val_if_fail(self && CHIMARA_IS_IF(self), CHIMARA_IF_FORMAT_NONE);
750         CHIMARA_IF_USE_PRIVATE(self, priv);
751         return priv->format;
752 }
753
754 /**
755  * chimara_if_get_interpreter:
756  * @self: A #ChimaraIF widget.
757  *
758  * Returns the interpreter plugin currently running.
759  *
760  * Returns: a #ChimaraIFInterpreter constant.
761  */
762 ChimaraIFInterpreter
763 chimara_if_get_interpreter(ChimaraIF *self)
764 {
765         g_return_val_if_fail(self && CHIMARA_IS_IF(self), CHIMARA_IF_FORMAT_NONE);
766         CHIMARA_IF_USE_PRIVATE(self, priv);
767         return priv->interpreter;
768 }