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