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 char *newgame_undo_buf;
67 int newgame_undo_len, newgame_undo_size;
69 game_params *params, *curparams;
70 game_drawstate *drawstate;
74 float anim_time, anim_pos;
75 float flash_time, flash_pos;
84 int pressed_mouse_button;
86 int preferred_tilesize, tilesize, winwidth, winheight;
88 void (*game_id_change_notify_function)(void *);
89 void *game_id_change_notify_ctx;
92 #define ensure(me) do { \
93 if ((me)->nstates >= (me)->statesize) { \
94 (me)->statesize = (me)->nstates + 128; \
95 (me)->states = sresize((me)->states, (me)->statesize, \
96 struct midend_state_entry); \
101 * Structure storing all the decoded data from reading a serialised
102 * game. We keep it in one of these while we check its sanity, and
103 * only once we're completely satisfied do we install it all in the
104 * midend structure proper.
106 struct deserialise_data {
107 char *seed, *parstr, *desc, *privdesc;
108 char *auxinfo, *uistr, *cparstr;
110 game_params *params, *cparams;
112 struct midend_state_entry *states;
113 int nstates, statepos;
119 static const char *midend_deserialise_internal(
120 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
121 char *(*check)(void *ctx, midend *, const struct deserialise_data *),
124 void midend_reset_tilesize(midend *me)
126 me->preferred_tilesize = me->ourgame->preferred_tilesize;
129 * Allow an environment-based override for the default tile
130 * size by defining a variable along the lines of
137 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
138 for (j = k = 0; buf[j]; j++)
139 if (!isspace((unsigned char)buf[j]))
140 buf[k++] = toupper((unsigned char)buf[j]);
142 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
143 me->preferred_tilesize = ts;
147 midend *midend_new(frontend *fe, const game *ourgame,
148 const drawing_api *drapi, void *drhandle)
150 midend *me = snew(midend);
154 get_random_seed(&randseed, &randseedsize);
157 me->ourgame = ourgame;
158 me->random = random_new(randseed, randseedsize);
159 me->nstates = me->statesize = me->statepos = 0;
161 me->newgame_undo_buf = NULL;
162 me->newgame_undo_size = me->newgame_undo_len = 0;
163 me->params = ourgame->default_params();
164 me->game_id_change_notify_function = NULL;
165 me->game_id_change_notify_ctx = NULL;
168 * Allow environment-based changing of the default settings by
169 * defining a variable along the lines of `NET_DEFAULT=25x25w'
170 * in which the value is an encoded parameter string.
175 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
176 for (j = k = 0; buf[j]; j++)
177 if (!isspace((unsigned char)buf[j]))
178 buf[k++] = toupper((unsigned char)buf[j]);
180 if ((e = getenv(buf)) != NULL)
181 me->ourgame->decode_params(me->params, e);
183 me->curparams = NULL;
184 me->desc = me->privdesc = NULL;
187 me->genmode = GOT_NOTHING;
188 me->drawstate = NULL;
190 me->preset_menu = NULL;
191 me->anim_time = me->anim_pos = 0.0F;
192 me->flash_time = me->flash_pos = 0.0F;
195 me->pressed_mouse_button = 0;
196 me->laststatus = NULL;
199 me->tilesize = me->winwidth = me->winheight = 0;
201 me->drawing = drawing_new(drapi, me, drhandle);
205 midend_reset_tilesize(me);
212 const game *midend_which_game(midend *me)
217 static void midend_purge_states(midend *me)
219 while (me->nstates > me->statepos) {
220 me->ourgame->free_game(me->states[--me->nstates].state);
221 if (me->states[me->nstates].movestr)
222 sfree(me->states[me->nstates].movestr);
226 static void midend_free_game(midend *me)
228 while (me->nstates > 0) {
230 me->ourgame->free_game(me->states[me->nstates].state);
231 sfree(me->states[me->nstates].movestr);
235 me->ourgame->free_drawstate(me->drawing, me->drawstate);
238 static void midend_free_preset_menu(midend *me, struct preset_menu *menu)
242 for (i = 0; i < menu->n_entries; i++) {
243 sfree(menu->entries[i].title);
244 if (menu->entries[i].params)
245 me->ourgame->free_params(menu->entries[i].params);
246 midend_free_preset_menu(me, menu->entries[i].submenu);
248 sfree(menu->entries);
253 void midend_free(midend *me)
255 midend_free_game(me);
258 drawing_free(me->drawing);
259 random_free(me->random);
260 sfree(me->newgame_undo_buf);
266 me->ourgame->free_params(me->params);
267 midend_free_preset_menu(me, me->preset_menu);
269 me->ourgame->free_ui(me->ui);
271 me->ourgame->free_params(me->curparams);
272 sfree(me->laststatus);
276 static void midend_size_new_drawstate(midend *me)
279 * Don't even bother, if we haven't worked out our tile size
282 if (me->tilesize > 0) {
283 me->ourgame->compute_size(me->params, me->tilesize,
284 &me->winwidth, &me->winheight);
285 me->ourgame->set_size(me->drawing, me->drawstate,
286 me->params, me->tilesize);
290 void midend_size(midend *me, int *x, int *y, int user_size)
296 * We can't set the size on the same drawstate twice. So if
297 * we've already sized one drawstate, we must throw it away and
300 if (me->drawstate && me->tilesize > 0) {
301 me->ourgame->free_drawstate(me->drawing, me->drawstate);
302 me->drawstate = me->ourgame->new_drawstate(me->drawing,
303 me->states[0].state);
307 * Find the tile size that best fits within the given space. If
308 * `user_size' is TRUE, we must actually find the _largest_ such
309 * tile size, in order to get as close to the user's explicit
310 * request as possible; otherwise, we bound above at the game's
311 * preferred tile size, so that the game gets what it wants
312 * provided that this doesn't break the constraint from the
313 * front-end (which is likely to be a screen size or similar).
319 me->ourgame->compute_size(me->params, max, &rx, &ry);
320 } while (rx <= *x && ry <= *y);
322 max = me->preferred_tilesize + 1;
326 * Now binary-search between min and max. We're looking for a
327 * boundary rather than a value: the point at which tile sizes
328 * stop fitting within the given dimensions. Thus, we stop when
329 * max and min differ by exactly 1.
331 while (max - min > 1) {
332 int mid = (max + min) / 2;
333 me->ourgame->compute_size(me->params, mid, &rx, &ry);
334 if (rx <= *x && ry <= *y)
341 * Now `min' is a valid size, and `max' isn't. So use `min'.
346 /* If the user requested a change in size, make it permanent. */
347 me->preferred_tilesize = me->tilesize;
348 midend_size_new_drawstate(me);
353 int midend_tilesize(midend *me) { return me->tilesize; }
355 void midend_set_params(midend *me, game_params *params)
357 me->ourgame->free_params(me->params);
358 me->params = me->ourgame->dup_params(params);
361 game_params *midend_get_params(midend *me)
363 return me->ourgame->dup_params(me->params);
366 static void midend_set_timer(midend *me)
368 me->timing = (me->ourgame->is_timed &&
369 me->ourgame->timing_state(me->states[me->statepos-1].state,
371 if (me->timing || me->flash_time || me->anim_time)
372 activate_timer(me->frontend);
374 deactivate_timer(me->frontend);
377 void midend_force_redraw(midend *me)
380 me->ourgame->free_drawstate(me->drawing, me->drawstate);
381 me->drawstate = me->ourgame->new_drawstate(me->drawing,
382 me->states[0].state);
383 midend_size_new_drawstate(me);
387 static void newgame_serialise_write(void *ctx, void *buf, int len)
389 midend *const me = ctx;
392 assert(len < INT_MAX - me->newgame_undo_len);
393 new_len = me->newgame_undo_len + len;
394 if (new_len > me->newgame_undo_size) {
395 me->newgame_undo_size = new_len + new_len / 4 + 1024;
396 me->newgame_undo_buf = sresize(me->newgame_undo_buf,
397 me->newgame_undo_size, char);
399 memcpy(me->newgame_undo_buf + me->newgame_undo_len, buf, len);
400 me->newgame_undo_len = new_len;
403 void midend_new_game(midend *me)
405 me->newgame_undo_len = 0;
406 midend_serialise(me, newgame_serialise_write, me);
408 midend_stop_anim(me);
409 midend_free_game(me);
411 assert(me->nstates == 0);
413 if (me->genmode == GOT_DESC) {
414 me->genmode = GOT_NOTHING;
418 if (me->genmode == GOT_SEED) {
419 me->genmode = GOT_NOTHING;
422 * Generate a new random seed. 15 digits comes to about
423 * 48 bits, which should be more than enough.
425 * I'll avoid putting a leading zero on the number,
426 * just in case it confuses anybody who thinks it's
427 * processed as an integer rather than a string.
432 newseed[0] = '1' + (char)random_upto(me->random, 9);
433 for (i = 1; i < 15; i++)
434 newseed[i] = '0' + (char)random_upto(me->random, 10);
436 me->seedstr = dupstr(newseed);
439 me->ourgame->free_params(me->curparams);
440 me->curparams = me->ourgame->dup_params(me->params);
448 rs = random_new(me->seedstr, strlen(me->seedstr));
450 * If this midend has been instantiated without providing a
451 * drawing API, it is non-interactive. This means that it's
452 * being used for bulk game generation, and hence we should
453 * pass the non-interactive flag to new_desc.
455 me->desc = me->ourgame->new_desc(me->curparams, rs,
456 &me->aux_info, (me->drawing != NULL));
464 * It might seem a bit odd that we're using me->params to
465 * create the initial game state, rather than me->curparams
466 * which is better tailored to this specific game and which we
469 * It's supposed to be an invariant in the midend that
470 * me->params and me->curparams differ in no aspect that is
471 * important after generation (i.e. after new_desc()). By
472 * deliberately passing the _less_ specific of these two
473 * parameter sets, we provoke play-time misbehaviour in the
474 * case where a game has failed to encode a play-time parameter
475 * in the non-full version of encode_params().
477 me->states[me->nstates].state =
478 me->ourgame->new_game(me, me->params, me->desc);
481 * As part of our commitment to self-testing, test the aux
482 * string to make sure nothing ghastly went wrong.
484 if (me->ourgame->can_solve && me->aux_info) {
490 movestr = me->ourgame->solve(me->states[0].state,
493 assert(movestr && !msg);
494 s = me->ourgame->execute_move(me->states[0].state, movestr);
496 me->ourgame->free_game(s);
500 me->states[me->nstates].movestr = NULL;
501 me->states[me->nstates].movetype = NEWGAME;
504 me->drawstate = me->ourgame->new_drawstate(me->drawing,
505 me->states[0].state);
506 midend_size_new_drawstate(me);
508 me->flash_pos = me->flash_time = 0.0F;
509 me->anim_pos = me->anim_time = 0.0F;
511 me->ourgame->free_ui(me->ui);
512 me->ui = me->ourgame->new_ui(me->states[0].state);
513 midend_set_timer(me);
514 me->pressed_mouse_button = 0;
516 if (me->game_id_change_notify_function)
517 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
520 int midend_can_undo(midend *me)
522 return (me->statepos > 1 || me->newgame_undo_len);
525 int midend_can_redo(midend *me)
527 return (me->statepos < me->nstates);
530 struct newgame_undo_deserialise_read_ctx {
535 static int newgame_undo_deserialise_read(void *ctx, void *buf, int len)
537 struct newgame_undo_deserialise_read_ctx *const rctx = ctx;
538 midend *const me = rctx->me;
540 int use = min(len, rctx->len - rctx->pos);
541 memcpy(buf, me->newgame_undo_buf + rctx->pos, use);
546 struct newgame_undo_deserialise_check_ctx {
550 static char *newgame_undo_deserialise_check(
551 void *vctx, midend *me, const struct deserialise_data *data)
553 struct newgame_undo_deserialise_check_ctx *ctx =
554 (struct newgame_undo_deserialise_check_ctx *)vctx;
558 * Undoing a New Game operation is only permitted if it doesn't
559 * change the game parameters. The point of having the ability at
560 * all is to recover from the momentary finger error of having hit
561 * the 'n' key (perhaps in place of some other nearby key), or hit
562 * the New Game menu item by mistake when aiming for the adjacent
563 * Restart; in both those situations, the game params are the same
564 * before and after the new-game operation.
566 * In principle, we could generalise this so that _any_ call to
567 * midend_new_game could be undone, but that would need all front
568 * ends to be alert to the possibility that any keystroke passed
569 * to midend_process_key might (if it turns out to have been one
570 * of the synonyms for undo, which the frontend doesn't
571 * necessarily check for) have various knock-on effects like
572 * needing to select a different preset in the game type menu, or
573 * even resizing the window. At least for the moment, it's easier
574 * not to do that, and to simply disallow any newgame-undo that is
575 * disruptive in either of those ways.
577 * We check both params and cparams, to be as safe as possible.
580 old = me->ourgame->encode_params(me->params, TRUE);
581 new = me->ourgame->encode_params(data->params, TRUE);
582 if (strcmp(old, new)) {
583 /* Set a flag to distinguish this deserialise failure
584 * from one due to faulty decoding */
586 return "Undoing this new-game operation would change params";
589 old = me->ourgame->encode_params(me->curparams, TRUE);
590 new = me->ourgame->encode_params(data->cparams, TRUE);
591 if (strcmp(old, new)) {
593 return "Undoing this new-game operation would change params";
597 * Otherwise, fine, go ahead.
602 static int midend_undo(midend *me)
604 const char *deserialise_error;
606 if (me->statepos > 1) {
608 me->ourgame->changed_state(me->ui,
609 me->states[me->statepos-1].state,
610 me->states[me->statepos-2].state);
614 } else if (me->newgame_undo_len) {
615 /* This undo cannot be undone with redo */
616 struct newgame_undo_deserialise_read_ctx rctx;
617 struct newgame_undo_deserialise_check_ctx cctx;
619 rctx.len = me->newgame_undo_len; /* copy for reentrancy safety */
621 cctx.refused = FALSE;
622 deserialise_error = midend_deserialise_internal(
623 me, newgame_undo_deserialise_read, &rctx,
624 newgame_undo_deserialise_check, &cctx);
627 * Our post-deserialisation check shows that we can't use
628 * this saved game after all. (deserialise_error will
629 * contain the dummy error message generated by our check
630 * function, which we ignore.)
635 * There should never be any _other_ deserialisation
636 * error, because this serialised data has been held in
637 * our memory since it was created, and hasn't had any
638 * opportunity to be corrupted on disk, accidentally
639 * replaced by the wrong file, etc., by user error.
641 assert(!deserialise_error);
648 static int midend_redo(midend *me)
650 if (me->statepos < me->nstates) {
652 me->ourgame->changed_state(me->ui,
653 me->states[me->statepos-1].state,
654 me->states[me->statepos].state);
662 static void midend_finish_move(midend *me)
667 * We do not flash if the later of the two states is special.
668 * This covers both forward Solve moves and backward (undone)
671 if ((me->oldstate || me->statepos > 1) &&
672 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
673 (me->dir < 0 && me->statepos < me->nstates &&
674 !special(me->states[me->statepos].movetype)))) {
675 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
676 me->states[me->statepos-2].state,
677 me->states[me->statepos-1].state,
678 me->oldstate ? me->dir : +1,
681 me->flash_pos = 0.0F;
682 me->flash_time = flashtime;
687 me->ourgame->free_game(me->oldstate);
689 me->anim_pos = me->anim_time = 0;
692 midend_set_timer(me);
695 void midend_stop_anim(midend *me)
697 if (me->oldstate || me->anim_time != 0) {
698 midend_finish_move(me);
703 void midend_restart_game(midend *me)
707 assert(me->statepos >= 1);
708 if (me->statepos == 1)
709 return; /* no point doing anything at all! */
712 * During restart, we reconstruct the game from the (public)
713 * game description rather than from states[0], because that
714 * way Mines gets slightly more sensible behaviour (restart
715 * goes to _after_ the first click so you don't have to
716 * remember where you clicked).
718 s = me->ourgame->new_game(me, me->params, me->desc);
721 * Now enter the restarted state as the next move.
723 midend_stop_anim(me);
724 midend_purge_states(me);
726 me->states[me->nstates].state = s;
727 me->states[me->nstates].movestr = dupstr(me->desc);
728 me->states[me->nstates].movetype = RESTART;
729 me->statepos = ++me->nstates;
731 me->ourgame->changed_state(me->ui,
732 me->states[me->statepos-2].state,
733 me->states[me->statepos-1].state);
734 me->flash_pos = me->flash_time = 0.0F;
735 midend_finish_move(me);
737 midend_set_timer(me);
740 static int midend_really_process_key(midend *me, int x, int y, int button)
742 game_state *oldstate =
743 me->ourgame->dup_game(me->states[me->statepos - 1].state);
744 int type = MOVE, gottype = FALSE, ret = 1;
747 char *movestr = NULL;
749 if (!IS_UI_FAKE_KEY(button)) {
750 movestr = me->ourgame->interpret_move(
751 me->states[me->statepos-1].state,
752 me->ui, me->drawstate, x, y, button);
756 if (button == 'n' || button == 'N' || button == '\x0E' ||
757 button == UI_NEWGAME) {
760 goto done; /* never animate */
761 } else if (button == 'u' || button == 'U' ||
762 button == '\x1A' || button == '\x1F' ||
764 midend_stop_anim(me);
765 type = me->states[me->statepos-1].movetype;
767 if (!midend_undo(me))
769 } else if (button == 'r' || button == 'R' ||
770 button == '\x12' || button == '\x19' ||
772 midend_stop_anim(me);
773 if (!midend_redo(me))
775 } else if ((button == '\x13' || button == UI_SOLVE) &&
776 me->ourgame->can_solve) {
777 if (midend_solve(me))
779 } else if (button == 'q' || button == 'Q' || button == '\x11' ||
786 if (movestr == UI_UPDATE)
787 s = me->states[me->statepos-1].state;
789 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
794 if (s == me->states[me->statepos-1].state) {
796 * make_move() is allowed to return its input state to
797 * indicate that although no move has been made, the UI
798 * state has been updated and a redraw is called for.
801 midend_set_timer(me);
804 midend_stop_anim(me);
805 midend_purge_states(me);
807 assert(movestr != NULL);
808 me->states[me->nstates].state = s;
809 me->states[me->nstates].movestr = movestr;
810 me->states[me->nstates].movetype = MOVE;
811 me->statepos = ++me->nstates;
814 me->ourgame->changed_state(me->ui,
815 me->states[me->statepos-2].state,
816 me->states[me->statepos-1].state);
823 type = me->states[me->statepos-1].movetype;
826 * See if this move requires an animation.
828 if (special(type) && !(type == SOLVE &&
829 (me->ourgame->flags & SOLVE_ANIMATES))) {
832 anim_time = me->ourgame->anim_length(oldstate,
833 me->states[me->statepos-1].state,
837 me->oldstate = oldstate; oldstate = NULL;
839 me->anim_time = anim_time;
842 midend_finish_move(me);
848 midend_set_timer(me);
851 if (oldstate) me->ourgame->free_game(oldstate);
855 int midend_process_key(midend *me, int x, int y, int button)
860 * Harmonise mouse drag and release messages.
862 * Some front ends might accidentally switch from sending, say,
863 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
864 * drag. (This can happen on the Mac, for example, since
865 * RIGHT_DRAG is usually done using Command+drag, and if the
866 * user accidentally releases Command half way through the drag
867 * then there will be trouble.)
869 * It would be an O(number of front ends) annoyance to fix this
870 * in the front ends, but an O(number of back ends) annoyance
871 * to have each game capable of dealing with it. Therefore, we
872 * fix it _here_ in the common midend code so that it only has
875 * The possible ways in which things can go screwy in the front
878 * - in a system containing multiple physical buttons button
879 * presses can inadvertently overlap. We can see ABab (caps
880 * meaning button-down and lowercase meaning button-up) when
881 * the user had semantically intended AaBb.
883 * - in a system where one button is simulated by means of a
884 * modifier key and another button, buttons can mutate
885 * between press and release (possibly during drag). So we
886 * can see Ab instead of Aa.
888 * Definite requirements are:
890 * - button _presses_ must never be invented or destroyed. If
891 * the user presses two buttons in succession, the button
892 * presses must be transferred to the backend unchanged. So
893 * if we see AaBb , that's fine; if we see ABab (the button
894 * presses inadvertently overlapped) we must somehow
895 * `correct' it to AaBb.
897 * - every mouse action must end up looking like a press, zero
898 * or more drags, then a release. This allows back ends to
899 * make the _assumption_ that incoming mouse data will be
900 * sane in this regard, and not worry about the details.
902 * So my policy will be:
904 * - treat any button-up as a button-up for the currently
905 * pressed button, or ignore it if there is no currently
908 * - treat any drag as a drag for the currently pressed
909 * button, or ignore it if there is no currently pressed
912 * - if we see a button-down while another button is currently
913 * pressed, invent a button-up for the first one and then
914 * pass the button-down through as before.
916 * 2005-05-31: An addendum to the above. Some games might want
917 * a `priority order' among buttons, such that if one button is
918 * pressed while another is down then a fixed one of the
919 * buttons takes priority no matter what order they're pressed
920 * in. Mines, in particular, wants to treat a left+right click
921 * like a left click for the benefit of users of other
922 * implementations. So the last of the above points is modified
923 * in the presence of an (optional) button priority order.
925 * A further addition: we translate certain keyboard presses to
926 * cursor key 'select' buttons, so that a) frontends don't have
927 * to translate these themselves (like they do for CURSOR_UP etc),
928 * and b) individual games don't have to hard-code button presses
929 * of '\n' etc for keyboard-based cursors. The choice of buttons
930 * here could eventually be controlled by a runtime configuration
933 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
934 if (me->pressed_mouse_button) {
935 if (IS_MOUSE_DRAG(button)) {
936 button = me->pressed_mouse_button +
937 (LEFT_DRAG - LEFT_BUTTON);
939 button = me->pressed_mouse_button +
940 (LEFT_RELEASE - LEFT_BUTTON);
943 return ret; /* ignore it */
944 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
946 * If the new button has lower priority than the old one,
947 * don't bother doing this.
949 if (me->ourgame->flags &
950 BUTTON_BEATS(me->pressed_mouse_button, button))
951 return ret; /* just ignore it */
954 * Fabricate a button-up for the previously pressed button.
956 ret = ret && midend_really_process_key
957 (me, x, y, (me->pressed_mouse_button +
958 (LEFT_RELEASE - LEFT_BUTTON)));
962 * Translate keyboard presses to cursor selection.
964 if (button == '\n' || button == '\r')
965 button = CURSOR_SELECT;
967 button = CURSOR_SELECT2;
970 * Normalise both backspace characters (8 and 127) to \b. Easier
971 * to do this once, here, than to require all front ends to
972 * carefully generate the same one - now each front end can
973 * generate whichever is easiest.
975 if (button == '\177')
979 * Now send on the event we originally received.
981 ret = ret && midend_really_process_key(me, x, y, button);
984 * And update the currently pressed button.
986 if (IS_MOUSE_RELEASE(button))
987 me->pressed_mouse_button = 0;
988 else if (IS_MOUSE_DOWN(button))
989 me->pressed_mouse_button = button;
994 void midend_redraw(midend *me)
998 if (me->statepos > 0 && me->drawstate) {
999 start_draw(me->drawing);
1000 if (me->oldstate && me->anim_time > 0 &&
1001 me->anim_pos < me->anim_time) {
1002 assert(me->dir != 0);
1003 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
1004 me->states[me->statepos-1].state, me->dir,
1005 me->ui, me->anim_pos, me->flash_pos);
1007 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
1008 me->states[me->statepos-1].state, +1 /*shrug*/,
1009 me->ui, 0.0, me->flash_pos);
1011 end_draw(me->drawing);
1016 * Nasty hacky function used to implement the --redo option in
1017 * gtk.c. Only used for generating the puzzles' icons.
1019 void midend_freeze_timer(midend *me, float tprop)
1021 me->anim_pos = me->anim_time * tprop;
1023 deactivate_timer(me->frontend);
1026 void midend_timer(midend *me, float tplus)
1028 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
1030 me->anim_pos += tplus;
1031 if (me->anim_pos >= me->anim_time ||
1032 me->anim_time == 0 || !me->oldstate) {
1033 if (me->anim_time > 0)
1034 midend_finish_move(me);
1037 me->flash_pos += tplus;
1038 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
1039 me->flash_pos = me->flash_time = 0;
1046 float oldelapsed = me->elapsed;
1047 me->elapsed += tplus;
1048 if ((int)oldelapsed != (int)me->elapsed)
1049 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
1052 midend_set_timer(me);
1055 float *midend_colours(midend *me, int *ncolours)
1059 ret = me->ourgame->colours(me->frontend, ncolours);
1065 * Allow environment-based overrides for the standard
1066 * colours by defining variables along the lines of
1067 * `NET_COLOUR_4=6000c0'.
1070 for (i = 0; i < *ncolours; i++) {
1072 unsigned int r, g, b;
1075 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
1076 for (j = k = 0; buf[j]; j++)
1077 if (!isspace((unsigned char)buf[j]))
1078 buf[k++] = toupper((unsigned char)buf[j]);
1080 if ((e = getenv(buf)) != NULL &&
1081 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
1082 ret[i*3 + 0] = r / 255.0F;
1083 ret[i*3 + 1] = g / 255.0F;
1084 ret[i*3 + 2] = b / 255.0F;
1092 struct preset_menu *preset_menu_new(void)
1094 struct preset_menu *menu = snew(struct preset_menu);
1095 menu->n_entries = 0;
1096 menu->entries_size = 0;
1097 menu->entries = NULL;
1101 static struct preset_menu_entry *preset_menu_add(struct preset_menu *menu,
1104 struct preset_menu_entry *toret;
1105 if (menu->n_entries >= menu->entries_size) {
1106 menu->entries_size = menu->n_entries * 5 / 4 + 10;
1107 menu->entries = sresize(menu->entries, menu->entries_size,
1108 struct preset_menu_entry);
1110 toret = &menu->entries[menu->n_entries++];
1111 toret->title = title;
1112 toret->params = NULL;
1113 toret->submenu = NULL;
1117 struct preset_menu *preset_menu_add_submenu(struct preset_menu *parent,
1120 struct preset_menu_entry *entry = preset_menu_add(parent, title);
1121 entry->submenu = preset_menu_new();
1122 return entry->submenu;
1125 void preset_menu_add_preset(struct preset_menu *parent,
1126 char *title, game_params *params)
1128 struct preset_menu_entry *entry = preset_menu_add(parent, title);
1129 entry->params = params;
1132 game_params *preset_menu_lookup_by_id(struct preset_menu *menu, int id)
1137 for (i = 0; i < menu->n_entries; i++) {
1138 if (id == menu->entries[i].id)
1139 return menu->entries[i].params;
1140 if (menu->entries[i].submenu &&
1141 (retd = preset_menu_lookup_by_id(
1142 menu->entries[i].submenu, id)) != NULL)
1149 static char *preset_menu_add_from_user_env(
1150 midend *me, struct preset_menu *menu, char *p, int top_level)
1154 game_params *preset;
1157 while (*p && *p != ':') p++;
1158 if (*p) *p++ = '\0';
1160 while (*p && *p != ':') p++;
1161 if (*p) *p++ = '\0';
1163 if (!strcmp(val, "#")) {
1165 * Special case: either open a new submenu with the given
1166 * title, or terminate the current submenu.
1169 struct preset_menu *submenu =
1170 preset_menu_add_submenu(menu, dupstr(name));
1171 p = preset_menu_add_from_user_env(me, submenu, p, FALSE);
1174 * If we get a 'close submenu' indication at the top
1175 * level, there's not much we can do but quietly
1184 preset = me->ourgame->default_params();
1185 me->ourgame->decode_params(preset, val);
1187 if (me->ourgame->validate_params(preset, TRUE)) {
1188 /* Drop this one from the list. */
1189 me->ourgame->free_params(preset);
1193 preset_menu_add_preset(menu, dupstr(name), preset);
1199 static void preset_menu_alloc_ids(midend *me, struct preset_menu *menu)
1203 for (i = 0; i < menu->n_entries; i++)
1204 menu->entries[i].id = me->n_encoded_presets++;
1206 for (i = 0; i < menu->n_entries; i++)
1207 if (menu->entries[i].submenu)
1208 preset_menu_alloc_ids(me, menu->entries[i].submenu);
1211 static void preset_menu_encode_params(midend *me, struct preset_menu *menu)
1215 for (i = 0; i < menu->n_entries; i++) {
1216 if (menu->entries[i].params) {
1217 me->encoded_presets[menu->entries[i].id] =
1218 me->ourgame->encode_params(menu->entries[i].params, TRUE);
1220 preset_menu_encode_params(me, menu->entries[i].submenu);
1225 struct preset_menu *midend_get_presets(midend *me, int *id_limit)
1229 if (me->preset_menu)
1230 return me->preset_menu;
1233 /* Expect the game to implement exactly one of the two preset APIs */
1234 assert(me->ourgame->fetch_preset || me->ourgame->preset_menu);
1235 assert(!(me->ourgame->fetch_preset && me->ourgame->preset_menu));
1238 if (me->ourgame->fetch_preset) {
1240 game_params *preset;
1242 /* Simple one-level menu */
1243 assert(!me->ourgame->preset_menu);
1244 me->preset_menu = preset_menu_new();
1245 for (i = 0; me->ourgame->fetch_preset(i, &name, &preset); i++)
1246 preset_menu_add_preset(me->preset_menu, name, preset);
1249 /* Hierarchical menu provided by the game backend */
1250 me->preset_menu = me->ourgame->preset_menu();
1255 * Allow user extensions to the preset list by defining an
1256 * environment variable <gamename>_PRESETS whose value is a
1257 * colon-separated list of items, alternating between textual
1258 * titles in the menu and encoded parameter strings. For
1259 * example, "SOLO_PRESETS=2x3 Advanced:2x3da" would define
1260 * just one additional preset for Solo.
1265 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1266 for (j = k = 0; buf[j]; j++)
1267 if (!isspace((unsigned char)buf[j]))
1268 buf[k++] = toupper((unsigned char)buf[j]);
1271 if ((e = getenv(buf)) != NULL) {
1273 preset_menu_add_from_user_env(me, me->preset_menu, e, TRUE);
1279 * Finalise the menu: allocate an integer id to each entry, and
1280 * store string encodings of the presets' parameters in
1281 * me->encoded_presets.
1283 me->n_encoded_presets = 0;
1284 preset_menu_alloc_ids(me, me->preset_menu);
1285 me->encoded_presets = snewn(me->n_encoded_presets, char *);
1286 for (i = 0; i < me->n_encoded_presets; i++)
1287 me->encoded_presets[i] = NULL;
1288 preset_menu_encode_params(me, me->preset_menu);
1291 *id_limit = me->n_encoded_presets;
1292 return me->preset_menu;
1295 int midend_which_preset(midend *me)
1297 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1301 for (i = 0; i < me->n_encoded_presets; i++)
1302 if (me->encoded_presets[i] &&
1303 !strcmp(encoding, me->encoded_presets[i])) {
1312 int midend_wants_statusbar(midend *me)
1314 return me->ourgame->wants_statusbar;
1317 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1319 me->game_id_change_notify_function = notify;
1320 me->game_id_change_notify_ctx = ctx;
1323 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1326 sfree(me->privdesc);
1327 me->desc = dupstr(desc);
1328 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1329 if (me->game_id_change_notify_function)
1330 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1333 config_item *midend_get_config(midend *me, int which, char **wintitle)
1335 char *titlebuf, *parstr, *rest;
1340 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1344 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1345 *wintitle = titlebuf;
1346 return me->ourgame->configure(me->params);
1349 if (!me->curparams) {
1353 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1354 which == CFG_SEED ? "random" : "game");
1355 *wintitle = titlebuf;
1357 ret = snewn(2, config_item);
1359 ret[0].type = C_STRING;
1360 if (which == CFG_SEED)
1361 ret[0].name = "Game random seed";
1363 ret[0].name = "Game ID";
1365 * For CFG_DESC the text going in here will be a string
1366 * encoding of the restricted parameters, plus a colon,
1367 * plus the game description. For CFG_SEED it will be the
1368 * full parameters, plus a hash, plus the random seed data.
1369 * Either of these is a valid full game ID (although only
1370 * the former is likely to persist across many code
1373 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1375 if (which == CFG_DESC) {
1376 rest = me->desc ? me->desc : "";
1379 rest = me->seedstr ? me->seedstr : "";
1382 ret[0].u.string.sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1383 sprintf(ret[0].u.string.sval, "%s%c%s", parstr, sep, rest);
1386 ret[1].type = C_END;
1392 assert(!"We shouldn't be here");
1396 static const char *midend_game_id_int(midend *me, char *id, int defmode)
1399 char *par, *desc, *seed;
1400 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1403 seed = strchr(id, '#');
1404 desc = strchr(id, ':');
1406 if (desc && (!seed || desc < seed)) {
1408 * We have a colon separating parameters from game
1409 * description. So `par' now points to the parameters
1410 * string, and `desc' to the description string.
1415 } else if (seed && (!desc || seed < desc)) {
1417 * We have a hash separating parameters from random seed.
1418 * So `par' now points to the parameters string, and `seed'
1419 * to the seed string.
1426 * We only have one string. Depending on `defmode', we take
1427 * it to be either parameters, seed or description.
1429 if (defmode == DEF_SEED) {
1432 } else if (defmode == DEF_DESC) {
1442 * We must be reasonably careful here not to modify anything in
1443 * `me' until we have finished validating things. This function
1444 * must either return an error and do nothing to the midend, or
1445 * return success and do everything; nothing in between is
1448 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1452 * The params string may underspecify the game parameters, so
1453 * we must first initialise newcurparams with a full set of
1454 * params from somewhere else before we decode_params the
1455 * input string over the top.
1457 * But which set? It depends on what other data we have.
1459 * If we've been given a _descriptive_ game id, then that may
1460 * well underspecify by design, e.g. Solo game descriptions
1461 * often start just '3x3:' without specifying one of Solo's
1462 * difficulty settings, because it isn't necessary once a game
1463 * has been generated (and you might not even know it, if
1464 * you're manually transcribing a game description). In that
1465 * situation, I've always felt that the best thing to set the
1466 * difficulty to (for use if the user hits 'New Game' after
1467 * pasting in that game id) is whatever it was previously set
1468 * to. That is, we use whatever is already in me->params as
1469 * the basis for our decoding of this input string.
1471 * A random-seed based game id, however, should use the real,
1472 * built-in default params, and not even check the
1473 * <game>_DEFAULT environment setting, because when people
1474 * paste each other random seeds - whether it's two users
1475 * arranging to generate the same game at the same time to
1476 * race solving them, or a user sending a bug report upstream
1477 * - the whole point is for the random game id to always be
1478 * interpreted the same way, even if it does underspecify.
1480 * A parameter string typed in on its own, with no seed _or_
1481 * description, gets treated the same way as a random seed,
1482 * because again I think the most likely reason for doing that
1483 * is to have a portable representation of a set of params.
1486 newcurparams = me->ourgame->dup_params(me->params);
1488 newcurparams = me->ourgame->default_params();
1490 me->ourgame->decode_params(newcurparams, par);
1491 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1493 me->ourgame->free_params(newcurparams);
1496 oldparams1 = me->curparams;
1499 * Now filter only the persistent parts of this state into
1500 * the long-term params structure, unless we've _only_
1501 * received a params string in which case the whole lot is
1504 oldparams2 = me->params;
1508 newparams = me->ourgame->dup_params(me->params);
1510 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1511 me->ourgame->decode_params(newparams, tmpstr);
1515 newparams = me->ourgame->dup_params(newcurparams);
1519 newcurparams = me->curparams;
1520 newparams = me->params;
1521 free_params = FALSE;
1525 error = me->ourgame->validate_desc(newparams, desc);
1529 me->ourgame->free_params(newcurparams);
1531 me->ourgame->free_params(newparams);
1538 * Now we've got past all possible error points. Update the
1541 me->params = newparams;
1542 me->curparams = newcurparams;
1544 me->ourgame->free_params(oldparams1);
1546 me->ourgame->free_params(oldparams2);
1549 sfree(me->privdesc);
1550 me->desc = me->privdesc = NULL;
1555 me->desc = dupstr(desc);
1556 me->genmode = GOT_DESC;
1557 sfree(me->aux_info);
1558 me->aux_info = NULL;
1562 me->seedstr = dupstr(seed);
1563 me->genmode = GOT_SEED;
1569 const char *midend_game_id(midend *me, char *id)
1571 return midend_game_id_int(me, id, DEF_PARAMS);
1574 char *midend_get_game_id(midend *me)
1578 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1581 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1582 sprintf(ret, "%s:%s", parstr, me->desc);
1587 char *midend_get_random_seed(midend *me)
1594 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1596 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1597 sprintf(ret, "%s#%s", parstr, me->seedstr);
1602 const char *midend_set_config(midend *me, int which, config_item *cfg)
1605 game_params *params;
1609 params = me->ourgame->custom_params(cfg);
1610 error = me->ourgame->validate_params(params, TRUE);
1613 me->ourgame->free_params(params);
1617 me->ourgame->free_params(me->params);
1618 me->params = params;
1623 error = midend_game_id_int(me, cfg[0].u.string.sval,
1624 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1633 int midend_can_format_as_text_now(midend *me)
1635 if (me->ourgame->can_format_as_text_ever)
1636 return me->ourgame->can_format_as_text_now(me->params);
1641 char *midend_text_format(midend *me)
1643 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1644 me->ourgame->can_format_as_text_now(me->params))
1645 return me->ourgame->text_format(me->states[me->statepos-1].state);
1650 const char *midend_solve(midend *me)
1656 if (!me->ourgame->can_solve)
1657 return "This game does not support the Solve operation";
1659 if (me->statepos < 1)
1660 return "No game set up to solve"; /* _shouldn't_ happen! */
1663 movestr = me->ourgame->solve(me->states[0].state,
1664 me->states[me->statepos-1].state,
1665 me->aux_info, &msg);
1666 assert(movestr != UI_UPDATE);
1669 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1672 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1676 * Now enter the solved state as the next move.
1678 midend_stop_anim(me);
1679 midend_purge_states(me);
1681 me->states[me->nstates].state = s;
1682 me->states[me->nstates].movestr = movestr;
1683 me->states[me->nstates].movetype = SOLVE;
1684 me->statepos = ++me->nstates;
1686 me->ourgame->changed_state(me->ui,
1687 me->states[me->statepos-2].state,
1688 me->states[me->statepos-1].state);
1690 if (me->ourgame->flags & SOLVE_ANIMATES) {
1691 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1693 me->ourgame->anim_length(me->states[me->statepos-2].state,
1694 me->states[me->statepos-1].state,
1698 me->anim_time = 0.0;
1699 midend_finish_move(me);
1703 midend_set_timer(me);
1707 int midend_status(midend *me)
1710 * We should probably never be called when the state stack has no
1711 * states on it at all - ideally, midends should never be left in
1712 * that state for long enough to get put down and forgotten about.
1713 * But if we are, I think we return _true_ - pedantically speaking
1714 * a midend in that state is 'vacuously solved', and more
1715 * practically, a user whose midend has been left in that state
1716 * probably _does_ want the 'new game' option to be prominent.
1718 if (me->statepos == 0)
1721 return me->ourgame->status(me->states[me->statepos-1].state);
1724 char *midend_rewrite_statusbar(midend *me, char *text)
1727 * An important special case is that we are occasionally called
1728 * with our own laststatus, to update the timer.
1730 if (me->laststatus != text) {
1731 sfree(me->laststatus);
1732 me->laststatus = dupstr(text);
1735 if (me->ourgame->is_timed) {
1736 char timebuf[100], *ret;
1739 sec = (int)me->elapsed;
1742 sprintf(timebuf, "[%d:%02d] ", min, sec);
1744 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1745 strcpy(ret, timebuf);
1750 return dupstr(text);
1754 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1755 #define SERIALISE_VERSION "1"
1757 void midend_serialise(midend *me,
1758 void (*write)(void *ctx, void *buf, int len),
1764 * Each line of the save file contains three components. First
1765 * exactly 8 characters of header word indicating what type of
1766 * data is contained on the line; then a colon followed by a
1767 * decimal integer giving the length of the main string on the
1768 * line; then a colon followed by the string itself (exactly as
1769 * many bytes as previously specified, no matter what they
1770 * contain). Then a newline (of reasonably flexible form).
1772 #define wr(h,s) do { \
1776 copy_left_justified(lbuf, sizeof(lbuf), h); \
1777 sprintf(hbuf, "%s:%d:", lbuf, (int)strlen(str)); \
1778 write(wctx, hbuf, strlen(hbuf)); \
1779 write(wctx, str, strlen(str)); \
1780 write(wctx, "\n", 1); \
1784 * Magic string identifying the file, and version number of the
1787 wr("SAVEFILE", SERIALISE_MAGIC);
1788 wr("VERSION", SERIALISE_VERSION);
1791 * The game name. (Copied locally to avoid const annoyance.)
1794 char *s = dupstr(me->ourgame->name);
1800 * The current long-term parameters structure, in full.
1803 char *s = me->ourgame->encode_params(me->params, TRUE);
1809 * The current short-term parameters structure, in full.
1811 if (me->curparams) {
1812 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1818 * The current game description, the privdesc, and the random seed.
1821 wr("SEED", me->seedstr);
1823 wr("DESC", me->desc);
1825 wr("PRIVDESC", me->privdesc);
1828 * The game's aux_info. We obfuscate this to prevent spoilers
1829 * (people are likely to run `head' or similar on a saved game
1830 * file simply to find out what it is, and don't necessarily
1831 * want to be told the answer to the puzzle!)
1838 len = strlen(me->aux_info);
1839 s1 = snewn(len, unsigned char);
1840 memcpy(s1, me->aux_info, len);
1841 obfuscate_bitmap(s1, len*8, FALSE);
1842 s2 = bin2hex(s1, len);
1851 * Any required serialisation of the game_ui.
1854 char *s = me->ourgame->encode_ui(me->ui);
1862 * The game time, if it's a timed game.
1864 if (me->ourgame->is_timed) {
1866 sprintf(buf, "%g", me->elapsed);
1871 * The length of, and position in, the states list.
1875 sprintf(buf, "%d", me->nstates);
1877 sprintf(buf, "%d", me->statepos);
1878 wr("STATEPOS", buf);
1882 * For each state after the initial one (which we know is
1883 * constructed from either privdesc or desc), enough
1884 * information for execute_move() to reconstruct it from the
1887 for (i = 1; i < me->nstates; i++) {
1888 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1889 switch (me->states[i].movetype) {
1891 wr("MOVE", me->states[i].movestr);
1894 wr("SOLVE", me->states[i].movestr);
1897 wr("RESTART", me->states[i].movestr);
1906 * Internal version of midend_deserialise, taking an extra check
1907 * function to be called just before beginning to install things in
1910 * Like midend_deserialise proper, this function returns NULL on
1911 * success, or an error message.
1913 static const char *midend_deserialise_internal(
1914 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx,
1915 char *(*check)(void *ctx, midend *, const struct deserialise_data *data),
1918 struct deserialise_data data;
1920 int started = FALSE;
1924 /* Initially all errors give the same report */
1925 char *ret = "Data does not appear to be a saved game file";
1927 data.seed = data.parstr = data.desc = data.privdesc = NULL;
1928 data.auxinfo = data.uistr = data.cparstr = NULL;
1929 data.elapsed = 0.0F;
1930 data.params = data.cparams = NULL;
1937 * Loop round and round reading one key/value pair at a time
1938 * from the serialised stream, until we have enough game states
1941 while (data.nstates <= 0 || data.statepos < 0 ||
1942 gotstates < data.nstates-1) {
1947 if (!read(rctx, key, 1)) {
1948 /* unexpected EOF */
1951 } while (key[0] == '\r' || key[0] == '\n');
1953 if (!read(rctx, key+1, 8)) {
1954 /* unexpected EOF */
1958 if (key[8] != ':') {
1960 ret = "Data was incorrectly formatted for a saved game file";
1963 len = strcspn(key, ": ");
1969 if (!read(rctx, &c, 1)) {
1970 /* unexpected EOF */
1976 } else if (c >= '0' && c <= '9') {
1977 len = (len * 10) + (c - '0');
1980 ret = "Data was incorrectly formatted for a"
1986 val = snewn(len+1, char);
1987 if (!read(rctx, val, len)) {
1994 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1995 /* ret already has the right message in it */
1998 /* Now most errors are this one, unless otherwise specified */
1999 ret = "Saved data ended unexpectedly";
2002 if (!strcmp(key, "VERSION")) {
2003 if (strcmp(val, SERIALISE_VERSION)) {
2004 ret = "Cannot handle this version of the saved game"
2008 } else if (!strcmp(key, "GAME")) {
2009 if (strcmp(val, me->ourgame->name)) {
2010 ret = "Save file is from a different game";
2013 } else if (!strcmp(key, "PARAMS")) {
2017 } else if (!strcmp(key, "CPARAMS")) {
2018 sfree(data.cparstr);
2021 } else if (!strcmp(key, "SEED")) {
2025 } else if (!strcmp(key, "DESC")) {
2029 } else if (!strcmp(key, "PRIVDESC")) {
2030 sfree(data.privdesc);
2031 data.privdesc = val;
2033 } else if (!strcmp(key, "AUXINFO")) {
2035 int len = strlen(val) / 2; /* length in bytes */
2036 tmp = hex2bin(val, len);
2037 obfuscate_bitmap(tmp, len*8, TRUE);
2039 sfree(data.auxinfo);
2040 data.auxinfo = snewn(len + 1, char);
2041 memcpy(data.auxinfo, tmp, len);
2042 data.auxinfo[len] = '\0';
2044 } else if (!strcmp(key, "UI")) {
2048 } else if (!strcmp(key, "TIME")) {
2049 data.elapsed = (float)atof(val);
2050 } else if (!strcmp(key, "NSTATES")) {
2051 data.nstates = atoi(val);
2052 if (data.nstates <= 0) {
2053 ret = "Number of states in save file was negative";
2057 ret = "Two state counts provided in save file";
2060 data.states = snewn(data.nstates, struct midend_state_entry);
2061 for (i = 0; i < data.nstates; i++) {
2062 data.states[i].state = NULL;
2063 data.states[i].movestr = NULL;
2064 data.states[i].movetype = NEWGAME;
2066 } else if (!strcmp(key, "STATEPOS")) {
2067 data.statepos = atoi(val);
2068 } else if (!strcmp(key, "MOVE")) {
2070 data.states[gotstates].movetype = MOVE;
2071 data.states[gotstates].movestr = val;
2073 } else if (!strcmp(key, "SOLVE")) {
2075 data.states[gotstates].movetype = SOLVE;
2076 data.states[gotstates].movestr = val;
2078 } else if (!strcmp(key, "RESTART")) {
2080 data.states[gotstates].movetype = RESTART;
2081 data.states[gotstates].movestr = val;
2090 data.params = me->ourgame->default_params();
2091 me->ourgame->decode_params(data.params, data.parstr);
2092 if (me->ourgame->validate_params(data.params, TRUE)) {
2093 ret = "Long-term parameters in save file are invalid";
2096 data.cparams = me->ourgame->default_params();
2097 me->ourgame->decode_params(data.cparams, data.cparstr);
2098 if (me->ourgame->validate_params(data.cparams, FALSE)) {
2099 ret = "Short-term parameters in save file are invalid";
2102 if (data.seed && me->ourgame->validate_params(data.cparams, TRUE)) {
2104 * The seed's no use with this version, but we can perfectly
2105 * well use the rest of the data.
2111 ret = "Game description in save file is missing";
2113 } else if (me->ourgame->validate_desc(data.cparams, data.desc)) {
2114 ret = "Game description in save file is invalid";
2117 if (data.privdesc &&
2118 me->ourgame->validate_desc(data.cparams, data.privdesc)) {
2119 ret = "Game private description in save file is invalid";
2122 if (data.statepos < 0 || data.statepos >= data.nstates) {
2123 ret = "Game position in save file is out of range";
2126 data.states[0].state = me->ourgame->new_game(
2127 me, data.cparams, data.privdesc ? data.privdesc : data.desc);
2128 for (i = 1; i < data.nstates; i++) {
2129 assert(data.states[i].movetype != NEWGAME);
2130 switch (data.states[i].movetype) {
2133 data.states[i].state = me->ourgame->execute_move(
2134 data.states[i-1].state, data.states[i].movestr);
2135 if (data.states[i].state == NULL) {
2136 ret = "Save file contained an invalid move";
2141 if (me->ourgame->validate_desc(
2142 data.cparams, data.states[i].movestr)) {
2143 ret = "Save file contained an invalid restart move";
2146 data.states[i].state = me->ourgame->new_game(
2147 me, data.cparams, data.states[i].movestr);
2152 data.ui = me->ourgame->new_ui(data.states[0].state);
2153 me->ourgame->decode_ui(data.ui, data.uistr);
2156 * Run the externally provided check function, and abort if it
2157 * returns an error message.
2159 if (check && (ret = check(cctx, me, &data)) != NULL)
2160 goto cleanup; /* error message is already in ret */
2163 * Now we've run out of possible error conditions, so we're
2164 * ready to start overwriting the real data in the current
2165 * midend. We'll do this by swapping things with the local
2166 * variables, so that the same cleanup code will free the old
2173 me->desc = data.desc;
2177 me->privdesc = data.privdesc;
2178 data.privdesc = tmp;
2181 me->seedstr = data.seed;
2185 me->aux_info = data.auxinfo;
2189 me->genmode = GOT_NOTHING;
2191 me->statesize = data.nstates;
2192 data.nstates = me->nstates;
2193 me->nstates = me->statesize;
2195 struct midend_state_entry *tmp;
2197 me->states = data.states;
2200 me->statepos = data.statepos;
2203 * Don't save the "new game undo" state. So "new game" twice or
2204 * (in some environments) switching away and back, will make a
2205 * "new game" irreversible. Maybe in the future we will have a
2206 * more sophisticated way to decide when to discard the previous
2209 me->newgame_undo_len = 0;
2215 me->params = data.params;
2218 tmp = me->curparams;
2219 me->curparams = data.cparams;
2223 me->oldstate = NULL;
2224 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
2235 me->elapsed = data.elapsed;
2236 me->pressed_mouse_button = 0;
2238 midend_set_timer(me);
2241 me->ourgame->free_drawstate(me->drawing, me->drawstate);
2243 me->ourgame->new_drawstate(me->drawing,
2244 me->states[me->statepos-1].state);
2245 midend_size_new_drawstate(me);
2246 if (me->game_id_change_notify_function)
2247 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
2249 ret = NULL; /* success! */
2255 sfree(data.cparstr);
2257 sfree(data.privdesc);
2258 sfree(data.auxinfo);
2261 me->ourgame->free_params(data.params);
2263 me->ourgame->free_params(data.cparams);
2265 me->ourgame->free_ui(data.ui);
2269 for (i = 0; i < data.nstates; i++) {
2270 if (data.states[i].state)
2271 me->ourgame->free_game(data.states[i].state);
2272 sfree(data.states[i].movestr);
2280 const char *midend_deserialise(
2281 midend *me, int (*read)(void *ctx, void *buf, int len), void *rctx)
2283 return midend_deserialise_internal(me, read, rctx, NULL, NULL);
2287 * This function examines a saved game file just far enough to
2288 * determine which game type it contains. It returns NULL on success
2289 * and the game name string in 'name' (which will be dynamically
2290 * allocated and should be caller-freed), or an error message on
2293 const char *identify_game(char **name,
2294 int (*read)(void *ctx, void *buf, int len),
2297 int nstates = 0, statepos = -1, gotstates = 0;
2298 int started = FALSE;
2301 /* Initially all errors give the same report */
2302 char *ret = "Data does not appear to be a saved game file";
2307 * Loop round and round reading one key/value pair at a time from
2308 * the serialised stream, until we've found the game name.
2310 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2315 if (!read(rctx, key, 1)) {
2316 /* unexpected EOF */
2319 } while (key[0] == '\r' || key[0] == '\n');
2321 if (!read(rctx, key+1, 8)) {
2322 /* unexpected EOF */
2326 if (key[8] != ':') {
2328 ret = "Data was incorrectly formatted for a saved game file";
2331 len = strcspn(key, ": ");
2337 if (!read(rctx, &c, 1)) {
2338 /* unexpected EOF */
2344 } else if (c >= '0' && c <= '9') {
2345 len = (len * 10) + (c - '0');
2348 ret = "Data was incorrectly formatted for a"
2354 val = snewn(len+1, char);
2355 if (!read(rctx, val, len)) {
2362 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2363 /* ret already has the right message in it */
2366 /* Now most errors are this one, unless otherwise specified */
2367 ret = "Saved data ended unexpectedly";
2370 if (!strcmp(key, "VERSION")) {
2371 if (strcmp(val, SERIALISE_VERSION)) {
2372 ret = "Cannot handle this version of the saved game"
2376 } else if (!strcmp(key, "GAME")) {
2377 *name = dupstr(val);
2392 const char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2394 game_state *soln = NULL;
2396 if (me->statepos < 1)
2397 return "No game set up to print";/* _shouldn't_ happen! */
2403 if (!me->ourgame->can_solve)
2404 return "This game does not support the Solve operation";
2406 msg = "Solve operation failed";/* game _should_ overwrite on error */
2407 movestr = me->ourgame->solve(me->states[0].state,
2408 me->states[me->statepos-1].state,
2409 me->aux_info, &msg);
2412 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2421 * This call passes over ownership of the two game_states and
2422 * the game_params. Hence we duplicate the ones we want to
2423 * keep, and we don't have to bother freeing soln if it was
2426 document_add_puzzle(doc, me->ourgame,
2427 me->ourgame->dup_params(me->curparams),
2428 me->ourgame->dup_game(me->states[0].state), soln);