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;
113 void midend_reset_tilesize(midend *me)
115 me->preferred_tilesize = me->ourgame->preferred_tilesize;
118 * Allow an environment-based override for the default tile
119 * size by defining a variable along the lines of
126 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
127 for (j = k = 0; buf[j]; j++)
128 if (!isspace((unsigned char)buf[j]))
129 buf[k++] = toupper((unsigned char)buf[j]);
131 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
132 me->preferred_tilesize = ts;
136 midend *midend_new(frontend *fe, const game *ourgame,
137 const drawing_api *drapi, void *drhandle)
139 midend *me = snew(midend);
143 get_random_seed(&randseed, &randseedsize);
146 me->ourgame = ourgame;
147 me->random = random_new(randseed, randseedsize);
148 me->nstates = me->statesize = me->statepos = 0;
150 me->params = ourgame->default_params();
151 me->game_id_change_notify_function = NULL;
152 me->game_id_change_notify_ctx = NULL;
155 * Allow environment-based changing of the default settings by
156 * defining a variable along the lines of `NET_DEFAULT=25x25w'
157 * in which the value is an encoded parameter string.
162 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
163 for (j = k = 0; buf[j]; j++)
164 if (!isspace((unsigned char)buf[j]))
165 buf[k++] = toupper((unsigned char)buf[j]);
167 if ((e = getenv(buf)) != NULL)
168 me->ourgame->decode_params(me->params, e);
170 me->curparams = NULL;
171 me->desc = me->privdesc = NULL;
174 me->genmode = GOT_NOTHING;
175 me->drawstate = NULL;
177 me->preset_menu = NULL;
178 me->anim_time = me->anim_pos = 0.0F;
179 me->flash_time = me->flash_pos = 0.0F;
182 me->pressed_mouse_button = 0;
183 me->laststatus = NULL;
186 me->tilesize = me->winwidth = me->winheight = 0;
188 me->drawing = drawing_new(drapi, me, drhandle);
192 midend_reset_tilesize(me);
199 const game *midend_which_game(midend *me)
204 static void midend_purge_states(midend *me)
206 while (me->nstates > me->statepos) {
207 me->ourgame->free_game(me->states[--me->nstates].state);
208 if (me->states[me->nstates].movestr)
209 sfree(me->states[me->nstates].movestr);
213 static void midend_free_game(midend *me)
215 while (me->nstates > 0) {
217 me->ourgame->free_game(me->states[me->nstates].state);
218 sfree(me->states[me->nstates].movestr);
222 me->ourgame->free_drawstate(me->drawing, me->drawstate);
225 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
229 for (i = 0; i < menu->n_entries; i++) {
230 sfree(menu->entries[i].title);
231 if (menu->entries[i].params)
232 me->ourgame->free_params(menu->entries[i].params);
233 midend_free_preset_menu(me, menu->entries[i].submenu);
235 sfree(menu->entries);
240 void midend_free(midend *me)
242 midend_free_game(me);
245 drawing_free(me->drawing);
246 random_free(me->random);
252 me->ourgame->free_params(me->params);
253 midend_free_preset_menu(me, me->preset_menu);
255 me->ourgame->free_ui(me->ui);
257 me->ourgame->free_params(me->curparams);
258 sfree(me->laststatus);
262 static void midend_size_new_drawstate(midend *me)
265 * Don't even bother, if we haven't worked out our tile size
268 if (me->tilesize > 0) {
269 me->ourgame->compute_size(me->params, me->tilesize,
270 &me->winwidth, &me->winheight);
271 me->ourgame->set_size(me->drawing, me->drawstate,
272 me->params, me->tilesize);
276 void midend_size(midend *me, int *x, int *y, int user_size)
282 * We can't set the size on the same drawstate twice. So if
283 * we've already sized one drawstate, we must throw it away and
286 if (me->drawstate && me->tilesize > 0) {
287 me->ourgame->free_drawstate(me->drawing, me->drawstate);
288 me->drawstate = me->ourgame->new_drawstate(me->drawing,
289 me->states[0].state);
293 * Find the tile size that best fits within the given space. If
294 * `user_size' is TRUE, we must actually find the _largest_ such
295 * tile size, in order to get as close to the user's explicit
296 * request as possible; otherwise, we bound above at the game's
297 * preferred tile size, so that the game gets what it wants
298 * provided that this doesn't break the constraint from the
299 * front-end (which is likely to be a screen size or similar).
305 me->ourgame->compute_size(me->params, max, &rx, &ry);
306 } while (rx <= *x && ry <= *y);
308 max = me->preferred_tilesize + 1;
312 * Now binary-search between min and max. We're looking for a
313 * boundary rather than a value: the point at which tile sizes
314 * stop fitting within the given dimensions. Thus, we stop when
315 * max and min differ by exactly 1.
317 while (max - min > 1) {
318 int mid = (max + min) / 2;
319 me->ourgame->compute_size(me->params, mid, &rx, &ry);
320 if (rx <= *x && ry <= *y)
327 * Now `min' is a valid size, and `max' isn't. So use `min'.
332 /* If the user requested a change in size, make it permanent. */
333 me->preferred_tilesize = me->tilesize;
334 midend_size_new_drawstate(me);
339 int midend_tilesize(midend *me) { return me->tilesize; }
341 void midend_set_params(midend *me, game_params *params)
343 me->ourgame->free_params(me->params);
344 me->params = me->ourgame->dup_params(params);
347 game_params *midend_get_params(midend *me)
349 return me->ourgame->dup_params(me->params);
352 static void midend_set_timer(midend *me)
354 me->timing = (me->ourgame->is_timed &&
355 me->ourgame->timing_state(me->states[me->statepos-1].state,
357 if (me->timing || me->flash_time || me->anim_time)
358 activate_timer(me->frontend);
360 deactivate_timer(me->frontend);
363 void midend_force_redraw(midend *me)
366 me->ourgame->free_drawstate(me->drawing, me->drawstate);
367 me->drawstate = me->ourgame->new_drawstate(me->drawing,
368 me->states[0].state);
369 midend_size_new_drawstate(me);
373 void midend_new_game(midend *me)
375 midend_stop_anim(me);
376 midend_free_game(me);
378 assert(me->nstates == 0);
380 if (me->genmode == GOT_DESC) {
381 me->genmode = GOT_NOTHING;
385 if (me->genmode == GOT_SEED) {
386 me->genmode = GOT_NOTHING;
389 * Generate a new random seed. 15 digits comes to about
390 * 48 bits, which should be more than enough.
392 * I'll avoid putting a leading zero on the number,
393 * just in case it confuses anybody who thinks it's
394 * processed as an integer rather than a string.
399 newseed[0] = '1' + (char)random_upto(me->random, 9);
400 for (i = 1; i < 15; i++)
401 newseed[i] = '0' + (char)random_upto(me->random, 10);
403 me->seedstr = dupstr(newseed);
406 me->ourgame->free_params(me->curparams);
407 me->curparams = me->ourgame->dup_params(me->params);
415 rs = random_new(me->seedstr, strlen(me->seedstr));
417 * If this midend has been instantiated without providing a
418 * drawing API, it is non-interactive. This means that it's
419 * being used for bulk game generation, and hence we should
420 * pass the non-interactive flag to new_desc.
422 me->desc = me->ourgame->new_desc(me->curparams, rs,
423 &me->aux_info, (me->drawing != NULL));
431 * It might seem a bit odd that we're using me->params to
432 * create the initial game state, rather than me->curparams
433 * which is better tailored to this specific game and which we
436 * It's supposed to be an invariant in the midend that
437 * me->params and me->curparams differ in no aspect that is
438 * important after generation (i.e. after new_desc()). By
439 * deliberately passing the _less_ specific of these two
440 * parameter sets, we provoke play-time misbehaviour in the
441 * case where a game has failed to encode a play-time parameter
442 * in the non-full version of encode_params().
444 me->states[me->nstates].state =
445 me->ourgame->new_game(me, me->params, me->desc);
448 * As part of our commitment to self-testing, test the aux
449 * string to make sure nothing ghastly went wrong.
451 if (me->ourgame->can_solve && me->aux_info) {
456 movestr = me->ourgame->solve(me->states[0].state,
459 assert(movestr && !msg);
460 s = me->ourgame->execute_move(me->states[0].state, movestr);
462 me->ourgame->free_game(s);
466 me->states[me->nstates].movestr = NULL;
467 me->states[me->nstates].movetype = NEWGAME;
470 me->drawstate = me->ourgame->new_drawstate(me->drawing,
471 me->states[0].state);
472 midend_size_new_drawstate(me);
474 me->flash_pos = me->flash_time = 0.0F;
475 me->anim_pos = me->anim_time = 0.0F;
477 me->ourgame->free_ui(me->ui);
478 me->ui = me->ourgame->new_ui(me->states[0].state);
479 midend_set_timer(me);
480 me->pressed_mouse_button = 0;
482 if (me->game_id_change_notify_function)
483 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
486 int midend_can_undo(midend *me)
488 return (me->statepos > 1);
491 int midend_can_redo(midend *me)
493 return (me->statepos < me->nstates);
496 static int midend_undo(midend *me)
498 if (me->statepos > 1) {
500 me->ourgame->changed_state(me->ui,
501 me->states[me->statepos-1].state,
502 me->states[me->statepos-2].state);
510 static int midend_redo(midend *me)
512 if (me->statepos < me->nstates) {
514 me->ourgame->changed_state(me->ui,
515 me->states[me->statepos-1].state,
516 me->states[me->statepos].state);
524 static void midend_finish_move(midend *me)
529 * We do not flash if the later of the two states is special.
530 * This covers both forward Solve moves and backward (undone)
533 if ((me->oldstate || me->statepos > 1) &&
534 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
535 (me->dir < 0 && me->statepos < me->nstates &&
536 !special(me->states[me->statepos].movetype)))) {
537 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
538 me->states[me->statepos-2].state,
539 me->states[me->statepos-1].state,
540 me->oldstate ? me->dir : +1,
543 me->flash_pos = 0.0F;
544 me->flash_time = flashtime;
549 me->ourgame->free_game(me->oldstate);
551 me->anim_pos = me->anim_time = 0;
554 midend_set_timer(me);
557 void midend_stop_anim(midend *me)
559 if (me->oldstate || me->anim_time != 0) {
560 midend_finish_move(me);
565 void midend_restart_game(midend *me)
569 assert(me->statepos >= 1);
570 if (me->statepos == 1)
571 return; /* no point doing anything at all! */
574 * During restart, we reconstruct the game from the (public)
575 * game description rather than from states[0], because that
576 * way Mines gets slightly more sensible behaviour (restart
577 * goes to _after_ the first click so you don't have to
578 * remember where you clicked).
580 s = me->ourgame->new_game(me, me->params, me->desc);
583 * Now enter the restarted state as the next move.
585 midend_stop_anim(me);
586 midend_purge_states(me);
588 me->states[me->nstates].state = s;
589 me->states[me->nstates].movestr = dupstr(me->desc);
590 me->states[me->nstates].movetype = RESTART;
591 me->statepos = ++me->nstates;
593 me->ourgame->changed_state(me->ui,
594 me->states[me->statepos-2].state,
595 me->states[me->statepos-1].state);
596 me->flash_pos = me->flash_time = 0.0F;
597 midend_finish_move(me);
599 midend_set_timer(me);
602 static int midend_really_process_key(midend *me, int x, int y, int button)
604 game_state *oldstate =
605 me->ourgame->dup_game(me->states[me->statepos - 1].state);
606 int type = MOVE, gottype = FALSE, ret = 1;
609 char *movestr = NULL;
611 if (!IS_UI_FAKE_KEY(button)) {
612 movestr = me->ourgame->interpret_move(
613 me->states[me->statepos-1].state,
614 me->ui, me->drawstate, x, y, button);
618 if (button == 'n' || button == 'N' || button == '\x0E' ||
619 button == UI_NEWGAME) {
622 goto done; /* never animate */
623 } else if (button == 'u' || button == 'U' ||
624 button == '\x1A' || button == '\x1F' ||
626 midend_stop_anim(me);
627 type = me->states[me->statepos-1].movetype;
629 if (!midend_undo(me))
631 } else if (button == 'r' || button == 'R' ||
632 button == '\x12' || button == '\x19' ||
634 midend_stop_anim(me);
635 if (!midend_redo(me))
637 } else if ((button == '\x13' || button == UI_SOLVE) &&
638 me->ourgame->can_solve) {
639 if (midend_solve(me))
641 } else if (button == 'q' || button == 'Q' || button == '\x11' ||
649 s = me->states[me->statepos-1].state;
651 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
656 if (s == me->states[me->statepos-1].state) {
658 * make_move() is allowed to return its input state to
659 * indicate that although no move has been made, the UI
660 * state has been updated and a redraw is called for.
663 midend_set_timer(me);
666 midend_stop_anim(me);
667 midend_purge_states(me);
669 assert(movestr != NULL);
670 me->states[me->nstates].state = s;
671 me->states[me->nstates].movestr = movestr;
672 me->states[me->nstates].movetype = MOVE;
673 me->statepos = ++me->nstates;
676 me->ourgame->changed_state(me->ui,
677 me->states[me->statepos-2].state,
678 me->states[me->statepos-1].state);
685 type = me->states[me->statepos-1].movetype;
688 * See if this move requires an animation.
690 if (special(type) && !(type == SOLVE &&
691 (me->ourgame->flags & SOLVE_ANIMATES))) {
694 anim_time = me->ourgame->anim_length(oldstate,
695 me->states[me->statepos-1].state,
699 me->oldstate = oldstate; oldstate = NULL;
701 me->anim_time = anim_time;
704 midend_finish_move(me);
710 midend_set_timer(me);
713 if (oldstate) me->ourgame->free_game(oldstate);
717 int midend_process_key(midend *me, int x, int y, int button)
722 * Harmonise mouse drag and release messages.
724 * Some front ends might accidentally switch from sending, say,
725 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
726 * drag. (This can happen on the Mac, for example, since
727 * RIGHT_DRAG is usually done using Command+drag, and if the
728 * user accidentally releases Command half way through the drag
729 * then there will be trouble.)
731 * It would be an O(number of front ends) annoyance to fix this
732 * in the front ends, but an O(number of back ends) annoyance
733 * to have each game capable of dealing with it. Therefore, we
734 * fix it _here_ in the common midend code so that it only has
737 * The possible ways in which things can go screwy in the front
740 * - in a system containing multiple physical buttons button
741 * presses can inadvertently overlap. We can see ABab (caps
742 * meaning button-down and lowercase meaning button-up) when
743 * the user had semantically intended AaBb.
745 * - in a system where one button is simulated by means of a
746 * modifier key and another button, buttons can mutate
747 * between press and release (possibly during drag). So we
748 * can see Ab instead of Aa.
750 * Definite requirements are:
752 * - button _presses_ must never be invented or destroyed. If
753 * the user presses two buttons in succession, the button
754 * presses must be transferred to the backend unchanged. So
755 * if we see AaBb , that's fine; if we see ABab (the button
756 * presses inadvertently overlapped) we must somehow
757 * `correct' it to AaBb.
759 * - every mouse action must end up looking like a press, zero
760 * or more drags, then a release. This allows back ends to
761 * make the _assumption_ that incoming mouse data will be
762 * sane in this regard, and not worry about the details.
764 * So my policy will be:
766 * - treat any button-up as a button-up for the currently
767 * pressed button, or ignore it if there is no currently
770 * - treat any drag as a drag for the currently pressed
771 * button, or ignore it if there is no currently pressed
774 * - if we see a button-down while another button is currently
775 * pressed, invent a button-up for the first one and then
776 * pass the button-down through as before.
778 * 2005-05-31: An addendum to the above. Some games might want
779 * a `priority order' among buttons, such that if one button is
780 * pressed while another is down then a fixed one of the
781 * buttons takes priority no matter what order they're pressed
782 * in. Mines, in particular, wants to treat a left+right click
783 * like a left click for the benefit of users of other
784 * implementations. So the last of the above points is modified
785 * in the presence of an (optional) button priority order.
787 * A further addition: we translate certain keyboard presses to
788 * cursor key 'select' buttons, so that a) frontends don't have
789 * to translate these themselves (like they do for CURSOR_UP etc),
790 * and b) individual games don't have to hard-code button presses
791 * of '\n' etc for keyboard-based cursors. The choice of buttons
792 * here could eventually be controlled by a runtime configuration
795 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
796 if (me->pressed_mouse_button) {
797 if (IS_MOUSE_DRAG(button)) {
798 button = me->pressed_mouse_button +
799 (LEFT_DRAG - LEFT_BUTTON);
801 button = me->pressed_mouse_button +
802 (LEFT_RELEASE - LEFT_BUTTON);
805 return ret; /* ignore it */
806 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
808 * If the new button has lower priority than the old one,
809 * don't bother doing this.
811 if (me->ourgame->flags &
812 BUTTON_BEATS(me->pressed_mouse_button, button))
813 return ret; /* just ignore it */
816 * Fabricate a button-up for the previously pressed button.
818 ret = ret && midend_really_process_key
819 (me, x, y, (me->pressed_mouse_button +
820 (LEFT_RELEASE - LEFT_BUTTON)));
824 * Translate keyboard presses to cursor selection.
826 if (button == '\n' || button == '\r')
827 button = CURSOR_SELECT;
829 button = CURSOR_SELECT2;
832 * Normalise both backspace characters (8 and 127) to \b. Easier
833 * to do this once, here, than to require all front ends to
834 * carefully generate the same one - now each front end can
835 * generate whichever is easiest.
837 if (button == '\177')
841 * Now send on the event we originally received.
843 ret = ret && midend_really_process_key(me, x, y, button);
846 * And update the currently pressed button.
848 if (IS_MOUSE_RELEASE(button))
849 me->pressed_mouse_button = 0;
850 else if (IS_MOUSE_DOWN(button))
851 me->pressed_mouse_button = button;
856 void midend_redraw(midend *me)
860 if (me->statepos > 0 && me->drawstate) {
861 start_draw(me->drawing);
862 if (me->oldstate && me->anim_time > 0 &&
863 me->anim_pos < me->anim_time) {
864 assert(me->dir != 0);
865 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
866 me->states[me->statepos-1].state, me->dir,
867 me->ui, me->anim_pos, me->flash_pos);
869 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
870 me->states[me->statepos-1].state, +1 /*shrug*/,
871 me->ui, 0.0, me->flash_pos);
873 end_draw(me->drawing);
878 * Nasty hacky function used to implement the --redo option in
879 * gtk.c. Only used for generating the puzzles' icons.
881 void midend_freeze_timer(midend *me, float tprop)
883 me->anim_pos = me->anim_time * tprop;
885 deactivate_timer(me->frontend);
888 void midend_timer(midend *me, float tplus)
890 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
892 me->anim_pos += tplus;
893 if (me->anim_pos >= me->anim_time ||
894 me->anim_time == 0 || !me->oldstate) {
895 if (me->anim_time > 0)
896 midend_finish_move(me);
899 me->flash_pos += tplus;
900 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
901 me->flash_pos = me->flash_time = 0;
908 float oldelapsed = me->elapsed;
909 me->elapsed += tplus;
910 if ((int)oldelapsed != (int)me->elapsed)
911 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
914 midend_set_timer(me);
917 float *midend_colours(midend *me, int *ncolours)
921 ret = me->ourgame->colours(me->frontend, ncolours);
927 * Allow environment-based overrides for the standard
928 * colours by defining variables along the lines of
929 * `NET_COLOUR_4=6000c0'.
932 for (i = 0; i < *ncolours; i++) {
934 unsigned int r, g, b;
937 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
938 for (j = k = 0; buf[j]; j++)
939 if (!isspace((unsigned char)buf[j]))
940 buf[k++] = toupper((unsigned char)buf[j]);
942 if ((e = getenv(buf)) != NULL &&
943 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
944 ret[i*3 + 0] = r / 255.0F;
945 ret[i*3 + 1] = g / 255.0F;
946 ret[i*3 + 2] = b / 255.0F;
954 struct preset_menu *preset_menu_new(void)
956 struct preset_menu *menu = snew(struct preset_menu);
958 menu->entries_size = 0;
959 menu->entries = NULL;
963 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
966 struct preset_menu_entry *toret;
967 if (menu->n_entries >= menu->entries_size) {
968 menu->entries_size = menu->n_entries * 5 / 4 + 10;
969 menu->entries = sresize(menu->entries, menu->entries_size,
970 struct preset_menu_entry);
972 toret = &menu->entries[menu->n_entries++];
973 toret->title = title;
974 toret->params = NULL;
975 toret->submenu = NULL;
979 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
982 struct preset_menu_entry *entry = preset_menu_add(parent, title);
983 entry->submenu = preset_menu_new();
984 return entry->submenu;
987 void preset_menu_add_preset(struct preset_menu *parent,
988 char *title, game_params *params)
990 struct preset_menu_entry *entry = preset_menu_add(parent, title);
991 entry->params = params;
994 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
999 for (i = 0; i < menu->n_entries; i++) {
1000 if (id == menu->entries[i].id)
1001 return menu->entries[i].params;
1002 if (menu->entries[i].submenu &&
1003 (retd = preset_menu_lookup_by_id(
1004 menu->entries[i].submenu, id)) != NULL)
1011 static char *preset_menu_add_from_user_env(
1012 midend *me, struct preset_menu *menu, char *p, int top_level)
1016 game_params *preset;
1019 while (*p && *p != ':') p++;
1020 if (*p) *p++ = '\0';
1022 while (*p && *p != ':') p++;
1023 if (*p) *p++ = '\0';
1025 if (!strcmp(val, "#")) {
1027 * Special case: either open a new submenu with the given
1028 * title, or terminate the current submenu.
1031 struct preset_menu *submenu =
1032 preset_menu_add_submenu(menu, dupstr(name));
1033 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1036 * If we get a 'close submenu' indication at the top
1037 * level, there's not much we can do but quietly
1046 preset = me->ourgame->default_params();
1047 me->ourgame->decode_params(preset, val);
1049 if (me->ourgame->validate_params(preset, TRUE)) {
1050 /* Drop this one from the list. */
1051 me->ourgame->free_params(preset);
1055 preset_menu_add_preset(menu, dupstr(name), preset);
1061 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1065 for (i = 0; i < menu->n_entries; i++)
1066 menu->entries[i].id = me->n_encoded_presets++;
1068 for (i = 0; i < menu->n_entries; i++)
1069 if (menu->entries[i].submenu)
1070 preset_menu_alloc_ids(me, menu->entries[i].submenu);
1073 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1077 for (i = 0; i < menu->n_entries; i++) {
1078 if (menu->entries[i].params) {
1079 me->encoded_presets[menu->entries[i].id] =
1080 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1082 preset_menu_encode_params(me, menu->entries[i].submenu);
1087 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1091 if (me->preset_menu)
1092 return me->preset_menu;
1095 /* Expect the game to implement exactly one of the two preset APIs */
1096 assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1097 assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1100 if (me->ourgame->fetch_preset) {
1102 game_params *preset;
1104 /* Simple one-level menu */
1105 assert(!me->ourgame->preset_menu);
1106 me->preset_menu = preset_menu_new();
1107 for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1108 preset_menu_add_preset(me->preset_menu, name, preset);
1111 /* Hierarchical menu provided by the game backend */
1112 me->preset_menu = me->ourgame->preset_menu();
1117 * Allow user extensions to the preset list by defining an
1118 * environment variable <gamename>_PRESETS whose value is a
1119 * colon-separated list of items, alternating between textual
1120 * titles in the menu and encoded parameter strings. For
1121 * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1122 * just one additional preset for Solo.
1127 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1128 for (j = k = 0; buf[j]; j++)
1129 if (!isspace((unsigned char)buf[j]))
1130 buf[k++] = toupper((unsigned char)buf[j]);
1133 if ((e = getenv(buf)) != NULL) {
1135 preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1141 * Finalise the menu: allocate an integer id to each entry, and
1142 * store string encodings of the presets' parameters in
1143 * me->encoded_presets.
1145 me->n_encoded_presets = 0;
1146 preset_menu_alloc_ids(me, me->preset_menu);
1147 me->encoded_presets = snewn(me->n_encoded_presets, char *);
1148 for (i = 0; i < me->n_encoded_presets; i++)
1149 me->encoded_presets[i] = NULL;
1150 preset_menu_encode_params(me, me->preset_menu);
1153 *id_limit = me->n_encoded_presets;
1154 return me->preset_menu;
1157 int midend_which_preset(midend *me)
1159 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1163 for (i = 0; i < me->n_encoded_presets; i++)
1164 if (me->encoded_presets[i] &&
1165 !strcmp(encoding, me->encoded_presets[i])) {
1174 int midend_wants_statusbar(midend *me)
1176 return me->ourgame->wants_statusbar;
1179 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1181 me->game_id_change_notify_function = notify;
1182 me->game_id_change_notify_ctx = ctx;
1185 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1188 sfree(me->privdesc);
1189 me->desc = dupstr(desc);
1190 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1191 if (me->game_id_change_notify_function)
1192 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1195 config_item *midend_get_config(midend *me, int which, char **wintitle)
1197 char *titlebuf, *parstr, *rest;
1202 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1206 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1207 *wintitle = titlebuf;
1208 return me->ourgame->configure(me->params);
1211 if (!me->curparams) {
1215 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1216 which == CFG_SEED ? "random" : "game");
1217 *wintitle = titlebuf;
1219 ret = snewn(2, config_item);
1221 ret[0].type = C_STRING;
1222 if (which == CFG_SEED)
1223 ret[0].name = "Game random seed";
1225 ret[0].name = "Game ID";
1228 * For CFG_DESC the text going in here will be a string
1229 * encoding of the restricted parameters, plus a colon,
1230 * plus the game description. For CFG_SEED it will be the
1231 * full parameters, plus a hash, plus the random seed data.
1232 * Either of these is a valid full game ID (although only
1233 * the former is likely to persist across many code
1236 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1238 if (which == CFG_DESC) {
1239 rest = me->desc ? me->desc : "";
1242 rest = me->seedstr ? me->seedstr : "";
1245 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1246 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1249 ret[1].type = C_END;
1250 ret[1].name = ret[1].sval = NULL;
1256 assert(!"We shouldn't be here");
1260 static char *midend_game_id_int(midend *me, char *id, int defmode)
1262 char *error, *par, *desc, *seed;
1263 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1266 seed = strchr(id, '#');
1267 desc = strchr(id, ':');
1269 if (desc && (!seed || desc < seed)) {
1271 * We have a colon separating parameters from game
1272 * description. So `par' now points to the parameters
1273 * string, and `desc' to the description string.
1278 } else if (seed && (!desc || seed < desc)) {
1280 * We have a hash separating parameters from random seed.
1281 * So `par' now points to the parameters string, and `seed'
1282 * to the seed string.
1289 * We only have one string. Depending on `defmode', we take
1290 * it to be either parameters, seed or description.
1292 if (defmode == DEF_SEED) {
1295 } else if (defmode == DEF_DESC) {
1305 * We must be reasonably careful here not to modify anything in
1306 * `me' until we have finished validating things. This function
1307 * must either return an error and do nothing to the midend, or
1308 * return success and do everything; nothing in between is
1311 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1315 * The params string may underspecify the game parameters, so
1316 * we must first initialise newcurparams with a full set of
1317 * params from somewhere else before we decode_params the
1318 * input string over the top.
1320 * But which set? It depends on what other data we have.
1322 * If we've been given a _descriptive_ game id, then that may
1323 * well underspecify by design, e.g. Solo game descriptions
1324 * often start just '3x3:' without specifying one of Solo's
1325 * difficulty settings, because it isn't necessary once a game
1326 * has been generated (and you might not even know it, if
1327 * you're manually transcribing a game description). In that
1328 * situation, I've always felt that the best thing to set the
1329 * difficulty to (for use if the user hits 'New Game' after
1330 * pasting in that game id) is whatever it was previously set
1331 * to. That is, we use whatever is already in me->params as
1332 * the basis for our decoding of this input string.
1334 * A random-seed based game id, however, should use the real,
1335 * built-in default params, and not even check the
1336 * <game>_DEFAULT environment setting, because when people
1337 * paste each other random seeds - whether it's two users
1338 * arranging to generate the same game at the same time to
1339 * race solving them, or a user sending a bug report upstream
1340 * - the whole point is for the random game id to always be
1341 * interpreted the same way, even if it does underspecify.
1343 * A parameter string typed in on its own, with no seed _or_
1344 * description, gets treated the same way as a random seed,
1345 * because again I think the most likely reason for doing that
1346 * is to have a portable representation of a set of params.
1349 newcurparams = me->ourgame->dup_params(me->params);
1351 newcurparams = me->ourgame->default_params();
1353 me->ourgame->decode_params(newcurparams, par);
1354 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1356 me->ourgame->free_params(newcurparams);
1359 oldparams1 = me->curparams;
1362 * Now filter only the persistent parts of this state into
1363 * the long-term params structure, unless we've _only_
1364 * received a params string in which case the whole lot is
1367 oldparams2 = me->params;
1371 newparams = me->ourgame->dup_params(me->params);
1373 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1374 me->ourgame->decode_params(newparams, tmpstr);
1378 newparams = me->ourgame->dup_params(newcurparams);
1382 newcurparams = me->curparams;
1383 newparams = me->params;
1384 free_params = FALSE;
1388 error = me->ourgame->validate_desc(newparams, desc);
1392 me->ourgame->free_params(newcurparams);
1394 me->ourgame->free_params(newparams);
1401 * Now we've got past all possible error points. Update the
1404 me->params = newparams;
1405 me->curparams = newcurparams;
1407 me->ourgame->free_params(oldparams1);
1409 me->ourgame->free_params(oldparams2);
1412 sfree(me->privdesc);
1413 me->desc = me->privdesc = NULL;
1418 me->desc = dupstr(desc);
1419 me->genmode = GOT_DESC;
1420 sfree(me->aux_info);
1421 me->aux_info = NULL;
1425 me->seedstr = dupstr(seed);
1426 me->genmode = GOT_SEED;
1432 char *midend_game_id(midend *me, char *id)
1434 return midend_game_id_int(me, id, DEF_PARAMS);
1437 char *midend_get_game_id(midend *me)
1441 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1444 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1445 sprintf(ret, "%s:%s", parstr, me->desc);
1450 char *midend_get_random_seed(midend *me)
1457 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1459 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1460 sprintf(ret, "%s#%s", parstr, me->seedstr);
1465 char *midend_set_config(midend *me, int which, config_item *cfg)
1468 game_params *params;
1472 params = me->ourgame->custom_params(cfg);
1473 error = me->ourgame->validate_params(params, TRUE);
1476 me->ourgame->free_params(params);
1480 me->ourgame->free_params(me->params);
1481 me->params = params;
1486 error = midend_game_id_int(me, cfg[0].sval,
1487 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1496 int midend_can_format_as_text_now(midend *me)
1498 if (me->ourgame->can_format_as_text_ever)
1499 return me->ourgame->can_format_as_text_now(me->params);
1504 char *midend_text_format(midend *me)
1506 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1507 me->ourgame->can_format_as_text_now(me->params))
1508 return me->ourgame->text_format(me->states[me->statepos-1].state);
1513 char *midend_solve(midend *me)
1516 char *msg, *movestr;
1518 if (!me->ourgame->can_solve)
1519 return "This game does not support the Solve operation";
1521 if (me->statepos < 1)
1522 return "No game set up to solve"; /* _shouldn't_ happen! */
1525 movestr = me->ourgame->solve(me->states[0].state,
1526 me->states[me->statepos-1].state,
1527 me->aux_info, &msg);
1530 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1533 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1537 * Now enter the solved state as the next move.
1539 midend_stop_anim(me);
1540 midend_purge_states(me);
1542 me->states[me->nstates].state = s;
1543 me->states[me->nstates].movestr = movestr;
1544 me->states[me->nstates].movetype = SOLVE;
1545 me->statepos = ++me->nstates;
1547 me->ourgame->changed_state(me->ui,
1548 me->states[me->statepos-2].state,
1549 me->states[me->statepos-1].state);
1551 if (me->ourgame->flags & SOLVE_ANIMATES) {
1552 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1554 me->ourgame->anim_length(me->states[me->statepos-2].state,
1555 me->states[me->statepos-1].state,
1559 me->anim_time = 0.0;
1560 midend_finish_move(me);
1564 midend_set_timer(me);
1568 int midend_status(midend *me)
1571 * We should probably never be called when the state stack has no
1572 * states on it at all - ideally, midends should never be left in
1573 * that state for long enough to get put down and forgotten about.
1574 * But if we are, I think we return _true_ - pedantically speaking
1575 * a midend in that state is 'vacuously solved', and more
1576 * practically, a user whose midend has been left in that state
1577 * probably _does_ want the 'new game' option to be prominent.
1579 if (me->statepos == 0)
1582 return me->ourgame->status(me->states[me->statepos-1].state);
1585 char *midend_rewrite_statusbar(midend *me, char *text)
1588 * An important special case is that we are occasionally called
1589 * with our own laststatus, to update the timer.
1591 if (me->laststatus != text) {
1592 sfree(me->laststatus);
1593 me->laststatus = dupstr(text);
1596 if (me->ourgame->is_timed) {
1597 char timebuf[100], *ret;
1600 sec = (int)me->elapsed;
1603 sprintf(timebuf, "[%d:%02d] ", min, sec);
1605 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1606 strcpy(ret, timebuf);
1611 return dupstr(text);
1615 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1616 #define SERIALISE_VERSION "1"
1618 void midend_serialise(midend *me,
1619 void (*write)(void *ctx, void *buf, int len),
1625 * Each line of the save file contains three components. First
1626 * exactly 8 characters of header word indicating what type of
1627 * data is contained on the line; then a colon followed by a
1628 * decimal integer giving the length of the main string on the
1629 * line; then a colon followed by the string itself (exactly as
1630 * many bytes as previously specified, no matter what they
1631 * contain). Then a newline (of reasonably flexible form).
1633 #define wr(h,s) do { \
1637 copy_left_justified(lbuf, sizeof(lbuf), h); \
1638 sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1639 write(wctx, hbuf, strlen(hbuf)); \
1640 write(wctx, str, strlen(str)); \
1641 write(wctx, "\n", 1); \
1645 * Magic string identifying the file, and version number of the
1648 wr("SAVEFILE", SERIALISE_MAGIC);
1649 wr("VERSION", SERIALISE_VERSION);
1652 * The game name. (Copied locally to avoid const annoyance.)
1655 char *s = dupstr(me->ourgame->name);
1661 * The current long-term parameters structure, in full.
1664 char *s = me->ourgame->encode_params(me->params, TRUE);
1670 * The current short-term parameters structure, in full.
1672 if (me->curparams) {
1673 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1679 * The current game description, the privdesc, and the random seed.
1682 wr("SEED", me->seedstr);
1684 wr("DESC", me->desc);
1686 wr("PRIVDESC", me->privdesc);
1689 * The game's aux_info. We obfuscate this to prevent spoilers
1690 * (people are likely to run `head' or similar on a saved game
1691 * file simply to find out what it is, and don't necessarily
1692 * want to be told the answer to the puzzle!)
1699 len = strlen(me->aux_info);
1700 s1 = snewn(len, unsigned char);
1701 memcpy(s1, me->aux_info, len);
1702 obfuscate_bitmap(s1, len*8, FALSE);
1703 s2 = bin2hex(s1, len);
1712 * Any required serialisation of the game_ui.
1715 char *s = me->ourgame->encode_ui(me->ui);
1723 * The game time, if it's a timed game.
1725 if (me->ourgame->is_timed) {
1727 sprintf(buf, "%g", me->elapsed);
1732 * The length of, and position in, the states list.
1736 sprintf(buf, "%d", me->nstates);
1738 sprintf(buf, "%d", me->statepos);
1739 wr("STATEPOS", buf);
1743 * For each state after the initial one (which we know is
1744 * constructed from either privdesc or desc), enough
1745 * information for execute_move() to reconstruct it from the
1748 for (i = 1; i < me->nstates; i++) {
1749 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1750 switch (me->states[i].movetype) {
1752 wr("MOVE", me->states[i].movestr);
1755 wr("SOLVE", me->states[i].movestr);
1758 wr("RESTART", me->states[i].movestr);
1767 * This function returns NULL on success, or an error message.
1769 char *midend_deserialise(midend *me,
1770 int (*read)(void *ctx, void *buf, int len),
1773 struct deserialise_data data;
1775 int started = FALSE;
1779 /* Initially all errors give the same report */
1780 char *ret = "Data does not appear to be a saved game file";
1782 data.seed = data.parstr = data.desc = data.privdesc = NULL;
1783 data.auxinfo = data.uistr = data.cparstr = NULL;
1784 data.elapsed = 0.0F;
1785 data.params = data.cparams = NULL;
1792 * Loop round and round reading one key/value pair at a time
1793 * from the serialised stream, until we have enough game states
1796 while (data.nstates <= 0 || data.statepos < 0 ||
1797 gotstates < data.nstates-1) {
1802 if (!read(rctx, key, 1)) {
1803 /* unexpected EOF */
1806 } while (key[0] == '\r' || key[0] == '\n');
1808 if (!read(rctx, key+1, 8)) {
1809 /* unexpected EOF */
1813 if (key[8] != ':') {
1815 ret = "Data was incorrectly formatted for a saved game file";
1818 len = strcspn(key, ": ");
1824 if (!read(rctx, &c, 1)) {
1825 /* unexpected EOF */
1831 } else if (c >= '0' && c <= '9') {
1832 len = (len * 10) + (c - '0');
1835 ret = "Data was incorrectly formatted for a"
1841 val = snewn(len+1, char);
1842 if (!read(rctx, val, len)) {
1849 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1850 /* ret already has the right message in it */
1853 /* Now most errors are this one, unless otherwise specified */
1854 ret = "Saved data ended unexpectedly";
1857 if (!strcmp(key, "VERSION")) {
1858 if (strcmp(val, SERIALISE_VERSION)) {
1859 ret = "Cannot handle this version of the saved game"
1863 } else if (!strcmp(key, "GAME")) {
1864 if (strcmp(val, me->ourgame->name)) {
1865 ret = "Save file is from a different game";
1868 } else if (!strcmp(key, "PARAMS")) {
1872 } else if (!strcmp(key, "CPARAMS")) {
1873 sfree(data.cparstr);
1876 } else if (!strcmp(key, "SEED")) {
1880 } else if (!strcmp(key, "DESC")) {
1884 } else if (!strcmp(key, "PRIVDESC")) {
1885 sfree(data.privdesc);
1886 data.privdesc = val;
1888 } else if (!strcmp(key, "AUXINFO")) {
1890 int len = strlen(val) / 2; /* length in bytes */
1891 tmp = hex2bin(val, len);
1892 obfuscate_bitmap(tmp, len*8, TRUE);
1894 sfree(data.auxinfo);
1895 data.auxinfo = snewn(len + 1, char);
1896 memcpy(data.auxinfo, tmp, len);
1897 data.auxinfo[len] = '\0';
1899 } else if (!strcmp(key, "UI")) {
1903 } else if (!strcmp(key, "TIME")) {
1904 data.elapsed = (float)atof(val);
1905 } else if (!strcmp(key, "NSTATES")) {
1906 data.nstates = atoi(val);
1907 if (data.nstates <= 0) {
1908 ret = "Number of states in save file was negative";
1912 ret = "Two state counts provided in save file";
1915 data.states = snewn(data.nstates, struct midend_state_entry);
1916 for (i = 0; i < data.nstates; i++) {
1917 data.states[i].state = NULL;
1918 data.states[i].movestr = NULL;
1919 data.states[i].movetype = NEWGAME;
1921 } else if (!strcmp(key, "STATEPOS")) {
1922 data.statepos = atoi(val);
1923 } else if (!strcmp(key, "MOVE")) {
1925 data.states[gotstates].movetype = MOVE;
1926 data.states[gotstates].movestr = val;
1928 } else if (!strcmp(key, "SOLVE")) {
1930 data.states[gotstates].movetype = SOLVE;
1931 data.states[gotstates].movestr = val;
1933 } else if (!strcmp(key, "RESTART")) {
1935 data.states[gotstates].movetype = RESTART;
1936 data.states[gotstates].movestr = val;
1945 data.params = me->ourgame->default_params();
1946 me->ourgame->decode_params(data.params, data.parstr);
1947 if (me->ourgame->validate_params(data.params, TRUE)) {
1948 ret = "Long-term parameters in save file are invalid";
1951 data.cparams = me->ourgame->default_params();
1952 me->ourgame->decode_params(data.cparams, data.cparstr);
1953 if (me->ourgame->validate_params(data.cparams, FALSE)) {
1954 ret = "Short-term parameters in save file are invalid";
1957 if (data.seed && me->ourgame->validate_params(data.cparams, TRUE)) {
1959 * The seed's no use with this version, but we can perfectly
1960 * well use the rest of the data.
1966 ret = "Game description in save file is missing";
1968 } else if (me->ourgame->validate_desc(data.cparams, data.desc)) {
1969 ret = "Game description in save file is invalid";
1972 if (data.privdesc &&
1973 me->ourgame->validate_desc(data.cparams, data.privdesc)) {
1974 ret = "Game private description in save file is invalid";
1977 if (data.statepos < 0 || data.statepos >= data.nstates) {
1978 ret = "Game position in save file is out of range";
1981 data.states[0].state = me->ourgame->new_game(
1982 me, data.cparams, data.privdesc ? data.privdesc : data.desc);
1983 for (i = 1; i < data.nstates; i++) {
1984 assert(data.states[i].movetype != NEWGAME);
1985 switch (data.states[i].movetype) {
1988 data.states[i].state = me->ourgame->execute_move(
1989 data.states[i-1].state, data.states[i].movestr);
1990 if (data.states[i].state == NULL) {
1991 ret = "Save file contained an invalid move";
1996 if (me->ourgame->validate_desc(
1997 data.cparams, data.states[i].movestr)) {
1998 ret = "Save file contained an invalid restart move";
2001 data.states[i].state = me->ourgame->new_game(
2002 me, data.cparams, data.states[i].movestr);
2007 data.ui = me->ourgame->new_ui(data.states[0].state);
2008 me->ourgame->decode_ui(data.ui, data.uistr);
2011 * Now we've run out of possible error conditions, so we're
2012 * ready to start overwriting the real data in the current
2013 * midend. We'll do this by swapping things with the local
2014 * variables, so that the same cleanup code will free the old
2021 me->desc = data.desc;
2025 me->privdesc = data.privdesc;
2026 data.privdesc = tmp;
2029 me->seedstr = data.seed;
2033 me->aux_info = data.auxinfo;
2037 me->genmode = GOT_NOTHING;
2039 me->statesize = data.nstates;
2040 data.nstates = me->nstates;
2041 me->nstates = me->statesize;
2043 struct midend_state_entry *tmp;
2045 me->states = data.states;
2048 me->statepos = data.statepos;
2054 me->params = data.params;
2057 tmp = me->curparams;
2058 me->curparams = data.cparams;
2062 me->oldstate = NULL;
2063 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2074 me->elapsed = data.elapsed;
2075 me->pressed_mouse_button = 0;
2077 midend_set_timer(me);
2080 me->ourgame->free_drawstate(me->drawing, me->drawstate);
2082 me->ourgame->new_drawstate(me->drawing,
2083 me->states[me->statepos-1].state);
2084 midend_size_new_drawstate(me);
2085 if (me->game_id_change_notify_function)
2086 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2088 ret = NULL; /* success! */
2094 sfree(data.cparstr);
2096 sfree(data.privdesc);
2097 sfree(data.auxinfo);
2100 me->ourgame->free_params(data.params);
2102 me->ourgame->free_params(data.cparams);
2104 me->ourgame->free_ui(data.ui);
2108 for (i = 0; i < data.nstates; i++) {
2109 if (data.states[i].state)
2110 me->ourgame->free_game(data.states[i].state);
2111 sfree(data.states[i].movestr);
2120 * This function examines a saved game file just far enough to
2121 * determine which game type it contains. It returns NULL on success
2122 * and the game name string in 'name' (which will be dynamically
2123 * allocated and should be caller-freed), or an error message on
2126 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2129 int nstates = 0, statepos = -1, gotstates = 0;
2130 int started = FALSE;
2133 /* Initially all errors give the same report */
2134 char *ret = "Data does not appear to be a saved game file";
2139 * Loop round and round reading one key/value pair at a time from
2140 * the serialised stream, until we've found the game name.
2142 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2147 if (!read(rctx, key, 1)) {
2148 /* unexpected EOF */
2151 } while (key[0] == '\r' || key[0] == '\n');
2153 if (!read(rctx, key+1, 8)) {
2154 /* unexpected EOF */
2158 if (key[8] != ':') {
2160 ret = "Data was incorrectly formatted for a saved game file";
2163 len = strcspn(key, ": ");
2169 if (!read(rctx, &c, 1)) {
2170 /* unexpected EOF */
2176 } else if (c >= '0' && c <= '9') {
2177 len = (len * 10) + (c - '0');
2180 ret = "Data was incorrectly formatted for a"
2186 val = snewn(len+1, char);
2187 if (!read(rctx, val, len)) {
2194 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2195 /* ret already has the right message in it */
2198 /* Now most errors are this one, unless otherwise specified */
2199 ret = "Saved data ended unexpectedly";
2202 if (!strcmp(key, "VERSION")) {
2203 if (strcmp(val, SERIALISE_VERSION)) {
2204 ret = "Cannot handle this version of the saved game"
2208 } else if (!strcmp(key, "GAME")) {
2209 *name = dupstr(val);
2224 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2226 game_state *soln = NULL;
2228 if (me->statepos < 1)
2229 return "No game set up to print";/* _shouldn't_ happen! */
2232 char *msg, *movestr;
2234 if (!me->ourgame->can_solve)
2235 return "This game does not support the Solve operation";
2237 msg = "Solve operation failed";/* game _should_ overwrite on error */
2238 movestr = me->ourgame->solve(me->states[0].state,
2239 me->states[me->statepos-1].state,
2240 me->aux_info, &msg);
2243 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2252 * This call passes over ownership of the two game_states and
2253 * the game_params. Hence we duplicate the ones we want to
2254 * keep, and we don't have to bother freeing soln if it was
2257 document_add_puzzle(doc, me->ourgame,
2258 me->ourgame->dup_params(me->curparams),
2259 me->ourgame->dup_game(me->states[0].state), soln);