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