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