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