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