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