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.
16 enum { DEF_PARAMS, DEF_SEED, DEF_DESC }; /* for midend_game_id_int */
18 enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
20 #define special(type) ( (type) != MOVE )
22 struct midend_state_entry {
33 struct preset_menu *preset_menu;
34 char **encoded_presets; /* for midend_which_preset to check against */
35 int n_encoded_presets;
38 * `desc' and `privdesc' deserve a comment.
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'
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.)
59 char *desc, *privdesc, *seedstr;
61 enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
63 int nstates, statesize, statepos;
64 struct midend_state_entry *states;
66 game_params *params, *curparams;
67 game_drawstate *drawstate;
71 float anim_time, anim_pos;
72 float flash_time, flash_pos;
81 int pressed_mouse_button;
83 int preferred_tilesize, tilesize, winwidth, winheight;
85 void (*game_id_change_notify_function)(void *);
86 void *game_id_change_notify_ctx;
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); \
98 * Structure storing all the decoded data from reading a serialised
99 * game. We keep it in one of these while we check its sanity, and
100 * only once we're completely satisfied do we install it all in the
101 * midend structure proper.
103 struct deserialise_data {
104 char *seed, *parstr, *desc, *privdesc;
105 char *auxinfo, *uistr, *cparstr;
107 game_params *params, *cparams;
109 struct midend_state_entry *states;
110 int nstates, statepos;
116 static char *midend_deserialise_internal(
117 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
118 char *(*check)(void *ctx, midend *, const struct deserialise_data *),
121 void midend_reset_tilesize(midend *me)
123 me->preferred_tilesize = me->ourgame->preferred_tilesize;
126 * Allow an environment-based override for the default tile
127 * size by defining a variable along the lines of
134 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
135 for (j = k = 0; buf[j]; j++)
136 if (!isspace((unsigned char)buf[j]))
137 buf[k++] = toupper((unsigned char)buf[j]);
139 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
140 me->preferred_tilesize = ts;
144 midend *midend_new(frontend *fe, const game *ourgame,
145 const drawing_api *drapi, void *drhandle)
147 midend *me = snew(midend);
151 get_random_seed(&randseed, &randseedsize);
154 me->ourgame = ourgame;
155 me->random = random_new(randseed, randseedsize);
156 me->nstates = me->statesize = me->statepos = 0;
158 me->params = ourgame->default_params();
159 me->game_id_change_notify_function = NULL;
160 me->game_id_change_notify_ctx = NULL;
163 * Allow environment-based changing of the default settings by
164 * defining a variable along the lines of `NET_DEFAULT=25x25w'
165 * in which the value is an encoded parameter string.
170 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
171 for (j = k = 0; buf[j]; j++)
172 if (!isspace((unsigned char)buf[j]))
173 buf[k++] = toupper((unsigned char)buf[j]);
175 if ((e = getenv(buf)) != NULL)
176 me->ourgame->decode_params(me->params, e);
178 me->curparams = NULL;
179 me->desc = me->privdesc = NULL;
182 me->genmode = GOT_NOTHING;
183 me->drawstate = NULL;
185 me->preset_menu = NULL;
186 me->anim_time = me->anim_pos = 0.0F;
187 me->flash_time = me->flash_pos = 0.0F;
190 me->pressed_mouse_button = 0;
191 me->laststatus = NULL;
194 me->tilesize = me->winwidth = me->winheight = 0;
196 me->drawing = drawing_new(drapi, me, drhandle);
200 midend_reset_tilesize(me);
207 const game *midend_which_game(midend *me)
212 static void midend_purge_states(midend *me)
214 while (me->nstates > me->statepos) {
215 me->ourgame->free_game(me->states[--me->nstates].state);
216 if (me->states[me->nstates].movestr)
217 sfree(me->states[me->nstates].movestr);
221 static void midend_free_game(midend *me)
223 while (me->nstates > 0) {
225 me->ourgame->free_game(me->states[me->nstates].state);
226 sfree(me->states[me->nstates].movestr);
230 me->ourgame->free_drawstate(me->drawing, me->drawstate);
233 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
237 for (i = 0; i < menu->n_entries; i++) {
238 sfree(menu->entries[i].title);
239 if (menu->entries[i].params)
240 me->ourgame->free_params(menu->entries[i].params);
241 midend_free_preset_menu(me, menu->entries[i].submenu);
243 sfree(menu->entries);
248 void midend_free(midend *me)
250 midend_free_game(me);
253 drawing_free(me->drawing);
254 random_free(me->random);
260 me->ourgame->free_params(me->params);
261 midend_free_preset_menu(me, me->preset_menu);
263 me->ourgame->free_ui(me->ui);
265 me->ourgame->free_params(me->curparams);
266 sfree(me->laststatus);
270 static void midend_size_new_drawstate(midend *me)
273 * Don't even bother, if we haven't worked out our tile size
276 if (me->tilesize > 0) {
277 me->ourgame->compute_size(me->params, me->tilesize,
278 &me->winwidth, &me->winheight);
279 me->ourgame->set_size(me->drawing, me->drawstate,
280 me->params, me->tilesize);
284 void midend_size(midend *me, int *x, int *y, int user_size)
290 * We can't set the size on the same drawstate twice. So if
291 * we've already sized one drawstate, we must throw it away and
294 if (me->drawstate && me->tilesize > 0) {
295 me->ourgame->free_drawstate(me->drawing, me->drawstate);
296 me->drawstate = me->ourgame->new_drawstate(me->drawing,
297 me->states[0].state);
301 * Find the tile size that best fits within the given space. If
302 * `user_size' is TRUE, we must actually find the _largest_ such
303 * tile size, in order to get as close to the user's explicit
304 * request as possible; otherwise, we bound above at the game's
305 * preferred tile size, so that the game gets what it wants
306 * provided that this doesn't break the constraint from the
307 * front-end (which is likely to be a screen size or similar).
313 me->ourgame->compute_size(me->params, max, &rx, &ry);
314 } while (rx <= *x && ry <= *y);
316 max = me->preferred_tilesize + 1;
320 * Now binary-search between min and max. We're looking for a
321 * boundary rather than a value: the point at which tile sizes
322 * stop fitting within the given dimensions. Thus, we stop when
323 * max and min differ by exactly 1.
325 while (max - min > 1) {
326 int mid = (max + min) / 2;
327 me->ourgame->compute_size(me->params, mid, &rx, &ry);
328 if (rx <= *x && ry <= *y)
335 * Now `min' is a valid size, and `max' isn't. So use `min'.
340 /* If the user requested a change in size, make it permanent. */
341 me->preferred_tilesize = me->tilesize;
342 midend_size_new_drawstate(me);
347 int midend_tilesize(midend *me) { return me->tilesize; }
349 void midend_set_params(midend *me, game_params *params)
351 me->ourgame->free_params(me->params);
352 me->params = me->ourgame->dup_params(params);
355 game_params *midend_get_params(midend *me)
357 return me->ourgame->dup_params(me->params);
360 static void midend_set_timer(midend *me)
362 me->timing = (me->ourgame->is_timed &&
363 me->ourgame->timing_state(me->states[me->statepos-1].state,
365 if (me->timing || me->flash_time || me->anim_time)
366 activate_timer(me->frontend);
368 deactivate_timer(me->frontend);
371 void midend_force_redraw(midend *me)
374 me->ourgame->free_drawstate(me->drawing, me->drawstate);
375 me->drawstate = me->ourgame->new_drawstate(me->drawing,
376 me->states[0].state);
377 midend_size_new_drawstate(me);
381 void midend_new_game(midend *me)
383 midend_stop_anim(me);
384 midend_free_game(me);
386 assert(me->nstates == 0);
388 if (me->genmode == GOT_DESC) {
389 me->genmode = GOT_NOTHING;
393 if (me->genmode == GOT_SEED) {
394 me->genmode = GOT_NOTHING;
397 * Generate a new random seed. 15 digits comes to about
398 * 48 bits, which should be more than enough.
400 * I'll avoid putting a leading zero on the number,
401 * just in case it confuses anybody who thinks it's
402 * processed as an integer rather than a string.
407 newseed[0] = '1' + (char)random_upto(me->random, 9);
408 for (i = 1; i < 15; i++)
409 newseed[i] = '0' + (char)random_upto(me->random, 10);
411 me->seedstr = dupstr(newseed);
414 me->ourgame->free_params(me->curparams);
415 me->curparams = me->ourgame->dup_params(me->params);
423 rs = random_new(me->seedstr, strlen(me->seedstr));
425 * If this midend has been instantiated without providing a
426 * drawing API, it is non-interactive. This means that it's
427 * being used for bulk game generation, and hence we should
428 * pass the non-interactive flag to new_desc.
430 me->desc = me->ourgame->new_desc(me->curparams, rs,
431 &me->aux_info, (me->drawing != NULL));
439 * It might seem a bit odd that we're using me->params to
440 * create the initial game state, rather than me->curparams
441 * which is better tailored to this specific game and which we
444 * It's supposed to be an invariant in the midend that
445 * me->params and me->curparams differ in no aspect that is
446 * important after generation (i.e. after new_desc()). By
447 * deliberately passing the _less_ specific of these two
448 * parameter sets, we provoke play-time misbehaviour in the
449 * case where a game has failed to encode a play-time parameter
450 * in the non-full version of encode_params().
452 me->states[me->nstates].state =
453 me->ourgame->new_game(me, me->params, me->desc);
456 * As part of our commitment to self-testing, test the aux
457 * string to make sure nothing ghastly went wrong.
459 if (me->ourgame->can_solve && me->aux_info) {
464 movestr = me->ourgame->solve(me->states[0].state,
467 assert(movestr && !msg);
468 s = me->ourgame->execute_move(me->states[0].state, movestr);
470 me->ourgame->free_game(s);
474 me->states[me->nstates].movestr = NULL;
475 me->states[me->nstates].movetype = NEWGAME;
478 me->drawstate = me->ourgame->new_drawstate(me->drawing,
479 me->states[0].state);
480 midend_size_new_drawstate(me);
482 me->flash_pos = me->flash_time = 0.0F;
483 me->anim_pos = me->anim_time = 0.0F;
485 me->ourgame->free_ui(me->ui);
486 me->ui = me->ourgame->new_ui(me->states[0].state);
487 midend_set_timer(me);
488 me->pressed_mouse_button = 0;
490 if (me->game_id_change_notify_function)
491 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
494 int midend_can_undo(midend *me)
496 return (me->statepos > 1);
499 int midend_can_redo(midend *me)
501 return (me->statepos < me->nstates);
504 static int midend_undo(midend *me)
506 if (me->statepos > 1) {
508 me->ourgame->changed_state(me->ui,
509 me->states[me->statepos-1].state,
510 me->states[me->statepos-2].state);
518 static int midend_redo(midend *me)
520 if (me->statepos < me->nstates) {
522 me->ourgame->changed_state(me->ui,
523 me->states[me->statepos-1].state,
524 me->states[me->statepos].state);
532 static void midend_finish_move(midend *me)
537 * We do not flash if the later of the two states is special.
538 * This covers both forward Solve moves and backward (undone)
541 if ((me->oldstate || me->statepos > 1) &&
542 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
543 (me->dir < 0 && me->statepos < me->nstates &&
544 !special(me->states[me->statepos].movetype)))) {
545 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
546 me->states[me->statepos-2].state,
547 me->states[me->statepos-1].state,
548 me->oldstate ? me->dir : +1,
551 me->flash_pos = 0.0F;
552 me->flash_time = flashtime;
557 me->ourgame->free_game(me->oldstate);
559 me->anim_pos = me->anim_time = 0;
562 midend_set_timer(me);
565 void midend_stop_anim(midend *me)
567 if (me->oldstate || me->anim_time != 0) {
568 midend_finish_move(me);
573 void midend_restart_game(midend *me)
577 assert(me->statepos >= 1);
578 if (me->statepos == 1)
579 return; /* no point doing anything at all! */
582 * During restart, we reconstruct the game from the (public)
583 * game description rather than from states[0], because that
584 * way Mines gets slightly more sensible behaviour (restart
585 * goes to _after_ the first click so you don't have to
586 * remember where you clicked).
588 s = me->ourgame->new_game(me, me->params, me->desc);
591 * Now enter the restarted state as the next move.
593 midend_stop_anim(me);
594 midend_purge_states(me);
596 me->states[me->nstates].state = s;
597 me->states[me->nstates].movestr = dupstr(me->desc);
598 me->states[me->nstates].movetype = RESTART;
599 me->statepos = ++me->nstates;
601 me->ourgame->changed_state(me->ui,
602 me->states[me->statepos-2].state,
603 me->states[me->statepos-1].state);
604 me->flash_pos = me->flash_time = 0.0F;
605 midend_finish_move(me);
607 midend_set_timer(me);
610 static int midend_really_process_key(midend *me, int x, int y, int button)
612 game_state *oldstate =
613 me->ourgame->dup_game(me->states[me->statepos - 1].state);
614 int type = MOVE, gottype = FALSE, ret = 1;
617 char *movestr = NULL;
619 if (!IS_UI_FAKE_KEY(button)) {
620 movestr = me->ourgame->interpret_move(
621 me->states[me->statepos-1].state,
622 me->ui, me->drawstate, x, y, button);
626 if (button == 'n' || button == 'N' || button == '\x0E' ||
627 button == UI_NEWGAME) {
630 goto done; /* never animate */
631 } else if (button == 'u' || button == 'U' ||
632 button == '\x1A' || button == '\x1F' ||
634 midend_stop_anim(me);
635 type = me->states[me->statepos-1].movetype;
637 if (!midend_undo(me))
639 } else if (button == 'r' || button == 'R' ||
640 button == '\x12' || button == '\x19' ||
642 midend_stop_anim(me);
643 if (!midend_redo(me))
645 } else if ((button == '\x13' || button == UI_SOLVE) &&
646 me->ourgame->can_solve) {
647 if (midend_solve(me))
649 } else if (button == 'q' || button == 'Q' || button == '\x11' ||
657 s = me->states[me->statepos-1].state;
659 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
664 if (s == me->states[me->statepos-1].state) {
666 * make_move() is allowed to return its input state to
667 * indicate that although no move has been made, the UI
668 * state has been updated and a redraw is called for.
671 midend_set_timer(me);
674 midend_stop_anim(me);
675 midend_purge_states(me);
677 assert(movestr != NULL);
678 me->states[me->nstates].state = s;
679 me->states[me->nstates].movestr = movestr;
680 me->states[me->nstates].movetype = MOVE;
681 me->statepos = ++me->nstates;
684 me->ourgame->changed_state(me->ui,
685 me->states[me->statepos-2].state,
686 me->states[me->statepos-1].state);
693 type = me->states[me->statepos-1].movetype;
696 * See if this move requires an animation.
698 if (special(type) && !(type == SOLVE &&
699 (me->ourgame->flags & SOLVE_ANIMATES))) {
702 anim_time = me->ourgame->anim_length(oldstate,
703 me->states[me->statepos-1].state,
707 me->oldstate = oldstate; oldstate = NULL;
709 me->anim_time = anim_time;
712 midend_finish_move(me);
718 midend_set_timer(me);
721 if (oldstate) me->ourgame->free_game(oldstate);
725 int midend_process_key(midend *me, int x, int y, int button)
730 * Harmonise mouse drag and release messages.
732 * Some front ends might accidentally switch from sending, say,
733 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
734 * drag. (This can happen on the Mac, for example, since
735 * RIGHT_DRAG is usually done using Command+drag, and if the
736 * user accidentally releases Command half way through the drag
737 * then there will be trouble.)
739 * It would be an O(number of front ends) annoyance to fix this
740 * in the front ends, but an O(number of back ends) annoyance
741 * to have each game capable of dealing with it. Therefore, we
742 * fix it _here_ in the common midend code so that it only has
745 * The possible ways in which things can go screwy in the front
748 * - in a system containing multiple physical buttons button
749 * presses can inadvertently overlap. We can see ABab (caps
750 * meaning button-down and lowercase meaning button-up) when
751 * the user had semantically intended AaBb.
753 * - in a system where one button is simulated by means of a
754 * modifier key and another button, buttons can mutate
755 * between press and release (possibly during drag). So we
756 * can see Ab instead of Aa.
758 * Definite requirements are:
760 * - button _presses_ must never be invented or destroyed. If
761 * the user presses two buttons in succession, the button
762 * presses must be transferred to the backend unchanged. So
763 * if we see AaBb , that's fine; if we see ABab (the button
764 * presses inadvertently overlapped) we must somehow
765 * `correct' it to AaBb.
767 * - every mouse action must end up looking like a press, zero
768 * or more drags, then a release. This allows back ends to
769 * make the _assumption_ that incoming mouse data will be
770 * sane in this regard, and not worry about the details.
772 * So my policy will be:
774 * - treat any button-up as a button-up for the currently
775 * pressed button, or ignore it if there is no currently
778 * - treat any drag as a drag for the currently pressed
779 * button, or ignore it if there is no currently pressed
782 * - if we see a button-down while another button is currently
783 * pressed, invent a button-up for the first one and then
784 * pass the button-down through as before.
786 * 2005-05-31: An addendum to the above. Some games might want
787 * a `priority order' among buttons, such that if one button is
788 * pressed while another is down then a fixed one of the
789 * buttons takes priority no matter what order they're pressed
790 * in. Mines, in particular, wants to treat a left+right click
791 * like a left click for the benefit of users of other
792 * implementations. So the last of the above points is modified
793 * in the presence of an (optional) button priority order.
795 * A further addition: we translate certain keyboard presses to
796 * cursor key 'select' buttons, so that a) frontends don't have
797 * to translate these themselves (like they do for CURSOR_UP etc),
798 * and b) individual games don't have to hard-code button presses
799 * of '\n' etc for keyboard-based cursors. The choice of buttons
800 * here could eventually be controlled by a runtime configuration
803 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
804 if (me->pressed_mouse_button) {
805 if (IS_MOUSE_DRAG(button)) {
806 button = me->pressed_mouse_button +
807 (LEFT_DRAG - LEFT_BUTTON);
809 button = me->pressed_mouse_button +
810 (LEFT_RELEASE - LEFT_BUTTON);
813 return ret; /* ignore it */
814 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
816 * If the new button has lower priority than the old one,
817 * don't bother doing this.
819 if (me->ourgame->flags &
820 BUTTON_BEATS(me->pressed_mouse_button, button))
821 return ret; /* just ignore it */
824 * Fabricate a button-up for the previously pressed button.
826 ret = ret && midend_really_process_key
827 (me, x, y, (me->pressed_mouse_button +
828 (LEFT_RELEASE - LEFT_BUTTON)));
832 * Translate keyboard presses to cursor selection.
834 if (button == '\n' || button == '\r')
835 button = CURSOR_SELECT;
837 button = CURSOR_SELECT2;
840 * Normalise both backspace characters (8 and 127) to \b. Easier
841 * to do this once, here, than to require all front ends to
842 * carefully generate the same one - now each front end can
843 * generate whichever is easiest.
845 if (button == '\177')
849 * Now send on the event we originally received.
851 ret = ret && midend_really_process_key(me, x, y, button);
854 * And update the currently pressed button.
856 if (IS_MOUSE_RELEASE(button))
857 me->pressed_mouse_button = 0;
858 else if (IS_MOUSE_DOWN(button))
859 me->pressed_mouse_button = button;
864 void midend_redraw(midend *me)
868 if (me->statepos > 0 && me->drawstate) {
869 start_draw(me->drawing);
870 if (me->oldstate && me->anim_time > 0 &&
871 me->anim_pos < me->anim_time) {
872 assert(me->dir != 0);
873 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
874 me->states[me->statepos-1].state, me->dir,
875 me->ui, me->anim_pos, me->flash_pos);
877 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
878 me->states[me->statepos-1].state, +1 /*shrug*/,
879 me->ui, 0.0, me->flash_pos);
881 end_draw(me->drawing);
886 * Nasty hacky function used to implement the --redo option in
887 * gtk.c. Only used for generating the puzzles' icons.
889 void midend_freeze_timer(midend *me, float tprop)
891 me->anim_pos = me->anim_time * tprop;
893 deactivate_timer(me->frontend);
896 void midend_timer(midend *me, float tplus)
898 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
900 me->anim_pos += tplus;
901 if (me->anim_pos >= me->anim_time ||
902 me->anim_time == 0 || !me->oldstate) {
903 if (me->anim_time > 0)
904 midend_finish_move(me);
907 me->flash_pos += tplus;
908 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
909 me->flash_pos = me->flash_time = 0;
916 float oldelapsed = me->elapsed;
917 me->elapsed += tplus;
918 if ((int)oldelapsed != (int)me->elapsed)
919 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
922 midend_set_timer(me);
925 float *midend_colours(midend *me, int *ncolours)
929 ret = me->ourgame->colours(me->frontend, ncolours);
935 * Allow environment-based overrides for the standard
936 * colours by defining variables along the lines of
937 * `NET_COLOUR_4=6000c0'.
940 for (i = 0; i < *ncolours; i++) {
942 unsigned int r, g, b;
945 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
946 for (j = k = 0; buf[j]; j++)
947 if (!isspace((unsigned char)buf[j]))
948 buf[k++] = toupper((unsigned char)buf[j]);
950 if ((e = getenv(buf)) != NULL &&
951 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
952 ret[i*3 + 0] = r / 255.0F;
953 ret[i*3 + 1] = g / 255.0F;
954 ret[i*3 + 2] = b / 255.0F;
962 struct preset_menu *preset_menu_new(void)
964 struct preset_menu *menu = snew(struct preset_menu);
966 menu->entries_size = 0;
967 menu->entries = NULL;
971 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
974 struct preset_menu_entry *toret;
975 if (menu->n_entries >= menu->entries_size) {
976 menu->entries_size = menu->n_entries * 5 / 4 + 10;
977 menu->entries = sresize(menu->entries, menu->entries_size,
978 struct preset_menu_entry);
980 toret = &menu->entries[menu->n_entries++];
981 toret->title = title;
982 toret->params = NULL;
983 toret->submenu = NULL;
987 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
990 struct preset_menu_entry *entry = preset_menu_add(parent, title);
991 entry->submenu = preset_menu_new();
992 return entry->submenu;
995 void preset_menu_add_preset(struct preset_menu *parent,
996 char *title, game_params *params)
998 struct preset_menu_entry *entry = preset_menu_add(parent, title);
999 entry->params = params;
1002 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
1007 for (i = 0; i < menu->n_entries; i++) {
1008 if (id == menu->entries[i].id)
1009 return menu->entries[i].params;
1010 if (menu->entries[i].submenu &&
1011 (retd = preset_menu_lookup_by_id(
1012 menu->entries[i].submenu, id)) != NULL)
1019 static char *preset_menu_add_from_user_env(
1020 midend *me, struct preset_menu *menu, char *p, int top_level)
1024 game_params *preset;
1027 while (*p && *p != ':') p++;
1028 if (*p) *p++ = '\0';
1030 while (*p && *p != ':') p++;
1031 if (*p) *p++ = '\0';
1033 if (!strcmp(val, "#")) {
1035 * Special case: either open a new submenu with the given
1036 * title, or terminate the current submenu.
1039 struct preset_menu *submenu =
1040 preset_menu_add_submenu(menu, dupstr(name));
1041 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1044 * If we get a 'close submenu' indication at the top
1045 * level, there's not much we can do but quietly
1054 preset = me->ourgame->default_params();
1055 me->ourgame->decode_params(preset, val);
1057 if (me->ourgame->validate_params(preset, TRUE)) {
1058 /* Drop this one from the list. */
1059 me->ourgame->free_params(preset);
1063 preset_menu_add_preset(menu, dupstr(name), preset);
1069 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1073 for (i = 0; i < menu->n_entries; i++)
1074 menu->entries[i].id = me->n_encoded_presets++;
1076 for (i = 0; i < menu->n_entries; i++)
1077 if (menu->entries[i].submenu)
1078 preset_menu_alloc_ids(me, menu->entries[i].submenu);
1081 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1085 for (i = 0; i < menu->n_entries; i++) {
1086 if (menu->entries[i].params) {
1087 me->encoded_presets[menu->entries[i].id] =
1088 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1090 preset_menu_encode_params(me, menu->entries[i].submenu);
1095 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1099 if (me->preset_menu)
1100 return me->preset_menu;
1103 /* Expect the game to implement exactly one of the two preset APIs */
1104 assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1105 assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1108 if (me->ourgame->fetch_preset) {
1110 game_params *preset;
1112 /* Simple one-level menu */
1113 assert(!me->ourgame->preset_menu);
1114 me->preset_menu = preset_menu_new();
1115 for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1116 preset_menu_add_preset(me->preset_menu, name, preset);
1119 /* Hierarchical menu provided by the game backend */
1120 me->preset_menu = me->ourgame->preset_menu();
1125 * Allow user extensions to the preset list by defining an
1126 * environment variable <gamename>_PRESETS whose value is a
1127 * colon-separated list of items, alternating between textual
1128 * titles in the menu and encoded parameter strings. For
1129 * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1130 * just one additional preset for Solo.
1135 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1136 for (j = k = 0; buf[j]; j++)
1137 if (!isspace((unsigned char)buf[j]))
1138 buf[k++] = toupper((unsigned char)buf[j]);
1141 if ((e = getenv(buf)) != NULL) {
1143 preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1149 * Finalise the menu: allocate an integer id to each entry, and
1150 * store string encodings of the presets' parameters in
1151 * me->encoded_presets.
1153 me->n_encoded_presets = 0;
1154 preset_menu_alloc_ids(me, me->preset_menu);
1155 me->encoded_presets = snewn(me->n_encoded_presets, char *);
1156 for (i = 0; i < me->n_encoded_presets; i++)
1157 me->encoded_presets[i] = NULL;
1158 preset_menu_encode_params(me, me->preset_menu);
1161 *id_limit = me->n_encoded_presets;
1162 return me->preset_menu;
1165 int midend_which_preset(midend *me)
1167 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1171 for (i = 0; i < me->n_encoded_presets; i++)
1172 if (me->encoded_presets[i] &&
1173 !strcmp(encoding, me->encoded_presets[i])) {
1182 int midend_wants_statusbar(midend *me)
1184 return me->ourgame->wants_statusbar;
1187 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1189 me->game_id_change_notify_function = notify;
1190 me->game_id_change_notify_ctx = ctx;
1193 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1196 sfree(me->privdesc);
1197 me->desc = dupstr(desc);
1198 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1199 if (me->game_id_change_notify_function)
1200 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1203 config_item *midend_get_config(midend *me, int which, char **wintitle)
1205 char *titlebuf, *parstr, *rest;
1210 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1214 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1215 *wintitle = titlebuf;
1216 return me->ourgame->configure(me->params);
1219 if (!me->curparams) {
1223 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1224 which == CFG_SEED ? "random" : "game");
1225 *wintitle = titlebuf;
1227 ret = snewn(2, config_item);
1229 ret[0].type = C_STRING;
1230 if (which == CFG_SEED)
1231 ret[0].name = "Game random seed";
1233 ret[0].name = "Game ID";
1236 * For CFG_DESC the text going in here will be a string
1237 * encoding of the restricted parameters, plus a colon,
1238 * plus the game description. For CFG_SEED it will be the
1239 * full parameters, plus a hash, plus the random seed data.
1240 * Either of these is a valid full game ID (although only
1241 * the former is likely to persist across many code
1244 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1246 if (which == CFG_DESC) {
1247 rest = me->desc ? me->desc : "";
1250 rest = me->seedstr ? me->seedstr : "";
1253 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1254 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1257 ret[1].type = C_END;
1258 ret[1].name = ret[1].sval = NULL;
1264 assert(!"We shouldn't be here");
1268 static char *midend_game_id_int(midend *me, char *id, int defmode)
1270 char *error, *par, *desc, *seed;
1271 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1274 seed = strchr(id, '#');
1275 desc = strchr(id, ':');
1277 if (desc && (!seed || desc < seed)) {
1279 * We have a colon separating parameters from game
1280 * description. So `par' now points to the parameters
1281 * string, and `desc' to the description string.
1286 } else if (seed && (!desc || seed < desc)) {
1288 * We have a hash separating parameters from random seed.
1289 * So `par' now points to the parameters string, and `seed'
1290 * to the seed string.
1297 * We only have one string. Depending on `defmode', we take
1298 * it to be either parameters, seed or description.
1300 if (defmode == DEF_SEED) {
1303 } else if (defmode == DEF_DESC) {
1313 * We must be reasonably careful here not to modify anything in
1314 * `me' until we have finished validating things. This function
1315 * must either return an error and do nothing to the midend, or
1316 * return success and do everything; nothing in between is
1319 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1323 * The params string may underspecify the game parameters, so
1324 * we must first initialise newcurparams with a full set of
1325 * params from somewhere else before we decode_params the
1326 * input string over the top.
1328 * But which set? It depends on what other data we have.
1330 * If we've been given a _descriptive_ game id, then that may
1331 * well underspecify by design, e.g. Solo game descriptions
1332 * often start just '3x3:' without specifying one of Solo's
1333 * difficulty settings, because it isn't necessary once a game
1334 * has been generated (and you might not even know it, if
1335 * you're manually transcribing a game description). In that
1336 * situation, I've always felt that the best thing to set the
1337 * difficulty to (for use if the user hits 'New Game' after
1338 * pasting in that game id) is whatever it was previously set
1339 * to. That is, we use whatever is already in me->params as
1340 * the basis for our decoding of this input string.
1342 * A random-seed based game id, however, should use the real,
1343 * built-in default params, and not even check the
1344 * <game>_DEFAULT environment setting, because when people
1345 * paste each other random seeds - whether it's two users
1346 * arranging to generate the same game at the same time to
1347 * race solving them, or a user sending a bug report upstream
1348 * - the whole point is for the random game id to always be
1349 * interpreted the same way, even if it does underspecify.
1351 * A parameter string typed in on its own, with no seed _or_
1352 * description, gets treated the same way as a random seed,
1353 * because again I think the most likely reason for doing that
1354 * is to have a portable representation of a set of params.
1357 newcurparams = me->ourgame->dup_params(me->params);
1359 newcurparams = me->ourgame->default_params();
1361 me->ourgame->decode_params(newcurparams, par);
1362 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1364 me->ourgame->free_params(newcurparams);
1367 oldparams1 = me->curparams;
1370 * Now filter only the persistent parts of this state into
1371 * the long-term params structure, unless we've _only_
1372 * received a params string in which case the whole lot is
1375 oldparams2 = me->params;
1379 newparams = me->ourgame->dup_params(me->params);
1381 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1382 me->ourgame->decode_params(newparams, tmpstr);
1386 newparams = me->ourgame->dup_params(newcurparams);
1390 newcurparams = me->curparams;
1391 newparams = me->params;
1392 free_params = FALSE;
1396 error = me->ourgame->validate_desc(newparams, desc);
1400 me->ourgame->free_params(newcurparams);
1402 me->ourgame->free_params(newparams);
1409 * Now we've got past all possible error points. Update the
1412 me->params = newparams;
1413 me->curparams = newcurparams;
1415 me->ourgame->free_params(oldparams1);
1417 me->ourgame->free_params(oldparams2);
1420 sfree(me->privdesc);
1421 me->desc = me->privdesc = NULL;
1426 me->desc = dupstr(desc);
1427 me->genmode = GOT_DESC;
1428 sfree(me->aux_info);
1429 me->aux_info = NULL;
1433 me->seedstr = dupstr(seed);
1434 me->genmode = GOT_SEED;
1440 char *midend_game_id(midend *me, char *id)
1442 return midend_game_id_int(me, id, DEF_PARAMS);
1445 char *midend_get_game_id(midend *me)
1449 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1452 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1453 sprintf(ret, "%s:%s", parstr, me->desc);
1458 char *midend_get_random_seed(midend *me)
1465 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1467 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1468 sprintf(ret, "%s#%s", parstr, me->seedstr);
1473 char *midend_set_config(midend *me, int which, config_item *cfg)
1476 game_params *params;
1480 params = me->ourgame->custom_params(cfg);
1481 error = me->ourgame->validate_params(params, TRUE);
1484 me->ourgame->free_params(params);
1488 me->ourgame->free_params(me->params);
1489 me->params = params;
1494 error = midend_game_id_int(me, cfg[0].sval,
1495 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1504 int midend_can_format_as_text_now(midend *me)
1506 if (me->ourgame->can_format_as_text_ever)
1507 return me->ourgame->can_format_as_text_now(me->params);
1512 char *midend_text_format(midend *me)
1514 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1515 me->ourgame->can_format_as_text_now(me->params))
1516 return me->ourgame->text_format(me->states[me->statepos-1].state);
1521 char *midend_solve(midend *me)
1524 char *msg, *movestr;
1526 if (!me->ourgame->can_solve)
1527 return "This game does not support the Solve operation";
1529 if (me->statepos < 1)
1530 return "No game set up to solve"; /* _shouldn't_ happen! */
1533 movestr = me->ourgame->solve(me->states[0].state,
1534 me->states[me->statepos-1].state,
1535 me->aux_info, &msg);
1538 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1541 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1545 * Now enter the solved state as the next move.
1547 midend_stop_anim(me);
1548 midend_purge_states(me);
1550 me->states[me->nstates].state = s;
1551 me->states[me->nstates].movestr = movestr;
1552 me->states[me->nstates].movetype = SOLVE;
1553 me->statepos = ++me->nstates;
1555 me->ourgame->changed_state(me->ui,
1556 me->states[me->statepos-2].state,
1557 me->states[me->statepos-1].state);
1559 if (me->ourgame->flags & SOLVE_ANIMATES) {
1560 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1562 me->ourgame->anim_length(me->states[me->statepos-2].state,
1563 me->states[me->statepos-1].state,
1567 me->anim_time = 0.0;
1568 midend_finish_move(me);
1572 midend_set_timer(me);
1576 int midend_status(midend *me)
1579 * We should probably never be called when the state stack has no
1580 * states on it at all - ideally, midends should never be left in
1581 * that state for long enough to get put down and forgotten about.
1582 * But if we are, I think we return _true_ - pedantically speaking
1583 * a midend in that state is 'vacuously solved', and more
1584 * practically, a user whose midend has been left in that state
1585 * probably _does_ want the 'new game' option to be prominent.
1587 if (me->statepos == 0)
1590 return me->ourgame->status(me->states[me->statepos-1].state);
1593 char *midend_rewrite_statusbar(midend *me, char *text)
1596 * An important special case is that we are occasionally called
1597 * with our own laststatus, to update the timer.
1599 if (me->laststatus != text) {
1600 sfree(me->laststatus);
1601 me->laststatus = dupstr(text);
1604 if (me->ourgame->is_timed) {
1605 char timebuf[100], *ret;
1608 sec = (int)me->elapsed;
1611 sprintf(timebuf, "[%d:%02d] ", min, sec);
1613 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1614 strcpy(ret, timebuf);
1619 return dupstr(text);
1623 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1624 #define SERIALISE_VERSION "1"
1626 void midend_serialise(midend *me,
1627 void (*write)(void *ctx, void *buf, int len),
1633 * Each line of the save file contains three components. First
1634 * exactly 8 characters of header word indicating what type of
1635 * data is contained on the line; then a colon followed by a
1636 * decimal integer giving the length of the main string on the
1637 * line; then a colon followed by the string itself (exactly as
1638 * many bytes as previously specified, no matter what they
1639 * contain). Then a newline (of reasonably flexible form).
1641 #define wr(h,s) do { \
1645 copy_left_justified(lbuf, sizeof(lbuf), h); \
1646 sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1647 write(wctx, hbuf, strlen(hbuf)); \
1648 write(wctx, str, strlen(str)); \
1649 write(wctx, "\n", 1); \
1653 * Magic string identifying the file, and version number of the
1656 wr("SAVEFILE", SERIALISE_MAGIC);
1657 wr("VERSION", SERIALISE_VERSION);
1660 * The game name. (Copied locally to avoid const annoyance.)
1663 char *s = dupstr(me->ourgame->name);
1669 * The current long-term parameters structure, in full.
1672 char *s = me->ourgame->encode_params(me->params, TRUE);
1678 * The current short-term parameters structure, in full.
1680 if (me->curparams) {
1681 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1687 * The current game description, the privdesc, and the random seed.
1690 wr("SEED", me->seedstr);
1692 wr("DESC", me->desc);
1694 wr("PRIVDESC", me->privdesc);
1697 * The game's aux_info. We obfuscate this to prevent spoilers
1698 * (people are likely to run `head' or similar on a saved game
1699 * file simply to find out what it is, and don't necessarily
1700 * want to be told the answer to the puzzle!)
1707 len = strlen(me->aux_info);
1708 s1 = snewn(len, unsigned char);
1709 memcpy(s1, me->aux_info, len);
1710 obfuscate_bitmap(s1, len*8, FALSE);
1711 s2 = bin2hex(s1, len);
1720 * Any required serialisation of the game_ui.
1723 char *s = me->ourgame->encode_ui(me->ui);
1731 * The game time, if it's a timed game.
1733 if (me->ourgame->is_timed) {
1735 sprintf(buf, "%g", me->elapsed);
1740 * The length of, and position in, the states list.
1744 sprintf(buf, "%d", me->nstates);
1746 sprintf(buf, "%d", me->statepos);
1747 wr("STATEPOS", buf);
1751 * For each state after the initial one (which we know is
1752 * constructed from either privdesc or desc), enough
1753 * information for execute_move() to reconstruct it from the
1756 for (i = 1; i < me->nstates; i++) {
1757 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1758 switch (me->states[i].movetype) {
1760 wr("MOVE", me->states[i].movestr);
1763 wr("SOLVE", me->states[i].movestr);
1766 wr("RESTART", me->states[i].movestr);
1775 * Internal version of midend_deserialise, taking an extra check
1776 * function to be called just before beginning to install things in
1779 * Like midend_deserialise proper, this function returns NULL on
1780 * success, or an error message.
1782 static char *midend_deserialise_internal(
1783 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
1784 char *(*check)(void *ctx, midend *, const struct deserialise_data *data),
1787 struct deserialise_data data;
1789 int started = FALSE;
1793 /* Initially all errors give the same report */
1794 char *ret = "Data does not appear to be a saved game file";
1796 data.seed = data.parstr = data.desc = data.privdesc = NULL;
1797 data.auxinfo = data.uistr = data.cparstr = NULL;
1798 data.elapsed = 0.0F;
1799 data.params = data.cparams = NULL;
1806 * Loop round and round reading one key/value pair at a time
1807 * from the serialised stream, until we have enough game states
1810 while (data.nstates <= 0 || data.statepos < 0 ||
1811 gotstates < data.nstates-1) {
1816 if (!read(rctx, key, 1)) {
1817 /* unexpected EOF */
1820 } while (key[0] == '\r' || key[0] == '\n');
1822 if (!read(rctx, key+1, 8)) {
1823 /* unexpected EOF */
1827 if (key[8] != ':') {
1829 ret = "Data was incorrectly formatted for a saved game file";
1832 len = strcspn(key, ": ");
1838 if (!read(rctx, &c, 1)) {
1839 /* unexpected EOF */
1845 } else if (c >= '0' && c <= '9') {
1846 len = (len * 10) + (c - '0');
1849 ret = "Data was incorrectly formatted for a"
1855 val = snewn(len+1, char);
1856 if (!read(rctx, val, len)) {
1863 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1864 /* ret already has the right message in it */
1867 /* Now most errors are this one, unless otherwise specified */
1868 ret = "Saved data ended unexpectedly";
1871 if (!strcmp(key, "VERSION")) {
1872 if (strcmp(val, SERIALISE_VERSION)) {
1873 ret = "Cannot handle this version of the saved game"
1877 } else if (!strcmp(key, "GAME")) {
1878 if (strcmp(val, me->ourgame->name)) {
1879 ret = "Save file is from a different game";
1882 } else if (!strcmp(key, "PARAMS")) {
1886 } else if (!strcmp(key, "CPARAMS")) {
1887 sfree(data.cparstr);
1890 } else if (!strcmp(key, "SEED")) {
1894 } else if (!strcmp(key, "DESC")) {
1898 } else if (!strcmp(key, "PRIVDESC")) {
1899 sfree(data.privdesc);
1900 data.privdesc = val;
1902 } else if (!strcmp(key, "AUXINFO")) {
1904 int len = strlen(val) / 2; /* length in bytes */
1905 tmp = hex2bin(val, len);
1906 obfuscate_bitmap(tmp, len*8, TRUE);
1908 sfree(data.auxinfo);
1909 data.auxinfo = snewn(len + 1, char);
1910 memcpy(data.auxinfo, tmp, len);
1911 data.auxinfo[len] = '\0';
1913 } else if (!strcmp(key, "UI")) {
1917 } else if (!strcmp(key, "TIME")) {
1918 data.elapsed = (float)atof(val);
1919 } else if (!strcmp(key, "NSTATES")) {
1920 data.nstates = atoi(val);
1921 if (data.nstates <= 0) {
1922 ret = "Number of states in save file was negative";
1926 ret = "Two state counts provided in save file";
1929 data.states = snewn(data.nstates, struct midend_state_entry);
1930 for (i = 0; i < data.nstates; i++) {
1931 data.states[i].state = NULL;
1932 data.states[i].movestr = NULL;
1933 data.states[i].movetype = NEWGAME;
1935 } else if (!strcmp(key, "STATEPOS")) {
1936 data.statepos = atoi(val);
1937 } else if (!strcmp(key, "MOVE")) {
1939 data.states[gotstates].movetype = MOVE;
1940 data.states[gotstates].movestr = val;
1942 } else if (!strcmp(key, "SOLVE")) {
1944 data.states[gotstates].movetype = SOLVE;
1945 data.states[gotstates].movestr = val;
1947 } else if (!strcmp(key, "RESTART")) {
1949 data.states[gotstates].movetype = RESTART;
1950 data.states[gotstates].movestr = val;
1959 data.params = me->ourgame->default_params();
1960 me->ourgame->decode_params(data.params, data.parstr);
1961 if (me->ourgame->validate_params(data.params, TRUE)) {
1962 ret = "Long-term parameters in save file are invalid";
1965 data.cparams = me->ourgame->default_params();
1966 me->ourgame->decode_params(data.cparams, data.cparstr);
1967 if (me->ourgame->validate_params(data.cparams, FALSE)) {
1968 ret = "Short-term parameters in save file are invalid";
1971 if (data.seed && me->ourgame->validate_params(data.cparams, TRUE)) {
1973 * The seed's no use with this version, but we can perfectly
1974 * well use the rest of the data.
1980 ret = "Game description in save file is missing";
1982 } else if (me->ourgame->validate_desc(data.cparams, data.desc)) {
1983 ret = "Game description in save file is invalid";
1986 if (data.privdesc &&
1987 me->ourgame->validate_desc(data.cparams, data.privdesc)) {
1988 ret = "Game private description in save file is invalid";
1991 if (data.statepos < 0 || data.statepos >= data.nstates) {
1992 ret = "Game position in save file is out of range";
1995 data.states[0].state = me->ourgame->new_game(
1996 me, data.cparams, data.privdesc ? data.privdesc : data.desc);
1997 for (i = 1; i < data.nstates; i++) {
1998 assert(data.states[i].movetype != NEWGAME);
1999 switch (data.states[i].movetype) {
2002 data.states[i].state = me->ourgame->execute_move(
2003 data.states[i-1].state, data.states[i].movestr);
2004 if (data.states[i].state == NULL) {
2005 ret = "Save file contained an invalid move";
2010 if (me->ourgame->validate_desc(
2011 data.cparams, data.states[i].movestr)) {
2012 ret = "Save file contained an invalid restart move";
2015 data.states[i].state = me->ourgame->new_game(
2016 me, data.cparams, data.states[i].movestr);
2021 data.ui = me->ourgame->new_ui(data.states[0].state);
2022 me->ourgame->decode_ui(data.ui, data.uistr);
2025 * Run the externally provided check function, and abort if it
2026 * returns an error message.
2028 if (check && (ret = check(cctx, me, &data)) != NULL)
2029 goto cleanup; /* error message is already in ret */
2032 * Now we've run out of possible error conditions, so we're
2033 * ready to start overwriting the real data in the current
2034 * midend. We'll do this by swapping things with the local
2035 * variables, so that the same cleanup code will free the old
2042 me->desc = data.desc;
2046 me->privdesc = data.privdesc;
2047 data.privdesc = tmp;
2050 me->seedstr = data.seed;
2054 me->aux_info = data.auxinfo;
2058 me->genmode = GOT_NOTHING;
2060 me->statesize = data.nstates;
2061 data.nstates = me->nstates;
2062 me->nstates = me->statesize;
2064 struct midend_state_entry *tmp;
2066 me->states = data.states;
2069 me->statepos = data.statepos;
2075 me->params = data.params;
2078 tmp = me->curparams;
2079 me->curparams = data.cparams;
2083 me->oldstate = NULL;
2084 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2095 me->elapsed = data.elapsed;
2096 me->pressed_mouse_button = 0;
2098 midend_set_timer(me);
2101 me->ourgame->free_drawstate(me->drawing, me->drawstate);
2103 me->ourgame->new_drawstate(me->drawing,
2104 me->states[me->statepos-1].state);
2105 midend_size_new_drawstate(me);
2106 if (me->game_id_change_notify_function)
2107 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2109 ret = NULL; /* success! */
2115 sfree(data.cparstr);
2117 sfree(data.privdesc);
2118 sfree(data.auxinfo);
2121 me->ourgame->free_params(data.params);
2123 me->ourgame->free_params(data.cparams);
2125 me->ourgame->free_ui(data.ui);
2129 for (i = 0; i < data.nstates; i++) {
2130 if (data.states[i].state)
2131 me->ourgame->free_game(data.states[i].state);
2132 sfree(data.states[i].movestr);
2140 char *midend_deserialise(
2141 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx)
2143 return midend_deserialise_internal(me, read, rctx, NULL, NULL);
2147 * This function examines a saved game file just far enough to
2148 * determine which game type it contains. It returns NULL on success
2149 * and the game name string in 'name' (which will be dynamically
2150 * allocated and should be caller-freed), or an error message on
2153 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2156 int nstates = 0, statepos = -1, gotstates = 0;
2157 int started = FALSE;
2160 /* Initially all errors give the same report */
2161 char *ret = "Data does not appear to be a saved game file";
2166 * Loop round and round reading one key/value pair at a time from
2167 * the serialised stream, until we've found the game name.
2169 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2174 if (!read(rctx, key, 1)) {
2175 /* unexpected EOF */
2178 } while (key[0] == '\r' || key[0] == '\n');
2180 if (!read(rctx, key+1, 8)) {
2181 /* unexpected EOF */
2185 if (key[8] != ':') {
2187 ret = "Data was incorrectly formatted for a saved game file";
2190 len = strcspn(key, ": ");
2196 if (!read(rctx, &c, 1)) {
2197 /* unexpected EOF */
2203 } else if (c >= '0' && c <= '9') {
2204 len = (len * 10) + (c - '0');
2207 ret = "Data was incorrectly formatted for a"
2213 val = snewn(len+1, char);
2214 if (!read(rctx, val, len)) {
2221 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2222 /* ret already has the right message in it */
2225 /* Now most errors are this one, unless otherwise specified */
2226 ret = "Saved data ended unexpectedly";
2229 if (!strcmp(key, "VERSION")) {
2230 if (strcmp(val, SERIALISE_VERSION)) {
2231 ret = "Cannot handle this version of the saved game"
2235 } else if (!strcmp(key, "GAME")) {
2236 *name = dupstr(val);
2251 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2253 game_state *soln = NULL;
2255 if (me->statepos < 1)
2256 return "No game set up to print";/* _shouldn't_ happen! */
2259 char *msg, *movestr;
2261 if (!me->ourgame->can_solve)
2262 return "This game does not support the Solve operation";
2264 msg = "Solve operation failed";/* game _should_ overwrite on error */
2265 movestr = me->ourgame->solve(me->states[0].state,
2266 me->states[me->statepos-1].state,
2267 me->aux_info, &msg);
2270 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2279 * This call passes over ownership of the two game_states and
2280 * the game_params. Hence we duplicate the ones we want to
2281 * keep, and we don't have to bother freeing soln if it was
2284 document_add_puzzle(doc, me->ourgame,
2285 me->ourgame->dup_params(me->curparams),
2286 me->ourgame->dup_game(me->states[0].state), soln);