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