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