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