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); \
97 void midend_reset_tilesize(midend *me)
99 me->preferred_tilesize = me->ourgame->preferred_tilesize;
102 * Allow an environment-based override for the default tile
103 * size by defining a variable along the lines of
110 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
111 for (j = k = 0; buf[j]; j++)
112 if (!isspace((unsigned char)buf[j]))
113 buf[k++] = toupper((unsigned char)buf[j]);
115 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
116 me->preferred_tilesize = ts;
120 midend *midend_new(frontend *fe, const game *ourgame,
121 const drawing_api *drapi, void *drhandle)
123 midend *me = snew(midend);
127 get_random_seed(&randseed, &randseedsize);
130 me->ourgame = ourgame;
131 me->random = random_new(randseed, randseedsize);
132 me->nstates = me->statesize = me->statepos = 0;
134 me->params = ourgame->default_params();
135 me->game_id_change_notify_function = NULL;
136 me->game_id_change_notify_ctx = NULL;
139 * Allow environment-based changing of the default settings by
140 * defining a variable along the lines of `NET_DEFAULT=25x25w'
141 * in which the value is an encoded parameter string.
146 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
147 for (j = k = 0; buf[j]; j++)
148 if (!isspace((unsigned char)buf[j]))
149 buf[k++] = toupper((unsigned char)buf[j]);
151 if ((e = getenv(buf)) != NULL)
152 me->ourgame->decode_params(me->params, e);
154 me->curparams = NULL;
155 me->desc = me->privdesc = NULL;
158 me->genmode = GOT_NOTHING;
159 me->drawstate = NULL;
161 me->preset_menu = NULL;
162 me->anim_time = me->anim_pos = 0.0F;
163 me->flash_time = me->flash_pos = 0.0F;
166 me->pressed_mouse_button = 0;
167 me->laststatus = NULL;
170 me->tilesize = me->winwidth = me->winheight = 0;
172 me->drawing = drawing_new(drapi, me, drhandle);
176 midend_reset_tilesize(me);
183 const game *midend_which_game(midend *me)
188 static void midend_purge_states(midend *me)
190 while (me->nstates > me->statepos) {
191 me->ourgame->free_game(me->states[--me->nstates].state);
192 if (me->states[me->nstates].movestr)
193 sfree(me->states[me->nstates].movestr);
197 static void midend_free_game(midend *me)
199 while (me->nstates > 0) {
201 me->ourgame->free_game(me->states[me->nstates].state);
202 sfree(me->states[me->nstates].movestr);
206 me->ourgame->free_drawstate(me->drawing, me->drawstate);
209 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
213 for (i = 0; i < menu->n_entries; i++) {
214 sfree(menu->entries[i].title);
215 if (menu->entries[i].params)
216 me->ourgame->free_params(menu->entries[i].params);
217 midend_free_preset_menu(me, menu->entries[i].submenu);
219 sfree(menu->entries);
224 void midend_free(midend *me)
226 midend_free_game(me);
229 drawing_free(me->drawing);
230 random_free(me->random);
236 me->ourgame->free_params(me->params);
237 midend_free_preset_menu(me, me->preset_menu);
239 me->ourgame->free_ui(me->ui);
241 me->ourgame->free_params(me->curparams);
242 sfree(me->laststatus);
246 static void midend_size_new_drawstate(midend *me)
249 * Don't even bother, if we haven't worked out our tile size
252 if (me->tilesize > 0) {
253 me->ourgame->compute_size(me->params, me->tilesize,
254 &me->winwidth, &me->winheight);
255 me->ourgame->set_size(me->drawing, me->drawstate,
256 me->params, me->tilesize);
260 void midend_size(midend *me, int *x, int *y, int user_size)
266 * We can't set the size on the same drawstate twice. So if
267 * we've already sized one drawstate, we must throw it away and
270 if (me->drawstate && me->tilesize > 0) {
271 me->ourgame->free_drawstate(me->drawing, me->drawstate);
272 me->drawstate = me->ourgame->new_drawstate(me->drawing,
273 me->states[0].state);
277 * Find the tile size that best fits within the given space. If
278 * `user_size' is TRUE, we must actually find the _largest_ such
279 * tile size, in order to get as close to the user's explicit
280 * request as possible; otherwise, we bound above at the game's
281 * preferred tile size, so that the game gets what it wants
282 * provided that this doesn't break the constraint from the
283 * front-end (which is likely to be a screen size or similar).
289 me->ourgame->compute_size(me->params, max, &rx, &ry);
290 } while (rx <= *x && ry <= *y);
292 max = me->preferred_tilesize + 1;
296 * Now binary-search between min and max. We're looking for a
297 * boundary rather than a value: the point at which tile sizes
298 * stop fitting within the given dimensions. Thus, we stop when
299 * max and min differ by exactly 1.
301 while (max - min > 1) {
302 int mid = (max + min) / 2;
303 me->ourgame->compute_size(me->params, mid, &rx, &ry);
304 if (rx <= *x && ry <= *y)
311 * Now `min' is a valid size, and `max' isn't. So use `min'.
316 /* If the user requested a change in size, make it permanent. */
317 me->preferred_tilesize = me->tilesize;
318 midend_size_new_drawstate(me);
323 int midend_tilesize(midend *me) { return me->tilesize; }
325 void midend_set_params(midend *me, game_params *params)
327 me->ourgame->free_params(me->params);
328 me->params = me->ourgame->dup_params(params);
331 game_params *midend_get_params(midend *me)
333 return me->ourgame->dup_params(me->params);
336 static void midend_set_timer(midend *me)
338 me->timing = (me->ourgame->is_timed &&
339 me->ourgame->timing_state(me->states[me->statepos-1].state,
341 if (me->timing || me->flash_time || me->anim_time)
342 activate_timer(me->frontend);
344 deactivate_timer(me->frontend);
347 void midend_force_redraw(midend *me)
350 me->ourgame->free_drawstate(me->drawing, me->drawstate);
351 me->drawstate = me->ourgame->new_drawstate(me->drawing,
352 me->states[0].state);
353 midend_size_new_drawstate(me);
357 void midend_new_game(midend *me)
359 midend_stop_anim(me);
360 midend_free_game(me);
362 assert(me->nstates == 0);
364 if (me->genmode == GOT_DESC) {
365 me->genmode = GOT_NOTHING;
369 if (me->genmode == GOT_SEED) {
370 me->genmode = GOT_NOTHING;
373 * Generate a new random seed. 15 digits comes to about
374 * 48 bits, which should be more than enough.
376 * I'll avoid putting a leading zero on the number,
377 * just in case it confuses anybody who thinks it's
378 * processed as an integer rather than a string.
383 newseed[0] = '1' + (char)random_upto(me->random, 9);
384 for (i = 1; i < 15; i++)
385 newseed[i] = '0' + (char)random_upto(me->random, 10);
387 me->seedstr = dupstr(newseed);
390 me->ourgame->free_params(me->curparams);
391 me->curparams = me->ourgame->dup_params(me->params);
399 rs = random_new(me->seedstr, strlen(me->seedstr));
401 * If this midend has been instantiated without providing a
402 * drawing API, it is non-interactive. This means that it's
403 * being used for bulk game generation, and hence we should
404 * pass the non-interactive flag to new_desc.
406 me->desc = me->ourgame->new_desc(me->curparams, rs,
407 &me->aux_info, (me->drawing != NULL));
415 * It might seem a bit odd that we're using me->params to
416 * create the initial game state, rather than me->curparams
417 * which is better tailored to this specific game and which we
420 * It's supposed to be an invariant in the midend that
421 * me->params and me->curparams differ in no aspect that is
422 * important after generation (i.e. after new_desc()). By
423 * deliberately passing the _less_ specific of these two
424 * parameter sets, we provoke play-time misbehaviour in the
425 * case where a game has failed to encode a play-time parameter
426 * in the non-full version of encode_params().
428 me->states[me->nstates].state =
429 me->ourgame->new_game(me, me->params, me->desc);
432 * As part of our commitment to self-testing, test the aux
433 * string to make sure nothing ghastly went wrong.
435 if (me->ourgame->can_solve && me->aux_info) {
440 movestr = me->ourgame->solve(me->states[0].state,
443 assert(movestr && !msg);
444 s = me->ourgame->execute_move(me->states[0].state, movestr);
446 me->ourgame->free_game(s);
450 me->states[me->nstates].movestr = NULL;
451 me->states[me->nstates].movetype = NEWGAME;
454 me->drawstate = me->ourgame->new_drawstate(me->drawing,
455 me->states[0].state);
456 midend_size_new_drawstate(me);
458 me->flash_pos = me->flash_time = 0.0F;
459 me->anim_pos = me->anim_time = 0.0F;
461 me->ourgame->free_ui(me->ui);
462 me->ui = me->ourgame->new_ui(me->states[0].state);
463 midend_set_timer(me);
464 me->pressed_mouse_button = 0;
466 if (me->game_id_change_notify_function)
467 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
470 int midend_can_undo(midend *me)
472 return (me->statepos > 1);
475 int midend_can_redo(midend *me)
477 return (me->statepos < me->nstates);
480 static int midend_undo(midend *me)
482 if (me->statepos > 1) {
484 me->ourgame->changed_state(me->ui,
485 me->states[me->statepos-1].state,
486 me->states[me->statepos-2].state);
494 static int midend_redo(midend *me)
496 if (me->statepos < me->nstates) {
498 me->ourgame->changed_state(me->ui,
499 me->states[me->statepos-1].state,
500 me->states[me->statepos].state);
508 static void midend_finish_move(midend *me)
513 * We do not flash if the later of the two states is special.
514 * This covers both forward Solve moves and backward (undone)
517 if ((me->oldstate || me->statepos > 1) &&
518 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
519 (me->dir < 0 && me->statepos < me->nstates &&
520 !special(me->states[me->statepos].movetype)))) {
521 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
522 me->states[me->statepos-2].state,
523 me->states[me->statepos-1].state,
524 me->oldstate ? me->dir : +1,
527 me->flash_pos = 0.0F;
528 me->flash_time = flashtime;
533 me->ourgame->free_game(me->oldstate);
535 me->anim_pos = me->anim_time = 0;
538 midend_set_timer(me);
541 void midend_stop_anim(midend *me)
543 if (me->oldstate || me->anim_time != 0) {
544 midend_finish_move(me);
549 void midend_restart_game(midend *me)
553 assert(me->statepos >= 1);
554 if (me->statepos == 1)
555 return; /* no point doing anything at all! */
558 * During restart, we reconstruct the game from the (public)
559 * game description rather than from states[0], because that
560 * way Mines gets slightly more sensible behaviour (restart
561 * goes to _after_ the first click so you don't have to
562 * remember where you clicked).
564 s = me->ourgame->new_game(me, me->params, me->desc);
567 * Now enter the restarted state as the next move.
569 midend_stop_anim(me);
570 midend_purge_states(me);
572 me->states[me->nstates].state = s;
573 me->states[me->nstates].movestr = dupstr(me->desc);
574 me->states[me->nstates].movetype = RESTART;
575 me->statepos = ++me->nstates;
577 me->ourgame->changed_state(me->ui,
578 me->states[me->statepos-2].state,
579 me->states[me->statepos-1].state);
580 me->flash_pos = me->flash_time = 0.0F;
581 midend_finish_move(me);
583 midend_set_timer(me);
586 static int midend_really_process_key(midend *me, int x, int y, int button)
588 game_state *oldstate =
589 me->ourgame->dup_game(me->states[me->statepos - 1].state);
590 int type = MOVE, gottype = FALSE, ret = 1;
593 char *movestr = NULL;
595 if (!IS_UI_FAKE_KEY(button)) {
596 movestr = me->ourgame->interpret_move(
597 me->states[me->statepos-1].state,
598 me->ui, me->drawstate, x, y, button);
602 if (button == 'n' || button == 'N' || button == '\x0E' ||
603 button == UI_NEWGAME) {
606 goto done; /* never animate */
607 } else if (button == 'u' || button == 'U' ||
608 button == '\x1A' || button == '\x1F' ||
610 midend_stop_anim(me);
611 type = me->states[me->statepos-1].movetype;
613 if (!midend_undo(me))
615 } else if (button == 'r' || button == 'R' ||
616 button == '\x12' || button == '\x19' ||
618 midend_stop_anim(me);
619 if (!midend_redo(me))
621 } else if ((button == '\x13' || button == UI_SOLVE) &&
622 me->ourgame->can_solve) {
623 if (midend_solve(me))
625 } else if (button == 'q' || button == 'Q' || button == '\x11' ||
633 s = me->states[me->statepos-1].state;
635 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
640 if (s == me->states[me->statepos-1].state) {
642 * make_move() is allowed to return its input state to
643 * indicate that although no move has been made, the UI
644 * state has been updated and a redraw is called for.
647 midend_set_timer(me);
650 midend_stop_anim(me);
651 midend_purge_states(me);
653 assert(movestr != NULL);
654 me->states[me->nstates].state = s;
655 me->states[me->nstates].movestr = movestr;
656 me->states[me->nstates].movetype = MOVE;
657 me->statepos = ++me->nstates;
660 me->ourgame->changed_state(me->ui,
661 me->states[me->statepos-2].state,
662 me->states[me->statepos-1].state);
669 type = me->states[me->statepos-1].movetype;
672 * See if this move requires an animation.
674 if (special(type) && !(type == SOLVE &&
675 (me->ourgame->flags & SOLVE_ANIMATES))) {
678 anim_time = me->ourgame->anim_length(oldstate,
679 me->states[me->statepos-1].state,
683 me->oldstate = oldstate; oldstate = NULL;
685 me->anim_time = anim_time;
688 midend_finish_move(me);
694 midend_set_timer(me);
697 if (oldstate) me->ourgame->free_game(oldstate);
701 int midend_process_key(midend *me, int x, int y, int button)
706 * Harmonise mouse drag and release messages.
708 * Some front ends might accidentally switch from sending, say,
709 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
710 * drag. (This can happen on the Mac, for example, since
711 * RIGHT_DRAG is usually done using Command+drag, and if the
712 * user accidentally releases Command half way through the drag
713 * then there will be trouble.)
715 * It would be an O(number of front ends) annoyance to fix this
716 * in the front ends, but an O(number of back ends) annoyance
717 * to have each game capable of dealing with it. Therefore, we
718 * fix it _here_ in the common midend code so that it only has
721 * The possible ways in which things can go screwy in the front
724 * - in a system containing multiple physical buttons button
725 * presses can inadvertently overlap. We can see ABab (caps
726 * meaning button-down and lowercase meaning button-up) when
727 * the user had semantically intended AaBb.
729 * - in a system where one button is simulated by means of a
730 * modifier key and another button, buttons can mutate
731 * between press and release (possibly during drag). So we
732 * can see Ab instead of Aa.
734 * Definite requirements are:
736 * - button _presses_ must never be invented or destroyed. If
737 * the user presses two buttons in succession, the button
738 * presses must be transferred to the backend unchanged. So
739 * if we see AaBb , that's fine; if we see ABab (the button
740 * presses inadvertently overlapped) we must somehow
741 * `correct' it to AaBb.
743 * - every mouse action must end up looking like a press, zero
744 * or more drags, then a release. This allows back ends to
745 * make the _assumption_ that incoming mouse data will be
746 * sane in this regard, and not worry about the details.
748 * So my policy will be:
750 * - treat any button-up as a button-up for the currently
751 * pressed button, or ignore it if there is no currently
754 * - treat any drag as a drag for the currently pressed
755 * button, or ignore it if there is no currently pressed
758 * - if we see a button-down while another button is currently
759 * pressed, invent a button-up for the first one and then
760 * pass the button-down through as before.
762 * 2005-05-31: An addendum to the above. Some games might want
763 * a `priority order' among buttons, such that if one button is
764 * pressed while another is down then a fixed one of the
765 * buttons takes priority no matter what order they're pressed
766 * in. Mines, in particular, wants to treat a left+right click
767 * like a left click for the benefit of users of other
768 * implementations. So the last of the above points is modified
769 * in the presence of an (optional) button priority order.
771 * A further addition: we translate certain keyboard presses to
772 * cursor key 'select' buttons, so that a) frontends don't have
773 * to translate these themselves (like they do for CURSOR_UP etc),
774 * and b) individual games don't have to hard-code button presses
775 * of '\n' etc for keyboard-based cursors. The choice of buttons
776 * here could eventually be controlled by a runtime configuration
779 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
780 if (me->pressed_mouse_button) {
781 if (IS_MOUSE_DRAG(button)) {
782 button = me->pressed_mouse_button +
783 (LEFT_DRAG - LEFT_BUTTON);
785 button = me->pressed_mouse_button +
786 (LEFT_RELEASE - LEFT_BUTTON);
789 return ret; /* ignore it */
790 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
792 * If the new button has lower priority than the old one,
793 * don't bother doing this.
795 if (me->ourgame->flags &
796 BUTTON_BEATS(me->pressed_mouse_button, button))
797 return ret; /* just ignore it */
800 * Fabricate a button-up for the previously pressed button.
802 ret = ret && midend_really_process_key
803 (me, x, y, (me->pressed_mouse_button +
804 (LEFT_RELEASE - LEFT_BUTTON)));
808 * Translate keyboard presses to cursor selection.
810 if (button == '\n' || button == '\r')
811 button = CURSOR_SELECT;
813 button = CURSOR_SELECT2;
816 * Normalise both backspace characters (8 and 127) to \b. Easier
817 * to do this once, here, than to require all front ends to
818 * carefully generate the same one - now each front end can
819 * generate whichever is easiest.
821 if (button == '\177')
825 * Now send on the event we originally received.
827 ret = ret && midend_really_process_key(me, x, y, button);
830 * And update the currently pressed button.
832 if (IS_MOUSE_RELEASE(button))
833 me->pressed_mouse_button = 0;
834 else if (IS_MOUSE_DOWN(button))
835 me->pressed_mouse_button = button;
840 void midend_redraw(midend *me)
844 if (me->statepos > 0 && me->drawstate) {
845 start_draw(me->drawing);
846 if (me->oldstate && me->anim_time > 0 &&
847 me->anim_pos < me->anim_time) {
848 assert(me->dir != 0);
849 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
850 me->states[me->statepos-1].state, me->dir,
851 me->ui, me->anim_pos, me->flash_pos);
853 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
854 me->states[me->statepos-1].state, +1 /*shrug*/,
855 me->ui, 0.0, me->flash_pos);
857 end_draw(me->drawing);
862 * Nasty hacky function used to implement the --redo option in
863 * gtk.c. Only used for generating the puzzles' icons.
865 void midend_freeze_timer(midend *me, float tprop)
867 me->anim_pos = me->anim_time * tprop;
869 deactivate_timer(me->frontend);
872 void midend_timer(midend *me, float tplus)
874 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
876 me->anim_pos += tplus;
877 if (me->anim_pos >= me->anim_time ||
878 me->anim_time == 0 || !me->oldstate) {
879 if (me->anim_time > 0)
880 midend_finish_move(me);
883 me->flash_pos += tplus;
884 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
885 me->flash_pos = me->flash_time = 0;
892 float oldelapsed = me->elapsed;
893 me->elapsed += tplus;
894 if ((int)oldelapsed != (int)me->elapsed)
895 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
898 midend_set_timer(me);
901 float *midend_colours(midend *me, int *ncolours)
905 ret = me->ourgame->colours(me->frontend, ncolours);
911 * Allow environment-based overrides for the standard
912 * colours by defining variables along the lines of
913 * `NET_COLOUR_4=6000c0'.
916 for (i = 0; i < *ncolours; i++) {
918 unsigned int r, g, b;
921 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
922 for (j = k = 0; buf[j]; j++)
923 if (!isspace((unsigned char)buf[j]))
924 buf[k++] = toupper((unsigned char)buf[j]);
926 if ((e = getenv(buf)) != NULL &&
927 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
928 ret[i*3 + 0] = r / 255.0F;
929 ret[i*3 + 1] = g / 255.0F;
930 ret[i*3 + 2] = b / 255.0F;
938 struct preset_menu *preset_menu_new(void)
940 struct preset_menu *menu = snew(struct preset_menu);
942 menu->entries_size = 0;
943 menu->entries = NULL;
947 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
950 struct preset_menu_entry *toret;
951 if (menu->n_entries >= menu->entries_size) {
952 menu->entries_size = menu->n_entries * 5 / 4 + 10;
953 menu->entries = sresize(menu->entries, menu->entries_size,
954 struct preset_menu_entry);
956 toret = &menu->entries[menu->n_entries++];
957 toret->title = title;
958 toret->params = NULL;
959 toret->submenu = NULL;
963 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
966 struct preset_menu_entry *entry = preset_menu_add(parent, title);
967 entry->submenu = preset_menu_new();
968 return entry->submenu;
971 void preset_menu_add_preset(struct preset_menu *parent,
972 char *title, game_params *params)
974 struct preset_menu_entry *entry = preset_menu_add(parent, title);
975 entry->params = params;
978 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
983 for (i = 0; i < menu->n_entries; i++) {
984 if (id == menu->entries[i].id)
985 return menu->entries[i].params;
986 if (menu->entries[i].submenu &&
987 (retd = preset_menu_lookup_by_id(
988 menu->entries[i].submenu, id)) != NULL)
995 static char *preset_menu_add_from_user_env(
996 midend *me, struct preset_menu *menu, char *p, int top_level)
1000 game_params *preset;
1003 while (*p && *p != ':') p++;
1004 if (*p) *p++ = '\0';
1006 while (*p && *p != ':') p++;
1007 if (*p) *p++ = '\0';
1009 if (!strcmp(val, "#")) {
1011 * Special case: either open a new submenu with the given
1012 * title, or terminate the current submenu.
1015 struct preset_menu *submenu =
1016 preset_menu_add_submenu(menu, dupstr(name));
1017 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1020 * If we get a 'close submenu' indication at the top
1021 * level, there's not much we can do but quietly
1030 preset = me->ourgame->default_params();
1031 me->ourgame->decode_params(preset, val);
1033 if (me->ourgame->validate_params(preset, TRUE)) {
1034 /* Drop this one from the list. */
1035 me->ourgame->free_params(preset);
1039 preset_menu_add_preset(menu, dupstr(name), preset);
1045 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1049 for (i = 0; i < menu->n_entries; i++)
1050 menu->entries[i].id = me->n_encoded_presets++;
1052 for (i = 0; i < menu->n_entries; i++)
1053 if (menu->entries[i].submenu)
1054 preset_menu_alloc_ids(me, menu->entries[i].submenu);
1057 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1061 for (i = 0; i < menu->n_entries; i++) {
1062 if (menu->entries[i].params) {
1063 me->encoded_presets[menu->entries[i].id] =
1064 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1066 preset_menu_encode_params(me, menu->entries[i].submenu);
1071 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1075 if (me->preset_menu)
1076 return me->preset_menu;
1079 /* Expect the game to implement exactly one of the two preset APIs */
1080 assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1081 assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1084 if (me->ourgame->fetch_preset) {
1086 game_params *preset;
1088 /* Simple one-level menu */
1089 assert(!me->ourgame->preset_menu);
1090 me->preset_menu = preset_menu_new();
1091 for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1092 preset_menu_add_preset(me->preset_menu, name, preset);
1095 /* Hierarchical menu provided by the game backend */
1096 me->preset_menu = me->ourgame->preset_menu();
1101 * Allow user extensions to the preset list by defining an
1102 * environment variable <gamename>_PRESETS whose value is a
1103 * colon-separated list of items, alternating between textual
1104 * titles in the menu and encoded parameter strings. For
1105 * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1106 * just one additional preset for Solo.
1111 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1112 for (j = k = 0; buf[j]; j++)
1113 if (!isspace((unsigned char)buf[j]))
1114 buf[k++] = toupper((unsigned char)buf[j]);
1117 if ((e = getenv(buf)) != NULL) {
1119 preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1125 * Finalise the menu: allocate an integer id to each entry, and
1126 * store string encodings of the presets' parameters in
1127 * me->encoded_presets.
1129 me->n_encoded_presets = 0;
1130 preset_menu_alloc_ids(me, me->preset_menu);
1131 me->encoded_presets = snewn(me->n_encoded_presets, char *);
1132 for (i = 0; i < me->n_encoded_presets; i++)
1133 me->encoded_presets[i] = NULL;
1134 preset_menu_encode_params(me, me->preset_menu);
1137 *id_limit = me->n_encoded_presets;
1138 return me->preset_menu;
1141 int midend_which_preset(midend *me)
1143 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1147 for (i = 0; i < me->n_encoded_presets; i++)
1148 if (me->encoded_presets[i] &&
1149 !strcmp(encoding, me->encoded_presets[i])) {
1158 int midend_wants_statusbar(midend *me)
1160 return me->ourgame->wants_statusbar;
1163 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1165 me->game_id_change_notify_function = notify;
1166 me->game_id_change_notify_ctx = ctx;
1169 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1172 sfree(me->privdesc);
1173 me->desc = dupstr(desc);
1174 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1175 if (me->game_id_change_notify_function)
1176 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1179 config_item *midend_get_config(midend *me, int which, char **wintitle)
1181 char *titlebuf, *parstr, *rest;
1186 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1190 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1191 *wintitle = titlebuf;
1192 return me->ourgame->configure(me->params);
1195 if (!me->curparams) {
1199 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1200 which == CFG_SEED ? "random" : "game");
1201 *wintitle = titlebuf;
1203 ret = snewn(2, config_item);
1205 ret[0].type = C_STRING;
1206 if (which == CFG_SEED)
1207 ret[0].name = "Game random seed";
1209 ret[0].name = "Game ID";
1212 * For CFG_DESC the text going in here will be a string
1213 * encoding of the restricted parameters, plus a colon,
1214 * plus the game description. For CFG_SEED it will be the
1215 * full parameters, plus a hash, plus the random seed data.
1216 * Either of these is a valid full game ID (although only
1217 * the former is likely to persist across many code
1220 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1222 if (which == CFG_DESC) {
1223 rest = me->desc ? me->desc : "";
1226 rest = me->seedstr ? me->seedstr : "";
1229 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1230 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1233 ret[1].type = C_END;
1234 ret[1].name = ret[1].sval = NULL;
1240 assert(!"We shouldn't be here");
1244 static char *midend_game_id_int(midend *me, char *id, int defmode)
1246 char *error, *par, *desc, *seed;
1247 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1250 seed = strchr(id, '#');
1251 desc = strchr(id, ':');
1253 if (desc && (!seed || desc < seed)) {
1255 * We have a colon separating parameters from game
1256 * description. So `par' now points to the parameters
1257 * string, and `desc' to the description string.
1262 } else if (seed && (!desc || seed < desc)) {
1264 * We have a hash separating parameters from random seed.
1265 * So `par' now points to the parameters string, and `seed'
1266 * to the seed string.
1273 * We only have one string. Depending on `defmode', we take
1274 * it to be either parameters, seed or description.
1276 if (defmode == DEF_SEED) {
1279 } else if (defmode == DEF_DESC) {
1289 * We must be reasonably careful here not to modify anything in
1290 * `me' until we have finished validating things. This function
1291 * must either return an error and do nothing to the midend, or
1292 * return success and do everything; nothing in between is
1295 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1299 * The params string may underspecify the game parameters, so
1300 * we must first initialise newcurparams with a full set of
1301 * params from somewhere else before we decode_params the
1302 * input string over the top.
1304 * But which set? It depends on what other data we have.
1306 * If we've been given a _descriptive_ game id, then that may
1307 * well underspecify by design, e.g. Solo game descriptions
1308 * often start just '3x3:' without specifying one of Solo's
1309 * difficulty settings, because it isn't necessary once a game
1310 * has been generated (and you might not even know it, if
1311 * you're manually transcribing a game description). In that
1312 * situation, I've always felt that the best thing to set the
1313 * difficulty to (for use if the user hits 'New Game' after
1314 * pasting in that game id) is whatever it was previously set
1315 * to. That is, we use whatever is already in me->params as
1316 * the basis for our decoding of this input string.
1318 * A random-seed based game id, however, should use the real,
1319 * built-in default params, and not even check the
1320 * <game>_DEFAULT environment setting, because when people
1321 * paste each other random seeds - whether it's two users
1322 * arranging to generate the same game at the same time to
1323 * race solving them, or a user sending a bug report upstream
1324 * - the whole point is for the random game id to always be
1325 * interpreted the same way, even if it does underspecify.
1327 * A parameter string typed in on its own, with no seed _or_
1328 * description, gets treated the same way as a random seed,
1329 * because again I think the most likely reason for doing that
1330 * is to have a portable representation of a set of params.
1333 newcurparams = me->ourgame->dup_params(me->params);
1335 newcurparams = me->ourgame->default_params();
1337 me->ourgame->decode_params(newcurparams, par);
1338 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1340 me->ourgame->free_params(newcurparams);
1343 oldparams1 = me->curparams;
1346 * Now filter only the persistent parts of this state into
1347 * the long-term params structure, unless we've _only_
1348 * received a params string in which case the whole lot is
1351 oldparams2 = me->params;
1355 newparams = me->ourgame->dup_params(me->params);
1357 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1358 me->ourgame->decode_params(newparams, tmpstr);
1362 newparams = me->ourgame->dup_params(newcurparams);
1366 newcurparams = me->curparams;
1367 newparams = me->params;
1368 free_params = FALSE;
1372 error = me->ourgame->validate_desc(newparams, desc);
1376 me->ourgame->free_params(newcurparams);
1378 me->ourgame->free_params(newparams);
1385 * Now we've got past all possible error points. Update the
1388 me->params = newparams;
1389 me->curparams = newcurparams;
1391 me->ourgame->free_params(oldparams1);
1393 me->ourgame->free_params(oldparams2);
1396 sfree(me->privdesc);
1397 me->desc = me->privdesc = NULL;
1402 me->desc = dupstr(desc);
1403 me->genmode = GOT_DESC;
1404 sfree(me->aux_info);
1405 me->aux_info = NULL;
1409 me->seedstr = dupstr(seed);
1410 me->genmode = GOT_SEED;
1416 char *midend_game_id(midend *me, char *id)
1418 return midend_game_id_int(me, id, DEF_PARAMS);
1421 char *midend_get_game_id(midend *me)
1425 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1428 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1429 sprintf(ret, "%s:%s", parstr, me->desc);
1434 char *midend_get_random_seed(midend *me)
1441 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1443 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1444 sprintf(ret, "%s#%s", parstr, me->seedstr);
1449 char *midend_set_config(midend *me, int which, config_item *cfg)
1452 game_params *params;
1456 params = me->ourgame->custom_params(cfg);
1457 error = me->ourgame->validate_params(params, TRUE);
1460 me->ourgame->free_params(params);
1464 me->ourgame->free_params(me->params);
1465 me->params = params;
1470 error = midend_game_id_int(me, cfg[0].sval,
1471 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1480 int midend_can_format_as_text_now(midend *me)
1482 if (me->ourgame->can_format_as_text_ever)
1483 return me->ourgame->can_format_as_text_now(me->params);
1488 char *midend_text_format(midend *me)
1490 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1491 me->ourgame->can_format_as_text_now(me->params))
1492 return me->ourgame->text_format(me->states[me->statepos-1].state);
1497 char *midend_solve(midend *me)
1500 char *msg, *movestr;
1502 if (!me->ourgame->can_solve)
1503 return "This game does not support the Solve operation";
1505 if (me->statepos < 1)
1506 return "No game set up to solve"; /* _shouldn't_ happen! */
1509 movestr = me->ourgame->solve(me->states[0].state,
1510 me->states[me->statepos-1].state,
1511 me->aux_info, &msg);
1514 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1517 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1521 * Now enter the solved state as the next move.
1523 midend_stop_anim(me);
1524 midend_purge_states(me);
1526 me->states[me->nstates].state = s;
1527 me->states[me->nstates].movestr = movestr;
1528 me->states[me->nstates].movetype = SOLVE;
1529 me->statepos = ++me->nstates;
1531 me->ourgame->changed_state(me->ui,
1532 me->states[me->statepos-2].state,
1533 me->states[me->statepos-1].state);
1535 if (me->ourgame->flags & SOLVE_ANIMATES) {
1536 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1538 me->ourgame->anim_length(me->states[me->statepos-2].state,
1539 me->states[me->statepos-1].state,
1543 me->anim_time = 0.0;
1544 midend_finish_move(me);
1548 midend_set_timer(me);
1552 int midend_status(midend *me)
1555 * We should probably never be called when the state stack has no
1556 * states on it at all - ideally, midends should never be left in
1557 * that state for long enough to get put down and forgotten about.
1558 * But if we are, I think we return _true_ - pedantically speaking
1559 * a midend in that state is 'vacuously solved', and more
1560 * practically, a user whose midend has been left in that state
1561 * probably _does_ want the 'new game' option to be prominent.
1563 if (me->statepos == 0)
1566 return me->ourgame->status(me->states[me->statepos-1].state);
1569 char *midend_rewrite_statusbar(midend *me, char *text)
1572 * An important special case is that we are occasionally called
1573 * with our own laststatus, to update the timer.
1575 if (me->laststatus != text) {
1576 sfree(me->laststatus);
1577 me->laststatus = dupstr(text);
1580 if (me->ourgame->is_timed) {
1581 char timebuf[100], *ret;
1584 sec = (int)me->elapsed;
1587 sprintf(timebuf, "[%d:%02d] ", min, sec);
1589 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1590 strcpy(ret, timebuf);
1595 return dupstr(text);
1599 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1600 #define SERIALISE_VERSION "1"
1602 void midend_serialise(midend *me,
1603 void (*write)(void *ctx, void *buf, int len),
1609 * Each line of the save file contains three components. First
1610 * exactly 8 characters of header word indicating what type of
1611 * data is contained on the line; then a colon followed by a
1612 * decimal integer giving the length of the main string on the
1613 * line; then a colon followed by the string itself (exactly as
1614 * many bytes as previously specified, no matter what they
1615 * contain). Then a newline (of reasonably flexible form).
1617 #define wr(h,s) do { \
1621 copy_left_justified(lbuf, sizeof(lbuf), h); \
1622 sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1623 write(wctx, hbuf, strlen(hbuf)); \
1624 write(wctx, str, strlen(str)); \
1625 write(wctx, "\n", 1); \
1629 * Magic string identifying the file, and version number of the
1632 wr("SAVEFILE", SERIALISE_MAGIC);
1633 wr("VERSION", SERIALISE_VERSION);
1636 * The game name. (Copied locally to avoid const annoyance.)
1639 char *s = dupstr(me->ourgame->name);
1645 * The current long-term parameters structure, in full.
1648 char *s = me->ourgame->encode_params(me->params, TRUE);
1654 * The current short-term parameters structure, in full.
1656 if (me->curparams) {
1657 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1663 * The current game description, the privdesc, and the random seed.
1666 wr("SEED", me->seedstr);
1668 wr("DESC", me->desc);
1670 wr("PRIVDESC", me->privdesc);
1673 * The game's aux_info. We obfuscate this to prevent spoilers
1674 * (people are likely to run `head' or similar on a saved game
1675 * file simply to find out what it is, and don't necessarily
1676 * want to be told the answer to the puzzle!)
1683 len = strlen(me->aux_info);
1684 s1 = snewn(len, unsigned char);
1685 memcpy(s1, me->aux_info, len);
1686 obfuscate_bitmap(s1, len*8, FALSE);
1687 s2 = bin2hex(s1, len);
1696 * Any required serialisation of the game_ui.
1699 char *s = me->ourgame->encode_ui(me->ui);
1707 * The game time, if it's a timed game.
1709 if (me->ourgame->is_timed) {
1711 sprintf(buf, "%g", me->elapsed);
1716 * The length of, and position in, the states list.
1720 sprintf(buf, "%d", me->nstates);
1722 sprintf(buf, "%d", me->statepos);
1723 wr("STATEPOS", buf);
1727 * For each state after the initial one (which we know is
1728 * constructed from either privdesc or desc), enough
1729 * information for execute_move() to reconstruct it from the
1732 for (i = 1; i < me->nstates; i++) {
1733 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1734 switch (me->states[i].movetype) {
1736 wr("MOVE", me->states[i].movestr);
1739 wr("SOLVE", me->states[i].movestr);
1742 wr("RESTART", me->states[i].movestr);
1751 * This function returns NULL on success, or an error message.
1753 char *midend_deserialise(midend *me,
1754 int (*read)(void *ctx, void *buf, int len),
1757 int nstates = 0, statepos = -1, gotstates = 0;
1758 int started = FALSE;
1762 /* Initially all errors give the same report */
1763 char *ret = "Data does not appear to be a saved game file";
1766 * We construct all the new state in local variables while we
1767 * check its sanity. Only once we have finished reading the
1768 * serialised data and detected no errors at all do we start
1769 * modifying stuff in the midend passed in.
1771 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1772 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1773 float elapsed = 0.0F;
1774 game_params *params = NULL, *cparams = NULL;
1776 struct midend_state_entry *states = NULL;
1779 * Loop round and round reading one key/value pair at a time
1780 * from the serialised stream, until we have enough game states
1783 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1788 if (!read(rctx, key, 1)) {
1789 /* unexpected EOF */
1792 } while (key[0] == '\r' || key[0] == '\n');
1794 if (!read(rctx, key+1, 8)) {
1795 /* unexpected EOF */
1799 if (key[8] != ':') {
1801 ret = "Data was incorrectly formatted for a saved game file";
1804 len = strcspn(key, ": ");
1810 if (!read(rctx, &c, 1)) {
1811 /* unexpected EOF */
1817 } else if (c >= '0' && c <= '9') {
1818 len = (len * 10) + (c - '0');
1821 ret = "Data was incorrectly formatted for a"
1827 val = snewn(len+1, char);
1828 if (!read(rctx, val, len)) {
1835 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1836 /* ret already has the right message in it */
1839 /* Now most errors are this one, unless otherwise specified */
1840 ret = "Saved data ended unexpectedly";
1843 if (!strcmp(key, "VERSION")) {
1844 if (strcmp(val, SERIALISE_VERSION)) {
1845 ret = "Cannot handle this version of the saved game"
1849 } else if (!strcmp(key, "GAME")) {
1850 if (strcmp(val, me->ourgame->name)) {
1851 ret = "Save file is from a different game";
1854 } else if (!strcmp(key, "PARAMS")) {
1858 } else if (!strcmp(key, "CPARAMS")) {
1862 } else if (!strcmp(key, "SEED")) {
1866 } else if (!strcmp(key, "DESC")) {
1870 } else if (!strcmp(key, "PRIVDESC")) {
1874 } else if (!strcmp(key, "AUXINFO")) {
1876 int len = strlen(val) / 2; /* length in bytes */
1877 tmp = hex2bin(val, len);
1878 obfuscate_bitmap(tmp, len*8, TRUE);
1881 auxinfo = snewn(len + 1, char);
1882 memcpy(auxinfo, tmp, len);
1883 auxinfo[len] = '\0';
1885 } else if (!strcmp(key, "UI")) {
1889 } else if (!strcmp(key, "TIME")) {
1890 elapsed = (float)atof(val);
1891 } else if (!strcmp(key, "NSTATES")) {
1892 nstates = atoi(val);
1894 ret = "Number of states in save file was negative";
1898 ret = "Two state counts provided in save file";
1901 states = snewn(nstates, struct midend_state_entry);
1902 for (i = 0; i < nstates; i++) {
1903 states[i].state = NULL;
1904 states[i].movestr = NULL;
1905 states[i].movetype = NEWGAME;
1907 } else if (!strcmp(key, "STATEPOS")) {
1908 statepos = atoi(val);
1909 } else if (!strcmp(key, "MOVE")) {
1911 states[gotstates].movetype = MOVE;
1912 states[gotstates].movestr = val;
1914 } else if (!strcmp(key, "SOLVE")) {
1916 states[gotstates].movetype = SOLVE;
1917 states[gotstates].movestr = val;
1919 } else if (!strcmp(key, "RESTART")) {
1921 states[gotstates].movetype = RESTART;
1922 states[gotstates].movestr = val;
1931 params = me->ourgame->default_params();
1932 me->ourgame->decode_params(params, parstr);
1933 if (me->ourgame->validate_params(params, TRUE)) {
1934 ret = "Long-term parameters in save file are invalid";
1937 cparams = me->ourgame->default_params();
1938 me->ourgame->decode_params(cparams, cparstr);
1939 if (me->ourgame->validate_params(cparams, FALSE)) {
1940 ret = "Short-term parameters in save file are invalid";
1943 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1945 * The seed's no use with this version, but we can perfectly
1946 * well use the rest of the data.
1952 ret = "Game description in save file is missing";
1954 } else if (me->ourgame->validate_desc(params, desc)) {
1955 ret = "Game description in save file is invalid";
1958 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1959 ret = "Game private description in save file is invalid";
1962 if (statepos < 0 || statepos >= nstates) {
1963 ret = "Game position in save file is out of range";
1966 states[0].state = me->ourgame->new_game(me, params,
1967 privdesc ? privdesc : desc);
1968 for (i = 1; i < nstates; i++) {
1969 assert(states[i].movetype != NEWGAME);
1970 switch (states[i].movetype) {
1973 states[i].state = me->ourgame->execute_move(states[i-1].state,
1975 if (states[i].state == NULL) {
1976 ret = "Save file contained an invalid move";
1981 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1982 ret = "Save file contained an invalid restart move";
1985 states[i].state = me->ourgame->new_game(me, params,
1991 ui = me->ourgame->new_ui(states[0].state);
1992 me->ourgame->decode_ui(ui, uistr);
1995 * Now we've run out of possible error conditions, so we're
1996 * ready to start overwriting the real data in the current
1997 * midend. We'll do this by swapping things with the local
1998 * variables, so that the same cleanup code will free the old
2009 me->privdesc = privdesc;
2017 me->aux_info = auxinfo;
2021 me->genmode = GOT_NOTHING;
2023 me->statesize = nstates;
2024 nstates = me->nstates;
2025 me->nstates = me->statesize;
2027 struct midend_state_entry *tmp;
2029 me->states = states;
2032 me->statepos = statepos;
2038 me->params = params;
2041 tmp = me->curparams;
2042 me->curparams = cparams;
2046 me->oldstate = NULL;
2047 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2058 me->elapsed = elapsed;
2059 me->pressed_mouse_button = 0;
2061 midend_set_timer(me);
2064 me->ourgame->free_drawstate(me->drawing, me->drawstate);
2066 me->ourgame->new_drawstate(me->drawing,
2067 me->states[me->statepos-1].state);
2068 midend_size_new_drawstate(me);
2069 if (me->game_id_change_notify_function)
2070 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2072 ret = NULL; /* success! */
2084 me->ourgame->free_params(params);
2086 me->ourgame->free_params(cparams);
2088 me->ourgame->free_ui(ui);
2092 for (i = 0; i < nstates; i++) {
2093 if (states[i].state)
2094 me->ourgame->free_game(states[i].state);
2095 sfree(states[i].movestr);
2104 * This function examines a saved game file just far enough to
2105 * determine which game type it contains. It returns NULL on success
2106 * and the game name string in 'name' (which will be dynamically
2107 * allocated and should be caller-freed), or an error message on
2110 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2113 int nstates = 0, statepos = -1, gotstates = 0;
2114 int started = FALSE;
2117 /* Initially all errors give the same report */
2118 char *ret = "Data does not appear to be a saved game file";
2123 * Loop round and round reading one key/value pair at a time from
2124 * the serialised stream, until we've found the game name.
2126 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2131 if (!read(rctx, key, 1)) {
2132 /* unexpected EOF */
2135 } while (key[0] == '\r' || key[0] == '\n');
2137 if (!read(rctx, key+1, 8)) {
2138 /* unexpected EOF */
2142 if (key[8] != ':') {
2144 ret = "Data was incorrectly formatted for a saved game file";
2147 len = strcspn(key, ": ");
2153 if (!read(rctx, &c, 1)) {
2154 /* unexpected EOF */
2160 } else if (c >= '0' && c <= '9') {
2161 len = (len * 10) + (c - '0');
2164 ret = "Data was incorrectly formatted for a"
2170 val = snewn(len+1, char);
2171 if (!read(rctx, val, len)) {
2178 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2179 /* ret already has the right message in it */
2182 /* Now most errors are this one, unless otherwise specified */
2183 ret = "Saved data ended unexpectedly";
2186 if (!strcmp(key, "VERSION")) {
2187 if (strcmp(val, SERIALISE_VERSION)) {
2188 ret = "Cannot handle this version of the saved game"
2192 } else if (!strcmp(key, "GAME")) {
2193 *name = dupstr(val);
2208 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2210 game_state *soln = NULL;
2212 if (me->statepos < 1)
2213 return "No game set up to print";/* _shouldn't_ happen! */
2216 char *msg, *movestr;
2218 if (!me->ourgame->can_solve)
2219 return "This game does not support the Solve operation";
2221 msg = "Solve operation failed";/* game _should_ overwrite on error */
2222 movestr = me->ourgame->solve(me->states[0].state,
2223 me->states[me->statepos-1].state,
2224 me->aux_info, &msg);
2227 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2236 * This call passes over ownership of the two game_states and
2237 * the game_params. Hence we duplicate the ones we want to
2238 * keep, and we don't have to bother freeing soln if it was
2241 document_add_puzzle(doc, me->ourgame,
2242 me->ourgame->dup_params(me->curparams),
2243 me->ourgame->dup_game(me->states[0].state), soln);