chiark / gitweb /
Make newgame_undo_buf 'char *', not 'void *'.
[sgt-puzzles.git] / midend.c
1 /*
2  * midend.c: general middle fragment sitting between the
3  * platform-specific front end and game-specific back end.
4  * Maintains a move list, takes care of Undo and Redo commands, and
5  * processes standard keystrokes for undo/redo/new/quit.
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <assert.h>
11 #include <stdlib.h>
12 #include <ctype.h>
13
14 #include "puzzles.h"
15
16 enum { DEF_PARAMS, DEF_SEED, DEF_DESC };   /* for midend_game_id_int */
17
18 enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
19
20 #define special(type) ( (type) != MOVE )
21
22 struct midend_state_entry {
23     game_state *state;
24     char *movestr;
25     int movetype;
26 };
27
28 struct midend {
29     frontend *frontend;
30     random_state *random;
31     const game *ourgame;
32
33     struct preset_menu *preset_menu;
34     char **encoded_presets; /* for midend_which_preset to check against */
35     int n_encoded_presets;
36
37     /*
38      * `desc' and `privdesc' deserve a comment.
39      * 
40      * `desc' is the game description as presented to the user when
41      * they ask for Game -> Specific. `privdesc', if non-NULL, is a
42      * different game description used to reconstruct the initial
43      * game_state when de-serialising. If privdesc is NULL, `desc'
44      * is used for both.
45      * 
46      * For almost all games, `privdesc' is NULL and never used. The
47      * exception (as usual) is Mines: the initial game state has no
48      * squares open at all, but after the first click `desc' is
49      * rewritten to describe a game state with an initial click and
50      * thus a bunch of squares open. If we used that desc to
51      * serialise and deserialise, then the initial game state after
52      * deserialisation would look unlike the initial game state
53      * beforehand, and worse still execute_move() might fail on the
54      * attempted first click. So `privdesc' is also used in this
55      * case, to provide a game description describing the same
56      * fixed mine layout _but_ no initial click. (These game IDs
57      * may also be typed directly into Mines if you like.)
58      */
59     char *desc, *privdesc, *seedstr;
60     char *aux_info;
61     enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
62
63     int nstates, statesize, statepos;
64     struct midend_state_entry *states;
65
66     char *newgame_undo_buf;
67     int newgame_undo_len, newgame_undo_size;
68
69     game_params *params, *curparams;
70     game_drawstate *drawstate;
71     game_ui *ui;
72
73     game_state *oldstate;
74     float anim_time, anim_pos;
75     float flash_time, flash_pos;
76     int dir;
77
78     int timing;
79     float elapsed;
80     char *laststatus;
81
82     drawing *drawing;
83
84     int pressed_mouse_button;
85
86     int preferred_tilesize, tilesize, winwidth, winheight;
87
88     void (*game_id_change_notify_function)(void *);
89     void *game_id_change_notify_ctx;
90 };
91
92 #define ensure(me) do { \
93     if ((me)->nstates >= (me)->statesize) { \
94         (me)->statesize = (me)->nstates + 128; \
95         (me)->states = sresize((me)->states, (me)->statesize, \
96                                struct midend_state_entry); \
97     } \
98 } while (0)
99
100 /*
101  * Structure storing all the decoded data from reading a serialised
102  * game. We keep it in one of these while we check its sanity, and
103  * only once we're completely satisfied do we install it all in the
104  * midend structure proper.
105  */
106 struct deserialise_data {
107     char *seed, *parstr, *desc, *privdesc;
108     char *auxinfo, *uistr, *cparstr;
109     float elapsed;
110     game_params *params, *cparams;
111     game_ui *ui;
112     struct midend_state_entry *states;
113     int nstates, statepos;
114 };
115
116 /*
117  * Forward reference.
118  */
119 static char *midend_deserialise_internal(
120     midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
121     char *(*check)(void *ctx, midend *, const struct deserialise_data *),
122     void *cctx);
123
124 void midend_reset_tilesize(midend *me)
125 {
126     me->preferred_tilesize = me->ourgame->preferred_tilesize;
127     {
128         /*
129          * Allow an environment-based override for the default tile
130          * size by defining a variable along the lines of
131          * `NET_TILESIZE=15'.
132          */
133
134         char buf[80], *e;
135         int j, k, ts;
136
137         sprintf(buf, "%s_TILESIZE", me->ourgame->name);
138         for (j = k = 0; buf[j]; j++)
139             if (!isspace((unsigned char)buf[j]))
140                 buf[k++] = toupper((unsigned char)buf[j]);
141         buf[k] = '\0';
142         if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
143             me->preferred_tilesize = ts;
144     }
145 }
146
147 midend *midend_new(frontend *fe, const game *ourgame,
148                    const drawing_api *drapi, void *drhandle)
149 {
150     midend *me = snew(midend);
151     void *randseed;
152     int randseedsize;
153
154     get_random_seed(&randseed, &randseedsize);
155
156     me->frontend = fe;
157     me->ourgame = ourgame;
158     me->random = random_new(randseed, randseedsize);
159     me->nstates = me->statesize = me->statepos = 0;
160     me->states = NULL;
161     me->newgame_undo_buf = NULL;
162     me->newgame_undo_size = me->newgame_undo_len = 0;
163     me->params = ourgame->default_params();
164     me->game_id_change_notify_function = NULL;
165     me->game_id_change_notify_ctx = NULL;
166
167     /*
168      * Allow environment-based changing of the default settings by
169      * defining a variable along the lines of `NET_DEFAULT=25x25w'
170      * in which the value is an encoded parameter string.
171      */
172     {
173         char buf[80], *e;
174         int j, k;
175         sprintf(buf, "%s_DEFAULT", me->ourgame->name);
176         for (j = k = 0; buf[j]; j++)
177             if (!isspace((unsigned char)buf[j]))
178                 buf[k++] = toupper((unsigned char)buf[j]);
179         buf[k] = '\0';
180         if ((e = getenv(buf)) != NULL)
181             me->ourgame->decode_params(me->params, e);
182     }
183     me->curparams = NULL;
184     me->desc = me->privdesc = NULL;
185     me->seedstr = NULL;
186     me->aux_info = NULL;
187     me->genmode = GOT_NOTHING;
188     me->drawstate = NULL;
189     me->oldstate = NULL;
190     me->preset_menu = NULL;
191     me->anim_time = me->anim_pos = 0.0F;
192     me->flash_time = me->flash_pos = 0.0F;
193     me->dir = 0;
194     me->ui = NULL;
195     me->pressed_mouse_button = 0;
196     me->laststatus = NULL;
197     me->timing = FALSE;
198     me->elapsed = 0.0F;
199     me->tilesize = me->winwidth = me->winheight = 0;
200     if (drapi)
201         me->drawing = drawing_new(drapi, me, drhandle);
202     else
203         me->drawing = NULL;
204
205     midend_reset_tilesize(me);
206
207     sfree(randseed);
208
209     return me;
210 }
211
212 const game *midend_which_game(midend *me)
213 {
214     return me->ourgame;
215 }
216
217 static void midend_purge_states(midend *me)
218 {
219     while (me->nstates > me->statepos) {
220         me->ourgame->free_game(me->states[--me->nstates].state);
221         if (me->states[me->nstates].movestr)
222             sfree(me->states[me->nstates].movestr);
223     }
224 }
225
226 static void midend_free_game(midend *me)
227 {
228     while (me->nstates > 0) {
229         me->nstates--;
230         me->ourgame->free_game(me->states[me->nstates].state);
231         sfree(me->states[me->nstates].movestr);
232     }
233
234     if (me->drawstate)
235         me->ourgame->free_drawstate(me->drawing, me->drawstate);
236 }
237
238 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
239 {
240     if (menu) {
241         int i;
242         for (i = 0; i < menu->n_entries; i++) {
243             sfree(menu->entries[i].title);
244             if (menu->entries[i].params)
245                 me->ourgame->free_params(menu->entries[i].params);
246             midend_free_preset_menu(me, menu->entries[i].submenu);
247         }
248         sfree(menu->entries);
249         sfree(menu);
250     }
251 }
252
253 void midend_free(midend *me)
254 {
255     midend_free_game(me);
256
257     if (me->drawing)
258         drawing_free(me->drawing);
259     random_free(me->random);
260     sfree(me->newgame_undo_buf);
261     sfree(me->states);
262     sfree(me->desc);
263     sfree(me->privdesc);
264     sfree(me->seedstr);
265     sfree(me->aux_info);
266     me->ourgame->free_params(me->params);
267     midend_free_preset_menu(me, me->preset_menu);
268     if (me->ui)
269         me->ourgame->free_ui(me->ui);
270     if (me->curparams)
271         me->ourgame->free_params(me->curparams);
272     sfree(me->laststatus);
273     sfree(me);
274 }
275
276 static void midend_size_new_drawstate(midend *me)
277 {
278     /*
279      * Don't even bother, if we haven't worked out our tile size
280      * anyway yet.
281      */
282     if (me->tilesize > 0) {
283         me->ourgame->compute_size(me->params, me->tilesize,
284                                   &me->winwidth, &me->winheight);
285         me->ourgame->set_size(me->drawing, me->drawstate,
286                               me->params, me->tilesize);
287     }
288 }
289
290 void midend_size(midend *me, int *x, int *y, int user_size)
291 {
292     int min, max;
293     int rx, ry;
294
295     /*
296      * We can't set the size on the same drawstate twice. So if
297      * we've already sized one drawstate, we must throw it away and
298      * create a new one.
299      */
300     if (me->drawstate && me->tilesize > 0) {
301         me->ourgame->free_drawstate(me->drawing, me->drawstate);
302         me->drawstate = me->ourgame->new_drawstate(me->drawing,
303                                                    me->states[0].state);
304     }
305
306     /*
307      * Find the tile size that best fits within the given space. If
308      * `user_size' is TRUE, we must actually find the _largest_ such
309      * tile size, in order to get as close to the user's explicit
310      * request as possible; otherwise, we bound above at the game's
311      * preferred tile size, so that the game gets what it wants
312      * provided that this doesn't break the constraint from the
313      * front-end (which is likely to be a screen size or similar).
314      */
315     if (user_size) {
316         max = 1;
317         do {
318             max *= 2;
319             me->ourgame->compute_size(me->params, max, &rx, &ry);
320         } while (rx <= *x && ry <= *y);
321     } else
322         max = me->preferred_tilesize + 1;
323     min = 1;
324
325     /*
326      * Now binary-search between min and max. We're looking for a
327      * boundary rather than a value: the point at which tile sizes
328      * stop fitting within the given dimensions. Thus, we stop when
329      * max and min differ by exactly 1.
330      */
331     while (max - min > 1) {
332         int mid = (max + min) / 2;
333         me->ourgame->compute_size(me->params, mid, &rx, &ry);
334         if (rx <= *x && ry <= *y)
335             min = mid;
336         else
337             max = mid;
338     }
339
340     /*
341      * Now `min' is a valid size, and `max' isn't. So use `min'.
342      */
343
344     me->tilesize = min;
345     if (user_size)
346         /* If the user requested a change in size, make it permanent. */
347         me->preferred_tilesize = me->tilesize;
348     midend_size_new_drawstate(me);
349     *x = me->winwidth;
350     *y = me->winheight;
351 }
352
353 int midend_tilesize(midend *me) { return me->tilesize; }
354
355 void midend_set_params(midend *me, game_params *params)
356 {
357     me->ourgame->free_params(me->params);
358     me->params = me->ourgame->dup_params(params);
359 }
360
361 game_params *midend_get_params(midend *me)
362 {
363     return me->ourgame->dup_params(me->params);
364 }
365
366 static void midend_set_timer(midend *me)
367 {
368     me->timing = (me->ourgame->is_timed &&
369                   me->ourgame->timing_state(me->states[me->statepos-1].state,
370                                             me->ui));
371     if (me->timing || me->flash_time || me->anim_time)
372         activate_timer(me->frontend);
373     else
374         deactivate_timer(me->frontend);
375 }
376
377 void midend_force_redraw(midend *me)
378 {
379     if (me->drawstate)
380         me->ourgame->free_drawstate(me->drawing, me->drawstate);
381     me->drawstate = me->ourgame->new_drawstate(me->drawing,
382                                                me->states[0].state);
383     midend_size_new_drawstate(me);
384     midend_redraw(me);
385 }
386
387 static void newgame_serialise_write(void *ctx, void *buf, int len)
388 {
389     midend *const me = ctx;
390     int new_len;
391
392     assert(len < INT_MAX - me->newgame_undo_len);
393     new_len = me->newgame_undo_len + len;
394     if (new_len > me->newgame_undo_size) {
395         me->newgame_undo_size = new_len + new_len / 4 + 1024;
396         me->newgame_undo_buf = sresize(me->newgame_undo_buf,
397                                        me->newgame_undo_size, char);
398     }
399     memcpy(me->newgame_undo_buf + me->newgame_undo_len, buf, len);
400     me->newgame_undo_len = new_len;
401 }
402
403 void midend_new_game(midend *me)
404 {
405     me->newgame_undo_len = 0;
406     midend_serialise(me, newgame_serialise_write, me);
407
408     midend_stop_anim(me);
409     midend_free_game(me);
410
411     assert(me->nstates == 0);
412
413     if (me->genmode == GOT_DESC) {
414         me->genmode = GOT_NOTHING;
415     } else {
416         random_state *rs;
417
418         if (me->genmode == GOT_SEED) {
419             me->genmode = GOT_NOTHING;
420         } else {
421             /*
422              * Generate a new random seed. 15 digits comes to about
423              * 48 bits, which should be more than enough.
424              * 
425              * I'll avoid putting a leading zero on the number,
426              * just in case it confuses anybody who thinks it's
427              * processed as an integer rather than a string.
428              */
429             char newseed[16];
430             int i;
431             newseed[15] = '\0';
432             newseed[0] = '1' + (char)random_upto(me->random, 9);
433             for (i = 1; i < 15; i++)
434                 newseed[i] = '0' + (char)random_upto(me->random, 10);
435             sfree(me->seedstr);
436             me->seedstr = dupstr(newseed);
437
438             if (me->curparams)
439                 me->ourgame->free_params(me->curparams);
440             me->curparams = me->ourgame->dup_params(me->params);
441         }
442
443         sfree(me->desc);
444         sfree(me->privdesc);
445         sfree(me->aux_info);
446         me->aux_info = NULL;
447
448         rs = random_new(me->seedstr, strlen(me->seedstr));
449         /*
450          * If this midend has been instantiated without providing a
451          * drawing API, it is non-interactive. This means that it's
452          * being used for bulk game generation, and hence we should
453          * pass the non-interactive flag to new_desc.
454          */
455         me->desc = me->ourgame->new_desc(me->curparams, rs,
456                                          &me->aux_info, (me->drawing != NULL));
457         me->privdesc = NULL;
458         random_free(rs);
459     }
460
461     ensure(me);
462
463     /*
464      * It might seem a bit odd that we're using me->params to
465      * create the initial game state, rather than me->curparams
466      * which is better tailored to this specific game and which we
467      * always know.
468      * 
469      * It's supposed to be an invariant in the midend that
470      * me->params and me->curparams differ in no aspect that is
471      * important after generation (i.e. after new_desc()). By
472      * deliberately passing the _less_ specific of these two
473      * parameter sets, we provoke play-time misbehaviour in the
474      * case where a game has failed to encode a play-time parameter
475      * in the non-full version of encode_params().
476      */
477     me->states[me->nstates].state =
478         me->ourgame->new_game(me, me->params, me->desc);
479
480     /*
481      * As part of our commitment to self-testing, test the aux
482      * string to make sure nothing ghastly went wrong.
483      */
484     if (me->ourgame->can_solve && me->aux_info) {
485         game_state *s;
486         char *msg, *movestr;
487
488         msg = NULL;
489         movestr = me->ourgame->solve(me->states[0].state,
490                                      me->states[0].state,
491                                      me->aux_info, &msg);
492         assert(movestr && !msg);
493         s = me->ourgame->execute_move(me->states[0].state, movestr);
494         assert(s);
495         me->ourgame->free_game(s);
496         sfree(movestr);
497     }
498
499     me->states[me->nstates].movestr = NULL;
500     me->states[me->nstates].movetype = NEWGAME;
501     me->nstates++;
502     me->statepos = 1;
503     me->drawstate = me->ourgame->new_drawstate(me->drawing,
504                                                me->states[0].state);
505     midend_size_new_drawstate(me);
506     me->elapsed = 0.0F;
507     me->flash_pos = me->flash_time = 0.0F;
508     me->anim_pos = me->anim_time = 0.0F;
509     if (me->ui)
510         me->ourgame->free_ui(me->ui);
511     me->ui = me->ourgame->new_ui(me->states[0].state);
512     midend_set_timer(me);
513     me->pressed_mouse_button = 0;
514
515     if (me->game_id_change_notify_function)
516         me->game_id_change_notify_function(me->game_id_change_notify_ctx);
517 }
518
519 int midend_can_undo(midend *me)
520 {
521     return (me->statepos > 1 || me->newgame_undo_len);
522 }
523
524 int midend_can_redo(midend *me)
525 {
526     return (me->statepos < me->nstates);
527 }
528
529 struct newgame_undo_deserialise_read_ctx {
530     midend *me;
531     int len, pos;
532 };
533
534 static int newgame_undo_deserialise_read(void *ctx, void *buf, int len)
535 {
536     struct newgame_undo_deserialise_read_ctx *const rctx = ctx;
537     midend *const me = rctx->me;
538
539     int use = min(len, rctx->len - rctx->pos);
540     memcpy(buf, me->newgame_undo_buf + rctx->pos, use);
541     rctx->pos += use;
542     return use;
543 }
544
545 struct newgame_undo_deserialise_check_ctx {
546     int refused;
547 };
548
549 static char *newgame_undo_deserialise_check(
550     void *vctx, midend *me, const struct deserialise_data *data)
551 {
552     struct newgame_undo_deserialise_check_ctx *ctx =
553         (struct newgame_undo_deserialise_check_ctx *)vctx;
554     char *old, *new;
555
556     /*
557      * Undoing a New Game operation is only permitted if it doesn't
558      * change the game parameters. The point of having the ability at
559      * all is to recover from the momentary finger error of having hit
560      * the 'n' key (perhaps in place of some other nearby key), or hit
561      * the New Game menu item by mistake when aiming for the adjacent
562      * Restart; in both those situations, the game params are the same
563      * before and after the new-game operation.
564      *
565      * In principle, we could generalise this so that _any_ call to
566      * midend_new_game could be undone, but that would need all front
567      * ends to be alert to the possibility that any keystroke passed
568      * to midend_process_key might (if it turns out to have been one
569      * of the synonyms for undo, which the frontend doesn't
570      * necessarily check for) have various knock-on effects like
571      * needing to select a different preset in the game type menu, or
572      * even resizing the window. At least for the moment, it's easier
573      * not to do that, and to simply disallow any newgame-undo that is
574      * disruptive in either of those ways.
575      *
576      * We check both params and cparams, to be as safe as possible.
577      */
578
579     old = me->ourgame->encode_params(me->params, TRUE);
580     new = me->ourgame->encode_params(data->params, TRUE);
581     if (strcmp(old, new)) {
582         /* Set a flag to distinguish this deserialise failure
583          * from one due to faulty decoding */
584         ctx->refused = TRUE;
585         return "Undoing this new-game operation would change params";
586     }
587
588     old = me->ourgame->encode_params(me->curparams, TRUE);
589     new = me->ourgame->encode_params(data->cparams, TRUE);
590     if (strcmp(old, new)) {
591         ctx->refused = TRUE;
592         return "Undoing this new-game operation would change params";
593     }
594
595     /*
596      * Otherwise, fine, go ahead.
597      */
598     return NULL;
599 }
600
601 static int midend_undo(midend *me)
602 {
603     char *deserialise_error;
604
605     if (me->statepos > 1) {
606         if (me->ui)
607             me->ourgame->changed_state(me->ui,
608                                        me->states[me->statepos-1].state,
609                                        me->states[me->statepos-2].state);
610         me->statepos--;
611         me->dir = -1;
612         return 1;
613     } else if (me->newgame_undo_len) {
614         /* This undo cannot be undone with redo */
615         struct newgame_undo_deserialise_read_ctx rctx;
616         struct newgame_undo_deserialise_check_ctx cctx;
617         rctx.me = me;
618         rctx.len = me->newgame_undo_len; /* copy for reentrancy safety */
619         rctx.pos = 0;
620         cctx.refused = FALSE;
621         deserialise_error = midend_deserialise_internal(
622             me, newgame_undo_deserialise_read, &rctx,
623             newgame_undo_deserialise_check, &cctx);
624         if (cctx.refused) {
625             /*
626              * Our post-deserialisation check shows that we can't use
627              * this saved game after all. (deserialise_error will
628              * contain the dummy error message generated by our check
629              * function, which we ignore.)
630              */
631             return 0;
632         } else {
633             /*
634              * There should never be any _other_ deserialisation
635              * error, because this serialised data has been held in
636              * our memory since it was created, and hasn't had any
637              * opportunity to be corrupted on disk, accidentally
638              * replaced by the wrong file, etc., by user error.
639              */
640             assert(!deserialise_error);
641             return 1;
642         }
643     } else
644         return 0;
645 }
646
647 static int midend_redo(midend *me)
648 {
649     if (me->statepos < me->nstates) {
650         if (me->ui)
651             me->ourgame->changed_state(me->ui,
652                                        me->states[me->statepos-1].state,
653                                        me->states[me->statepos].state);
654         me->statepos++;
655         me->dir = +1;
656         return 1;
657     } else
658         return 0;
659 }
660
661 static void midend_finish_move(midend *me)
662 {
663     float flashtime;
664
665     /*
666      * We do not flash if the later of the two states is special.
667      * This covers both forward Solve moves and backward (undone)
668      * Restart moves.
669      */
670     if ((me->oldstate || me->statepos > 1) &&
671         ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
672          (me->dir < 0 && me->statepos < me->nstates &&
673           !special(me->states[me->statepos].movetype)))) {
674         flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
675                                               me->states[me->statepos-2].state,
676                                               me->states[me->statepos-1].state,
677                                               me->oldstate ? me->dir : +1,
678                                               me->ui);
679         if (flashtime > 0) {
680             me->flash_pos = 0.0F;
681             me->flash_time = flashtime;
682         }
683     }
684
685     if (me->oldstate)
686         me->ourgame->free_game(me->oldstate);
687     me->oldstate = NULL;
688     me->anim_pos = me->anim_time = 0;
689     me->dir = 0;
690
691     midend_set_timer(me);
692 }
693
694 void midend_stop_anim(midend *me)
695 {
696     if (me->oldstate || me->anim_time != 0) {
697         midend_finish_move(me);
698         midend_redraw(me);
699     }
700 }
701
702 void midend_restart_game(midend *me)
703 {
704     game_state *s;
705
706     assert(me->statepos >= 1);
707     if (me->statepos == 1)
708         return;                        /* no point doing anything at all! */
709
710     /*
711      * During restart, we reconstruct the game from the (public)
712      * game description rather than from states[0], because that
713      * way Mines gets slightly more sensible behaviour (restart
714      * goes to _after_ the first click so you don't have to
715      * remember where you clicked).
716      */
717     s = me->ourgame->new_game(me, me->params, me->desc);
718
719     /*
720      * Now enter the restarted state as the next move.
721      */
722     midend_stop_anim(me);
723     midend_purge_states(me);
724     ensure(me);
725     me->states[me->nstates].state = s;
726     me->states[me->nstates].movestr = dupstr(me->desc);
727     me->states[me->nstates].movetype = RESTART;
728     me->statepos = ++me->nstates;
729     if (me->ui)
730         me->ourgame->changed_state(me->ui,
731                                    me->states[me->statepos-2].state,
732                                    me->states[me->statepos-1].state);
733     me->flash_pos = me->flash_time = 0.0F;
734     midend_finish_move(me);
735     midend_redraw(me);
736     midend_set_timer(me);
737 }
738
739 static int midend_really_process_key(midend *me, int x, int y, int button)
740 {
741     game_state *oldstate =
742         me->ourgame->dup_game(me->states[me->statepos - 1].state);
743     int type = MOVE, gottype = FALSE, ret = 1;
744     float anim_time;
745     game_state *s;
746     char *movestr = NULL;
747
748     if (!IS_UI_FAKE_KEY(button)) {
749         movestr = me->ourgame->interpret_move(
750             me->states[me->statepos-1].state,
751             me->ui, me->drawstate, x, y, button);
752     }
753
754     if (!movestr) {
755         if (button == 'n' || button == 'N' || button == '\x0E' ||
756             button == UI_NEWGAME) {
757             midend_new_game(me);
758             midend_redraw(me);
759             goto done;                 /* never animate */
760         } else if (button == 'u' || button == 'U' ||
761                    button == '\x1A' || button == '\x1F' ||
762                    button == UI_UNDO) {
763             midend_stop_anim(me);
764             type = me->states[me->statepos-1].movetype;
765             gottype = TRUE;
766             if (!midend_undo(me))
767                 goto done;
768         } else if (button == 'r' || button == 'R' ||
769                    button == '\x12' || button == '\x19' ||
770                    button == UI_REDO) {
771             midend_stop_anim(me);
772             if (!midend_redo(me))
773                 goto done;
774         } else if ((button == '\x13' || button == UI_SOLVE) &&
775                    me->ourgame->can_solve) {
776             if (midend_solve(me))
777                 goto done;
778         } else if (button == 'q' || button == 'Q' || button == '\x11' ||
779                    button == UI_QUIT) {
780             ret = 0;
781             goto done;
782         } else
783             goto done;
784     } else {
785         if (!*movestr)
786             s = me->states[me->statepos-1].state;
787         else {
788             s = me->ourgame->execute_move(me->states[me->statepos-1].state,
789                                           movestr);
790             assert(s != NULL);
791         }
792
793         if (s == me->states[me->statepos-1].state) {
794             /*
795              * make_move() is allowed to return its input state to
796              * indicate that although no move has been made, the UI
797              * state has been updated and a redraw is called for.
798              */
799             midend_redraw(me);
800             midend_set_timer(me);
801             goto done;
802         } else if (s) {
803             midend_stop_anim(me);
804             midend_purge_states(me);
805             ensure(me);
806             assert(movestr != NULL);
807             me->states[me->nstates].state = s;
808             me->states[me->nstates].movestr = movestr;
809             me->states[me->nstates].movetype = MOVE;
810             me->statepos = ++me->nstates;
811             me->dir = +1;
812             if (me->ui)
813                 me->ourgame->changed_state(me->ui,
814                                            me->states[me->statepos-2].state,
815                                            me->states[me->statepos-1].state);
816         } else {
817             goto done;
818         }
819     }
820
821     if (!gottype)
822         type = me->states[me->statepos-1].movetype;
823
824     /*
825      * See if this move requires an animation.
826      */
827     if (special(type) && !(type == SOLVE &&
828                            (me->ourgame->flags & SOLVE_ANIMATES))) {
829         anim_time = 0;
830     } else {
831         anim_time = me->ourgame->anim_length(oldstate,
832                                              me->states[me->statepos-1].state,
833                                              me->dir, me->ui);
834     }
835
836     me->oldstate = oldstate; oldstate = NULL;
837     if (anim_time > 0) {
838         me->anim_time = anim_time;
839     } else {
840         me->anim_time = 0.0;
841         midend_finish_move(me);
842     }
843     me->anim_pos = 0.0;
844
845     midend_redraw(me);
846
847     midend_set_timer(me);
848
849     done:
850     if (oldstate) me->ourgame->free_game(oldstate);
851     return ret;
852 }
853
854 int midend_process_key(midend *me, int x, int y, int button)
855 {
856     int ret = 1;
857
858     /*
859      * Harmonise mouse drag and release messages.
860      * 
861      * Some front ends might accidentally switch from sending, say,
862      * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
863      * drag. (This can happen on the Mac, for example, since
864      * RIGHT_DRAG is usually done using Command+drag, and if the
865      * user accidentally releases Command half way through the drag
866      * then there will be trouble.)
867      * 
868      * It would be an O(number of front ends) annoyance to fix this
869      * in the front ends, but an O(number of back ends) annoyance
870      * to have each game capable of dealing with it. Therefore, we
871      * fix it _here_ in the common midend code so that it only has
872      * to be done once.
873      * 
874      * The possible ways in which things can go screwy in the front
875      * end are:
876      * 
877      *  - in a system containing multiple physical buttons button
878      *    presses can inadvertently overlap. We can see ABab (caps
879      *    meaning button-down and lowercase meaning button-up) when
880      *    the user had semantically intended AaBb.
881      * 
882      *  - in a system where one button is simulated by means of a
883      *    modifier key and another button, buttons can mutate
884      *    between press and release (possibly during drag). So we
885      *    can see Ab instead of Aa.
886      * 
887      * Definite requirements are:
888      * 
889      *  - button _presses_ must never be invented or destroyed. If
890      *    the user presses two buttons in succession, the button
891      *    presses must be transferred to the backend unchanged. So
892      *    if we see AaBb , that's fine; if we see ABab (the button
893      *    presses inadvertently overlapped) we must somehow
894      *    `correct' it to AaBb.
895      * 
896      *  - every mouse action must end up looking like a press, zero
897      *    or more drags, then a release. This allows back ends to
898      *    make the _assumption_ that incoming mouse data will be
899      *    sane in this regard, and not worry about the details.
900      * 
901      * So my policy will be:
902      * 
903      *  - treat any button-up as a button-up for the currently
904      *    pressed button, or ignore it if there is no currently
905      *    pressed button.
906      * 
907      *  - treat any drag as a drag for the currently pressed
908      *    button, or ignore it if there is no currently pressed
909      *    button.
910      * 
911      *  - if we see a button-down while another button is currently
912      *    pressed, invent a button-up for the first one and then
913      *    pass the button-down through as before.
914      * 
915      * 2005-05-31: An addendum to the above. Some games might want
916      * a `priority order' among buttons, such that if one button is
917      * pressed while another is down then a fixed one of the
918      * buttons takes priority no matter what order they're pressed
919      * in. Mines, in particular, wants to treat a left+right click
920      * like a left click for the benefit of users of other
921      * implementations. So the last of the above points is modified
922      * in the presence of an (optional) button priority order.
923      *
924      * A further addition: we translate certain keyboard presses to
925      * cursor key 'select' buttons, so that a) frontends don't have
926      * to translate these themselves (like they do for CURSOR_UP etc),
927      * and b) individual games don't have to hard-code button presses
928      * of '\n' etc for keyboard-based cursors. The choice of buttons
929      * here could eventually be controlled by a runtime configuration
930      * option.
931      */
932     if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
933         if (me->pressed_mouse_button) {
934             if (IS_MOUSE_DRAG(button)) {
935                 button = me->pressed_mouse_button +
936                     (LEFT_DRAG - LEFT_BUTTON);
937             } else {
938                 button = me->pressed_mouse_button +
939                     (LEFT_RELEASE - LEFT_BUTTON);
940             }
941         } else
942             return ret;                /* ignore it */
943     } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
944         /*
945          * If the new button has lower priority than the old one,
946          * don't bother doing this.
947          */
948         if (me->ourgame->flags &
949             BUTTON_BEATS(me->pressed_mouse_button, button))
950             return ret;                /* just ignore it */
951
952         /*
953          * Fabricate a button-up for the previously pressed button.
954          */
955         ret = ret && midend_really_process_key
956             (me, x, y, (me->pressed_mouse_button +
957                         (LEFT_RELEASE - LEFT_BUTTON)));
958     }
959
960     /*
961      * Translate keyboard presses to cursor selection.
962      */
963     if (button == '\n' || button == '\r')
964       button = CURSOR_SELECT;
965     if (button == ' ')
966       button = CURSOR_SELECT2;
967
968     /*
969      * Normalise both backspace characters (8 and 127) to \b. Easier
970      * to do this once, here, than to require all front ends to
971      * carefully generate the same one - now each front end can
972      * generate whichever is easiest.
973      */
974     if (button == '\177')
975         button = '\b';
976
977     /*
978      * Now send on the event we originally received.
979      */
980     ret = ret && midend_really_process_key(me, x, y, button);
981
982     /*
983      * And update the currently pressed button.
984      */
985     if (IS_MOUSE_RELEASE(button))
986         me->pressed_mouse_button = 0;
987     else if (IS_MOUSE_DOWN(button))
988         me->pressed_mouse_button = button;
989
990     return ret;
991 }
992
993 void midend_redraw(midend *me)
994 {
995     assert(me->drawing);
996
997     if (me->statepos > 0 && me->drawstate) {
998         start_draw(me->drawing);
999         if (me->oldstate && me->anim_time > 0 &&
1000             me->anim_pos < me->anim_time) {
1001             assert(me->dir != 0);
1002             me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
1003                                 me->states[me->statepos-1].state, me->dir,
1004                                 me->ui, me->anim_pos, me->flash_pos);
1005         } else {
1006             me->ourgame->redraw(me->drawing, me->drawstate, NULL,
1007                                 me->states[me->statepos-1].state, +1 /*shrug*/,
1008                                 me->ui, 0.0, me->flash_pos);
1009         }
1010         end_draw(me->drawing);
1011     }
1012 }
1013
1014 /*
1015  * Nasty hacky function used to implement the --redo option in
1016  * gtk.c. Only used for generating the puzzles' icons.
1017  */
1018 void midend_freeze_timer(midend *me, float tprop)
1019 {
1020     me->anim_pos = me->anim_time * tprop;
1021     midend_redraw(me);
1022     deactivate_timer(me->frontend);
1023 }
1024
1025 void midend_timer(midend *me, float tplus)
1026 {
1027     int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
1028
1029     me->anim_pos += tplus;
1030     if (me->anim_pos >= me->anim_time ||
1031         me->anim_time == 0 || !me->oldstate) {
1032         if (me->anim_time > 0)
1033             midend_finish_move(me);
1034     }
1035
1036     me->flash_pos += tplus;
1037     if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
1038         me->flash_pos = me->flash_time = 0;
1039     }
1040
1041     if (need_redraw)
1042         midend_redraw(me);
1043
1044     if (me->timing) {
1045         float oldelapsed = me->elapsed;
1046         me->elapsed += tplus;
1047         if ((int)oldelapsed != (int)me->elapsed)
1048             status_bar(me->drawing, me->laststatus ? me->laststatus : "");
1049     }
1050
1051     midend_set_timer(me);
1052 }
1053
1054 float *midend_colours(midend *me, int *ncolours)
1055 {
1056     float *ret;
1057
1058     ret = me->ourgame->colours(me->frontend, ncolours);
1059
1060     {
1061         int i;
1062
1063         /*
1064          * Allow environment-based overrides for the standard
1065          * colours by defining variables along the lines of
1066          * `NET_COLOUR_4=6000c0'.
1067          */
1068
1069         for (i = 0; i < *ncolours; i++) {
1070             char buf[80], *e;
1071             unsigned int r, g, b;
1072             int j, k;
1073
1074             sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
1075             for (j = k = 0; buf[j]; j++)
1076                 if (!isspace((unsigned char)buf[j]))
1077                     buf[k++] = toupper((unsigned char)buf[j]);
1078             buf[k] = '\0';
1079             if ((e = getenv(buf)) != NULL &&
1080                 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
1081                 ret[i*3 + 0] = r / 255.0F;
1082                 ret[i*3 + 1] = g / 255.0F;
1083                 ret[i*3 + 2] = b / 255.0F;
1084             }
1085         }
1086     }
1087
1088     return ret;
1089 }
1090
1091 struct preset_menu *preset_menu_new(void)
1092 {
1093     struct preset_menu *menu = snew(struct preset_menu);
1094     menu->n_entries = 0;
1095     menu->entries_size = 0;
1096     menu->entries = NULL;
1097     return menu;
1098 }
1099
1100 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
1101                                                  char *title)
1102 {
1103     struct preset_menu_entry *toret;
1104     if (menu->n_entries >= menu->entries_size) {
1105         menu->entries_size = menu->n_entries * 5 / 4 + 10;
1106         menu->entries = sresize(menu->entries, menu->entries_size,
1107                                 struct preset_menu_entry);
1108     }
1109     toret = &menu->entries[menu->n_entries++];
1110     toret->title = title;
1111     toret->params = NULL;
1112     toret->submenu = NULL;
1113     return toret;
1114 }
1115
1116 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
1117                                             char *title)
1118 {
1119     struct preset_menu_entry *entry = preset_menu_add(parent, title);
1120     entry->submenu = preset_menu_new();
1121     return entry->submenu;
1122 }
1123
1124 void preset_menu_add_preset(struct preset_menu *parent,
1125                             char *title, game_params *params)
1126 {
1127     struct preset_menu_entry *entry = preset_menu_add(parent, title);
1128     entry->params = params;
1129 }
1130
1131 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
1132 {
1133     int i;
1134     game_params *retd;
1135
1136     for (i = 0; i < menu->n_entries; i++) {
1137         if (id == menu->entries[i].id)
1138             return menu->entries[i].params;
1139         if (menu->entries[i].submenu &&
1140             (retd = preset_menu_lookup_by_id(
1141                  menu->entries[i].submenu, id)) != NULL)
1142             return retd;
1143     }
1144
1145     return NULL;
1146 }
1147
1148 static char *preset_menu_add_from_user_env(
1149     midend *me, struct preset_menu *menu, char *p, int top_level)
1150 {
1151     while (*p) {
1152         char *name, *val;
1153         game_params *preset;
1154
1155         name = p;
1156         while (*p && *p != ':') p++;
1157         if (*p) *p++ = '\0';
1158         val = p;
1159         while (*p && *p != ':') p++;
1160         if (*p) *p++ = '\0';
1161
1162         if (!strcmp(val, "#")) {
1163             /*
1164              * Special case: either open a new submenu with the given
1165              * title, or terminate the current submenu.
1166              */
1167             if (*name) {
1168                 struct preset_menu *submenu =
1169                     preset_menu_add_submenu(menu, dupstr(name));
1170                 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1171             } else {
1172                 /*
1173                  * If we get a 'close submenu' indication at the top
1174                  * level, there's not much we can do but quietly
1175                  * ignore it.
1176                  */
1177                 if (!top_level)
1178                     return p;
1179             }
1180             continue;
1181         }
1182
1183         preset = me->ourgame->default_params();
1184         me->ourgame->decode_params(preset, val);
1185
1186         if (me->ourgame->validate_params(preset, TRUE)) {
1187             /* Drop this one from the list. */
1188             me->ourgame->free_params(preset);
1189             continue;
1190         }
1191
1192         preset_menu_add_preset(menu, dupstr(name), preset);
1193     }
1194
1195     return p;
1196 }
1197
1198 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1199 {
1200     int i;
1201
1202     for (i = 0; i < menu->n_entries; i++)
1203         menu->entries[i].id = me->n_encoded_presets++;
1204
1205     for (i = 0; i < menu->n_entries; i++)
1206         if (menu->entries[i].submenu)
1207             preset_menu_alloc_ids(me, menu->entries[i].submenu);
1208 }
1209
1210 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1211 {
1212     int i;
1213
1214     for (i = 0; i < menu->n_entries; i++) {
1215         if (menu->entries[i].params) {
1216             me->encoded_presets[menu->entries[i].id] =
1217                 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1218         } else {
1219             preset_menu_encode_params(me, menu->entries[i].submenu);
1220         }
1221     }
1222 }
1223
1224 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1225 {
1226     int i;
1227
1228     if (me->preset_menu)
1229         return me->preset_menu;
1230
1231 #if 0
1232     /* Expect the game to implement exactly one of the two preset APIs */
1233     assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1234     assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1235 #endif
1236
1237     if (me->ourgame->fetch_preset) {
1238         char *name;
1239         game_params *preset;
1240
1241         /* Simple one-level menu */
1242         assert(!me->ourgame->preset_menu);
1243         me->preset_menu = preset_menu_new();
1244         for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1245             preset_menu_add_preset(me->preset_menu, name, preset);
1246
1247     } else {
1248         /* Hierarchical menu provided by the game backend */
1249         me->preset_menu = me->ourgame->preset_menu();
1250     }
1251
1252     {
1253         /*
1254          * Allow user extensions to the preset list by defining an
1255          * environment variable <gamename>_PRESETS whose value is a
1256          * colon-separated list of items, alternating between textual
1257          * titles in the menu and encoded parameter strings. For
1258          * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1259          * just one additional preset for Solo.
1260          */
1261         char buf[80], *e;
1262         int j, k;
1263
1264         sprintf(buf, "%s_PRESETS", me->ourgame->name);
1265         for (j = k = 0; buf[j]; j++)
1266             if (!isspace((unsigned char)buf[j]))
1267                 buf[k++] = toupper((unsigned char)buf[j]);
1268         buf[k] = '\0';
1269
1270         if ((e = getenv(buf)) != NULL) {
1271             e = dupstr(e);
1272             preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1273             sfree(e);
1274         }
1275     }
1276
1277     /*
1278      * Finalise the menu: allocate an integer id to each entry, and
1279      * store string encodings of the presets' parameters in
1280      * me->encoded_presets.
1281      */
1282     me->n_encoded_presets = 0;
1283     preset_menu_alloc_ids(me, me->preset_menu);
1284     me->encoded_presets = snewn(me->n_encoded_presets, char *);
1285     for (i = 0; i < me->n_encoded_presets; i++)
1286         me->encoded_presets[i] = NULL;
1287     preset_menu_encode_params(me, me->preset_menu);
1288
1289     if (id_limit)
1290         *id_limit = me->n_encoded_presets;
1291     return me->preset_menu;
1292 }
1293
1294 int midend_which_preset(midend *me)
1295 {
1296     char *encoding = me->ourgame->encode_params(me->params, TRUE);
1297     int i, ret;
1298
1299     ret = -1;
1300     for (i = 0; i < me->n_encoded_presets; i++)
1301         if (me->encoded_presets[i] &&
1302             !strcmp(encoding, me->encoded_presets[i])) {
1303             ret = i;
1304             break;
1305         }
1306
1307     sfree(encoding);
1308     return ret;
1309 }
1310
1311 int midend_wants_statusbar(midend *me)
1312 {
1313     return me->ourgame->wants_statusbar;
1314 }
1315
1316 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1317 {
1318     me->game_id_change_notify_function = notify;
1319     me->game_id_change_notify_ctx = ctx;
1320 }
1321
1322 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1323 {
1324     sfree(me->desc);
1325     sfree(me->privdesc);
1326     me->desc = dupstr(desc);
1327     me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1328     if (me->game_id_change_notify_function)
1329         me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1330 }
1331
1332 config_item *midend_get_config(midend *me, int which, char **wintitle)
1333 {
1334     char *titlebuf, *parstr, *rest;
1335     config_item *ret;
1336     char sep;
1337
1338     assert(wintitle);
1339     titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1340
1341     switch (which) {
1342       case CFG_SETTINGS:
1343         sprintf(titlebuf, "%s configuration", me->ourgame->name);
1344         *wintitle = titlebuf;
1345         return me->ourgame->configure(me->params);
1346       case CFG_SEED:
1347       case CFG_DESC:
1348         if (!me->curparams) {
1349           sfree(titlebuf);
1350           return NULL;
1351         }
1352         sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1353                 which == CFG_SEED ? "random" : "game");
1354         *wintitle = titlebuf;
1355
1356         ret = snewn(2, config_item);
1357
1358         ret[0].type = C_STRING;
1359         if (which == CFG_SEED)
1360             ret[0].name = "Game random seed";
1361         else
1362             ret[0].name = "Game ID";
1363         ret[0].ival = 0;
1364         /*
1365          * For CFG_DESC the text going in here will be a string
1366          * encoding of the restricted parameters, plus a colon,
1367          * plus the game description. For CFG_SEED it will be the
1368          * full parameters, plus a hash, plus the random seed data.
1369          * Either of these is a valid full game ID (although only
1370          * the former is likely to persist across many code
1371          * changes).
1372          */
1373         parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1374         assert(parstr);
1375         if (which == CFG_DESC) {
1376             rest = me->desc ? me->desc : "";
1377             sep = ':';
1378         } else {
1379             rest = me->seedstr ? me->seedstr : "";
1380             sep = '#';
1381         }
1382         ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1383         sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1384         sfree(parstr);
1385
1386         ret[1].type = C_END;
1387         ret[1].name = ret[1].sval = NULL;
1388         ret[1].ival = 0;
1389
1390         return ret;
1391     }
1392
1393     assert(!"We shouldn't be here");
1394     return NULL;
1395 }
1396
1397 static char *midend_game_id_int(midend *me, char *id, int defmode)
1398 {
1399     char *error, *par, *desc, *seed;
1400     game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1401     int free_params;
1402
1403     seed = strchr(id, '#');
1404     desc = strchr(id, ':');
1405
1406     if (desc && (!seed || desc < seed)) {
1407         /*
1408          * We have a colon separating parameters from game
1409          * description. So `par' now points to the parameters
1410          * string, and `desc' to the description string.
1411          */
1412         *desc++ = '\0';
1413         par = id;
1414         seed = NULL;
1415     } else if (seed && (!desc || seed < desc)) {
1416         /*
1417          * We have a hash separating parameters from random seed.
1418          * So `par' now points to the parameters string, and `seed'
1419          * to the seed string.
1420          */
1421         *seed++ = '\0';
1422         par = id;
1423         desc = NULL;
1424     } else {
1425         /*
1426          * We only have one string. Depending on `defmode', we take
1427          * it to be either parameters, seed or description.
1428          */
1429         if (defmode == DEF_SEED) {
1430             seed = id;
1431             par = desc = NULL;
1432         } else if (defmode == DEF_DESC) {
1433             desc = id;
1434             par = seed = NULL;
1435         } else {
1436             par = id;
1437             seed = desc = NULL;
1438         }
1439     }
1440
1441     /*
1442      * We must be reasonably careful here not to modify anything in
1443      * `me' until we have finished validating things. This function
1444      * must either return an error and do nothing to the midend, or
1445      * return success and do everything; nothing in between is
1446      * acceptable.
1447      */
1448     newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1449
1450     if (par) {
1451         /*
1452          * The params string may underspecify the game parameters, so
1453          * we must first initialise newcurparams with a full set of
1454          * params from somewhere else before we decode_params the
1455          * input string over the top.
1456          *
1457          * But which set? It depends on what other data we have.
1458          *
1459          * If we've been given a _descriptive_ game id, then that may
1460          * well underspecify by design, e.g. Solo game descriptions
1461          * often start just '3x3:' without specifying one of Solo's
1462          * difficulty settings, because it isn't necessary once a game
1463          * has been generated (and you might not even know it, if
1464          * you're manually transcribing a game description). In that
1465          * situation, I've always felt that the best thing to set the
1466          * difficulty to (for use if the user hits 'New Game' after
1467          * pasting in that game id) is whatever it was previously set
1468          * to. That is, we use whatever is already in me->params as
1469          * the basis for our decoding of this input string.
1470          *
1471          * A random-seed based game id, however, should use the real,
1472          * built-in default params, and not even check the
1473          * <game>_DEFAULT environment setting, because when people
1474          * paste each other random seeds - whether it's two users
1475          * arranging to generate the same game at the same time to
1476          * race solving them, or a user sending a bug report upstream
1477          * - the whole point is for the random game id to always be
1478          * interpreted the same way, even if it does underspecify.
1479          *
1480          * A parameter string typed in on its own, with no seed _or_
1481          * description, gets treated the same way as a random seed,
1482          * because again I think the most likely reason for doing that
1483          * is to have a portable representation of a set of params.
1484          */
1485         if (desc) {
1486             newcurparams = me->ourgame->dup_params(me->params);
1487         } else {
1488             newcurparams = me->ourgame->default_params();
1489         }
1490         me->ourgame->decode_params(newcurparams, par);
1491         error = me->ourgame->validate_params(newcurparams, desc == NULL);
1492         if (error) {
1493             me->ourgame->free_params(newcurparams);
1494             return error;
1495         }
1496         oldparams1 = me->curparams;
1497
1498         /*
1499          * Now filter only the persistent parts of this state into
1500          * the long-term params structure, unless we've _only_
1501          * received a params string in which case the whole lot is
1502          * persistent.
1503          */
1504         oldparams2 = me->params;
1505         if (seed || desc) {
1506             char *tmpstr;
1507
1508             newparams = me->ourgame->dup_params(me->params);
1509
1510             tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1511             me->ourgame->decode_params(newparams, tmpstr);
1512
1513             sfree(tmpstr);
1514         } else {
1515             newparams = me->ourgame->dup_params(newcurparams);
1516         }
1517         free_params = TRUE;
1518     } else {
1519         newcurparams = me->curparams;
1520         newparams = me->params;
1521         free_params = FALSE;
1522     }
1523
1524     if (desc) {
1525         error = me->ourgame->validate_desc(newparams, desc);
1526         if (error) {
1527             if (free_params) {
1528                 if (newcurparams)
1529                     me->ourgame->free_params(newcurparams);
1530                 if (newparams)
1531                     me->ourgame->free_params(newparams);
1532             }
1533             return error;
1534         }
1535     }
1536
1537     /*
1538      * Now we've got past all possible error points. Update the
1539      * midend itself.
1540      */
1541     me->params = newparams;
1542     me->curparams = newcurparams;
1543     if (oldparams1)
1544         me->ourgame->free_params(oldparams1);
1545     if (oldparams2)
1546         me->ourgame->free_params(oldparams2);
1547
1548     sfree(me->desc);
1549     sfree(me->privdesc);
1550     me->desc = me->privdesc = NULL;
1551     sfree(me->seedstr);
1552     me->seedstr = NULL;
1553
1554     if (desc) {
1555         me->desc = dupstr(desc);
1556         me->genmode = GOT_DESC;
1557         sfree(me->aux_info);
1558         me->aux_info = NULL;
1559     }
1560
1561     if (seed) {
1562         me->seedstr = dupstr(seed);
1563         me->genmode = GOT_SEED;
1564     }
1565
1566     return NULL;
1567 }
1568
1569 char *midend_game_id(midend *me, char *id)
1570 {
1571     return midend_game_id_int(me, id, DEF_PARAMS);
1572 }
1573
1574 char *midend_get_game_id(midend *me)
1575 {
1576     char *parstr, *ret;
1577
1578     parstr = me->ourgame->encode_params(me->curparams, FALSE);
1579     assert(parstr);
1580     assert(me->desc);
1581     ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1582     sprintf(ret, "%s:%s", parstr, me->desc);
1583     sfree(parstr);
1584     return ret;
1585 }
1586
1587 char *midend_get_random_seed(midend *me)
1588 {
1589     char *parstr, *ret;
1590
1591     if (!me->seedstr)
1592         return NULL;
1593
1594     parstr = me->ourgame->encode_params(me->curparams, TRUE);
1595     assert(parstr);
1596     ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1597     sprintf(ret, "%s#%s", parstr, me->seedstr);
1598     sfree(parstr);
1599     return ret;
1600 }
1601
1602 char *midend_set_config(midend *me, int which, config_item *cfg)
1603 {
1604     char *error;
1605     game_params *params;
1606
1607     switch (which) {
1608       case CFG_SETTINGS:
1609         params = me->ourgame->custom_params(cfg);
1610         error = me->ourgame->validate_params(params, TRUE);
1611
1612         if (error) {
1613             me->ourgame->free_params(params);
1614             return error;
1615         }
1616
1617         me->ourgame->free_params(me->params);
1618         me->params = params;
1619         break;
1620
1621       case CFG_SEED:
1622       case CFG_DESC:
1623         error = midend_game_id_int(me, cfg[0].sval,
1624                                    (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1625         if (error)
1626             return error;
1627         break;
1628     }
1629
1630     return NULL;
1631 }
1632
1633 int midend_can_format_as_text_now(midend *me)
1634 {
1635     if (me->ourgame->can_format_as_text_ever)
1636         return me->ourgame->can_format_as_text_now(me->params);
1637     else
1638         return FALSE;
1639 }
1640
1641 char *midend_text_format(midend *me)
1642 {
1643     if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1644         me->ourgame->can_format_as_text_now(me->params))
1645         return me->ourgame->text_format(me->states[me->statepos-1].state);
1646     else
1647         return NULL;
1648 }
1649
1650 char *midend_solve(midend *me)
1651 {
1652     game_state *s;
1653     char *msg, *movestr;
1654
1655     if (!me->ourgame->can_solve)
1656         return "This game does not support the Solve operation";
1657
1658     if (me->statepos < 1)
1659         return "No game set up to solve";   /* _shouldn't_ happen! */
1660
1661     msg = NULL;
1662     movestr = me->ourgame->solve(me->states[0].state,
1663                                  me->states[me->statepos-1].state,
1664                                  me->aux_info, &msg);
1665     if (!movestr) {
1666         if (!msg)
1667             msg = "Solve operation failed";   /* _shouldn't_ happen, but can */
1668         return msg;
1669     }
1670     s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1671     assert(s);
1672
1673     /*
1674      * Now enter the solved state as the next move.
1675      */
1676     midend_stop_anim(me);
1677     midend_purge_states(me);
1678     ensure(me);
1679     me->states[me->nstates].state = s;
1680     me->states[me->nstates].movestr = movestr;
1681     me->states[me->nstates].movetype = SOLVE;
1682     me->statepos = ++me->nstates;
1683     if (me->ui)
1684         me->ourgame->changed_state(me->ui,
1685                                    me->states[me->statepos-2].state,
1686                                    me->states[me->statepos-1].state);
1687     me->dir = +1;
1688     if (me->ourgame->flags & SOLVE_ANIMATES) {
1689         me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1690         me->anim_time =
1691             me->ourgame->anim_length(me->states[me->statepos-2].state,
1692                                      me->states[me->statepos-1].state,
1693                                      +1, me->ui);
1694         me->anim_pos = 0.0;
1695     } else {
1696         me->anim_time = 0.0;
1697         midend_finish_move(me);
1698     }
1699     if (me->drawing)
1700         midend_redraw(me);
1701     midend_set_timer(me);
1702     return NULL;
1703 }
1704
1705 int midend_status(midend *me)
1706 {
1707     /*
1708      * We should probably never be called when the state stack has no
1709      * states on it at all - ideally, midends should never be left in
1710      * that state for long enough to get put down and forgotten about.
1711      * But if we are, I think we return _true_ - pedantically speaking
1712      * a midend in that state is 'vacuously solved', and more
1713      * practically, a user whose midend has been left in that state
1714      * probably _does_ want the 'new game' option to be prominent.
1715      */
1716     if (me->statepos == 0)
1717         return +1;
1718
1719     return me->ourgame->status(me->states[me->statepos-1].state);
1720 }
1721
1722 char *midend_rewrite_statusbar(midend *me, char *text)
1723 {
1724     /*
1725      * An important special case is that we are occasionally called
1726      * with our own laststatus, to update the timer.
1727      */
1728     if (me->laststatus != text) {
1729         sfree(me->laststatus);
1730         me->laststatus = dupstr(text);
1731     }
1732
1733     if (me->ourgame->is_timed) {
1734         char timebuf[100], *ret;
1735         int min, sec;
1736
1737         sec = (int)me->elapsed;
1738         min = sec / 60;
1739         sec %= 60;
1740         sprintf(timebuf, "[%d:%02d] ", min, sec);
1741
1742         ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1743         strcpy(ret, timebuf);
1744         strcat(ret, text);
1745         return ret;
1746
1747     } else {
1748         return dupstr(text);
1749     }
1750 }
1751
1752 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1753 #define SERIALISE_VERSION "1"
1754
1755 void midend_serialise(midend *me,
1756                       void (*write)(void *ctx, void *buf, int len),
1757                       void *wctx)
1758 {
1759     int i;
1760
1761     /*
1762      * Each line of the save file contains three components. First
1763      * exactly 8 characters of header word indicating what type of
1764      * data is contained on the line; then a colon followed by a
1765      * decimal integer giving the length of the main string on the
1766      * line; then a colon followed by the string itself (exactly as
1767      * many bytes as previously specified, no matter what they
1768      * contain). Then a newline (of reasonably flexible form).
1769      */
1770 #define wr(h,s) do { \
1771     char hbuf[80]; \
1772     char *str = (s); \
1773     char lbuf[9];                               \
1774     copy_left_justified(lbuf, sizeof(lbuf), h); \
1775     sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1776     write(wctx, hbuf, strlen(hbuf)); \
1777     write(wctx, str, strlen(str)); \
1778     write(wctx, "\n", 1); \
1779 } while (0)
1780
1781     /*
1782      * Magic string identifying the file, and version number of the
1783      * file format.
1784      */
1785     wr("SAVEFILE", SERIALISE_MAGIC);
1786     wr("VERSION", SERIALISE_VERSION);
1787
1788     /*
1789      * The game name. (Copied locally to avoid const annoyance.)
1790      */
1791     {
1792         char *s = dupstr(me->ourgame->name);
1793         wr("GAME", s);
1794         sfree(s);
1795     }
1796
1797     /*
1798      * The current long-term parameters structure, in full.
1799      */
1800     if (me->params) {
1801         char *s = me->ourgame->encode_params(me->params, TRUE);
1802         wr("PARAMS", s);
1803         sfree(s);
1804     }
1805
1806     /*
1807      * The current short-term parameters structure, in full.
1808      */
1809     if (me->curparams) {
1810         char *s = me->ourgame->encode_params(me->curparams, TRUE);
1811         wr("CPARAMS", s);
1812         sfree(s);
1813     }
1814
1815     /*
1816      * The current game description, the privdesc, and the random seed.
1817      */
1818     if (me->seedstr)
1819         wr("SEED", me->seedstr);
1820     if (me->desc)
1821         wr("DESC", me->desc);
1822     if (me->privdesc)
1823         wr("PRIVDESC", me->privdesc);
1824
1825     /*
1826      * The game's aux_info. We obfuscate this to prevent spoilers
1827      * (people are likely to run `head' or similar on a saved game
1828      * file simply to find out what it is, and don't necessarily
1829      * want to be told the answer to the puzzle!)
1830      */
1831     if (me->aux_info) {
1832         unsigned char *s1;
1833         char *s2;
1834         int len;
1835
1836         len = strlen(me->aux_info);
1837         s1 = snewn(len, unsigned char);
1838         memcpy(s1, me->aux_info, len);
1839         obfuscate_bitmap(s1, len*8, FALSE);
1840         s2 = bin2hex(s1, len);
1841
1842         wr("AUXINFO", s2);
1843
1844         sfree(s2);
1845         sfree(s1);
1846     }
1847
1848     /*
1849      * Any required serialisation of the game_ui.
1850      */
1851     if (me->ui) {
1852         char *s = me->ourgame->encode_ui(me->ui);
1853         if (s) {
1854             wr("UI", s);
1855             sfree(s);
1856         }
1857     }
1858
1859     /*
1860      * The game time, if it's a timed game.
1861      */
1862     if (me->ourgame->is_timed) {
1863         char buf[80];
1864         sprintf(buf, "%g", me->elapsed);
1865         wr("TIME", buf);
1866     }
1867
1868     /*
1869      * The length of, and position in, the states list.
1870      */
1871     {
1872         char buf[80];
1873         sprintf(buf, "%d", me->nstates);
1874         wr("NSTATES", buf);
1875         sprintf(buf, "%d", me->statepos);
1876         wr("STATEPOS", buf);
1877     }
1878
1879     /*
1880      * For each state after the initial one (which we know is
1881      * constructed from either privdesc or desc), enough
1882      * information for execute_move() to reconstruct it from the
1883      * previous one.
1884      */
1885     for (i = 1; i < me->nstates; i++) {
1886         assert(me->states[i].movetype != NEWGAME);   /* only state 0 */
1887         switch (me->states[i].movetype) {
1888           case MOVE:
1889             wr("MOVE", me->states[i].movestr);
1890             break;
1891           case SOLVE:
1892             wr("SOLVE", me->states[i].movestr);
1893             break;
1894           case RESTART:
1895             wr("RESTART", me->states[i].movestr);
1896             break;
1897         }
1898     }
1899
1900 #undef wr
1901 }
1902
1903 /*
1904  * Internal version of midend_deserialise, taking an extra check
1905  * function to be called just before beginning to install things in
1906  * the midend.
1907  *
1908  * Like midend_deserialise proper, this function returns NULL on
1909  * success, or an error message.
1910  */
1911 static char *midend_deserialise_internal(
1912     midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
1913     char *(*check)(void *ctx, midend *, const struct deserialise_data *data),
1914     void *cctx)
1915 {
1916     struct deserialise_data data;
1917     int gotstates = 0;
1918     int started = FALSE;
1919     int i;
1920
1921     char *val = NULL;
1922     /* Initially all errors give the same report */
1923     char *ret = "Data does not appear to be a saved game file";
1924
1925     data.seed = data.parstr = data.desc = data.privdesc = NULL;
1926     data.auxinfo = data.uistr = data.cparstr = NULL;
1927     data.elapsed = 0.0F;
1928     data.params = data.cparams = NULL;
1929     data.ui = NULL;
1930     data.states = NULL;
1931     data.nstates = 0;
1932     data.statepos = -1;
1933
1934     /*
1935      * Loop round and round reading one key/value pair at a time
1936      * from the serialised stream, until we have enough game states
1937      * to finish.
1938      */
1939     while (data.nstates <= 0 || data.statepos < 0 ||
1940            gotstates < data.nstates-1) {
1941         char key[9], c;
1942         int len;
1943
1944         do {
1945             if (!read(rctx, key, 1)) {
1946                 /* unexpected EOF */
1947                 goto cleanup;
1948             }
1949         } while (key[0] == '\r' || key[0] == '\n');
1950
1951         if (!read(rctx, key+1, 8)) {
1952             /* unexpected EOF */
1953             goto cleanup;
1954         }
1955
1956         if (key[8] != ':') {
1957             if (started)
1958                 ret = "Data was incorrectly formatted for a saved game file";
1959             goto cleanup;
1960         }
1961         len = strcspn(key, ": ");
1962         assert(len <= 8);
1963         key[len] = '\0';
1964
1965         len = 0;
1966         while (1) {
1967             if (!read(rctx, &c, 1)) {
1968                 /* unexpected EOF */
1969                 goto cleanup;
1970             }
1971
1972             if (c == ':') {
1973                 break;
1974             } else if (c >= '0' && c <= '9') {
1975                 len = (len * 10) + (c - '0');
1976             } else {
1977                 if (started)
1978                     ret = "Data was incorrectly formatted for a"
1979                     " saved game file";
1980                 goto cleanup;
1981             }
1982         }
1983
1984         val = snewn(len+1, char);
1985         if (!read(rctx, val, len)) {
1986             if (started)
1987             goto cleanup;
1988         }
1989         val[len] = '\0';
1990
1991         if (!started) {
1992             if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1993                 /* ret already has the right message in it */
1994                 goto cleanup;
1995             }
1996             /* Now most errors are this one, unless otherwise specified */
1997             ret = "Saved data ended unexpectedly";
1998             started = TRUE;
1999         } else {
2000             if (!strcmp(key, "VERSION")) {
2001                 if (strcmp(val, SERIALISE_VERSION)) {
2002                     ret = "Cannot handle this version of the saved game"
2003                         " file format";
2004                     goto cleanup;
2005                 }
2006             } else if (!strcmp(key, "GAME")) {
2007                 if (strcmp(val, me->ourgame->name)) {
2008                     ret = "Save file is from a different game";
2009                     goto cleanup;
2010                 }
2011             } else if (!strcmp(key, "PARAMS")) {
2012                 sfree(data.parstr);
2013                 data.parstr = val;
2014                 val = NULL;
2015             } else if (!strcmp(key, "CPARAMS")) {
2016                 sfree(data.cparstr);
2017                 data.cparstr = val;
2018                 val = NULL;
2019             } else if (!strcmp(key, "SEED")) {
2020                 sfree(data.seed);
2021                 data.seed = val;
2022                 val = NULL;
2023             } else if (!strcmp(key, "DESC")) {
2024                 sfree(data.desc);
2025                 data.desc = val;
2026                 val = NULL;
2027             } else if (!strcmp(key, "PRIVDESC")) {
2028                 sfree(data.privdesc);
2029                 data.privdesc = val;
2030                 val = NULL;
2031             } else if (!strcmp(key, "AUXINFO")) {
2032                 unsigned char *tmp;
2033                 int len = strlen(val) / 2;   /* length in bytes */
2034                 tmp = hex2bin(val, len);
2035                 obfuscate_bitmap(tmp, len*8, TRUE);
2036
2037                 sfree(data.auxinfo);
2038                 data.auxinfo = snewn(len + 1, char);
2039                 memcpy(data.auxinfo, tmp, len);
2040                 data.auxinfo[len] = '\0';
2041                 sfree(tmp);
2042             } else if (!strcmp(key, "UI")) {
2043                 sfree(data.uistr);
2044                 data.uistr = val;
2045                 val = NULL;
2046             } else if (!strcmp(key, "TIME")) {
2047                 data.elapsed = (float)atof(val);
2048             } else if (!strcmp(key, "NSTATES")) {
2049                 data.nstates = atoi(val);
2050                 if (data.nstates <= 0) {
2051                     ret = "Number of states in save file was negative";
2052                     goto cleanup;
2053                 }
2054                 if (data.states) {
2055                     ret = "Two state counts provided in save file";
2056                     goto cleanup;
2057                 }
2058                 data.states = snewn(data.nstates, struct midend_state_entry);
2059                 for (i = 0; i < data.nstates; i++) {
2060                     data.states[i].state = NULL;
2061                     data.states[i].movestr = NULL;
2062                     data.states[i].movetype = NEWGAME;
2063                 }
2064             } else if (!strcmp(key, "STATEPOS")) {
2065                 data.statepos = atoi(val);
2066             } else if (!strcmp(key, "MOVE")) {
2067                 gotstates++;
2068                 data.states[gotstates].movetype = MOVE;
2069                 data.states[gotstates].movestr = val;
2070                 val = NULL;
2071             } else if (!strcmp(key, "SOLVE")) {
2072                 gotstates++;
2073                 data.states[gotstates].movetype = SOLVE;
2074                 data.states[gotstates].movestr = val;
2075                 val = NULL;
2076             } else if (!strcmp(key, "RESTART")) {
2077                 gotstates++;
2078                 data.states[gotstates].movetype = RESTART;
2079                 data.states[gotstates].movestr = val;
2080                 val = NULL;
2081             }
2082         }
2083
2084         sfree(val);
2085         val = NULL;
2086     }
2087
2088     data.params = me->ourgame->default_params();
2089     me->ourgame->decode_params(data.params, data.parstr);
2090     if (me->ourgame->validate_params(data.params, TRUE)) {
2091         ret = "Long-term parameters in save file are invalid";
2092         goto cleanup;
2093     }
2094     data.cparams = me->ourgame->default_params();
2095     me->ourgame->decode_params(data.cparams, data.cparstr);
2096     if (me->ourgame->validate_params(data.cparams, FALSE)) {
2097         ret = "Short-term parameters in save file are invalid";
2098         goto cleanup;
2099     }
2100     if (data.seed && me->ourgame->validate_params(data.cparams, TRUE)) {
2101         /*
2102          * The seed's no use with this version, but we can perfectly
2103          * well use the rest of the data.
2104          */
2105         sfree(data.seed);
2106         data.seed = NULL;
2107     }
2108     if (!data.desc) {
2109         ret = "Game description in save file is missing";
2110         goto cleanup;
2111     } else if (me->ourgame->validate_desc(data.cparams, data.desc)) {
2112         ret = "Game description in save file is invalid";
2113         goto cleanup;
2114     }
2115     if (data.privdesc &&
2116         me->ourgame->validate_desc(data.cparams, data.privdesc)) {
2117         ret = "Game private description in save file is invalid";
2118         goto cleanup;
2119     }
2120     if (data.statepos < 0 || data.statepos >= data.nstates) {
2121         ret = "Game position in save file is out of range";
2122     }
2123
2124     data.states[0].state = me->ourgame->new_game(
2125         me, data.cparams, data.privdesc ? data.privdesc : data.desc);
2126     for (i = 1; i < data.nstates; i++) {
2127         assert(data.states[i].movetype != NEWGAME);
2128         switch (data.states[i].movetype) {
2129           case MOVE:
2130           case SOLVE:
2131             data.states[i].state = me->ourgame->execute_move(
2132                 data.states[i-1].state, data.states[i].movestr);
2133             if (data.states[i].state == NULL) {
2134                 ret = "Save file contained an invalid move";
2135                 goto cleanup;
2136             }
2137             break;
2138           case RESTART:
2139             if (me->ourgame->validate_desc(
2140                     data.cparams, data.states[i].movestr)) {
2141                 ret = "Save file contained an invalid restart move";
2142                 goto cleanup;
2143             }
2144             data.states[i].state = me->ourgame->new_game(
2145                 me, data.cparams, data.states[i].movestr);
2146             break;
2147         }
2148     }
2149
2150     data.ui = me->ourgame->new_ui(data.states[0].state);
2151     me->ourgame->decode_ui(data.ui, data.uistr);
2152
2153     /*
2154      * Run the externally provided check function, and abort if it
2155      * returns an error message.
2156      */
2157     if (check && (ret = check(cctx, me, &data)) != NULL)
2158         goto cleanup;            /* error message is already in ret */
2159
2160     /*
2161      * Now we've run out of possible error conditions, so we're
2162      * ready to start overwriting the real data in the current
2163      * midend. We'll do this by swapping things with the local
2164      * variables, so that the same cleanup code will free the old
2165      * stuff.
2166      */
2167     {
2168         char *tmp;
2169
2170         tmp = me->desc;
2171         me->desc = data.desc;
2172         data.desc = tmp;
2173
2174         tmp = me->privdesc;
2175         me->privdesc = data.privdesc;
2176         data.privdesc = tmp;
2177
2178         tmp = me->seedstr;
2179         me->seedstr = data.seed;
2180         data.seed = tmp;
2181
2182         tmp = me->aux_info;
2183         me->aux_info = data.auxinfo;
2184         data.auxinfo = tmp;
2185     }
2186
2187     me->genmode = GOT_NOTHING;
2188
2189     me->statesize = data.nstates;
2190     data.nstates = me->nstates;
2191     me->nstates = me->statesize;
2192     {
2193         struct midend_state_entry *tmp;
2194         tmp = me->states;
2195         me->states = data.states;
2196         data.states = tmp;
2197     }
2198     me->statepos = data.statepos;
2199
2200     /*
2201      * Don't save the "new game undo" state.  So "new game" twice or
2202      * (in some environments) switching away and back, will make a
2203      * "new game" irreversible.  Maybe in the future we will have a
2204      * more sophisticated way to decide when to discard the previous
2205      * game state.
2206      */
2207     me->newgame_undo_len = 0;
2208
2209     {
2210         game_params *tmp;
2211
2212         tmp = me->params;
2213         me->params = data.params;
2214         data.params = tmp;
2215
2216         tmp = me->curparams;
2217         me->curparams = data.cparams;
2218         data.cparams = tmp;
2219     }
2220
2221     me->oldstate = NULL;
2222     me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2223     me->dir = 0;
2224
2225     {
2226         game_ui *tmp;
2227
2228         tmp = me->ui;
2229         me->ui = data.ui;
2230         data.ui = tmp;
2231     }
2232
2233     me->elapsed = data.elapsed;
2234     me->pressed_mouse_button = 0;
2235
2236     midend_set_timer(me);
2237
2238     if (me->drawstate)
2239         me->ourgame->free_drawstate(me->drawing, me->drawstate);
2240     me->drawstate =
2241         me->ourgame->new_drawstate(me->drawing,
2242                                    me->states[me->statepos-1].state);
2243     midend_size_new_drawstate(me);
2244     if (me->game_id_change_notify_function)
2245         me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2246
2247     ret = NULL;                        /* success! */
2248
2249     cleanup:
2250     sfree(val);
2251     sfree(data.seed);
2252     sfree(data.parstr);
2253     sfree(data.cparstr);
2254     sfree(data.desc);
2255     sfree(data.privdesc);
2256     sfree(data.auxinfo);
2257     sfree(data.uistr);
2258     if (data.params)
2259         me->ourgame->free_params(data.params);
2260     if (data.cparams)
2261         me->ourgame->free_params(data.cparams);
2262     if (data.ui)
2263         me->ourgame->free_ui(data.ui);
2264     if (data.states) {
2265         int i;
2266
2267         for (i = 0; i < data.nstates; i++) {
2268             if (data.states[i].state)
2269                 me->ourgame->free_game(data.states[i].state);
2270             sfree(data.states[i].movestr);
2271         }
2272         sfree(data.states);
2273     }
2274
2275     return ret;
2276 }
2277
2278 char *midend_deserialise(
2279     midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx)
2280 {
2281     return midend_deserialise_internal(me, read, rctx, NULL, NULL);
2282 }
2283
2284 /*
2285  * This function examines a saved game file just far enough to
2286  * determine which game type it contains. It returns NULL on success
2287  * and the game name string in 'name' (which will be dynamically
2288  * allocated and should be caller-freed), or an error message on
2289  * failure.
2290  */
2291 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2292                     void *rctx)
2293 {
2294     int nstates = 0, statepos = -1, gotstates = 0;
2295     int started = FALSE;
2296
2297     char *val = NULL;
2298     /* Initially all errors give the same report */
2299     char *ret = "Data does not appear to be a saved game file";
2300
2301     *name = NULL;
2302
2303     /*
2304      * Loop round and round reading one key/value pair at a time from
2305      * the serialised stream, until we've found the game name.
2306      */
2307     while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2308         char key[9], c;
2309         int len;
2310
2311         do {
2312             if (!read(rctx, key, 1)) {
2313                 /* unexpected EOF */
2314                 goto cleanup;
2315             }
2316         } while (key[0] == '\r' || key[0] == '\n');
2317
2318         if (!read(rctx, key+1, 8)) {
2319             /* unexpected EOF */
2320             goto cleanup;
2321         }
2322
2323         if (key[8] != ':') {
2324             if (started)
2325                 ret = "Data was incorrectly formatted for a saved game file";
2326             goto cleanup;
2327         }
2328         len = strcspn(key, ": ");
2329         assert(len <= 8);
2330         key[len] = '\0';
2331
2332         len = 0;
2333         while (1) {
2334             if (!read(rctx, &c, 1)) {
2335                 /* unexpected EOF */
2336                 goto cleanup;
2337             }
2338
2339             if (c == ':') {
2340                 break;
2341             } else if (c >= '0' && c <= '9') {
2342                 len = (len * 10) + (c - '0');
2343             } else {
2344                 if (started)
2345                     ret = "Data was incorrectly formatted for a"
2346                     " saved game file";
2347                 goto cleanup;
2348             }
2349         }
2350
2351         val = snewn(len+1, char);
2352         if (!read(rctx, val, len)) {
2353             if (started)
2354             goto cleanup;
2355         }
2356         val[len] = '\0';
2357
2358         if (!started) {
2359             if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2360                 /* ret already has the right message in it */
2361                 goto cleanup;
2362             }
2363             /* Now most errors are this one, unless otherwise specified */
2364             ret = "Saved data ended unexpectedly";
2365             started = TRUE;
2366         } else {
2367             if (!strcmp(key, "VERSION")) {
2368                 if (strcmp(val, SERIALISE_VERSION)) {
2369                     ret = "Cannot handle this version of the saved game"
2370                         " file format";
2371                     goto cleanup;
2372                 }
2373             } else if (!strcmp(key, "GAME")) {
2374                 *name = dupstr(val);
2375                 ret = NULL;
2376                 goto cleanup;
2377             }
2378         }
2379
2380         sfree(val);
2381         val = NULL;
2382     }
2383
2384     cleanup:
2385     sfree(val);
2386     return ret;
2387 }
2388
2389 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2390 {
2391     game_state *soln = NULL;
2392
2393     if (me->statepos < 1)
2394         return "No game set up to print";/* _shouldn't_ happen! */
2395
2396     if (with_soln) {
2397         char *msg, *movestr;
2398
2399         if (!me->ourgame->can_solve)
2400             return "This game does not support the Solve operation";
2401
2402         msg = "Solve operation failed";/* game _should_ overwrite on error */
2403         movestr = me->ourgame->solve(me->states[0].state,
2404                                      me->states[me->statepos-1].state,
2405                                      me->aux_info, &msg);
2406         if (!movestr)
2407             return msg;
2408         soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2409                                          movestr);
2410         assert(soln);
2411
2412         sfree(movestr);
2413     } else
2414         soln = NULL;
2415
2416     /*
2417      * This call passes over ownership of the two game_states and
2418      * the game_params. Hence we duplicate the ones we want to
2419      * keep, and we don't have to bother freeing soln if it was
2420      * non-NULL.
2421      */
2422     document_add_puzzle(doc, me->ourgame,
2423                         me->ourgame->dup_params(me->curparams),
2424                         me->ourgame->dup_game(me->states[0].state), soln);
2425
2426     return NULL;
2427 }