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