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