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