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