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