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