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