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