chiark / gitweb /
New infrastructure feature. Games are now permitted to be
[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     game_params **presets;
34     char **preset_names, **preset_encodings;
35     int npresets, presetsize;
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     game_params *params, *curparams;
67     game_drawstate *drawstate;
68     game_ui *ui;
69
70     game_state *oldstate;
71     float anim_time, anim_pos;
72     float flash_time, flash_pos;
73     int dir;
74
75     int timing;
76     float elapsed;
77     char *laststatus;
78
79     drawing *drawing;
80
81     int pressed_mouse_button;
82
83     int preferred_tilesize, tilesize, winwidth, winheight;
84 };
85
86 #define ensure(me) do { \
87     if ((me)->nstates >= (me)->statesize) { \
88         (me)->statesize = (me)->nstates + 128; \
89         (me)->states = sresize((me)->states, (me)->statesize, \
90                                struct midend_state_entry); \
91     } \
92 } while (0)
93
94 midend *midend_new(frontend *fe, const game *ourgame,
95                    const drawing_api *drapi, void *drhandle)
96 {
97     midend *me = snew(midend);
98     void *randseed;
99     int randseedsize;
100
101     get_random_seed(&randseed, &randseedsize);
102
103     me->frontend = fe;
104     me->ourgame = ourgame;
105     me->random = random_new(randseed, randseedsize);
106     me->nstates = me->statesize = me->statepos = 0;
107     me->states = NULL;
108     me->params = ourgame->default_params();
109     me->curparams = NULL;
110     me->desc = me->privdesc = NULL;
111     me->seedstr = NULL;
112     me->aux_info = NULL;
113     me->genmode = GOT_NOTHING;
114     me->drawstate = NULL;
115     me->oldstate = NULL;
116     me->presets = NULL;
117     me->preset_names = NULL;
118     me->preset_encodings = NULL;
119     me->npresets = me->presetsize = 0;
120     me->anim_time = me->anim_pos = 0.0F;
121     me->flash_time = me->flash_pos = 0.0F;
122     me->dir = 0;
123     me->ui = NULL;
124     me->pressed_mouse_button = 0;
125     me->laststatus = NULL;
126     me->timing = FALSE;
127     me->elapsed = 0.0F;
128     me->tilesize = me->winwidth = me->winheight = 0;
129     if (drapi)
130         me->drawing = drawing_new(drapi, me, drhandle);
131     else
132         me->drawing = NULL;
133
134     me->preferred_tilesize = ourgame->preferred_tilesize;
135     {
136         /*
137          * Allow an environment-based override for the default tile
138          * size by defining a variable along the lines of
139          * `NET_TILESIZE=15'.
140          */
141
142         char buf[80], *e;
143         int j, k, ts;
144
145         sprintf(buf, "%s_TILESIZE", me->ourgame->name);
146         for (j = k = 0; buf[j]; j++)
147             if (!isspace((unsigned char)buf[j]))
148                 buf[k++] = toupper((unsigned char)buf[j]);
149         buf[k] = '\0';
150         if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
151             me->preferred_tilesize = ts;
152     }
153
154     sfree(randseed);
155
156     return me;
157 }
158
159 static void midend_free_game(midend *me)
160 {
161     while (me->nstates > 0) {
162         me->nstates--;
163         me->ourgame->free_game(me->states[me->nstates].state);
164         sfree(me->states[me->nstates].movestr);
165     }
166
167     if (me->drawstate)
168         me->ourgame->free_drawstate(me->drawing, me->drawstate);
169 }
170
171 void midend_free(midend *me)
172 {
173     int i;
174
175     midend_free_game(me);
176
177     if (me->drawing)
178         drawing_free(me->drawing);
179     random_free(me->random);
180     sfree(me->states);
181     sfree(me->desc);
182     sfree(me->privdesc);
183     sfree(me->seedstr);
184     sfree(me->aux_info);
185     me->ourgame->free_params(me->params);
186     if (me->npresets) {
187         for (i = 0; i < me->npresets; i++) {
188             sfree(me->presets[i]);
189             sfree(me->preset_names[i]);
190             sfree(me->preset_encodings[i]);
191         }
192         sfree(me->presets);
193         sfree(me->preset_names);
194         sfree(me->preset_encodings);
195     }
196     if (me->ui)
197         me->ourgame->free_ui(me->ui);
198     if (me->curparams)
199         me->ourgame->free_params(me->curparams);
200     sfree(me->laststatus);
201     sfree(me);
202 }
203
204 static void midend_size_new_drawstate(midend *me)
205 {
206     /*
207      * Don't even bother, if we haven't worked out our tile size
208      * anyway yet.
209      */
210     if (me->tilesize > 0) {
211         me->ourgame->compute_size(me->params, me->tilesize,
212                                   &me->winwidth, &me->winheight);
213         me->ourgame->set_size(me->drawing, me->drawstate,
214                               me->params, me->tilesize);
215     }
216 }
217
218 void midend_size(midend *me, int *x, int *y, int user_size)
219 {
220     int min, max;
221     int rx, ry;
222
223     /*
224      * We can't set the size on the same drawstate twice. So if
225      * we've already sized one drawstate, we must throw it away and
226      * create a new one.
227      */
228     if (me->drawstate && me->tilesize > 0) {
229         me->ourgame->free_drawstate(me->drawing, me->drawstate);
230         me->drawstate = me->ourgame->new_drawstate(me->drawing,
231                                                    me->states[0].state);
232     }
233
234     /*
235      * Find the tile size that best fits within the given space. If
236      * `user_size' is TRUE, we must actually find the _largest_ such
237      * tile size, in order to get as close to the user's explicit
238      * request as possible; otherwise, we bound above at the game's
239      * preferred tile size, so that the game gets what it wants
240      * provided that this doesn't break the constraint from the
241      * front-end (which is likely to be a screen size or similar).
242      */
243     if (user_size) {
244         max = 1;
245         do {
246             max *= 2;
247             me->ourgame->compute_size(me->params, max, &rx, &ry);
248         } while (rx <= *x && ry <= *y);
249     } else
250         max = me->preferred_tilesize + 1;
251     min = 1;
252
253     /*
254      * Now binary-search between min and max. We're looking for a
255      * boundary rather than a value: the point at which tile sizes
256      * stop fitting within the given dimensions. Thus, we stop when
257      * max and min differ by exactly 1.
258      */
259     while (max - min > 1) {
260         int mid = (max + min) / 2;
261         me->ourgame->compute_size(me->params, mid, &rx, &ry);
262         if (rx <= *x && ry <= *y)
263             min = mid;
264         else
265             max = mid;
266     }
267
268     /*
269      * Now `min' is a valid size, and `max' isn't. So use `min'.
270      */
271
272     me->tilesize = min;
273     if (user_size)
274         /* If the user requested a change in size, make it permanent. */
275         me->preferred_tilesize = me->tilesize;
276     midend_size_new_drawstate(me);
277     *x = me->winwidth;
278     *y = me->winheight;
279 }
280
281 void midend_set_params(midend *me, game_params *params)
282 {
283     me->ourgame->free_params(me->params);
284     me->params = me->ourgame->dup_params(params);
285 }
286
287 game_params *midend_get_params(midend *me)
288 {
289     return me->ourgame->dup_params(me->params);
290 }
291
292 static void midend_set_timer(midend *me)
293 {
294     me->timing = (me->ourgame->is_timed &&
295                   me->ourgame->timing_state(me->states[me->statepos-1].state,
296                                             me->ui));
297     if (me->timing || me->flash_time || me->anim_time)
298         activate_timer(me->frontend);
299     else
300         deactivate_timer(me->frontend);
301 }
302
303 void midend_force_redraw(midend *me)
304 {
305     if (me->drawstate)
306         me->ourgame->free_drawstate(me->drawing, me->drawstate);
307     me->drawstate = me->ourgame->new_drawstate(me->drawing,
308                                                me->states[0].state);
309     midend_size_new_drawstate(me);
310     midend_redraw(me);
311 }
312
313 void midend_new_game(midend *me)
314 {
315     midend_free_game(me);
316
317     assert(me->nstates == 0);
318
319     if (me->genmode == GOT_DESC) {
320         me->genmode = GOT_NOTHING;
321     } else {
322         random_state *rs;
323
324         if (me->genmode == GOT_SEED) {
325             me->genmode = GOT_NOTHING;
326         } else {
327             /*
328              * Generate a new random seed. 15 digits comes to about
329              * 48 bits, which should be more than enough.
330              * 
331              * I'll avoid putting a leading zero on the number,
332              * just in case it confuses anybody who thinks it's
333              * processed as an integer rather than a string.
334              */
335             char newseed[16];
336             int i;
337             newseed[15] = '\0';
338             newseed[0] = '1' + random_upto(me->random, 9);
339             for (i = 1; i < 15; i++)
340                 newseed[i] = '0' + random_upto(me->random, 10);
341             sfree(me->seedstr);
342             me->seedstr = dupstr(newseed);
343
344             if (me->curparams)
345                 me->ourgame->free_params(me->curparams);
346             me->curparams = me->ourgame->dup_params(me->params);
347         }
348
349         sfree(me->desc);
350         sfree(me->privdesc);
351         sfree(me->aux_info);
352         me->aux_info = NULL;
353
354         rs = random_new(me->seedstr, strlen(me->seedstr));
355         /*
356          * If this midend has been instantiated without providing a
357          * drawing API, it is non-interactive. This means that it's
358          * being used for bulk game generation, and hence we should
359          * pass the non-interactive flag to new_desc.
360          */
361         me->desc = me->ourgame->new_desc(me->curparams, rs,
362                                          &me->aux_info, (me->drawing != NULL));
363         me->privdesc = NULL;
364         random_free(rs);
365     }
366
367     ensure(me);
368
369     /*
370      * It might seem a bit odd that we're using me->params to
371      * create the initial game state, rather than me->curparams
372      * which is better tailored to this specific game and which we
373      * always know.
374      * 
375      * It's supposed to be an invariant in the midend that
376      * me->params and me->curparams differ in no aspect that is
377      * important after generation (i.e. after new_desc()). By
378      * deliberately passing the _less_ specific of these two
379      * parameter sets, we provoke play-time misbehaviour in the
380      * case where a game has failed to encode a play-time parameter
381      * in the non-full version of encode_params().
382      */
383     me->states[me->nstates].state =
384         me->ourgame->new_game(me, me->params, me->desc);
385
386     me->states[me->nstates].movestr = NULL;
387     me->states[me->nstates].movetype = NEWGAME;
388     me->nstates++;
389     me->statepos = 1;
390     me->drawstate = me->ourgame->new_drawstate(me->drawing,
391                                                me->states[0].state);
392     midend_size_new_drawstate(me);
393     me->elapsed = 0.0F;
394     if (me->ui)
395         me->ourgame->free_ui(me->ui);
396     me->ui = me->ourgame->new_ui(me->states[0].state);
397     midend_set_timer(me);
398     me->pressed_mouse_button = 0;
399 }
400
401 static int midend_undo(midend *me)
402 {
403     if (me->statepos > 1) {
404         if (me->ui)
405             me->ourgame->changed_state(me->ui,
406                                        me->states[me->statepos-1].state,
407                                        me->states[me->statepos-2].state);
408         me->statepos--;
409         me->dir = -1;
410         return 1;
411     } else
412         return 0;
413 }
414
415 static int midend_redo(midend *me)
416 {
417     if (me->statepos < me->nstates) {
418         if (me->ui)
419             me->ourgame->changed_state(me->ui,
420                                        me->states[me->statepos-1].state,
421                                        me->states[me->statepos].state);
422         me->statepos++;
423         me->dir = +1;
424         return 1;
425     } else
426         return 0;
427 }
428
429 static void midend_finish_move(midend *me)
430 {
431     float flashtime;
432
433     /*
434      * We do not flash if the later of the two states is special.
435      * This covers both forward Solve moves and backward (undone)
436      * Restart moves.
437      */
438     if ((me->oldstate || me->statepos > 1) &&
439         ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
440          (me->dir < 0 && me->statepos < me->nstates &&
441           !special(me->states[me->statepos].movetype)))) {
442         flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
443                                               me->states[me->statepos-2].state,
444                                               me->states[me->statepos-1].state,
445                                               me->oldstate ? me->dir : +1,
446                                               me->ui);
447         if (flashtime > 0) {
448             me->flash_pos = 0.0F;
449             me->flash_time = flashtime;
450         }
451     }
452
453     if (me->oldstate)
454         me->ourgame->free_game(me->oldstate);
455     me->oldstate = NULL;
456     me->anim_pos = me->anim_time = 0;
457     me->dir = 0;
458
459     midend_set_timer(me);
460 }
461
462 void midend_stop_anim(midend *me)
463 {
464     if (me->oldstate || me->anim_time != 0) {
465         midend_finish_move(me);
466         midend_redraw(me);
467     }
468 }
469
470 void midend_restart_game(midend *me)
471 {
472     game_state *s;
473
474     midend_stop_anim(me);
475
476     assert(me->statepos >= 1);
477     if (me->statepos == 1)
478         return;                        /* no point doing anything at all! */
479
480     /*
481      * During restart, we reconstruct the game from the (public)
482      * game description rather than from states[0], because that
483      * way Mines gets slightly more sensible behaviour (restart
484      * goes to _after_ the first click so you don't have to
485      * remember where you clicked).
486      */
487     s = me->ourgame->new_game(me, me->params, me->desc);
488
489     /*
490      * Now enter the restarted state as the next move.
491      */
492     midend_stop_anim(me);
493     while (me->nstates > me->statepos)
494         me->ourgame->free_game(me->states[--me->nstates].state);
495     ensure(me);
496     me->states[me->nstates].state = s;
497     me->states[me->nstates].movestr = dupstr(me->desc);
498     me->states[me->nstates].movetype = RESTART;
499     me->statepos = ++me->nstates;
500     if (me->ui)
501         me->ourgame->changed_state(me->ui,
502                                    me->states[me->statepos-2].state,
503                                    me->states[me->statepos-1].state);
504     me->anim_time = 0.0;
505     midend_finish_move(me);
506     midend_redraw(me);
507     midend_set_timer(me);
508 }
509
510 static int midend_really_process_key(midend *me, int x, int y, int button)
511 {
512     game_state *oldstate =
513         me->ourgame->dup_game(me->states[me->statepos - 1].state);
514     int type = MOVE, gottype = FALSE, ret = 1;
515     float anim_time;
516     game_state *s;
517     char *movestr;
518         
519     movestr =
520         me->ourgame->interpret_move(me->states[me->statepos-1].state,
521                                     me->ui, me->drawstate, x, y, button);
522
523     if (!movestr) {
524         if (button == 'n' || button == 'N' || button == '\x0E') {
525             midend_stop_anim(me);
526             midend_new_game(me);
527             midend_redraw(me);
528             goto done;                 /* never animate */
529         } else if (button == 'u' || button == 'u' ||
530                    button == '\x1A' || button == '\x1F') {
531             midend_stop_anim(me);
532             type = me->states[me->statepos-1].movetype;
533             gottype = TRUE;
534             if (!midend_undo(me))
535                 goto done;
536         } else if (button == 'r' || button == 'R' ||
537                    button == '\x12' || button == '\x19') {
538             midend_stop_anim(me);
539             if (!midend_redo(me))
540                 goto done;
541         } else if (button == 'q' || button == 'Q' || button == '\x11') {
542             ret = 0;
543             goto done;
544         } else
545             goto done;
546     } else {
547         if (!*movestr)
548             s = me->states[me->statepos-1].state;
549         else {
550             s = me->ourgame->execute_move(me->states[me->statepos-1].state,
551                                           movestr);
552             assert(s != NULL);
553         }
554
555         if (s == me->states[me->statepos-1].state) {
556             /*
557              * make_move() is allowed to return its input state to
558              * indicate that although no move has been made, the UI
559              * state has been updated and a redraw is called for.
560              */
561             midend_redraw(me);
562             midend_set_timer(me);
563             goto done;
564         } else if (s) {
565             midend_stop_anim(me);
566             while (me->nstates > me->statepos)
567                 me->ourgame->free_game(me->states[--me->nstates].state);
568             ensure(me);
569             assert(movestr != NULL);
570             me->states[me->nstates].state = s;
571             me->states[me->nstates].movestr = movestr;
572             me->states[me->nstates].movetype = MOVE;
573             me->statepos = ++me->nstates;
574             me->dir = +1;
575             if (me->ui)
576                 me->ourgame->changed_state(me->ui,
577                                            me->states[me->statepos-2].state,
578                                            me->states[me->statepos-1].state);
579         } else {
580             goto done;
581         }
582     }
583
584     if (!gottype)
585         type = me->states[me->statepos-1].movetype;
586
587     /*
588      * See if this move requires an animation.
589      */
590     if (special(type) && !(type == SOLVE &&
591                            (me->ourgame->flags & SOLVE_ANIMATES))) {
592         anim_time = 0;
593     } else {
594         anim_time = me->ourgame->anim_length(oldstate,
595                                              me->states[me->statepos-1].state,
596                                              me->dir, me->ui);
597     }
598
599     me->oldstate = oldstate; oldstate = NULL;
600     if (anim_time > 0) {
601         me->anim_time = anim_time;
602     } else {
603         me->anim_time = 0.0;
604         midend_finish_move(me);
605     }
606     me->anim_pos = 0.0;
607
608     midend_redraw(me);
609
610     midend_set_timer(me);
611
612     done:
613     if (oldstate) me->ourgame->free_game(oldstate);
614     return ret;
615 }
616
617 int midend_process_key(midend *me, int x, int y, int button)
618 {
619     int ret = 1;
620
621     /*
622      * Harmonise mouse drag and release messages.
623      * 
624      * Some front ends might accidentally switch from sending, say,
625      * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
626      * drag. (This can happen on the Mac, for example, since
627      * RIGHT_DRAG is usually done using Command+drag, and if the
628      * user accidentally releases Command half way through the drag
629      * then there will be trouble.)
630      * 
631      * It would be an O(number of front ends) annoyance to fix this
632      * in the front ends, but an O(number of back ends) annoyance
633      * to have each game capable of dealing with it. Therefore, we
634      * fix it _here_ in the common midend code so that it only has
635      * to be done once.
636      * 
637      * The possible ways in which things can go screwy in the front
638      * end are:
639      * 
640      *  - in a system containing multiple physical buttons button
641      *    presses can inadvertently overlap. We can see ABab (caps
642      *    meaning button-down and lowercase meaning button-up) when
643      *    the user had semantically intended AaBb.
644      * 
645      *  - in a system where one button is simulated by means of a
646      *    modifier key and another button, buttons can mutate
647      *    between press and release (possibly during drag). So we
648      *    can see Ab instead of Aa.
649      * 
650      * Definite requirements are:
651      * 
652      *  - button _presses_ must never be invented or destroyed. If
653      *    the user presses two buttons in succession, the button
654      *    presses must be transferred to the backend unchanged. So
655      *    if we see AaBb , that's fine; if we see ABab (the button
656      *    presses inadvertently overlapped) we must somehow
657      *    `correct' it to AaBb.
658      * 
659      *  - every mouse action must end up looking like a press, zero
660      *    or more drags, then a release. This allows back ends to
661      *    make the _assumption_ that incoming mouse data will be
662      *    sane in this regard, and not worry about the details.
663      * 
664      * So my policy will be:
665      * 
666      *  - treat any button-up as a button-up for the currently
667      *    pressed button, or ignore it if there is no currently
668      *    pressed button.
669      * 
670      *  - treat any drag as a drag for the currently pressed
671      *    button, or ignore it if there is no currently pressed
672      *    button.
673      * 
674      *  - if we see a button-down while another button is currently
675      *    pressed, invent a button-up for the first one and then
676      *    pass the button-down through as before.
677      * 
678      * 2005-05-31: An addendum to the above. Some games might want
679      * a `priority order' among buttons, such that if one button is
680      * pressed while another is down then a fixed one of the
681      * buttons takes priority no matter what order they're pressed
682      * in. Mines, in particular, wants to treat a left+right click
683      * like a left click for the benefit of users of other
684      * implementations. So the last of the above points is modified
685      * in the presence of an (optional) button priority order.
686      */
687     if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
688         if (me->pressed_mouse_button) {
689             if (IS_MOUSE_DRAG(button)) {
690                 button = me->pressed_mouse_button +
691                     (LEFT_DRAG - LEFT_BUTTON);
692             } else {
693                 button = me->pressed_mouse_button +
694                     (LEFT_RELEASE - LEFT_BUTTON);
695             }
696         } else
697             return ret;                /* ignore it */
698     } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
699         /*
700          * If the new button has lower priority than the old one,
701          * don't bother doing this.
702          */
703         if (me->ourgame->flags &
704             BUTTON_BEATS(me->pressed_mouse_button, button))
705             return ret;                /* just ignore it */
706
707         /*
708          * Fabricate a button-up for the previously pressed button.
709          */
710         ret = ret && midend_really_process_key
711             (me, x, y, (me->pressed_mouse_button +
712                         (LEFT_RELEASE - LEFT_BUTTON)));
713     }
714
715     /*
716      * Now send on the event we originally received.
717      */
718     ret = ret && midend_really_process_key(me, x, y, button);
719
720     /*
721      * And update the currently pressed button.
722      */
723     if (IS_MOUSE_RELEASE(button))
724         me->pressed_mouse_button = 0;
725     else if (IS_MOUSE_DOWN(button))
726         me->pressed_mouse_button = button;
727
728     return ret;
729 }
730
731 void midend_redraw(midend *me)
732 {
733     assert(me->drawing);
734
735     if (me->statepos > 0 && me->drawstate) {
736         start_draw(me->drawing);
737         if (me->oldstate && me->anim_time > 0 &&
738             me->anim_pos < me->anim_time) {
739             assert(me->dir != 0);
740             me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
741                                 me->states[me->statepos-1].state, me->dir,
742                                 me->ui, me->anim_pos, me->flash_pos);
743         } else {
744             me->ourgame->redraw(me->drawing, me->drawstate, NULL,
745                                 me->states[me->statepos-1].state, +1 /*shrug*/,
746                                 me->ui, 0.0, me->flash_pos);
747         }
748         end_draw(me->drawing);
749     }
750 }
751
752 /*
753  * Nasty hacky function used to implement the --redo option in
754  * gtk.c. Only used for generating the puzzles' icons.
755  */
756 void midend_freeze_timer(midend *me, float tprop)
757 {
758     me->anim_pos = me->anim_time * tprop;
759     midend_redraw(me);
760     deactivate_timer(me->frontend);
761 }
762
763 void midend_timer(midend *me, float tplus)
764 {
765     int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
766
767     me->anim_pos += tplus;
768     if (me->anim_pos >= me->anim_time ||
769         me->anim_time == 0 || !me->oldstate) {
770         if (me->anim_time > 0)
771             midend_finish_move(me);
772     }
773
774     me->flash_pos += tplus;
775     if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
776         me->flash_pos = me->flash_time = 0;
777     }
778
779     if (need_redraw)
780         midend_redraw(me);
781
782     if (me->timing) {
783         float oldelapsed = me->elapsed;
784         me->elapsed += tplus;
785         if ((int)oldelapsed != (int)me->elapsed)
786             status_bar(me->drawing, me->laststatus ? me->laststatus : "");
787     }
788
789     midend_set_timer(me);
790 }
791
792 float *midend_colours(midend *me, int *ncolours)
793 {
794     float *ret;
795
796     ret = me->ourgame->colours(me->frontend, ncolours);
797
798     {
799         int i;
800
801         /*
802          * Allow environment-based overrides for the standard
803          * colours by defining variables along the lines of
804          * `NET_COLOUR_4=6000c0'.
805          */
806
807         for (i = 0; i < *ncolours; i++) {
808             char buf[80], *e;
809             unsigned int r, g, b;
810             int j, k;
811
812             sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
813             for (j = k = 0; buf[j]; j++)
814                 if (!isspace((unsigned char)buf[j]))
815                     buf[k++] = toupper((unsigned char)buf[j]);
816             buf[k] = '\0';
817             if ((e = getenv(buf)) != NULL &&
818                 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
819                 ret[i*3 + 0] = r / 255.0;
820                 ret[i*3 + 1] = g / 255.0;
821                 ret[i*3 + 2] = b / 255.0;
822             }
823         }
824     }
825
826     return ret;
827 }
828
829 int midend_num_presets(midend *me)
830 {
831     if (!me->npresets) {
832         char *name;
833         game_params *preset;
834
835         while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
836             if (me->presetsize <= me->npresets) {
837                 me->presetsize = me->npresets + 10;
838                 me->presets = sresize(me->presets, me->presetsize,
839                                       game_params *);
840                 me->preset_names = sresize(me->preset_names, me->presetsize,
841                                            char *);
842                 me->preset_encodings = sresize(me->preset_encodings,
843                                                me->presetsize, char *);
844             }
845
846             me->presets[me->npresets] = preset;
847             me->preset_names[me->npresets] = name;
848             me->preset_encodings[me->npresets] =
849                 me->ourgame->encode_params(preset, TRUE);;
850             me->npresets++;
851         }
852     }
853
854     {
855         /*
856          * Allow environment-based extensions to the preset list by
857          * defining a variable along the lines of `SOLO_PRESETS=2x3
858          * Advanced:2x3da'. Colon-separated list of items,
859          * alternating between textual titles in the menu and
860          * encoded parameter strings.
861          */
862         char buf[80], *e, *p;
863         int j, k;
864
865         sprintf(buf, "%s_PRESETS", me->ourgame->name);
866         for (j = k = 0; buf[j]; j++)
867             if (!isspace((unsigned char)buf[j]))
868                 buf[k++] = toupper((unsigned char)buf[j]);
869         buf[k] = '\0';
870
871         if ((e = getenv(buf)) != NULL) {
872             p = e = dupstr(e);
873
874             while (*p) {
875                 char *name, *val;
876                 game_params *preset;
877
878                 name = p;
879                 while (*p && *p != ':') p++;
880                 if (*p) *p++ = '\0';
881                 val = p;
882                 while (*p && *p != ':') p++;
883                 if (*p) *p++ = '\0';
884
885                 preset = me->ourgame->default_params();
886                 me->ourgame->decode_params(preset, val);
887
888                 if (me->ourgame->validate_params(preset, TRUE)) {
889                     /* Drop this one from the list. */
890                     me->ourgame->free_params(preset);
891                     continue;
892                 }
893
894                 if (me->presetsize <= me->npresets) {
895                     me->presetsize = me->npresets + 10;
896                     me->presets = sresize(me->presets, me->presetsize,
897                                           game_params *);
898                     me->preset_names = sresize(me->preset_names,
899                                                me->presetsize, char *);
900                     me->preset_encodings = sresize(me->preset_encodings,
901                                                    me->presetsize, char *);
902                 }
903
904                 me->presets[me->npresets] = preset;
905                 me->preset_names[me->npresets] = dupstr(name);
906                 me->preset_encodings[me->npresets] =
907                     me->ourgame->encode_params(preset, TRUE);
908                 me->npresets++;
909             }
910         }
911     }
912
913     return me->npresets;
914 }
915
916 void midend_fetch_preset(midend *me, int n,
917                          char **name, game_params **params)
918 {
919     assert(n >= 0 && n < me->npresets);
920     *name = me->preset_names[n];
921     *params = me->presets[n];
922 }
923
924 int midend_which_preset(midend *me)
925 {
926     char *encoding = me->ourgame->encode_params(me->params, TRUE);
927     int i, ret;
928
929     ret = -1;
930     for (i = 0; i < me->npresets; i++)
931         if (!strcmp(encoding, me->preset_encodings[i])) {
932             ret = i;
933             break;
934         }
935
936     sfree(encoding);
937     return ret;
938 }
939
940 int midend_wants_statusbar(midend *me)
941 {
942     return me->ourgame->wants_statusbar;
943 }
944
945 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
946 {
947     sfree(me->desc);
948     sfree(me->privdesc);
949     me->desc = dupstr(desc);
950     me->privdesc = privdesc ? dupstr(privdesc) : NULL;
951 }
952
953 config_item *midend_get_config(midend *me, int which, char **wintitle)
954 {
955     char *titlebuf, *parstr, *rest;
956     config_item *ret;
957     char sep;
958
959     assert(wintitle);
960     titlebuf = snewn(40 + strlen(me->ourgame->name), char);
961
962     switch (which) {
963       case CFG_SETTINGS:
964         sprintf(titlebuf, "%s configuration", me->ourgame->name);
965         *wintitle = titlebuf;
966         return me->ourgame->configure(me->params);
967       case CFG_SEED:
968       case CFG_DESC:
969         if (!me->curparams) {
970           sfree(titlebuf);
971           return NULL;
972         }
973         sprintf(titlebuf, "%s %s selection", me->ourgame->name,
974                 which == CFG_SEED ? "random" : "game");
975         *wintitle = titlebuf;
976
977         ret = snewn(2, config_item);
978
979         ret[0].type = C_STRING;
980         if (which == CFG_SEED)
981             ret[0].name = "Game random seed";
982         else
983             ret[0].name = "Game ID";
984         ret[0].ival = 0;
985         /*
986          * For CFG_DESC the text going in here will be a string
987          * encoding of the restricted parameters, plus a colon,
988          * plus the game description. For CFG_SEED it will be the
989          * full parameters, plus a hash, plus the random seed data.
990          * Either of these is a valid full game ID (although only
991          * the former is likely to persist across many code
992          * changes).
993          */
994         parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
995         assert(parstr);
996         if (which == CFG_DESC) {
997             rest = me->desc ? me->desc : "";
998             sep = ':';
999         } else {
1000             rest = me->seedstr ? me->seedstr : "";
1001             sep = '#';
1002         }
1003         ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1004         sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1005         sfree(parstr);
1006
1007         ret[1].type = C_END;
1008         ret[1].name = ret[1].sval = NULL;
1009         ret[1].ival = 0;
1010
1011         return ret;
1012     }
1013
1014     assert(!"We shouldn't be here");
1015     return NULL;
1016 }
1017
1018 static char *midend_game_id_int(midend *me, char *id, int defmode)
1019 {
1020     char *error, *par, *desc, *seed;
1021     game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1022     int free_params;
1023
1024     seed = strchr(id, '#');
1025     desc = strchr(id, ':');
1026
1027     if (desc && (!seed || desc < seed)) {
1028         /*
1029          * We have a colon separating parameters from game
1030          * description. So `par' now points to the parameters
1031          * string, and `desc' to the description string.
1032          */
1033         *desc++ = '\0';
1034         par = id;
1035         seed = NULL;
1036     } else if (seed && (!desc || seed < desc)) {
1037         /*
1038          * We have a hash separating parameters from random seed.
1039          * So `par' now points to the parameters string, and `seed'
1040          * to the seed string.
1041          */
1042         *seed++ = '\0';
1043         par = id;
1044         desc = NULL;
1045     } else {
1046         /*
1047          * We only have one string. Depending on `defmode', we take
1048          * it to be either parameters, seed or description.
1049          */
1050         if (defmode == DEF_SEED) {
1051             seed = id;
1052             par = desc = NULL;
1053         } else if (defmode == DEF_DESC) {
1054             desc = id;
1055             par = seed = NULL;
1056         } else {
1057             par = id;
1058             seed = desc = NULL;
1059         }
1060     }
1061
1062     /*
1063      * We must be reasonably careful here not to modify anything in
1064      * `me' until we have finished validating things. This function
1065      * must either return an error and do nothing to the midend, or
1066      * return success and do everything; nothing in between is
1067      * acceptable.
1068      */
1069     newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1070
1071     if (par) {
1072         newcurparams = me->ourgame->dup_params(me->params);
1073         me->ourgame->decode_params(newcurparams, par);
1074         error = me->ourgame->validate_params(newcurparams, desc == NULL);
1075         if (error) {
1076             me->ourgame->free_params(newcurparams);
1077             return error;
1078         }
1079         oldparams1 = me->curparams;
1080
1081         /*
1082          * Now filter only the persistent parts of this state into
1083          * the long-term params structure, unless we've _only_
1084          * received a params string in which case the whole lot is
1085          * persistent.
1086          */
1087         oldparams2 = me->params;
1088         if (seed || desc) {
1089             char *tmpstr;
1090
1091             newparams = me->ourgame->dup_params(me->params);
1092
1093             tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1094             me->ourgame->decode_params(newparams, tmpstr);
1095
1096             sfree(tmpstr);
1097         } else {
1098             newparams = me->ourgame->dup_params(newcurparams);
1099         }
1100         free_params = TRUE;
1101     } else {
1102         newcurparams = me->curparams;
1103         newparams = me->params;
1104         free_params = FALSE;
1105     }
1106
1107     if (desc) {
1108         error = me->ourgame->validate_desc(newparams, desc);
1109         if (error) {
1110             if (free_params) {
1111                 if (newcurparams)
1112                     me->ourgame->free_params(newcurparams);
1113                 if (newparams)
1114                     me->ourgame->free_params(newparams);
1115             }
1116             return error;
1117         }
1118     }
1119
1120     /*
1121      * Now we've got past all possible error points. Update the
1122      * midend itself.
1123      */
1124     me->params = newparams;
1125     me->curparams = newcurparams;
1126     if (oldparams1)
1127         me->ourgame->free_params(oldparams1);
1128     if (oldparams2)
1129         me->ourgame->free_params(oldparams2);
1130
1131     sfree(me->desc);
1132     sfree(me->privdesc);
1133     me->desc = me->privdesc = NULL;
1134     sfree(me->seedstr);
1135     me->seedstr = NULL;
1136
1137     if (desc) {
1138         me->desc = dupstr(desc);
1139         me->genmode = GOT_DESC;
1140         sfree(me->aux_info);
1141         me->aux_info = NULL;
1142     }
1143
1144     if (seed) {
1145         me->seedstr = dupstr(seed);
1146         me->genmode = GOT_SEED;
1147     }
1148
1149     return NULL;
1150 }
1151
1152 char *midend_game_id(midend *me, char *id)
1153 {
1154     return midend_game_id_int(me, id, DEF_PARAMS);
1155 }
1156
1157 char *midend_get_game_id(midend *me)
1158 {
1159     char *parstr, *ret;
1160
1161     parstr = me->ourgame->encode_params(me->curparams, FALSE);
1162     assert(parstr);
1163     assert(me->desc);
1164     ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1165     sprintf(ret, "%s:%s", parstr, me->desc);
1166     sfree(parstr);
1167     return ret;
1168 }
1169
1170 char *midend_set_config(midend *me, int which, config_item *cfg)
1171 {
1172     char *error;
1173     game_params *params;
1174
1175     switch (which) {
1176       case CFG_SETTINGS:
1177         params = me->ourgame->custom_params(cfg);
1178         error = me->ourgame->validate_params(params, TRUE);
1179
1180         if (error) {
1181             me->ourgame->free_params(params);
1182             return error;
1183         }
1184
1185         me->ourgame->free_params(me->params);
1186         me->params = params;
1187         break;
1188
1189       case CFG_SEED:
1190       case CFG_DESC:
1191         error = midend_game_id_int(me, cfg[0].sval,
1192                                    (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1193         if (error)
1194             return error;
1195         break;
1196     }
1197
1198     return NULL;
1199 }
1200
1201 int midend_can_format_as_text_now(midend *me)
1202 {
1203     if (me->ourgame->can_format_as_text_ever)
1204         return me->ourgame->can_format_as_text_now(me->params);
1205     else
1206         return FALSE;
1207 }
1208
1209 char *midend_text_format(midend *me)
1210 {
1211     if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1212         me->ourgame->can_format_as_text_now(me->params))
1213         return me->ourgame->text_format(me->states[me->statepos-1].state);
1214     else
1215         return NULL;
1216 }
1217
1218 char *midend_solve(midend *me)
1219 {
1220     game_state *s;
1221     char *msg, *movestr;
1222
1223     if (!me->ourgame->can_solve)
1224         return "This game does not support the Solve operation";
1225
1226     if (me->statepos < 1)
1227         return "No game set up to solve";   /* _shouldn't_ happen! */
1228
1229     msg = NULL;
1230     movestr = me->ourgame->solve(me->states[0].state,
1231                                  me->states[me->statepos-1].state,
1232                                  me->aux_info, &msg);
1233     if (!movestr) {
1234         if (!msg)
1235             msg = "Solve operation failed";   /* _shouldn't_ happen, but can */
1236         return msg;
1237     }
1238     s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1239     assert(s);
1240
1241     /*
1242      * Now enter the solved state as the next move.
1243      */
1244     midend_stop_anim(me);
1245     while (me->nstates > me->statepos) {
1246         me->ourgame->free_game(me->states[--me->nstates].state);
1247         if (me->states[me->nstates].movestr)
1248             sfree(me->states[me->nstates].movestr);
1249     }
1250     ensure(me);
1251     me->states[me->nstates].state = s;
1252     me->states[me->nstates].movestr = movestr;
1253     me->states[me->nstates].movetype = SOLVE;
1254     me->statepos = ++me->nstates;
1255     if (me->ui)
1256         me->ourgame->changed_state(me->ui,
1257                                    me->states[me->statepos-2].state,
1258                                    me->states[me->statepos-1].state);
1259     me->dir = +1;
1260     if (me->ourgame->flags & SOLVE_ANIMATES) {
1261         me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1262         me->anim_time =
1263             me->ourgame->anim_length(me->states[me->statepos-2].state,
1264                                      me->states[me->statepos-1].state,
1265                                      +1, me->ui);
1266         me->anim_pos = 0.0;
1267     } else {
1268         me->anim_time = 0.0;
1269         midend_finish_move(me);
1270     }
1271     midend_redraw(me);
1272     midend_set_timer(me);
1273     return NULL;
1274 }
1275
1276 char *midend_rewrite_statusbar(midend *me, char *text)
1277 {
1278     /*
1279      * An important special case is that we are occasionally called
1280      * with our own laststatus, to update the timer.
1281      */
1282     if (me->laststatus != text) {
1283         sfree(me->laststatus);
1284         me->laststatus = dupstr(text);
1285     }
1286
1287     if (me->ourgame->is_timed) {
1288         char timebuf[100], *ret;
1289         int min, sec;
1290
1291         sec = me->elapsed;
1292         min = sec / 60;
1293         sec %= 60;
1294         sprintf(timebuf, "[%d:%02d] ", min, sec);
1295
1296         ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1297         strcpy(ret, timebuf);
1298         strcat(ret, text);
1299         return ret;
1300
1301     } else {
1302         return dupstr(text);
1303     }
1304 }
1305
1306 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1307 #define SERIALISE_VERSION "1"
1308
1309 void midend_serialise(midend *me,
1310                       void (*write)(void *ctx, void *buf, int len),
1311                       void *wctx)
1312 {
1313     int i;
1314
1315     /*
1316      * Each line of the save file contains three components. First
1317      * exactly 8 characters of header word indicating what type of
1318      * data is contained on the line; then a colon followed by a
1319      * decimal integer giving the length of the main string on the
1320      * line; then a colon followed by the string itself (exactly as
1321      * many bytes as previously specified, no matter what they
1322      * contain). Then a newline (of reasonably flexible form).
1323      */
1324 #define wr(h,s) do { \
1325     char hbuf[80]; \
1326     char *str = (s); \
1327     sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1328     write(wctx, hbuf, strlen(hbuf)); \
1329     write(wctx, str, strlen(str)); \
1330     write(wctx, "\n", 1); \
1331 } while (0)
1332
1333     /*
1334      * Magic string identifying the file, and version number of the
1335      * file format.
1336      */
1337     wr("SAVEFILE", SERIALISE_MAGIC);
1338     wr("VERSION", SERIALISE_VERSION);
1339
1340     /*
1341      * The game name. (Copied locally to avoid const annoyance.)
1342      */
1343     {
1344         char *s = dupstr(me->ourgame->name);
1345         wr("GAME", s);
1346         sfree(s);
1347     }
1348
1349     /*
1350      * The current long-term parameters structure, in full.
1351      */
1352     if (me->params) {
1353         char *s = me->ourgame->encode_params(me->params, TRUE);
1354         wr("PARAMS", s);
1355         sfree(s);
1356     }
1357
1358     /*
1359      * The current short-term parameters structure, in full.
1360      */
1361     if (me->curparams) {
1362         char *s = me->ourgame->encode_params(me->curparams, TRUE);
1363         wr("CPARAMS", s);
1364         sfree(s);
1365     }
1366
1367     /*
1368      * The current game description, the privdesc, and the random seed.
1369      */
1370     if (me->seedstr)
1371         wr("SEED", me->seedstr);
1372     if (me->desc)
1373         wr("DESC", me->desc);
1374     if (me->privdesc)
1375         wr("PRIVDESC", me->privdesc);
1376
1377     /*
1378      * The game's aux_info. We obfuscate this to prevent spoilers
1379      * (people are likely to run `head' or similar on a saved game
1380      * file simply to find out what it is, and don't necessarily
1381      * want to be told the answer to the puzzle!)
1382      */
1383     if (me->aux_info) {
1384         unsigned char *s1;
1385         char *s2;
1386         int len;
1387
1388         len = strlen(me->aux_info);
1389         s1 = snewn(len, unsigned char);
1390         memcpy(s1, me->aux_info, len);
1391         obfuscate_bitmap(s1, len*8, FALSE);
1392         s2 = bin2hex(s1, len);
1393
1394         wr("AUXINFO", s2);
1395
1396         sfree(s2);
1397         sfree(s1);
1398     }
1399
1400     /*
1401      * Any required serialisation of the game_ui.
1402      */
1403     if (me->ui) {
1404         char *s = me->ourgame->encode_ui(me->ui);
1405         if (s) {
1406             wr("UI", s);
1407             sfree(s);
1408         }
1409     }
1410
1411     /*
1412      * The game time, if it's a timed game.
1413      */
1414     if (me->ourgame->is_timed) {
1415         char buf[80];
1416         sprintf(buf, "%g", me->elapsed);
1417         wr("TIME", buf);
1418     }
1419
1420     /*
1421      * The length of, and position in, the states list.
1422      */
1423     {
1424         char buf[80];
1425         sprintf(buf, "%d", me->nstates);
1426         wr("NSTATES", buf);
1427         sprintf(buf, "%d", me->statepos);
1428         wr("STATEPOS", buf);
1429     }
1430
1431     /*
1432      * For each state after the initial one (which we know is
1433      * constructed from either privdesc or desc), enough
1434      * information for execute_move() to reconstruct it from the
1435      * previous one.
1436      */
1437     for (i = 1; i < me->nstates; i++) {
1438         assert(me->states[i].movetype != NEWGAME);   /* only state 0 */
1439         switch (me->states[i].movetype) {
1440           case MOVE:
1441             wr("MOVE", me->states[i].movestr);
1442             break;
1443           case SOLVE:
1444             wr("SOLVE", me->states[i].movestr);
1445             break;
1446           case RESTART:
1447             wr("RESTART", me->states[i].movestr);
1448             break;
1449         }
1450     }
1451
1452 #undef wr
1453 }
1454
1455 /*
1456  * This function returns NULL on success, or an error message.
1457  */
1458 char *midend_deserialise(midend *me,
1459                          int (*read)(void *ctx, void *buf, int len),
1460                          void *rctx)
1461 {
1462     int nstates = 0, statepos = -1, gotstates = 0;
1463     int started = FALSE;
1464     int i;
1465
1466     char *val = NULL;
1467     /* Initially all errors give the same report */
1468     char *ret = "Data does not appear to be a saved game file";
1469
1470     /*
1471      * We construct all the new state in local variables while we
1472      * check its sanity. Only once we have finished reading the
1473      * serialised data and detected no errors at all do we start
1474      * modifying stuff in the midend passed in.
1475      */
1476     char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1477     char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1478     float elapsed = 0.0F;
1479     game_params *params = NULL, *cparams = NULL;
1480     game_ui *ui = NULL;
1481     struct midend_state_entry *states = NULL;
1482
1483     /*
1484      * Loop round and round reading one key/value pair at a time
1485      * from the serialised stream, until we have enough game states
1486      * to finish.
1487      */
1488     while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1489         char key[9], c;
1490         int len;
1491
1492         do {
1493             if (!read(rctx, key, 1)) {
1494                 /* unexpected EOF */
1495                 goto cleanup;
1496             }
1497         } while (key[0] == '\r' || key[0] == '\n');
1498
1499         if (!read(rctx, key+1, 8)) {
1500             /* unexpected EOF */
1501             goto cleanup;
1502         }
1503
1504         if (key[8] != ':') {
1505             if (started)
1506                 ret = "Data was incorrectly formatted for a saved game file";
1507             goto cleanup;
1508         }
1509         len = strcspn(key, ": ");
1510         assert(len <= 8);
1511         key[len] = '\0';
1512
1513         len = 0;
1514         while (1) {
1515             if (!read(rctx, &c, 1)) {
1516                 /* unexpected EOF */
1517                 goto cleanup;
1518             }
1519
1520             if (c == ':') {
1521                 break;
1522             } else if (c >= '0' && c <= '9') {
1523                 len = (len * 10) + (c - '0');
1524             } else {
1525                 if (started)
1526                     ret = "Data was incorrectly formatted for a"
1527                     " saved game file";
1528                 goto cleanup;
1529             }
1530         }
1531
1532         val = snewn(len+1, char);
1533         if (!read(rctx, val, len)) {
1534             if (started)
1535             goto cleanup;
1536         }
1537         val[len] = '\0';
1538
1539         if (!started) {
1540             if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1541                 /* ret already has the right message in it */
1542                 goto cleanup;
1543             }
1544             /* Now most errors are this one, unless otherwise specified */
1545             ret = "Saved data ended unexpectedly";
1546             started = TRUE;
1547         } else {
1548             if (!strcmp(key, "VERSION")) {
1549                 if (strcmp(val, SERIALISE_VERSION)) {
1550                     ret = "Cannot handle this version of the saved game"
1551                         " file format";
1552                     goto cleanup;
1553                 }
1554             } else if (!strcmp(key, "GAME")) {
1555                 if (strcmp(val, me->ourgame->name)) {
1556                     ret = "Save file is from a different game";
1557                     goto cleanup;
1558                 }
1559             } else if (!strcmp(key, "PARAMS")) {
1560                 sfree(parstr);
1561                 parstr = val;
1562                 val = NULL;
1563             } else if (!strcmp(key, "CPARAMS")) {
1564                 sfree(cparstr);
1565                 cparstr = val;
1566                 val = NULL;
1567             } else if (!strcmp(key, "SEED")) {
1568                 sfree(seed);
1569                 seed = val;
1570                 val = NULL;
1571             } else if (!strcmp(key, "DESC")) {
1572                 sfree(desc);
1573                 desc = val;
1574                 val = NULL;
1575             } else if (!strcmp(key, "PRIVDESC")) {
1576                 sfree(privdesc);
1577                 privdesc = val;
1578                 val = NULL;
1579             } else if (!strcmp(key, "AUXINFO")) {
1580                 unsigned char *tmp;
1581                 int len = strlen(val) / 2;   /* length in bytes */
1582                 tmp = hex2bin(val, len);
1583                 obfuscate_bitmap(tmp, len*8, TRUE);
1584
1585                 sfree(auxinfo);
1586                 auxinfo = snewn(len + 1, char);
1587                 memcpy(auxinfo, tmp, len);
1588                 auxinfo[len] = '\0';
1589                 sfree(tmp);
1590             } else if (!strcmp(key, "UI")) {
1591                 sfree(uistr);
1592                 uistr = val;
1593                 val = NULL;
1594             } else if (!strcmp(key, "TIME")) {
1595                 elapsed = atof(val);
1596             } else if (!strcmp(key, "NSTATES")) {
1597                 nstates = atoi(val);
1598                 if (nstates <= 0) {
1599                     ret = "Number of states in save file was negative";
1600                     goto cleanup;
1601                 }
1602                 if (states) {
1603                     ret = "Two state counts provided in save file";
1604                     goto cleanup;
1605                 }
1606                 states = snewn(nstates, struct midend_state_entry);
1607                 for (i = 0; i < nstates; i++) {
1608                     states[i].state = NULL;
1609                     states[i].movestr = NULL;
1610                     states[i].movetype = NEWGAME;
1611                 }
1612             } else if (!strcmp(key, "STATEPOS")) {
1613                 statepos = atoi(val);
1614             } else if (!strcmp(key, "MOVE")) {
1615                 gotstates++;
1616                 states[gotstates].movetype = MOVE;
1617                 states[gotstates].movestr = val;
1618                 val = NULL;
1619             } else if (!strcmp(key, "SOLVE")) {
1620                 gotstates++;
1621                 states[gotstates].movetype = SOLVE;
1622                 states[gotstates].movestr = val;
1623                 val = NULL;
1624             } else if (!strcmp(key, "RESTART")) {
1625                 gotstates++;
1626                 states[gotstates].movetype = RESTART;
1627                 states[gotstates].movestr = val;
1628                 val = NULL;
1629             }
1630         }
1631
1632         sfree(val);
1633         val = NULL;
1634     }
1635
1636     params = me->ourgame->default_params();
1637     me->ourgame->decode_params(params, parstr);
1638     if (me->ourgame->validate_params(params, TRUE)) {
1639         ret = "Long-term parameters in save file are invalid";
1640         goto cleanup;
1641     }
1642     cparams = me->ourgame->default_params();
1643     me->ourgame->decode_params(cparams, cparstr);
1644     if (me->ourgame->validate_params(cparams, FALSE)) {
1645         ret = "Short-term parameters in save file are invalid";
1646         goto cleanup;
1647     }
1648     if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1649         /*
1650          * The seed's no use with this version, but we can perfectly
1651          * well use the rest of the data.
1652          */
1653         sfree(seed);
1654         seed = NULL;
1655     }
1656     if (!desc) {
1657         ret = "Game description in save file is missing";
1658         goto cleanup;
1659     } else if (me->ourgame->validate_desc(params, desc)) {
1660         ret = "Game description in save file is invalid";
1661         goto cleanup;
1662     }
1663     if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1664         ret = "Game private description in save file is invalid";
1665         goto cleanup;
1666     }
1667     if (statepos < 0 || statepos >= nstates) {
1668         ret = "Game position in save file is out of range";
1669     }
1670
1671     states[0].state = me->ourgame->new_game(me, params,
1672                                             privdesc ? privdesc : desc);
1673     for (i = 1; i < nstates; i++) {
1674         assert(states[i].movetype != NEWGAME);
1675         switch (states[i].movetype) {
1676           case MOVE:
1677           case SOLVE:
1678             states[i].state = me->ourgame->execute_move(states[i-1].state,
1679                                                         states[i].movestr);
1680             if (states[i].state == NULL) {
1681                 ret = "Save file contained an invalid move";
1682                 goto cleanup;
1683             }
1684             break;
1685           case RESTART:
1686             if (me->ourgame->validate_desc(params, states[i].movestr)) {
1687                 ret = "Save file contained an invalid restart move";
1688                 goto cleanup;
1689             }
1690             states[i].state = me->ourgame->new_game(me, params,
1691                                                     states[i].movestr);
1692             break;
1693         }
1694     }
1695
1696     ui = me->ourgame->new_ui(states[0].state);
1697     me->ourgame->decode_ui(ui, uistr);
1698
1699     /*
1700      * Now we've run out of possible error conditions, so we're
1701      * ready to start overwriting the real data in the current
1702      * midend. We'll do this by swapping things with the local
1703      * variables, so that the same cleanup code will free the old
1704      * stuff.
1705      */
1706     {
1707         char *tmp;
1708
1709         tmp = me->desc;
1710         me->desc = desc;
1711         desc = tmp;
1712
1713         tmp = me->privdesc;
1714         me->privdesc = privdesc;
1715         privdesc = tmp;
1716
1717         tmp = me->seedstr;
1718         me->seedstr = seed;
1719         seed = tmp;
1720
1721         tmp = me->aux_info;
1722         me->aux_info = auxinfo;
1723         auxinfo = tmp;
1724     }
1725
1726     me->genmode = GOT_NOTHING;
1727
1728     me->statesize = nstates;
1729     nstates = me->nstates;
1730     me->nstates = me->statesize;
1731     {
1732         struct midend_state_entry *tmp;
1733         tmp = me->states;
1734         me->states = states;
1735         states = tmp;
1736     }
1737     me->statepos = statepos;
1738
1739     {
1740         game_params *tmp;
1741
1742         tmp = me->params;
1743         me->params = params;
1744         params = tmp;
1745
1746         tmp = me->curparams;
1747         me->curparams = cparams;
1748         cparams = tmp;
1749     }
1750
1751     me->oldstate = NULL;
1752     me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1753     me->dir = 0;
1754
1755     {
1756         game_ui *tmp;
1757
1758         tmp = me->ui;
1759         me->ui = ui;
1760         ui = tmp;
1761     }
1762
1763     me->elapsed = elapsed;
1764     me->pressed_mouse_button = 0;
1765
1766     midend_set_timer(me);
1767
1768     if (me->drawstate)
1769         me->ourgame->free_drawstate(me->drawing, me->drawstate);
1770     me->drawstate =
1771         me->ourgame->new_drawstate(me->drawing,
1772                                    me->states[me->statepos-1].state);
1773     midend_size_new_drawstate(me);
1774
1775     ret = NULL;                        /* success! */
1776
1777     cleanup:
1778     sfree(val);
1779     sfree(seed);
1780     sfree(parstr);
1781     sfree(cparstr);
1782     sfree(desc);
1783     sfree(privdesc);
1784     sfree(auxinfo);
1785     sfree(uistr);
1786     if (params)
1787         me->ourgame->free_params(params);
1788     if (cparams)
1789         me->ourgame->free_params(cparams);
1790     if (ui)
1791         me->ourgame->free_ui(ui);
1792     if (states) {
1793         int i;
1794
1795         for (i = 0; i < nstates; i++) {
1796             if (states[i].state)
1797                 me->ourgame->free_game(states[i].state);
1798             sfree(states[i].movestr);
1799         }
1800         sfree(states);
1801     }
1802
1803     return ret;
1804 }
1805
1806 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
1807 {
1808     game_state *soln = NULL;
1809
1810     if (me->statepos < 1)
1811         return "No game set up to print";/* _shouldn't_ happen! */
1812
1813     if (with_soln) {
1814         char *msg, *movestr;
1815
1816         if (!me->ourgame->can_solve)
1817             return "This game does not support the Solve operation";
1818
1819         msg = "Solve operation failed";/* game _should_ overwrite on error */
1820         movestr = me->ourgame->solve(me->states[0].state,
1821                                      me->states[me->statepos-1].state,
1822                                      me->aux_info, &msg);
1823         if (!movestr)
1824             return msg;
1825         soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
1826                                          movestr);
1827         assert(soln);
1828
1829         sfree(movestr);
1830     } else
1831         soln = NULL;
1832
1833     /*
1834      * This call passes over ownership of the two game_states and
1835      * the game_params. Hence we duplicate the ones we want to
1836      * keep, and we don't have to bother freeing soln if it was
1837      * non-NULL.
1838      */
1839     document_add_puzzle(doc, me->ourgame,
1840                         me->ourgame->dup_params(me->curparams),
1841                         me->ourgame->dup_game(me->states[0].state), soln);
1842
1843     return NULL;
1844 }