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;
67 int newgame_undo_avail, newgame_undo_used;
69 game_params *params, *curparams;
70 game_drawstate *drawstate;
74 float anim_time, anim_pos;
75 float flash_time, flash_pos;
84 int pressed_mouse_button;
86 int preferred_tilesize, tilesize, winwidth, winheight;
88 void (*game_id_change_notify_function)(void *);
89 void *game_id_change_notify_ctx;
92 #define ensure(me) do { \
93 if ((me)->nstates >= (me)->statesize) { \
94 (me)->statesize = (me)->nstates + 128; \
95 (me)->states = sresize((me)->states, (me)->statesize, \
96 struct midend_state_entry); \
100 void midend_reset_tilesize(midend *me)
102 me->preferred_tilesize = me->ourgame->preferred_tilesize;
105 * Allow an environment-based override for the default tile
106 * size by defining a variable along the lines of
113 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
114 for (j = k = 0; buf[j]; j++)
115 if (!isspace((unsigned char)buf[j]))
116 buf[k++] = toupper((unsigned char)buf[j]);
118 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
119 me->preferred_tilesize = ts;
123 midend *midend_new(frontend *fe, const game *ourgame,
124 const drawing_api *drapi, void *drhandle)
126 midend *me = snew(midend);
130 get_random_seed(&randseed, &randseedsize);
133 me->ourgame = ourgame;
134 me->random = random_new(randseed, randseedsize);
135 me->nstates = me->statesize = me->statepos = 0;
137 me->newgame_undo = 0;
138 me->newgame_undo_avail = me->newgame_undo_used = 0;
139 me->params = ourgame->default_params();
140 me->game_id_change_notify_function = NULL;
141 me->game_id_change_notify_ctx = NULL;
144 * Allow environment-based changing of the default settings by
145 * defining a variable along the lines of `NET_DEFAULT=25x25w'
146 * in which the value is an encoded parameter string.
151 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
152 for (j = k = 0; buf[j]; j++)
153 if (!isspace((unsigned char)buf[j]))
154 buf[k++] = toupper((unsigned char)buf[j]);
156 if ((e = getenv(buf)) != NULL)
157 me->ourgame->decode_params(me->params, e);
159 me->curparams = NULL;
160 me->desc = me->privdesc = NULL;
163 me->genmode = GOT_NOTHING;
164 me->drawstate = NULL;
166 me->preset_menu = NULL;
167 me->anim_time = me->anim_pos = 0.0F;
168 me->flash_time = me->flash_pos = 0.0F;
171 me->pressed_mouse_button = 0;
172 me->laststatus = NULL;
175 me->tilesize = me->winwidth = me->winheight = 0;
177 me->drawing = drawing_new(drapi, me, drhandle);
181 midend_reset_tilesize(me);
188 const game *midend_which_game(midend *me)
193 static void midend_purge_states(midend *me)
195 while (me->nstates > me->statepos) {
196 me->ourgame->free_game(me->states[--me->nstates].state);
197 if (me->states[me->nstates].movestr)
198 sfree(me->states[me->nstates].movestr);
202 static void midend_free_game(midend *me)
204 while (me->nstates > 0) {
206 me->ourgame->free_game(me->states[me->nstates].state);
207 sfree(me->states[me->nstates].movestr);
211 me->ourgame->free_drawstate(me->drawing, me->drawstate);
214 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
218 for (i = 0; i < menu->n_entries; i++) {
219 sfree(menu->entries[i].title);
220 if (menu->entries[i].params)
221 me->ourgame->free_params(menu->entries[i].params);
222 midend_free_preset_menu(me, menu->entries[i].submenu);
224 sfree(menu->entries);
229 void midend_free(midend *me)
231 midend_free_game(me);
234 drawing_free(me->drawing);
235 random_free(me->random);
241 me->ourgame->free_params(me->params);
242 midend_free_preset_menu(me, me->preset_menu);
244 me->ourgame->free_ui(me->ui);
246 me->ourgame->free_params(me->curparams);
247 sfree(me->laststatus);
251 static void midend_size_new_drawstate(midend *me)
254 * Don't even bother, if we haven't worked out our tile size
257 if (me->tilesize > 0) {
258 me->ourgame->compute_size(me->params, me->tilesize,
259 &me->winwidth, &me->winheight);
260 me->ourgame->set_size(me->drawing, me->drawstate,
261 me->params, me->tilesize);
265 void midend_size(midend *me, int *x, int *y, int user_size)
271 * We can't set the size on the same drawstate twice. So if
272 * we've already sized one drawstate, we must throw it away and
275 if (me->drawstate && me->tilesize > 0) {
276 me->ourgame->free_drawstate(me->drawing, me->drawstate);
277 me->drawstate = me->ourgame->new_drawstate(me->drawing,
278 me->states[0].state);
282 * Find the tile size that best fits within the given space. If
283 * `user_size' is TRUE, we must actually find the _largest_ such
284 * tile size, in order to get as close to the user's explicit
285 * request as possible; otherwise, we bound above at the game's
286 * preferred tile size, so that the game gets what it wants
287 * provided that this doesn't break the constraint from the
288 * front-end (which is likely to be a screen size or similar).
294 me->ourgame->compute_size(me->params, max, &rx, &ry);
295 } while (rx <= *x && ry <= *y);
297 max = me->preferred_tilesize + 1;
301 * Now binary-search between min and max. We're looking for a
302 * boundary rather than a value: the point at which tile sizes
303 * stop fitting within the given dimensions. Thus, we stop when
304 * max and min differ by exactly 1.
306 while (max - min > 1) {
307 int mid = (max + min) / 2;
308 me->ourgame->compute_size(me->params, mid, &rx, &ry);
309 if (rx <= *x && ry <= *y)
316 * Now `min' is a valid size, and `max' isn't. So use `min'.
321 /* If the user requested a change in size, make it permanent. */
322 me->preferred_tilesize = me->tilesize;
323 midend_size_new_drawstate(me);
328 int midend_tilesize(midend *me) { return me->tilesize; }
330 void midend_set_params(midend *me, game_params *params)
332 me->ourgame->free_params(me->params);
333 me->params = me->ourgame->dup_params(params);
336 game_params *midend_get_params(midend *me)
338 return me->ourgame->dup_params(me->params);
341 static void midend_set_timer(midend *me)
343 me->timing = (me->ourgame->is_timed &&
344 me->ourgame->timing_state(me->states[me->statepos-1].state,
346 if (me->timing || me->flash_time || me->anim_time)
347 activate_timer(me->frontend);
349 deactivate_timer(me->frontend);
352 void midend_force_redraw(midend *me)
355 me->ourgame->free_drawstate(me->drawing, me->drawstate);
356 me->drawstate = me->ourgame->new_drawstate(me->drawing,
357 me->states[0].state);
358 midend_size_new_drawstate(me);
362 static void newgame_serialise_write(void *ctx, void *buf, int len)
364 midend *const me = ctx;
367 assert(len < INT_MAX - me->newgame_undo_used);
368 new_used = me->newgame_undo_used + len;
369 if (new_used > me-> newgame_undo_avail) {
370 me->newgame_undo_avail = max(me->newgame_undo_avail, new_used);
371 me->newgame_undo_avail *= 2;
372 me->newgame_undo = sresize(me->newgame_undo,
373 me->newgame_undo_avail, char);
375 memcpy(me->newgame_undo + me->newgame_undo_used, buf, len);
376 me->newgame_undo_used = new_used;
379 void midend_new_game(midend *me)
381 me->newgame_undo_used = 0;
382 midend_serialise(me, newgame_serialise_write, me);
384 midend_stop_anim(me);
385 midend_free_game(me);
387 assert(me->nstates == 0);
389 if (me->genmode == GOT_DESC) {
390 me->genmode = GOT_NOTHING;
394 if (me->genmode == GOT_SEED) {
395 me->genmode = GOT_NOTHING;
398 * Generate a new random seed. 15 digits comes to about
399 * 48 bits, which should be more than enough.
401 * I'll avoid putting a leading zero on the number,
402 * just in case it confuses anybody who thinks it's
403 * processed as an integer rather than a string.
408 newseed[0] = '1' + (char)random_upto(me->random, 9);
409 for (i = 1; i < 15; i++)
410 newseed[i] = '0' + (char)random_upto(me->random, 10);
412 me->seedstr = dupstr(newseed);
415 me->ourgame->free_params(me->curparams);
416 me->curparams = me->ourgame->dup_params(me->params);
424 rs = random_new(me->seedstr, strlen(me->seedstr));
426 * If this midend has been instantiated without providing a
427 * drawing API, it is non-interactive. This means that it's
428 * being used for bulk game generation, and hence we should
429 * pass the non-interactive flag to new_desc.
431 me->desc = me->ourgame->new_desc(me->curparams, rs,
432 &me->aux_info, (me->drawing != NULL));
440 * It might seem a bit odd that we're using me->params to
441 * create the initial game state, rather than me->curparams
442 * which is better tailored to this specific game and which we
445 * It's supposed to be an invariant in the midend that
446 * me->params and me->curparams differ in no aspect that is
447 * important after generation (i.e. after new_desc()). By
448 * deliberately passing the _less_ specific of these two
449 * parameter sets, we provoke play-time misbehaviour in the
450 * case where a game has failed to encode a play-time parameter
451 * in the non-full version of encode_params().
453 me->states[me->nstates].state =
454 me->ourgame->new_game(me, me->params, me->desc);
457 * As part of our commitment to self-testing, test the aux
458 * string to make sure nothing ghastly went wrong.
460 if (me->ourgame->can_solve && me->aux_info) {
465 movestr = me->ourgame->solve(me->states[0].state,
468 assert(movestr && !msg);
469 s = me->ourgame->execute_move(me->states[0].state, movestr);
471 me->ourgame->free_game(s);
475 me->states[me->nstates].movestr = NULL;
476 me->states[me->nstates].movetype = NEWGAME;
479 me->drawstate = me->ourgame->new_drawstate(me->drawing,
480 me->states[0].state);
481 midend_size_new_drawstate(me);
483 me->flash_pos = me->flash_time = 0.0F;
484 me->anim_pos = me->anim_time = 0.0F;
486 me->ourgame->free_ui(me->ui);
487 me->ui = me->ourgame->new_ui(me->states[0].state);
488 midend_set_timer(me);
489 me->pressed_mouse_button = 0;
491 if (me->game_id_change_notify_function)
492 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
495 int midend_can_undo(midend *me)
497 return (me->statepos > 1 || me->newgame_undo_used);
500 int midend_can_redo(midend *me)
502 return (me->statepos < me->nstates);
505 struct newgame_undo_deserialise_read_ctx {
510 int newgame_undo_deserialise_read(void *ctx, void *buf, int len)
512 struct newgame_undo_deserialise_read_ctx *const rctx = ctx;
513 midend *const me = rctx->me;
515 int use = min(len, rctx->size - rctx->pos);
516 memcpy(buf, me->newgame_undo + rctx->pos, use);
521 static int midend_undo(midend *me)
523 char *deserialise_error;
525 if (me->statepos > 1) {
527 me->ourgame->changed_state(me->ui,
528 me->states[me->statepos-1].state,
529 me->states[me->statepos-2].state);
533 } else if (me->newgame_undo_used) {
534 /* This undo cannot be undone with redo */
535 struct newgame_undo_deserialise_read_ctx rctx;
537 rctx.size = me->newgame_undo_used; /* copy for reentrancy safety */
540 midend_deserialise(me, newgame_undo_deserialise_read, &rctx);
541 if (deserialise_error)
542 /* umm, better to carry on than to crash ? */
549 static int midend_redo(midend *me)
551 if (me->statepos < me->nstates) {
553 me->ourgame->changed_state(me->ui,
554 me->states[me->statepos-1].state,
555 me->states[me->statepos].state);
563 static void midend_finish_move(midend *me)
568 * We do not flash if the later of the two states is special.
569 * This covers both forward Solve moves and backward (undone)
572 if ((me->oldstate || me->statepos > 1) &&
573 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
574 (me->dir < 0 && me->statepos < me->nstates &&
575 !special(me->states[me->statepos].movetype)))) {
576 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
577 me->states[me->statepos-2].state,
578 me->states[me->statepos-1].state,
579 me->oldstate ? me->dir : +1,
582 me->flash_pos = 0.0F;
583 me->flash_time = flashtime;
588 me->ourgame->free_game(me->oldstate);
590 me->anim_pos = me->anim_time = 0;
593 midend_set_timer(me);
596 void midend_stop_anim(midend *me)
598 if (me->oldstate || me->anim_time != 0) {
599 midend_finish_move(me);
604 void midend_restart_game(midend *me)
608 assert(me->statepos >= 1);
609 if (me->statepos == 1)
610 return; /* no point doing anything at all! */
613 * During restart, we reconstruct the game from the (public)
614 * game description rather than from states[0], because that
615 * way Mines gets slightly more sensible behaviour (restart
616 * goes to _after_ the first click so you don't have to
617 * remember where you clicked).
619 s = me->ourgame->new_game(me, me->params, me->desc);
622 * Now enter the restarted state as the next move.
624 midend_stop_anim(me);
625 midend_purge_states(me);
627 me->states[me->nstates].state = s;
628 me->states[me->nstates].movestr = dupstr(me->desc);
629 me->states[me->nstates].movetype = RESTART;
630 me->statepos = ++me->nstates;
632 me->ourgame->changed_state(me->ui,
633 me->states[me->statepos-2].state,
634 me->states[me->statepos-1].state);
635 me->flash_pos = me->flash_time = 0.0F;
636 midend_finish_move(me);
638 midend_set_timer(me);
641 static int midend_really_process_key(midend *me, int x, int y, int button)
643 game_state *oldstate =
644 me->ourgame->dup_game(me->states[me->statepos - 1].state);
645 int type = MOVE, gottype = FALSE, ret = 1;
648 char *movestr = NULL;
650 if (!IS_UI_FAKE_KEY(button)) {
651 movestr = me->ourgame->interpret_move(
652 me->states[me->statepos-1].state,
653 me->ui, me->drawstate, x, y, button);
657 if (button == 'n' || button == 'N' || button == '\x0E' ||
658 button == UI_NEWGAME) {
661 goto done; /* never animate */
662 } else if (button == 'u' || button == 'U' ||
663 button == '\x1A' || button == '\x1F' ||
665 midend_stop_anim(me);
666 type = me->states[me->statepos-1].movetype;
668 if (!midend_undo(me))
670 } else if (button == 'r' || button == 'R' ||
671 button == '\x12' || button == '\x19' ||
673 midend_stop_anim(me);
674 if (!midend_redo(me))
676 } else if ((button == '\x13' || button == UI_SOLVE) &&
677 me->ourgame->can_solve) {
678 if (midend_solve(me))
680 } else if (button == 'q' || button == 'Q' || button == '\x11' ||
688 s = me->states[me->statepos-1].state;
690 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
695 if (s == me->states[me->statepos-1].state) {
697 * make_move() is allowed to return its input state to
698 * indicate that although no move has been made, the UI
699 * state has been updated and a redraw is called for.
702 midend_set_timer(me);
705 midend_stop_anim(me);
706 midend_purge_states(me);
708 assert(movestr != NULL);
709 me->states[me->nstates].state = s;
710 me->states[me->nstates].movestr = movestr;
711 me->states[me->nstates].movetype = MOVE;
712 me->statepos = ++me->nstates;
715 me->ourgame->changed_state(me->ui,
716 me->states[me->statepos-2].state,
717 me->states[me->statepos-1].state);
724 type = me->states[me->statepos-1].movetype;
727 * See if this move requires an animation.
729 if (special(type) && !(type == SOLVE &&
730 (me->ourgame->flags & SOLVE_ANIMATES))) {
733 anim_time = me->ourgame->anim_length(oldstate,
734 me->states[me->statepos-1].state,
738 me->oldstate = oldstate; oldstate = NULL;
740 me->anim_time = anim_time;
743 midend_finish_move(me);
749 midend_set_timer(me);
752 if (oldstate) me->ourgame->free_game(oldstate);
756 int midend_process_key(midend *me, int x, int y, int button)
761 * Harmonise mouse drag and release messages.
763 * Some front ends might accidentally switch from sending, say,
764 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
765 * drag. (This can happen on the Mac, for example, since
766 * RIGHT_DRAG is usually done using Command+drag, and if the
767 * user accidentally releases Command half way through the drag
768 * then there will be trouble.)
770 * It would be an O(number of front ends) annoyance to fix this
771 * in the front ends, but an O(number of back ends) annoyance
772 * to have each game capable of dealing with it. Therefore, we
773 * fix it _here_ in the common midend code so that it only has
776 * The possible ways in which things can go screwy in the front
779 * - in a system containing multiple physical buttons button
780 * presses can inadvertently overlap. We can see ABab (caps
781 * meaning button-down and lowercase meaning button-up) when
782 * the user had semantically intended AaBb.
784 * - in a system where one button is simulated by means of a
785 * modifier key and another button, buttons can mutate
786 * between press and release (possibly during drag). So we
787 * can see Ab instead of Aa.
789 * Definite requirements are:
791 * - button _presses_ must never be invented or destroyed. If
792 * the user presses two buttons in succession, the button
793 * presses must be transferred to the backend unchanged. So
794 * if we see AaBb , that's fine; if we see ABab (the button
795 * presses inadvertently overlapped) we must somehow
796 * `correct' it to AaBb.
798 * - every mouse action must end up looking like a press, zero
799 * or more drags, then a release. This allows back ends to
800 * make the _assumption_ that incoming mouse data will be
801 * sane in this regard, and not worry about the details.
803 * So my policy will be:
805 * - treat any button-up as a button-up for the currently
806 * pressed button, or ignore it if there is no currently
809 * - treat any drag as a drag for the currently pressed
810 * button, or ignore it if there is no currently pressed
813 * - if we see a button-down while another button is currently
814 * pressed, invent a button-up for the first one and then
815 * pass the button-down through as before.
817 * 2005-05-31: An addendum to the above. Some games might want
818 * a `priority order' among buttons, such that if one button is
819 * pressed while another is down then a fixed one of the
820 * buttons takes priority no matter what order they're pressed
821 * in. Mines, in particular, wants to treat a left+right click
822 * like a left click for the benefit of users of other
823 * implementations. So the last of the above points is modified
824 * in the presence of an (optional) button priority order.
826 * A further addition: we translate certain keyboard presses to
827 * cursor key 'select' buttons, so that a) frontends don't have
828 * to translate these themselves (like they do for CURSOR_UP etc),
829 * and b) individual games don't have to hard-code button presses
830 * of '\n' etc for keyboard-based cursors. The choice of buttons
831 * here could eventually be controlled by a runtime configuration
834 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
835 if (me->pressed_mouse_button) {
836 if (IS_MOUSE_DRAG(button)) {
837 button = me->pressed_mouse_button +
838 (LEFT_DRAG - LEFT_BUTTON);
840 button = me->pressed_mouse_button +
841 (LEFT_RELEASE - LEFT_BUTTON);
844 return ret; /* ignore it */
845 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
847 * If the new button has lower priority than the old one,
848 * don't bother doing this.
850 if (me->ourgame->flags &
851 BUTTON_BEATS(me->pressed_mouse_button, button))
852 return ret; /* just ignore it */
855 * Fabricate a button-up for the previously pressed button.
857 ret = ret && midend_really_process_key
858 (me, x, y, (me->pressed_mouse_button +
859 (LEFT_RELEASE - LEFT_BUTTON)));
863 * Translate keyboard presses to cursor selection.
865 if (button == '\n' || button == '\r')
866 button = CURSOR_SELECT;
868 button = CURSOR_SELECT2;
871 * Normalise both backspace characters (8 and 127) to \b. Easier
872 * to do this once, here, than to require all front ends to
873 * carefully generate the same one - now each front end can
874 * generate whichever is easiest.
876 if (button == '\177')
880 * Now send on the event we originally received.
882 ret = ret && midend_really_process_key(me, x, y, button);
885 * And update the currently pressed button.
887 if (IS_MOUSE_RELEASE(button))
888 me->pressed_mouse_button = 0;
889 else if (IS_MOUSE_DOWN(button))
890 me->pressed_mouse_button = button;
895 void midend_redraw(midend *me)
899 if (me->statepos > 0 && me->drawstate) {
900 start_draw(me->drawing);
901 if (me->oldstate && me->anim_time > 0 &&
902 me->anim_pos < me->anim_time) {
903 assert(me->dir != 0);
904 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
905 me->states[me->statepos-1].state, me->dir,
906 me->ui, me->anim_pos, me->flash_pos);
908 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
909 me->states[me->statepos-1].state, +1 /*shrug*/,
910 me->ui, 0.0, me->flash_pos);
912 end_draw(me->drawing);
917 * Nasty hacky function used to implement the --redo option in
918 * gtk.c. Only used for generating the puzzles' icons.
920 void midend_freeze_timer(midend *me, float tprop)
922 me->anim_pos = me->anim_time * tprop;
924 deactivate_timer(me->frontend);
927 void midend_timer(midend *me, float tplus)
929 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
931 me->anim_pos += tplus;
932 if (me->anim_pos >= me->anim_time ||
933 me->anim_time == 0 || !me->oldstate) {
934 if (me->anim_time > 0)
935 midend_finish_move(me);
938 me->flash_pos += tplus;
939 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
940 me->flash_pos = me->flash_time = 0;
947 float oldelapsed = me->elapsed;
948 me->elapsed += tplus;
949 if ((int)oldelapsed != (int)me->elapsed)
950 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
953 midend_set_timer(me);
956 float *midend_colours(midend *me, int *ncolours)
960 ret = me->ourgame->colours(me->frontend, ncolours);
966 * Allow environment-based overrides for the standard
967 * colours by defining variables along the lines of
968 * `NET_COLOUR_4=6000c0'.
971 for (i = 0; i < *ncolours; i++) {
973 unsigned int r, g, b;
976 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
977 for (j = k = 0; buf[j]; j++)
978 if (!isspace((unsigned char)buf[j]))
979 buf[k++] = toupper((unsigned char)buf[j]);
981 if ((e = getenv(buf)) != NULL &&
982 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
983 ret[i*3 + 0] = r / 255.0F;
984 ret[i*3 + 1] = g / 255.0F;
985 ret[i*3 + 2] = b / 255.0F;
993 struct preset_menu *preset_menu_new(void)
995 struct preset_menu *menu = snew(struct preset_menu);
997 menu->entries_size = 0;
998 menu->entries = NULL;
1002 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
1005 struct preset_menu_entry *toret;
1006 if (menu->n_entries >= menu->entries_size) {
1007 menu->entries_size = menu->n_entries * 5 / 4 + 10;
1008 menu->entries = sresize(menu->entries, menu->entries_size,
1009 struct preset_menu_entry);
1011 toret = &menu->entries[menu->n_entries++];
1012 toret->title = title;
1013 toret->params = NULL;
1014 toret->submenu = NULL;
1018 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
1021 struct preset_menu_entry *entry = preset_menu_add(parent, title);
1022 entry->submenu = preset_menu_new();
1023 return entry->submenu;
1026 void preset_menu_add_preset(struct preset_menu *parent,
1027 char *title, game_params *params)
1029 struct preset_menu_entry *entry = preset_menu_add(parent, title);
1030 entry->params = params;
1033 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
1038 for (i = 0; i < menu->n_entries; i++) {
1039 if (id == menu->entries[i].id)
1040 return menu->entries[i].params;
1041 if (menu->entries[i].submenu &&
1042 (retd = preset_menu_lookup_by_id(
1043 menu->entries[i].submenu, id)) != NULL)
1050 static char *preset_menu_add_from_user_env(
1051 midend *me, struct preset_menu *menu, char *p, int top_level)
1055 game_params *preset;
1058 while (*p && *p != ':') p++;
1059 if (*p) *p++ = '\0';
1061 while (*p && *p != ':') p++;
1062 if (*p) *p++ = '\0';
1064 if (!strcmp(val, "#")) {
1066 * Special case: either open a new submenu with the given
1067 * title, or terminate the current submenu.
1070 struct preset_menu *submenu =
1071 preset_menu_add_submenu(menu, dupstr(name));
1072 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1075 * If we get a 'close submenu' indication at the top
1076 * level, there's not much we can do but quietly
1085 preset = me->ourgame->default_params();
1086 me->ourgame->decode_params(preset, val);
1088 if (me->ourgame->validate_params(preset, TRUE)) {
1089 /* Drop this one from the list. */
1090 me->ourgame->free_params(preset);
1094 preset_menu_add_preset(menu, dupstr(name), preset);
1100 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1104 for (i = 0; i < menu->n_entries; i++)
1105 menu->entries[i].id = me->n_encoded_presets++;
1107 for (i = 0; i < menu->n_entries; i++)
1108 if (menu->entries[i].submenu)
1109 preset_menu_alloc_ids(me, menu->entries[i].submenu);
1112 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1116 for (i = 0; i < menu->n_entries; i++) {
1117 if (menu->entries[i].params) {
1118 me->encoded_presets[menu->entries[i].id] =
1119 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1121 preset_menu_encode_params(me, menu->entries[i].submenu);
1126 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1130 if (me->preset_menu)
1131 return me->preset_menu;
1134 /* Expect the game to implement exactly one of the two preset APIs */
1135 assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1136 assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1139 if (me->ourgame->fetch_preset) {
1141 game_params *preset;
1143 /* Simple one-level menu */
1144 assert(!me->ourgame->preset_menu);
1145 me->preset_menu = preset_menu_new();
1146 for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1147 preset_menu_add_preset(me->preset_menu, name, preset);
1150 /* Hierarchical menu provided by the game backend */
1151 me->preset_menu = me->ourgame->preset_menu();
1156 * Allow user extensions to the preset list by defining an
1157 * environment variable <gamename>_PRESETS whose value is a
1158 * colon-separated list of items, alternating between textual
1159 * titles in the menu and encoded parameter strings. For
1160 * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1161 * just one additional preset for Solo.
1166 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1167 for (j = k = 0; buf[j]; j++)
1168 if (!isspace((unsigned char)buf[j]))
1169 buf[k++] = toupper((unsigned char)buf[j]);
1172 if ((e = getenv(buf)) != NULL) {
1174 preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1180 * Finalise the menu: allocate an integer id to each entry, and
1181 * store string encodings of the presets' parameters in
1182 * me->encoded_presets.
1184 me->n_encoded_presets = 0;
1185 preset_menu_alloc_ids(me, me->preset_menu);
1186 me->encoded_presets = snewn(me->n_encoded_presets, char *);
1187 for (i = 0; i < me->n_encoded_presets; i++)
1188 me->encoded_presets[i] = NULL;
1189 preset_menu_encode_params(me, me->preset_menu);
1192 *id_limit = me->n_encoded_presets;
1193 return me->preset_menu;
1196 int midend_which_preset(midend *me)
1198 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1202 for (i = 0; i < me->n_encoded_presets; i++)
1203 if (me->encoded_presets[i] &&
1204 !strcmp(encoding, me->encoded_presets[i])) {
1213 int midend_wants_statusbar(midend *me)
1215 return me->ourgame->wants_statusbar;
1218 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1220 me->game_id_change_notify_function = notify;
1221 me->game_id_change_notify_ctx = ctx;
1224 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1227 sfree(me->privdesc);
1228 me->desc = dupstr(desc);
1229 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1230 if (me->game_id_change_notify_function)
1231 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1234 config_item *midend_get_config(midend *me, int which, char **wintitle)
1236 char *titlebuf, *parstr, *rest;
1241 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1245 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1246 *wintitle = titlebuf;
1247 return me->ourgame->configure(me->params);
1250 if (!me->curparams) {
1254 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1255 which == CFG_SEED ? "random" : "game");
1256 *wintitle = titlebuf;
1258 ret = snewn(2, config_item);
1260 ret[0].type = C_STRING;
1261 if (which == CFG_SEED)
1262 ret[0].name = "Game random seed";
1264 ret[0].name = "Game ID";
1267 * For CFG_DESC the text going in here will be a string
1268 * encoding of the restricted parameters, plus a colon,
1269 * plus the game description. For CFG_SEED it will be the
1270 * full parameters, plus a hash, plus the random seed data.
1271 * Either of these is a valid full game ID (although only
1272 * the former is likely to persist across many code
1275 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1277 if (which == CFG_DESC) {
1278 rest = me->desc ? me->desc : "";
1281 rest = me->seedstr ? me->seedstr : "";
1284 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1285 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1288 ret[1].type = C_END;
1289 ret[1].name = ret[1].sval = NULL;
1295 assert(!"We shouldn't be here");
1299 static char *midend_game_id_int(midend *me, char *id, int defmode)
1301 char *error, *par, *desc, *seed;
1302 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1305 seed = strchr(id, '#');
1306 desc = strchr(id, ':');
1308 if (desc && (!seed || desc < seed)) {
1310 * We have a colon separating parameters from game
1311 * description. So `par' now points to the parameters
1312 * string, and `desc' to the description string.
1317 } else if (seed && (!desc || seed < desc)) {
1319 * We have a hash separating parameters from random seed.
1320 * So `par' now points to the parameters string, and `seed'
1321 * to the seed string.
1328 * We only have one string. Depending on `defmode', we take
1329 * it to be either parameters, seed or description.
1331 if (defmode == DEF_SEED) {
1334 } else if (defmode == DEF_DESC) {
1344 * We must be reasonably careful here not to modify anything in
1345 * `me' until we have finished validating things. This function
1346 * must either return an error and do nothing to the midend, or
1347 * return success and do everything; nothing in between is
1350 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1354 * The params string may underspecify the game parameters, so
1355 * we must first initialise newcurparams with a full set of
1356 * params from somewhere else before we decode_params the
1357 * input string over the top.
1359 * But which set? It depends on what other data we have.
1361 * If we've been given a _descriptive_ game id, then that may
1362 * well underspecify by design, e.g. Solo game descriptions
1363 * often start just '3x3:' without specifying one of Solo's
1364 * difficulty settings, because it isn't necessary once a game
1365 * has been generated (and you might not even know it, if
1366 * you're manually transcribing a game description). In that
1367 * situation, I've always felt that the best thing to set the
1368 * difficulty to (for use if the user hits 'New Game' after
1369 * pasting in that game id) is whatever it was previously set
1370 * to. That is, we use whatever is already in me->params as
1371 * the basis for our decoding of this input string.
1373 * A random-seed based game id, however, should use the real,
1374 * built-in default params, and not even check the
1375 * <game>_DEFAULT environment setting, because when people
1376 * paste each other random seeds - whether it's two users
1377 * arranging to generate the same game at the same time to
1378 * race solving them, or a user sending a bug report upstream
1379 * - the whole point is for the random game id to always be
1380 * interpreted the same way, even if it does underspecify.
1382 * A parameter string typed in on its own, with no seed _or_
1383 * description, gets treated the same way as a random seed,
1384 * because again I think the most likely reason for doing that
1385 * is to have a portable representation of a set of params.
1388 newcurparams = me->ourgame->dup_params(me->params);
1390 newcurparams = me->ourgame->default_params();
1392 me->ourgame->decode_params(newcurparams, par);
1393 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1395 me->ourgame->free_params(newcurparams);
1398 oldparams1 = me->curparams;
1401 * Now filter only the persistent parts of this state into
1402 * the long-term params structure, unless we've _only_
1403 * received a params string in which case the whole lot is
1406 oldparams2 = me->params;
1410 newparams = me->ourgame->dup_params(me->params);
1412 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1413 me->ourgame->decode_params(newparams, tmpstr);
1417 newparams = me->ourgame->dup_params(newcurparams);
1421 newcurparams = me->curparams;
1422 newparams = me->params;
1423 free_params = FALSE;
1427 error = me->ourgame->validate_desc(newparams, desc);
1431 me->ourgame->free_params(newcurparams);
1433 me->ourgame->free_params(newparams);
1440 * Now we've got past all possible error points. Update the
1443 me->params = newparams;
1444 me->curparams = newcurparams;
1446 me->ourgame->free_params(oldparams1);
1448 me->ourgame->free_params(oldparams2);
1451 sfree(me->privdesc);
1452 me->desc = me->privdesc = NULL;
1457 me->desc = dupstr(desc);
1458 me->genmode = GOT_DESC;
1459 sfree(me->aux_info);
1460 me->aux_info = NULL;
1464 me->seedstr = dupstr(seed);
1465 me->genmode = GOT_SEED;
1471 char *midend_game_id(midend *me, char *id)
1473 return midend_game_id_int(me, id, DEF_PARAMS);
1476 char *midend_get_game_id(midend *me)
1480 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1483 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1484 sprintf(ret, "%s:%s", parstr, me->desc);
1489 char *midend_get_random_seed(midend *me)
1496 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1498 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1499 sprintf(ret, "%s#%s", parstr, me->seedstr);
1504 char *midend_set_config(midend *me, int which, config_item *cfg)
1507 game_params *params;
1511 params = me->ourgame->custom_params(cfg);
1512 error = me->ourgame->validate_params(params, TRUE);
1515 me->ourgame->free_params(params);
1519 me->ourgame->free_params(me->params);
1520 me->params = params;
1525 error = midend_game_id_int(me, cfg[0].sval,
1526 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1535 int midend_can_format_as_text_now(midend *me)
1537 if (me->ourgame->can_format_as_text_ever)
1538 return me->ourgame->can_format_as_text_now(me->params);
1543 char *midend_text_format(midend *me)
1545 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1546 me->ourgame->can_format_as_text_now(me->params))
1547 return me->ourgame->text_format(me->states[me->statepos-1].state);
1552 char *midend_solve(midend *me)
1555 char *msg, *movestr;
1557 if (!me->ourgame->can_solve)
1558 return "This game does not support the Solve operation";
1560 if (me->statepos < 1)
1561 return "No game set up to solve"; /* _shouldn't_ happen! */
1564 movestr = me->ourgame->solve(me->states[0].state,
1565 me->states[me->statepos-1].state,
1566 me->aux_info, &msg);
1569 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1572 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1576 * Now enter the solved state as the next move.
1578 midend_stop_anim(me);
1579 midend_purge_states(me);
1581 me->states[me->nstates].state = s;
1582 me->states[me->nstates].movestr = movestr;
1583 me->states[me->nstates].movetype = SOLVE;
1584 me->statepos = ++me->nstates;
1586 me->ourgame->changed_state(me->ui,
1587 me->states[me->statepos-2].state,
1588 me->states[me->statepos-1].state);
1590 if (me->ourgame->flags & SOLVE_ANIMATES) {
1591 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1593 me->ourgame->anim_length(me->states[me->statepos-2].state,
1594 me->states[me->statepos-1].state,
1598 me->anim_time = 0.0;
1599 midend_finish_move(me);
1603 midend_set_timer(me);
1607 int midend_status(midend *me)
1610 * We should probably never be called when the state stack has no
1611 * states on it at all - ideally, midends should never be left in
1612 * that state for long enough to get put down and forgotten about.
1613 * But if we are, I think we return _true_ - pedantically speaking
1614 * a midend in that state is 'vacuously solved', and more
1615 * practically, a user whose midend has been left in that state
1616 * probably _does_ want the 'new game' option to be prominent.
1618 if (me->statepos == 0)
1621 return me->ourgame->status(me->states[me->statepos-1].state);
1624 char *midend_rewrite_statusbar(midend *me, char *text)
1627 * An important special case is that we are occasionally called
1628 * with our own laststatus, to update the timer.
1630 if (me->laststatus != text) {
1631 sfree(me->laststatus);
1632 me->laststatus = dupstr(text);
1635 if (me->ourgame->is_timed) {
1636 char timebuf[100], *ret;
1639 sec = (int)me->elapsed;
1642 sprintf(timebuf, "[%d:%02d] ", min, sec);
1644 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1645 strcpy(ret, timebuf);
1650 return dupstr(text);
1654 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1655 #define SERIALISE_VERSION "1"
1657 void midend_serialise(midend *me,
1658 void (*write)(void *ctx, void *buf, int len),
1664 * Each line of the save file contains three components. First
1665 * exactly 8 characters of header word indicating what type of
1666 * data is contained on the line; then a colon followed by a
1667 * decimal integer giving the length of the main string on the
1668 * line; then a colon followed by the string itself (exactly as
1669 * many bytes as previously specified, no matter what they
1670 * contain). Then a newline (of reasonably flexible form).
1672 #define wr(h,s) do { \
1676 copy_left_justified(lbuf, sizeof(lbuf), h); \
1677 sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1678 write(wctx, hbuf, strlen(hbuf)); \
1679 write(wctx, str, strlen(str)); \
1680 write(wctx, "\n", 1); \
1684 * Magic string identifying the file, and version number of the
1687 wr("SAVEFILE", SERIALISE_MAGIC);
1688 wr("VERSION", SERIALISE_VERSION);
1691 * The game name. (Copied locally to avoid const annoyance.)
1694 char *s = dupstr(me->ourgame->name);
1700 * The current long-term parameters structure, in full.
1703 char *s = me->ourgame->encode_params(me->params, TRUE);
1709 * The current short-term parameters structure, in full.
1711 if (me->curparams) {
1712 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1718 * The current game description, the privdesc, and the random seed.
1721 wr("SEED", me->seedstr);
1723 wr("DESC", me->desc);
1725 wr("PRIVDESC", me->privdesc);
1728 * The game's aux_info. We obfuscate this to prevent spoilers
1729 * (people are likely to run `head' or similar on a saved game
1730 * file simply to find out what it is, and don't necessarily
1731 * want to be told the answer to the puzzle!)
1738 len = strlen(me->aux_info);
1739 s1 = snewn(len, unsigned char);
1740 memcpy(s1, me->aux_info, len);
1741 obfuscate_bitmap(s1, len*8, FALSE);
1742 s2 = bin2hex(s1, len);
1751 * Any required serialisation of the game_ui.
1754 char *s = me->ourgame->encode_ui(me->ui);
1762 * The game time, if it's a timed game.
1764 if (me->ourgame->is_timed) {
1766 sprintf(buf, "%g", me->elapsed);
1771 * The length of, and position in, the states list.
1775 sprintf(buf, "%d", me->nstates);
1777 sprintf(buf, "%d", me->statepos);
1778 wr("STATEPOS", buf);
1782 * For each state after the initial one (which we know is
1783 * constructed from either privdesc or desc), enough
1784 * information for execute_move() to reconstruct it from the
1787 for (i = 1; i < me->nstates; i++) {
1788 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1789 switch (me->states[i].movetype) {
1791 wr("MOVE", me->states[i].movestr);
1794 wr("SOLVE", me->states[i].movestr);
1797 wr("RESTART", me->states[i].movestr);
1806 * This function returns NULL on success, or an error message.
1808 char *midend_deserialise(midend *me,
1809 int (*read)(void *ctx, void *buf, int len),
1812 int nstates = 0, statepos = -1, gotstates = 0;
1813 int started = FALSE;
1817 /* Initially all errors give the same report */
1818 char *ret = "Data does not appear to be a saved game file";
1821 * We construct all the new state in local variables while we
1822 * check its sanity. Only once we have finished reading the
1823 * serialised data and detected no errors at all do we start
1824 * modifying stuff in the midend passed in.
1826 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1827 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1828 float elapsed = 0.0F;
1829 game_params *params = NULL, *cparams = NULL;
1831 struct midend_state_entry *states = NULL;
1834 * Loop round and round reading one key/value pair at a time
1835 * from the serialised stream, until we have enough game states
1838 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1843 if (!read(rctx, key, 1)) {
1844 /* unexpected EOF */
1847 } while (key[0] == '\r' || key[0] == '\n');
1849 if (!read(rctx, key+1, 8)) {
1850 /* unexpected EOF */
1854 if (key[8] != ':') {
1856 ret = "Data was incorrectly formatted for a saved game file";
1859 len = strcspn(key, ": ");
1865 if (!read(rctx, &c, 1)) {
1866 /* unexpected EOF */
1872 } else if (c >= '0' && c <= '9') {
1873 len = (len * 10) + (c - '0');
1876 ret = "Data was incorrectly formatted for a"
1882 val = snewn(len+1, char);
1883 if (!read(rctx, val, len)) {
1890 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1891 /* ret already has the right message in it */
1894 /* Now most errors are this one, unless otherwise specified */
1895 ret = "Saved data ended unexpectedly";
1898 if (!strcmp(key, "VERSION")) {
1899 if (strcmp(val, SERIALISE_VERSION)) {
1900 ret = "Cannot handle this version of the saved game"
1904 } else if (!strcmp(key, "GAME")) {
1905 if (strcmp(val, me->ourgame->name)) {
1906 ret = "Save file is from a different game";
1909 } else if (!strcmp(key, "PARAMS")) {
1913 } else if (!strcmp(key, "CPARAMS")) {
1917 } else if (!strcmp(key, "SEED")) {
1921 } else if (!strcmp(key, "DESC")) {
1925 } else if (!strcmp(key, "PRIVDESC")) {
1929 } else if (!strcmp(key, "AUXINFO")) {
1931 int len = strlen(val) / 2; /* length in bytes */
1932 tmp = hex2bin(val, len);
1933 obfuscate_bitmap(tmp, len*8, TRUE);
1936 auxinfo = snewn(len + 1, char);
1937 memcpy(auxinfo, tmp, len);
1938 auxinfo[len] = '\0';
1940 } else if (!strcmp(key, "UI")) {
1944 } else if (!strcmp(key, "TIME")) {
1945 elapsed = (float)atof(val);
1946 } else if (!strcmp(key, "NSTATES")) {
1947 nstates = atoi(val);
1949 ret = "Number of states in save file was negative";
1953 ret = "Two state counts provided in save file";
1956 states = snewn(nstates, struct midend_state_entry);
1957 for (i = 0; i < nstates; i++) {
1958 states[i].state = NULL;
1959 states[i].movestr = NULL;
1960 states[i].movetype = NEWGAME;
1962 } else if (!strcmp(key, "STATEPOS")) {
1963 statepos = atoi(val);
1964 } else if (!strcmp(key, "MOVE")) {
1966 states[gotstates].movetype = MOVE;
1967 states[gotstates].movestr = val;
1969 } else if (!strcmp(key, "SOLVE")) {
1971 states[gotstates].movetype = SOLVE;
1972 states[gotstates].movestr = val;
1974 } else if (!strcmp(key, "RESTART")) {
1976 states[gotstates].movetype = RESTART;
1977 states[gotstates].movestr = val;
1986 params = me->ourgame->default_params();
1987 me->ourgame->decode_params(params, parstr);
1988 if (me->ourgame->validate_params(params, TRUE)) {
1989 ret = "Long-term parameters in save file are invalid";
1992 cparams = me->ourgame->default_params();
1993 me->ourgame->decode_params(cparams, cparstr);
1994 if (me->ourgame->validate_params(cparams, FALSE)) {
1995 ret = "Short-term parameters in save file are invalid";
1998 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
2000 * The seed's no use with this version, but we can perfectly
2001 * well use the rest of the data.
2007 ret = "Game description in save file is missing";
2009 } else if (me->ourgame->validate_desc(params, desc)) {
2010 ret = "Game description in save file is invalid";
2013 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
2014 ret = "Game private description in save file is invalid";
2017 if (statepos < 0 || statepos >= nstates) {
2018 ret = "Game position in save file is out of range";
2021 states[0].state = me->ourgame->new_game(me, params,
2022 privdesc ? privdesc : desc);
2023 for (i = 1; i < nstates; i++) {
2024 assert(states[i].movetype != NEWGAME);
2025 switch (states[i].movetype) {
2028 states[i].state = me->ourgame->execute_move(states[i-1].state,
2030 if (states[i].state == NULL) {
2031 ret = "Save file contained an invalid move";
2036 if (me->ourgame->validate_desc(params, states[i].movestr)) {
2037 ret = "Save file contained an invalid restart move";
2040 states[i].state = me->ourgame->new_game(me, params,
2046 ui = me->ourgame->new_ui(states[0].state);
2047 me->ourgame->decode_ui(ui, uistr);
2050 * Now we've run out of possible error conditions, so we're
2051 * ready to start overwriting the real data in the current
2052 * midend. We'll do this by swapping things with the local
2053 * variables, so that the same cleanup code will free the old
2064 me->privdesc = privdesc;
2072 me->aux_info = auxinfo;
2076 me->genmode = GOT_NOTHING;
2078 me->statesize = nstates;
2079 nstates = me->nstates;
2080 me->nstates = me->statesize;
2082 struct midend_state_entry *tmp;
2084 me->states = states;
2087 me->statepos = statepos;
2090 * Don't save the "new game undo" state. So "new game" twice or
2091 * (in some environments) switching away and back, will make a
2092 * "new game" irreversible. Maybe in the future we will have a
2093 * more sophisticated way to decide when to discard the previous
2096 me->newgame_undo_used = 0;
2102 me->params = params;
2105 tmp = me->curparams;
2106 me->curparams = cparams;
2110 me->oldstate = NULL;
2111 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2122 me->elapsed = elapsed;
2123 me->pressed_mouse_button = 0;
2125 midend_set_timer(me);
2128 me->ourgame->free_drawstate(me->drawing, me->drawstate);
2130 me->ourgame->new_drawstate(me->drawing,
2131 me->states[me->statepos-1].state);
2132 midend_size_new_drawstate(me);
2133 if (me->game_id_change_notify_function)
2134 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2136 ret = NULL; /* success! */
2148 me->ourgame->free_params(params);
2150 me->ourgame->free_params(cparams);
2152 me->ourgame->free_ui(ui);
2156 for (i = 0; i < nstates; i++) {
2157 if (states[i].state)
2158 me->ourgame->free_game(states[i].state);
2159 sfree(states[i].movestr);
2168 * This function examines a saved game file just far enough to
2169 * determine which game type it contains. It returns NULL on success
2170 * and the game name string in 'name' (which will be dynamically
2171 * allocated and should be caller-freed), or an error message on
2174 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2177 int nstates = 0, statepos = -1, gotstates = 0;
2178 int started = FALSE;
2181 /* Initially all errors give the same report */
2182 char *ret = "Data does not appear to be a saved game file";
2187 * Loop round and round reading one key/value pair at a time from
2188 * the serialised stream, until we've found the game name.
2190 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2195 if (!read(rctx, key, 1)) {
2196 /* unexpected EOF */
2199 } while (key[0] == '\r' || key[0] == '\n');
2201 if (!read(rctx, key+1, 8)) {
2202 /* unexpected EOF */
2206 if (key[8] != ':') {
2208 ret = "Data was incorrectly formatted for a saved game file";
2211 len = strcspn(key, ": ");
2217 if (!read(rctx, &c, 1)) {
2218 /* unexpected EOF */
2224 } else if (c >= '0' && c <= '9') {
2225 len = (len * 10) + (c - '0');
2228 ret = "Data was incorrectly formatted for a"
2234 val = snewn(len+1, char);
2235 if (!read(rctx, val, len)) {
2242 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2243 /* ret already has the right message in it */
2246 /* Now most errors are this one, unless otherwise specified */
2247 ret = "Saved data ended unexpectedly";
2250 if (!strcmp(key, "VERSION")) {
2251 if (strcmp(val, SERIALISE_VERSION)) {
2252 ret = "Cannot handle this version of the saved game"
2256 } else if (!strcmp(key, "GAME")) {
2257 *name = dupstr(val);
2272 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2274 game_state *soln = NULL;
2276 if (me->statepos < 1)
2277 return "No game set up to print";/* _shouldn't_ happen! */
2280 char *msg, *movestr;
2282 if (!me->ourgame->can_solve)
2283 return "This game does not support the Solve operation";
2285 msg = "Solve operation failed";/* game _should_ overwrite on error */
2286 movestr = me->ourgame->solve(me->states[0].state,
2287 me->states[me->statepos-1].state,
2288 me->aux_info, &msg);
2291 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2300 * This call passes over ownership of the two game_states and
2301 * the game_params. Hence we duplicate the ones we want to
2302 * keep, and we don't have to bother freeing soln if it was
2305 document_add_puzzle(doc, me->ourgame,
2306 me->ourgame->dup_params(me->curparams),
2307 me->ourgame->dup_game(me->states[0].state), soln);