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 game_params **presets;
35 int npresets, presetsize;
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 tilesize, winwidth, winheight;
86 #define ensure(me) do { \
87 if ((me)->nstates >= (me)->statesize) { \
88 (me)->statesize = (me)->nstates + 128; \
89 (me)->states = sresize((me)->states, (me)->statesize, \
90 struct midend_state_entry); \
94 midend *midend_new(frontend *fe, const game *ourgame,
95 const drawing_api *drapi, void *drhandle)
97 midend *me = snew(midend);
101 get_random_seed(&randseed, &randseedsize);
104 me->ourgame = ourgame;
105 me->random = random_init(randseed, randseedsize);
106 me->nstates = me->statesize = me->statepos = 0;
108 me->params = ourgame->default_params();
109 me->curparams = NULL;
110 me->desc = me->privdesc = NULL;
113 me->genmode = GOT_NOTHING;
114 me->drawstate = NULL;
117 me->preset_names = NULL;
118 me->npresets = me->presetsize = 0;
119 me->anim_time = me->anim_pos = 0.0F;
120 me->flash_time = me->flash_pos = 0.0F;
123 me->pressed_mouse_button = 0;
124 me->laststatus = NULL;
127 me->tilesize = me->winwidth = me->winheight = 0;
129 me->drawing = drawing_init(drapi, drhandle);
138 static void midend_free_game(midend *me)
140 while (me->nstates > 0) {
142 me->ourgame->free_game(me->states[me->nstates].state);
143 sfree(me->states[me->nstates].movestr);
147 me->ourgame->free_drawstate(me->drawing, me->drawstate);
150 void midend_free(midend *me)
154 midend_free_game(me);
157 drawing_free(me->drawing);
158 random_free(me->random);
164 me->ourgame->free_params(me->params);
166 for (i = 0; i < me->npresets; i++) {
167 sfree(me->presets[i]);
168 sfree(me->preset_names[i]);
171 sfree(me->preset_names);
174 me->ourgame->free_ui(me->ui);
176 me->ourgame->free_params(me->curparams);
177 sfree(me->laststatus);
181 static void midend_size_new_drawstate(midend *me)
184 * Don't even bother, if we haven't worked out our tile size
187 if (me->tilesize > 0) {
188 me->ourgame->compute_size(me->params, me->tilesize,
189 &me->winwidth, &me->winheight);
190 me->ourgame->set_size(me->drawing, me->drawstate,
191 me->params, me->tilesize);
195 void midend_size(midend *me, int *x, int *y, int expand)
201 * Find the tile size that best fits within the given space. If
202 * `expand' is TRUE, we must actually find the _largest_ such
203 * tile size; otherwise, we bound above at the game's preferred
210 me->ourgame->compute_size(me->params, max, &rx, &ry);
211 } while (rx <= *x && ry <= *y);
213 max = me->ourgame->preferred_tilesize + 1;
217 * Now binary-search between min and max. We're looking for a
218 * boundary rather than a value: the point at which tile sizes
219 * stop fitting within the given dimensions. Thus, we stop when
220 * max and min differ by exactly 1.
222 while (max - min > 1) {
223 int mid = (max + min) / 2;
224 me->ourgame->compute_size(me->params, mid, &rx, &ry);
225 if (rx <= *x && ry <= *y)
232 * Now `min' is a valid size, and `max' isn't. So use `min'.
236 midend_size_new_drawstate(me);
241 void midend_set_params(midend *me, game_params *params)
243 me->ourgame->free_params(me->params);
244 me->params = me->ourgame->dup_params(params);
247 game_params *midend_get_params(midend *me)
249 return me->ourgame->dup_params(me->params);
252 static void midend_set_timer(midend *me)
254 me->timing = (me->ourgame->is_timed &&
255 me->ourgame->timing_state(me->states[me->statepos-1].state,
257 if (me->timing || me->flash_time || me->anim_time)
258 activate_timer(me->frontend);
260 deactivate_timer(me->frontend);
263 void midend_force_redraw(midend *me)
266 me->ourgame->free_drawstate(me->drawing, me->drawstate);
267 me->drawstate = me->ourgame->new_drawstate(me->drawing,
268 me->states[0].state);
269 midend_size_new_drawstate(me);
273 void midend_new_game(midend *me)
275 midend_free_game(me);
277 assert(me->nstates == 0);
279 if (me->genmode == GOT_DESC) {
280 me->genmode = GOT_NOTHING;
284 if (me->genmode == GOT_SEED) {
285 me->genmode = GOT_NOTHING;
288 * Generate a new random seed. 15 digits comes to about
289 * 48 bits, which should be more than enough.
291 * I'll avoid putting a leading zero on the number,
292 * just in case it confuses anybody who thinks it's
293 * processed as an integer rather than a string.
298 newseed[0] = '1' + random_upto(me->random, 9);
299 for (i = 1; i < 15; i++)
300 newseed[i] = '0' + random_upto(me->random, 10);
302 me->seedstr = dupstr(newseed);
305 me->ourgame->free_params(me->curparams);
306 me->curparams = me->ourgame->dup_params(me->params);
314 rs = random_init(me->seedstr, strlen(me->seedstr));
316 * If this midend has been instantiated without providing a
317 * drawing API, it is non-interactive. This means that it's
318 * being used for bulk game generation, and hence we should
319 * pass the non-interactive flag to new_desc.
321 me->desc = me->ourgame->new_desc(me->curparams, rs,
322 &me->aux_info, (me->drawing != NULL));
328 me->states[me->nstates].state =
329 me->ourgame->new_game(me, me->params, me->desc);
330 me->states[me->nstates].movestr = NULL;
331 me->states[me->nstates].movetype = NEWGAME;
334 me->drawstate = me->ourgame->new_drawstate(me->drawing,
335 me->states[0].state);
336 midend_size_new_drawstate(me);
339 me->ourgame->free_ui(me->ui);
340 me->ui = me->ourgame->new_ui(me->states[0].state);
341 midend_set_timer(me);
342 me->pressed_mouse_button = 0;
345 static int midend_undo(midend *me)
347 if (me->statepos > 1) {
349 me->ourgame->changed_state(me->ui,
350 me->states[me->statepos-1].state,
351 me->states[me->statepos-2].state);
359 static int midend_redo(midend *me)
361 if (me->statepos < me->nstates) {
363 me->ourgame->changed_state(me->ui,
364 me->states[me->statepos-1].state,
365 me->states[me->statepos].state);
373 static void midend_finish_move(midend *me)
378 * We do not flash if the later of the two states is special.
379 * This covers both forward Solve moves and backward (undone)
382 if ((me->oldstate || me->statepos > 1) &&
383 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
384 (me->dir < 0 && me->statepos < me->nstates &&
385 !special(me->states[me->statepos].movetype)))) {
386 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
387 me->states[me->statepos-2].state,
388 me->states[me->statepos-1].state,
389 me->oldstate ? me->dir : +1,
392 me->flash_pos = 0.0F;
393 me->flash_time = flashtime;
398 me->ourgame->free_game(me->oldstate);
400 me->anim_pos = me->anim_time = 0;
403 midend_set_timer(me);
406 void midend_stop_anim(midend *me)
408 if (me->oldstate || me->anim_time != 0) {
409 midend_finish_move(me);
414 void midend_restart_game(midend *me)
418 midend_stop_anim(me);
420 assert(me->statepos >= 1);
421 if (me->statepos == 1)
422 return; /* no point doing anything at all! */
425 * During restart, we reconstruct the game from the (public)
426 * game description rather than from states[0], because that
427 * way Mines gets slightly more sensible behaviour (restart
428 * goes to _after_ the first click so you don't have to
429 * remember where you clicked).
431 s = me->ourgame->new_game(me, me->params, me->desc);
434 * Now enter the restarted state as the next move.
436 midend_stop_anim(me);
437 while (me->nstates > me->statepos)
438 me->ourgame->free_game(me->states[--me->nstates].state);
440 me->states[me->nstates].state = s;
441 me->states[me->nstates].movestr = dupstr(me->desc);
442 me->states[me->nstates].movetype = RESTART;
443 me->statepos = ++me->nstates;
445 me->ourgame->changed_state(me->ui,
446 me->states[me->statepos-2].state,
447 me->states[me->statepos-1].state);
449 midend_finish_move(me);
451 midend_set_timer(me);
454 static int midend_really_process_key(midend *me, int x, int y, int button)
456 game_state *oldstate =
457 me->ourgame->dup_game(me->states[me->statepos - 1].state);
458 int type = MOVE, gottype = FALSE, ret = 1;
464 me->ourgame->interpret_move(me->states[me->statepos-1].state,
465 me->ui, me->drawstate, x, y, button);
468 if (button == 'n' || button == 'N' || button == '\x0E') {
469 midend_stop_anim(me);
472 goto done; /* never animate */
473 } else if (button == 'u' || button == 'u' ||
474 button == '\x1A' || button == '\x1F') {
475 midend_stop_anim(me);
476 type = me->states[me->statepos-1].movetype;
478 if (!midend_undo(me))
480 } else if (button == 'r' || button == 'R' ||
481 button == '\x12' || button == '\x19') {
482 midend_stop_anim(me);
483 if (!midend_redo(me))
485 } else if (button == 'q' || button == 'Q' || button == '\x11') {
492 s = me->states[me->statepos-1].state;
494 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
499 if (s == me->states[me->statepos-1].state) {
501 * make_move() is allowed to return its input state to
502 * indicate that although no move has been made, the UI
503 * state has been updated and a redraw is called for.
508 midend_stop_anim(me);
509 while (me->nstates > me->statepos)
510 me->ourgame->free_game(me->states[--me->nstates].state);
512 assert(movestr != NULL);
513 me->states[me->nstates].state = s;
514 me->states[me->nstates].movestr = movestr;
515 me->states[me->nstates].movetype = MOVE;
516 me->statepos = ++me->nstates;
519 me->ourgame->changed_state(me->ui,
520 me->states[me->statepos-2].state,
521 me->states[me->statepos-1].state);
528 type = me->states[me->statepos-1].movetype;
531 * See if this move requires an animation.
533 if (special(type) && !(type == SOLVE &&
534 (me->ourgame->mouse_priorities & SOLVE_ANIMATES))) {
537 anim_time = me->ourgame->anim_length(oldstate,
538 me->states[me->statepos-1].state,
542 me->oldstate = oldstate; oldstate = NULL;
544 me->anim_time = anim_time;
547 midend_finish_move(me);
553 midend_set_timer(me);
556 if (oldstate) me->ourgame->free_game(oldstate);
560 int midend_process_key(midend *me, int x, int y, int button)
565 * Harmonise mouse drag and release messages.
567 * Some front ends might accidentally switch from sending, say,
568 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
569 * drag. (This can happen on the Mac, for example, since
570 * RIGHT_DRAG is usually done using Command+drag, and if the
571 * user accidentally releases Command half way through the drag
572 * then there will be trouble.)
574 * It would be an O(number of front ends) annoyance to fix this
575 * in the front ends, but an O(number of back ends) annoyance
576 * to have each game capable of dealing with it. Therefore, we
577 * fix it _here_ in the common midend code so that it only has
580 * The possible ways in which things can go screwy in the front
583 * - in a system containing multiple physical buttons button
584 * presses can inadvertently overlap. We can see ABab (caps
585 * meaning button-down and lowercase meaning button-up) when
586 * the user had semantically intended AaBb.
588 * - in a system where one button is simulated by means of a
589 * modifier key and another button, buttons can mutate
590 * between press and release (possibly during drag). So we
591 * can see Ab instead of Aa.
593 * Definite requirements are:
595 * - button _presses_ must never be invented or destroyed. If
596 * the user presses two buttons in succession, the button
597 * presses must be transferred to the backend unchanged. So
598 * if we see AaBb , that's fine; if we see ABab (the button
599 * presses inadvertently overlapped) we must somehow
600 * `correct' it to AaBb.
602 * - every mouse action must end up looking like a press, zero
603 * or more drags, then a release. This allows back ends to
604 * make the _assumption_ that incoming mouse data will be
605 * sane in this regard, and not worry about the details.
607 * So my policy will be:
609 * - treat any button-up as a button-up for the currently
610 * pressed button, or ignore it if there is no currently
613 * - treat any drag as a drag for the currently pressed
614 * button, or ignore it if there is no currently pressed
617 * - if we see a button-down while another button is currently
618 * pressed, invent a button-up for the first one and then
619 * pass the button-down through as before.
621 * 2005-05-31: An addendum to the above. Some games might want
622 * a `priority order' among buttons, such that if one button is
623 * pressed while another is down then a fixed one of the
624 * buttons takes priority no matter what order they're pressed
625 * in. Mines, in particular, wants to treat a left+right click
626 * like a left click for the benefit of users of other
627 * implementations. So the last of the above points is modified
628 * in the presence of an (optional) button priority order.
630 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
631 if (me->pressed_mouse_button) {
632 if (IS_MOUSE_DRAG(button)) {
633 button = me->pressed_mouse_button +
634 (LEFT_DRAG - LEFT_BUTTON);
636 button = me->pressed_mouse_button +
637 (LEFT_RELEASE - LEFT_BUTTON);
640 return ret; /* ignore it */
641 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
643 * If the new button has lower priority than the old one,
644 * don't bother doing this.
646 if (me->ourgame->mouse_priorities &
647 BUTTON_BEATS(me->pressed_mouse_button, button))
648 return ret; /* just ignore it */
651 * Fabricate a button-up for the previously pressed button.
653 ret = ret && midend_really_process_key
654 (me, x, y, (me->pressed_mouse_button +
655 (LEFT_RELEASE - LEFT_BUTTON)));
659 * Now send on the event we originally received.
661 ret = ret && midend_really_process_key(me, x, y, button);
664 * And update the currently pressed button.
666 if (IS_MOUSE_RELEASE(button))
667 me->pressed_mouse_button = 0;
668 else if (IS_MOUSE_DOWN(button))
669 me->pressed_mouse_button = button;
674 void midend_redraw(midend *me)
678 if (me->statepos > 0 && me->drawstate) {
679 start_draw(me->drawing);
680 if (me->oldstate && me->anim_time > 0 &&
681 me->anim_pos < me->anim_time) {
682 assert(me->dir != 0);
683 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
684 me->states[me->statepos-1].state, me->dir,
685 me->ui, me->anim_pos, me->flash_pos);
687 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
688 me->states[me->statepos-1].state, +1 /*shrug*/,
689 me->ui, 0.0, me->flash_pos);
691 end_draw(me->drawing);
695 void midend_timer(midend *me, float tplus)
697 me->anim_pos += tplus;
698 if (me->anim_pos >= me->anim_time ||
699 me->anim_time == 0 || !me->oldstate) {
700 if (me->anim_time > 0)
701 midend_finish_move(me);
704 me->flash_pos += tplus;
705 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
706 me->flash_pos = me->flash_time = 0;
712 float oldelapsed = me->elapsed;
713 me->elapsed += tplus;
714 if ((int)oldelapsed != (int)me->elapsed)
715 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
718 midend_set_timer(me);
721 float *midend_colours(midend *me, int *ncolours)
723 game_state *state = NULL;
726 if (me->nstates == 0) {
728 char *desc = me->ourgame->new_desc(me->params, me->random,
730 state = me->ourgame->new_game(me, me->params, desc);
734 state = me->states[0].state;
736 ret = me->ourgame->colours(me->frontend, state, ncolours);
742 * Allow environment-based overrides for the standard
743 * colours by defining variables along the lines of
744 * `NET_COLOUR_4=6000c0'.
747 for (i = 0; i < *ncolours; i++) {
749 unsigned int r, g, b;
752 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
753 for (j = k = 0; buf[j]; j++)
754 if (!isspace((unsigned char)buf[j]))
755 buf[k++] = toupper((unsigned char)buf[j]);
757 if ((e = getenv(buf)) != NULL &&
758 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
759 ret[i*3 + 0] = r / 255.0;
760 ret[i*3 + 1] = g / 255.0;
761 ret[i*3 + 2] = b / 255.0;
766 if (me->nstates == 0)
767 me->ourgame->free_game(state);
772 int midend_num_presets(midend *me)
778 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
779 if (me->presetsize <= me->npresets) {
780 me->presetsize = me->npresets + 10;
781 me->presets = sresize(me->presets, me->presetsize,
783 me->preset_names = sresize(me->preset_names, me->presetsize,
787 me->presets[me->npresets] = preset;
788 me->preset_names[me->npresets] = name;
795 * Allow environment-based extensions to the preset list by
796 * defining a variable along the lines of `SOLO_PRESETS=2x3
797 * Advanced:2x3da'. Colon-separated list of items,
798 * alternating between textual titles in the menu and
799 * encoded parameter strings.
801 char buf[80], *e, *p;
804 sprintf(buf, "%s_PRESETS", me->ourgame->name);
805 for (j = k = 0; buf[j]; j++)
806 if (!isspace((unsigned char)buf[j]))
807 buf[k++] = toupper((unsigned char)buf[j]);
810 if ((e = getenv(buf)) != NULL) {
818 while (*p && *p != ':') p++;
821 while (*p && *p != ':') p++;
824 preset = me->ourgame->default_params();
825 me->ourgame->decode_params(preset, val);
827 if (me->ourgame->validate_params(preset, TRUE)) {
828 /* Drop this one from the list. */
829 me->ourgame->free_params(preset);
833 if (me->presetsize <= me->npresets) {
834 me->presetsize = me->npresets + 10;
835 me->presets = sresize(me->presets, me->presetsize,
837 me->preset_names = sresize(me->preset_names,
838 me->presetsize, char *);
841 me->presets[me->npresets] = preset;
842 me->preset_names[me->npresets] = dupstr(name);
851 void midend_fetch_preset(midend *me, int n,
852 char **name, game_params **params)
854 assert(n >= 0 && n < me->npresets);
855 *name = me->preset_names[n];
856 *params = me->presets[n];
859 int midend_wants_statusbar(midend *me)
861 return me->ourgame->wants_statusbar();
864 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
868 me->desc = dupstr(desc);
869 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
872 config_item *midend_get_config(midend *me, int which, char **wintitle)
874 char *titlebuf, *parstr, *rest;
879 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
883 sprintf(titlebuf, "%s configuration", me->ourgame->name);
884 *wintitle = titlebuf;
885 return me->ourgame->configure(me->params);
888 if (!me->curparams) {
892 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
893 which == CFG_SEED ? "random" : "game");
894 *wintitle = titlebuf;
896 ret = snewn(2, config_item);
898 ret[0].type = C_STRING;
899 if (which == CFG_SEED)
900 ret[0].name = "Game random seed";
902 ret[0].name = "Game ID";
905 * For CFG_DESC the text going in here will be a string
906 * encoding of the restricted parameters, plus a colon,
907 * plus the game description. For CFG_SEED it will be the
908 * full parameters, plus a hash, plus the random seed data.
909 * Either of these is a valid full game ID (although only
910 * the former is likely to persist across many code
913 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
915 if (which == CFG_DESC) {
916 rest = me->desc ? me->desc : "";
919 rest = me->seedstr ? me->seedstr : "";
922 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
923 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
927 ret[1].name = ret[1].sval = NULL;
933 assert(!"We shouldn't be here");
937 static char *midend_game_id_int(midend *me, char *id, int defmode)
939 char *error, *par, *desc, *seed;
940 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
943 seed = strchr(id, '#');
944 desc = strchr(id, ':');
946 if (desc && (!seed || desc < seed)) {
948 * We have a colon separating parameters from game
949 * description. So `par' now points to the parameters
950 * string, and `desc' to the description string.
955 } else if (seed && (!desc || seed < desc)) {
957 * We have a hash separating parameters from random seed.
958 * So `par' now points to the parameters string, and `seed'
959 * to the seed string.
966 * We only have one string. Depending on `defmode', we take
967 * it to be either parameters, seed or description.
969 if (defmode == DEF_SEED) {
972 } else if (defmode == DEF_DESC) {
982 * We must be reasonably careful here not to modify anything in
983 * `me' until we have finished validating things. This function
984 * must either return an error and do nothing to the midend, or
985 * return success and do everything; nothing in between is
988 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
991 newcurparams = me->ourgame->dup_params(me->params);
992 me->ourgame->decode_params(newcurparams, par);
993 error = me->ourgame->validate_params(newcurparams, desc == NULL);
995 me->ourgame->free_params(newcurparams);
998 oldparams1 = me->curparams;
1001 * Now filter only the persistent parts of this state into
1002 * the long-term params structure, unless we've _only_
1003 * received a params string in which case the whole lot is
1006 oldparams2 = me->params;
1010 newparams = me->ourgame->dup_params(me->params);
1012 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1013 me->ourgame->decode_params(newparams, tmpstr);
1017 newparams = me->ourgame->dup_params(newcurparams);
1021 newcurparams = me->curparams;
1022 newparams = me->params;
1023 free_params = FALSE;
1027 error = me->ourgame->validate_desc(newparams, desc);
1031 me->ourgame->free_params(newcurparams);
1033 me->ourgame->free_params(newparams);
1040 * Now we've got past all possible error points. Update the
1043 me->params = newparams;
1044 me->curparams = newcurparams;
1046 me->ourgame->free_params(oldparams1);
1048 me->ourgame->free_params(oldparams2);
1051 sfree(me->privdesc);
1052 me->desc = me->privdesc = NULL;
1057 me->desc = dupstr(desc);
1058 me->genmode = GOT_DESC;
1059 sfree(me->aux_info);
1060 me->aux_info = NULL;
1064 me->seedstr = dupstr(seed);
1065 me->genmode = GOT_SEED;
1071 char *midend_game_id(midend *me, char *id)
1073 return midend_game_id_int(me, id, DEF_PARAMS);
1076 char *midend_get_game_id(midend *me)
1080 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1083 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1084 sprintf(ret, "%s:%s", parstr, me->desc);
1089 char *midend_set_config(midend *me, int which, config_item *cfg)
1092 game_params *params;
1096 params = me->ourgame->custom_params(cfg);
1097 error = me->ourgame->validate_params(params, TRUE);
1100 me->ourgame->free_params(params);
1104 me->ourgame->free_params(me->params);
1105 me->params = params;
1110 error = midend_game_id_int(me, cfg[0].sval,
1111 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1120 char *midend_text_format(midend *me)
1122 if (me->ourgame->can_format_as_text && me->statepos > 0)
1123 return me->ourgame->text_format(me->states[me->statepos-1].state);
1128 char *midend_solve(midend *me)
1131 char *msg, *movestr;
1133 if (!me->ourgame->can_solve)
1134 return "This game does not support the Solve operation";
1136 if (me->statepos < 1)
1137 return "No game set up to solve"; /* _shouldn't_ happen! */
1139 msg = "Solve operation failed"; /* game _should_ overwrite on error */
1140 movestr = me->ourgame->solve(me->states[0].state,
1141 me->states[me->statepos-1].state,
1142 me->aux_info, &msg);
1145 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1149 * Now enter the solved state as the next move.
1151 midend_stop_anim(me);
1152 while (me->nstates > me->statepos)
1153 me->ourgame->free_game(me->states[--me->nstates].state);
1155 me->states[me->nstates].state = s;
1156 me->states[me->nstates].movestr = movestr;
1157 me->states[me->nstates].movetype = SOLVE;
1158 me->statepos = ++me->nstates;
1160 me->ourgame->changed_state(me->ui,
1161 me->states[me->statepos-2].state,
1162 me->states[me->statepos-1].state);
1164 if (me->ourgame->mouse_priorities & SOLVE_ANIMATES) {
1165 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1167 me->ourgame->anim_length(me->states[me->statepos-2].state,
1168 me->states[me->statepos-1].state,
1172 me->anim_time = 0.0;
1173 midend_finish_move(me);
1176 midend_set_timer(me);
1180 char *midend_rewrite_statusbar(midend *me, char *text)
1183 * An important special case is that we are occasionally called
1184 * with our own laststatus, to update the timer.
1186 if (me->laststatus != text) {
1187 sfree(me->laststatus);
1188 me->laststatus = dupstr(text);
1191 if (me->ourgame->is_timed) {
1192 char timebuf[100], *ret;
1198 sprintf(timebuf, "[%d:%02d] ", min, sec);
1200 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1201 strcpy(ret, timebuf);
1206 return dupstr(text);
1210 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1211 #define SERIALISE_VERSION "1"
1213 void midend_serialise(midend *me,
1214 void (*write)(void *ctx, void *buf, int len),
1220 * Each line of the save file contains three components. First
1221 * exactly 8 characters of header word indicating what type of
1222 * data is contained on the line; then a colon followed by a
1223 * decimal integer giving the length of the main string on the
1224 * line; then a colon followed by the string itself (exactly as
1225 * many bytes as previously specified, no matter what they
1226 * contain). Then a newline (of reasonably flexible form).
1228 #define wr(h,s) do { \
1231 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1232 write(wctx, hbuf, strlen(hbuf)); \
1233 write(wctx, str, strlen(str)); \
1234 write(wctx, "\n", 1); \
1238 * Magic string identifying the file, and version number of the
1241 wr("SAVEFILE", SERIALISE_MAGIC);
1242 wr("VERSION", SERIALISE_VERSION);
1245 * The game name. (Copied locally to avoid const annoyance.)
1248 char *s = dupstr(me->ourgame->name);
1254 * The current long-term parameters structure, in full.
1257 char *s = me->ourgame->encode_params(me->params, TRUE);
1263 * The current short-term parameters structure, in full.
1265 if (me->curparams) {
1266 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1272 * The current game description, the privdesc, and the random seed.
1275 wr("SEED", me->seedstr);
1277 wr("DESC", me->desc);
1279 wr("PRIVDESC", me->privdesc);
1282 * The game's aux_info. We obfuscate this to prevent spoilers
1283 * (people are likely to run `head' or similar on a saved game
1284 * file simply to find out what it is, and don't necessarily
1285 * want to be told the answer to the puzzle!)
1292 len = strlen(me->aux_info);
1293 s1 = snewn(len, unsigned char);
1294 memcpy(s1, me->aux_info, len);
1295 obfuscate_bitmap(s1, len*8, FALSE);
1296 s2 = bin2hex(s1, len);
1305 * Any required serialisation of the game_ui.
1308 char *s = me->ourgame->encode_ui(me->ui);
1316 * The game time, if it's a timed game.
1318 if (me->ourgame->is_timed) {
1320 sprintf(buf, "%g", me->elapsed);
1325 * The length of, and position in, the states list.
1329 sprintf(buf, "%d", me->nstates);
1331 sprintf(buf, "%d", me->statepos);
1332 wr("STATEPOS", buf);
1336 * For each state after the initial one (which we know is
1337 * constructed from either privdesc or desc), enough
1338 * information for execute_move() to reconstruct it from the
1341 for (i = 1; i < me->nstates; i++) {
1342 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1343 switch (me->states[i].movetype) {
1345 wr("MOVE", me->states[i].movestr);
1348 wr("SOLVE", me->states[i].movestr);
1351 wr("RESTART", me->states[i].movestr);
1360 * This function returns NULL on success, or an error message.
1362 char *midend_deserialise(midend *me,
1363 int (*read)(void *ctx, void *buf, int len),
1366 int nstates = 0, statepos = -1, gotstates = 0;
1367 int started = FALSE;
1371 /* Initially all errors give the same report */
1372 char *ret = "Data does not appear to be a saved game file";
1375 * We construct all the new state in local variables while we
1376 * check its sanity. Only once we have finished reading the
1377 * serialised data and detected no errors at all do we start
1378 * modifying stuff in the midend passed in.
1380 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1381 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1382 float elapsed = 0.0F;
1383 game_params *params = NULL, *cparams = NULL;
1385 struct midend_state_entry *states = NULL;
1388 * Loop round and round reading one key/value pair at a time
1389 * from the serialised stream, until we have enough game states
1392 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1397 if (!read(rctx, key, 1)) {
1398 /* unexpected EOF */
1401 } while (key[0] == '\r' || key[0] == '\n');
1403 if (!read(rctx, key+1, 8)) {
1404 /* unexpected EOF */
1408 if (key[8] != ':') {
1410 ret = "Data was incorrectly formatted for a saved game file";
1413 len = strcspn(key, ": ");
1419 if (!read(rctx, &c, 1)) {
1420 /* unexpected EOF */
1426 } else if (c >= '0' && c <= '9') {
1427 len = (len * 10) + (c - '0');
1430 ret = "Data was incorrectly formatted for a"
1436 val = snewn(len+1, char);
1437 if (!read(rctx, val, len)) {
1444 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1445 /* ret already has the right message in it */
1448 /* Now most errors are this one, unless otherwise specified */
1449 ret = "Saved data ended unexpectedly";
1452 if (!strcmp(key, "VERSION")) {
1453 if (strcmp(val, SERIALISE_VERSION)) {
1454 ret = "Cannot handle this version of the saved game"
1458 } else if (!strcmp(key, "GAME")) {
1459 if (strcmp(val, me->ourgame->name)) {
1460 ret = "Save file is from a different game";
1463 } else if (!strcmp(key, "PARAMS")) {
1467 } else if (!strcmp(key, "CPARAMS")) {
1471 } else if (!strcmp(key, "SEED")) {
1475 } else if (!strcmp(key, "DESC")) {
1479 } else if (!strcmp(key, "PRIVDESC")) {
1483 } else if (!strcmp(key, "AUXINFO")) {
1485 int len = strlen(val) / 2; /* length in bytes */
1486 tmp = hex2bin(val, len);
1487 obfuscate_bitmap(tmp, len*8, TRUE);
1490 auxinfo = snewn(len + 1, char);
1491 memcpy(auxinfo, tmp, len);
1492 auxinfo[len] = '\0';
1494 } else if (!strcmp(key, "UI")) {
1498 } else if (!strcmp(key, "TIME")) {
1499 elapsed = atof(val);
1500 } else if (!strcmp(key, "NSTATES")) {
1501 nstates = atoi(val);
1503 ret = "Number of states in save file was negative";
1507 ret = "Two state counts provided in save file";
1510 states = snewn(nstates, struct midend_state_entry);
1511 for (i = 0; i < nstates; i++) {
1512 states[i].state = NULL;
1513 states[i].movestr = NULL;
1514 states[i].movetype = NEWGAME;
1516 } else if (!strcmp(key, "STATEPOS")) {
1517 statepos = atoi(val);
1518 } else if (!strcmp(key, "MOVE")) {
1520 states[gotstates].movetype = MOVE;
1521 states[gotstates].movestr = val;
1523 } else if (!strcmp(key, "SOLVE")) {
1525 states[gotstates].movetype = SOLVE;
1526 states[gotstates].movestr = val;
1528 } else if (!strcmp(key, "RESTART")) {
1530 states[gotstates].movetype = RESTART;
1531 states[gotstates].movestr = val;
1540 params = me->ourgame->default_params();
1541 me->ourgame->decode_params(params, parstr);
1542 if (me->ourgame->validate_params(params, TRUE)) {
1543 ret = "Long-term parameters in save file are invalid";
1546 cparams = me->ourgame->default_params();
1547 me->ourgame->decode_params(cparams, cparstr);
1548 if (me->ourgame->validate_params(cparams, FALSE)) {
1549 ret = "Short-term parameters in save file are invalid";
1552 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1554 * The seed's no use with this version, but we can perfectly
1555 * well use the rest of the data.
1561 ret = "Game description in save file is missing";
1563 } else if (me->ourgame->validate_desc(params, desc)) {
1564 ret = "Game description in save file is invalid";
1567 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1568 ret = "Game private description in save file is invalid";
1571 if (statepos < 0 || statepos >= nstates) {
1572 ret = "Game position in save file is out of range";
1575 states[0].state = me->ourgame->new_game(me, params,
1576 privdesc ? privdesc : desc);
1577 for (i = 1; i < nstates; i++) {
1578 assert(states[i].movetype != NEWGAME);
1579 switch (states[i].movetype) {
1582 states[i].state = me->ourgame->execute_move(states[i-1].state,
1584 if (states[i].state == NULL) {
1585 ret = "Save file contained an invalid move";
1590 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1591 ret = "Save file contained an invalid restart move";
1594 states[i].state = me->ourgame->new_game(me, params,
1600 ui = me->ourgame->new_ui(states[0].state);
1601 me->ourgame->decode_ui(ui, uistr);
1604 * Now we've run out of possible error conditions, so we're
1605 * ready to start overwriting the real data in the current
1606 * midend. We'll do this by swapping things with the local
1607 * variables, so that the same cleanup code will free the old
1618 me->privdesc = privdesc;
1626 me->aux_info = auxinfo;
1630 me->genmode = GOT_NOTHING;
1632 me->statesize = nstates;
1633 nstates = me->nstates;
1634 me->nstates = me->statesize;
1636 struct midend_state_entry *tmp;
1638 me->states = states;
1641 me->statepos = statepos;
1647 me->params = params;
1650 tmp = me->curparams;
1651 me->curparams = cparams;
1655 me->oldstate = NULL;
1656 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1667 me->elapsed = elapsed;
1668 me->pressed_mouse_button = 0;
1670 midend_set_timer(me);
1673 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1675 me->ourgame->new_drawstate(me->drawing,
1676 me->states[me->statepos-1].state);
1677 midend_size_new_drawstate(me);
1679 ret = NULL; /* success! */
1691 me->ourgame->free_params(params);
1693 me->ourgame->free_params(cparams);
1695 me->ourgame->free_ui(ui);
1699 for (i = 0; i < nstates; i++) {
1700 if (states[i].state)
1701 me->ourgame->free_game(states[i].state);
1702 sfree(states[i].movestr);
1710 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
1712 game_state *soln = NULL;
1714 if (me->statepos < 1)
1715 return "No game set up to print";/* _shouldn't_ happen! */
1718 char *msg, *movestr;
1720 if (!me->ourgame->can_solve)
1721 return "This game does not support the Solve operation";
1723 msg = "Solve operation failed";/* game _should_ overwrite on error */
1724 movestr = me->ourgame->solve(me->states[0].state,
1725 me->states[me->statepos-1].state,
1726 me->aux_info, &msg);
1729 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
1738 * This call passes over ownership of the two game_states and
1739 * the game_params. Hence we duplicate the ones we want to
1740 * keep, and we don't have to bother freeing soln if it was
1743 document_add_puzzle(doc, me->ourgame,
1744 me->ourgame->dup_params(me->curparams),
1745 me->ourgame->dup_game(me->states[0].state), soln);