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