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