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