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;
79 int pressed_mouse_button;
81 int tilesize, winwidth, winheight;
84 #define ensure(me) do { \
85 if ((me)->nstates >= (me)->statesize) { \
86 (me)->statesize = (me)->nstates + 128; \
87 (me)->states = sresize((me)->states, (me)->statesize, \
88 struct midend_state_entry); \
92 midend_data *midend_new(frontend *fe, const game *ourgame)
94 midend_data *me = snew(midend_data);
98 get_random_seed(&randseed, &randseedsize);
101 me->ourgame = ourgame;
102 me->random = random_init(randseed, randseedsize);
103 me->nstates = me->statesize = me->statepos = 0;
105 me->params = ourgame->default_params();
106 me->curparams = NULL;
107 me->desc = me->privdesc = NULL;
110 me->genmode = GOT_NOTHING;
111 me->drawstate = NULL;
114 me->preset_names = NULL;
115 me->npresets = me->presetsize = 0;
116 me->anim_time = me->anim_pos = 0.0F;
117 me->flash_time = me->flash_pos = 0.0F;
120 me->pressed_mouse_button = 0;
121 me->laststatus = NULL;
124 me->tilesize = me->winwidth = me->winheight = 0;
131 static void midend_free_game(midend_data *me)
133 while (me->nstates > 0) {
135 me->ourgame->free_game(me->states[me->nstates].state);
136 sfree(me->states[me->nstates].movestr);
140 me->ourgame->free_drawstate(me->drawstate);
143 void midend_free(midend_data *me)
147 midend_free_game(me);
149 random_free(me->random);
155 me->ourgame->free_params(me->params);
157 for (i = 0; i < me->npresets; i++) {
158 sfree(me->presets[i]);
159 sfree(me->preset_names[i]);
162 sfree(me->preset_names);
165 me->ourgame->free_ui(me->ui);
167 me->ourgame->free_params(me->curparams);
168 sfree(me->laststatus);
172 static void midend_size_new_drawstate(midend_data *me)
175 * Don't even bother, if we haven't worked out our tile size
178 if (me->tilesize > 0) {
179 me->ourgame->compute_size(me->params, me->tilesize,
180 &me->winwidth, &me->winheight);
181 me->ourgame->set_size(me->drawstate, me->params, me->tilesize);
185 void midend_size(midend_data *me, int *x, int *y, int expand)
191 * Find the tile size that best fits within the given space. If
192 * `expand' is TRUE, we must actually find the _largest_ such
193 * tile size; otherwise, we bound above at the game's preferred
200 me->ourgame->compute_size(me->params, max, &rx, &ry);
201 } while (rx <= *x && ry <= *y);
203 max = me->ourgame->preferred_tilesize + 1;
207 * Now binary-search between min and max. We're looking for a
208 * boundary rather than a value: the point at which tile sizes
209 * stop fitting within the given dimensions. Thus, we stop when
210 * max and min differ by exactly 1.
212 while (max - min > 1) {
213 int mid = (max + min) / 2;
214 me->ourgame->compute_size(me->params, mid, &rx, &ry);
215 if (rx <= *x && ry <= *y)
222 * Now `min' is a valid size, and `max' isn't. So use `min'.
226 midend_size_new_drawstate(me);
231 void midend_set_params(midend_data *me, game_params *params)
233 me->ourgame->free_params(me->params);
234 me->params = me->ourgame->dup_params(params);
237 static void midend_set_timer(midend_data *me)
239 me->timing = (me->ourgame->is_timed &&
240 me->ourgame->timing_state(me->states[me->statepos-1].state,
242 if (me->timing || me->flash_time || me->anim_time)
243 activate_timer(me->frontend);
245 deactivate_timer(me->frontend);
248 void midend_force_redraw(midend_data *me)
251 me->ourgame->free_drawstate(me->drawstate);
252 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
253 midend_size_new_drawstate(me);
257 void midend_new_game(midend_data *me)
259 midend_free_game(me);
261 assert(me->nstates == 0);
263 if (me->genmode == GOT_DESC) {
264 me->genmode = GOT_NOTHING;
268 if (me->genmode == GOT_SEED) {
269 me->genmode = GOT_NOTHING;
272 * Generate a new random seed. 15 digits comes to about
273 * 48 bits, which should be more than enough.
275 * I'll avoid putting a leading zero on the number,
276 * just in case it confuses anybody who thinks it's
277 * processed as an integer rather than a string.
282 newseed[0] = '1' + random_upto(me->random, 9);
283 for (i = 1; i < 15; i++)
284 newseed[i] = '0' + random_upto(me->random, 10);
286 me->seedstr = dupstr(newseed);
289 me->ourgame->free_params(me->curparams);
290 me->curparams = me->ourgame->dup_params(me->params);
298 rs = random_init(me->seedstr, strlen(me->seedstr));
299 me->desc = me->ourgame->new_desc(me->curparams, rs,
300 &me->aux_info, TRUE);
306 me->states[me->nstates].state =
307 me->ourgame->new_game(me, me->params, me->desc);
308 me->states[me->nstates].movestr = NULL;
309 me->states[me->nstates].movetype = NEWGAME;
312 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
313 midend_size_new_drawstate(me);
316 me->ourgame->free_ui(me->ui);
317 me->ui = me->ourgame->new_ui(me->states[0].state);
318 midend_set_timer(me);
319 me->pressed_mouse_button = 0;
322 static int midend_undo(midend_data *me)
324 if (me->statepos > 1) {
326 me->ourgame->changed_state(me->ui,
327 me->states[me->statepos-1].state,
328 me->states[me->statepos-2].state);
336 static int midend_redo(midend_data *me)
338 if (me->statepos < me->nstates) {
340 me->ourgame->changed_state(me->ui,
341 me->states[me->statepos-1].state,
342 me->states[me->statepos].state);
350 static void midend_finish_move(midend_data *me)
355 * We do not flash if the later of the two states is special.
356 * This covers both forward Solve moves and backward (undone)
359 if ((me->oldstate || me->statepos > 1) &&
360 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
361 (me->dir < 0 && me->statepos < me->nstates &&
362 !special(me->states[me->statepos].movetype)))) {
363 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
364 me->states[me->statepos-2].state,
365 me->states[me->statepos-1].state,
366 me->oldstate ? me->dir : +1,
369 me->flash_pos = 0.0F;
370 me->flash_time = flashtime;
375 me->ourgame->free_game(me->oldstate);
377 me->anim_pos = me->anim_time = 0;
380 midend_set_timer(me);
383 void midend_stop_anim(midend_data *me)
385 if (me->oldstate || me->anim_time != 0) {
386 midend_finish_move(me);
391 void midend_restart_game(midend_data *me)
395 midend_stop_anim(me);
397 assert(me->statepos >= 1);
398 if (me->statepos == 1)
399 return; /* no point doing anything at all! */
402 * During restart, we reconstruct the game from the (public)
403 * game description rather than from states[0], because that
404 * way Mines gets slightly more sensible behaviour (restart
405 * goes to _after_ the first click so you don't have to
406 * remember where you clicked).
408 s = me->ourgame->new_game(me, me->params, me->desc);
411 * Now enter the restarted state as the next move.
413 midend_stop_anim(me);
414 while (me->nstates > me->statepos)
415 me->ourgame->free_game(me->states[--me->nstates].state);
417 me->states[me->nstates].state = s;
418 me->states[me->nstates].movestr = dupstr(me->desc);
419 me->states[me->nstates].movetype = RESTART;
420 me->statepos = ++me->nstates;
422 me->ourgame->changed_state(me->ui,
423 me->states[me->statepos-2].state,
424 me->states[me->statepos-1].state);
426 midend_finish_move(me);
428 midend_set_timer(me);
431 static int midend_really_process_key(midend_data *me, int x, int y, int button)
433 game_state *oldstate =
434 me->ourgame->dup_game(me->states[me->statepos - 1].state);
435 int special = FALSE, gotspecial = FALSE, ret = 1;
441 me->ourgame->interpret_move(me->states[me->statepos-1].state,
442 me->ui, me->drawstate, x, y, button);
445 if (button == 'n' || button == 'N' || button == '\x0E') {
446 midend_stop_anim(me);
449 goto done; /* never animate */
450 } else if (button == 'u' || button == 'u' ||
451 button == '\x1A' || button == '\x1F') {
452 midend_stop_anim(me);
453 special = special(me->states[me->statepos-1].movetype);
455 if (!midend_undo(me))
457 } else if (button == 'r' || button == 'R' ||
458 button == '\x12' || button == '\x19') {
459 midend_stop_anim(me);
460 if (!midend_redo(me))
462 } else if (button == 'q' || button == 'Q' || button == '\x11') {
469 s = me->states[me->statepos-1].state;
471 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
476 if (s == me->states[me->statepos-1].state) {
478 * make_move() is allowed to return its input state to
479 * indicate that although no move has been made, the UI
480 * state has been updated and a redraw is called for.
485 midend_stop_anim(me);
486 while (me->nstates > me->statepos)
487 me->ourgame->free_game(me->states[--me->nstates].state);
489 assert(movestr != NULL);
490 me->states[me->nstates].state = s;
491 me->states[me->nstates].movestr = movestr;
492 me->states[me->nstates].movetype = MOVE;
493 me->statepos = ++me->nstates;
496 me->ourgame->changed_state(me->ui,
497 me->states[me->statepos-2].state,
498 me->states[me->statepos-1].state);
505 special = special(me->states[me->statepos-1].movetype);
508 * See if this move requires an animation.
513 anim_time = me->ourgame->anim_length(oldstate,
514 me->states[me->statepos-1].state,
518 me->oldstate = oldstate; oldstate = NULL;
520 me->anim_time = anim_time;
523 midend_finish_move(me);
529 midend_set_timer(me);
532 if (oldstate) me->ourgame->free_game(oldstate);
536 int midend_process_key(midend_data *me, int x, int y, int button)
541 * Harmonise mouse drag and release messages.
543 * Some front ends might accidentally switch from sending, say,
544 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
545 * drag. (This can happen on the Mac, for example, since
546 * RIGHT_DRAG is usually done using Command+drag, and if the
547 * user accidentally releases Command half way through the drag
548 * then there will be trouble.)
550 * It would be an O(number of front ends) annoyance to fix this
551 * in the front ends, but an O(number of back ends) annoyance
552 * to have each game capable of dealing with it. Therefore, we
553 * fix it _here_ in the common midend code so that it only has
556 * The possible ways in which things can go screwy in the front
559 * - in a system containing multiple physical buttons button
560 * presses can inadvertently overlap. We can see ABab (caps
561 * meaning button-down and lowercase meaning button-up) when
562 * the user had semantically intended AaBb.
564 * - in a system where one button is simulated by means of a
565 * modifier key and another button, buttons can mutate
566 * between press and release (possibly during drag). So we
567 * can see Ab instead of Aa.
569 * Definite requirements are:
571 * - button _presses_ must never be invented or destroyed. If
572 * the user presses two buttons in succession, the button
573 * presses must be transferred to the backend unchanged. So
574 * if we see AaBb , that's fine; if we see ABab (the button
575 * presses inadvertently overlapped) we must somehow
576 * `correct' it to AaBb.
578 * - every mouse action must end up looking like a press, zero
579 * or more drags, then a release. This allows back ends to
580 * make the _assumption_ that incoming mouse data will be
581 * sane in this regard, and not worry about the details.
583 * So my policy will be:
585 * - treat any button-up as a button-up for the currently
586 * pressed button, or ignore it if there is no currently
589 * - treat any drag as a drag for the currently pressed
590 * button, or ignore it if there is no currently pressed
593 * - if we see a button-down while another button is currently
594 * pressed, invent a button-up for the first one and then
595 * pass the button-down through as before.
597 * 2005-05-31: An addendum to the above. Some games might want
598 * a `priority order' among buttons, such that if one button is
599 * pressed while another is down then a fixed one of the
600 * buttons takes priority no matter what order they're pressed
601 * in. Mines, in particular, wants to treat a left+right click
602 * like a left click for the benefit of users of other
603 * implementations. So the last of the above points is modified
604 * in the presence of an (optional) button priority order.
606 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
607 if (me->pressed_mouse_button) {
608 if (IS_MOUSE_DRAG(button)) {
609 button = me->pressed_mouse_button +
610 (LEFT_DRAG - LEFT_BUTTON);
612 button = me->pressed_mouse_button +
613 (LEFT_RELEASE - LEFT_BUTTON);
616 return ret; /* ignore it */
617 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
619 * If the new button has lower priority than the old one,
620 * don't bother doing this.
622 if (me->ourgame->mouse_priorities &
623 BUTTON_BEATS(me->pressed_mouse_button, button))
624 return ret; /* just ignore it */
627 * Fabricate a button-up for the previously pressed button.
629 ret = ret && midend_really_process_key
630 (me, x, y, (me->pressed_mouse_button +
631 (LEFT_RELEASE - LEFT_BUTTON)));
635 * Now send on the event we originally received.
637 ret = ret && midend_really_process_key(me, x, y, button);
640 * And update the currently pressed button.
642 if (IS_MOUSE_RELEASE(button))
643 me->pressed_mouse_button = 0;
644 else if (IS_MOUSE_DOWN(button))
645 me->pressed_mouse_button = button;
650 void midend_redraw(midend_data *me)
652 if (me->statepos > 0 && me->drawstate) {
653 start_draw(me->frontend);
654 if (me->oldstate && me->anim_time > 0 &&
655 me->anim_pos < me->anim_time) {
656 assert(me->dir != 0);
657 me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
658 me->states[me->statepos-1].state, me->dir,
659 me->ui, me->anim_pos, me->flash_pos);
661 me->ourgame->redraw(me->frontend, me->drawstate, NULL,
662 me->states[me->statepos-1].state, +1 /*shrug*/,
663 me->ui, 0.0, me->flash_pos);
665 end_draw(me->frontend);
669 void midend_timer(midend_data *me, float tplus)
671 me->anim_pos += tplus;
672 if (me->anim_pos >= me->anim_time ||
673 me->anim_time == 0 || !me->oldstate) {
674 if (me->anim_time > 0)
675 midend_finish_move(me);
678 me->flash_pos += tplus;
679 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
680 me->flash_pos = me->flash_time = 0;
686 float oldelapsed = me->elapsed;
687 me->elapsed += tplus;
688 if ((int)oldelapsed != (int)me->elapsed)
689 status_bar(me->frontend, me->laststatus ? me->laststatus : "");
692 midend_set_timer(me);
695 float *midend_colours(midend_data *me, int *ncolours)
697 game_state *state = NULL;
700 if (me->nstates == 0) {
702 char *desc = me->ourgame->new_desc(me->params, me->random,
704 state = me->ourgame->new_game(me, me->params, desc);
708 state = me->states[0].state;
710 ret = me->ourgame->colours(me->frontend, state, ncolours);
716 * Allow environment-based overrides for the standard
717 * colours by defining variables along the lines of
718 * `NET_COLOUR_4=6000c0'.
721 for (i = 0; i < *ncolours; i++) {
723 unsigned int r, g, b;
726 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
727 for (j = 0; buf[j]; j++)
728 buf[j] = toupper((unsigned char)buf[j]);
729 if ((e = getenv(buf)) != NULL &&
730 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
731 ret[i*3 + 0] = r / 255.0;
732 ret[i*3 + 1] = g / 255.0;
733 ret[i*3 + 2] = b / 255.0;
738 if (me->nstates == 0)
739 me->ourgame->free_game(state);
744 int midend_num_presets(midend_data *me)
750 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
751 if (me->presetsize <= me->npresets) {
752 me->presetsize = me->npresets + 10;
753 me->presets = sresize(me->presets, me->presetsize,
755 me->preset_names = sresize(me->preset_names, me->presetsize,
759 me->presets[me->npresets] = preset;
760 me->preset_names[me->npresets] = name;
767 * Allow environment-based extensions to the preset list by
768 * defining a variable along the lines of `SOLO_PRESETS=2x3
769 * Advanced:2x3da'. Colon-separated list of items,
770 * alternating between textual titles in the menu and
771 * encoded parameter strings.
773 char buf[80], *e, *p;
776 sprintf(buf, "%s_PRESETS", me->ourgame->name);
777 for (j = 0; buf[j]; j++)
778 buf[j] = toupper((unsigned char)buf[j]);
780 if ((e = getenv(buf)) != NULL) {
788 while (*p && *p != ':') p++;
791 while (*p && *p != ':') p++;
794 preset = me->ourgame->default_params();
795 me->ourgame->decode_params(preset, val);
797 if (me->ourgame->validate_params(preset, TRUE)) {
798 /* Drop this one from the list. */
799 me->ourgame->free_params(preset);
803 if (me->presetsize <= me->npresets) {
804 me->presetsize = me->npresets + 10;
805 me->presets = sresize(me->presets, me->presetsize,
807 me->preset_names = sresize(me->preset_names,
808 me->presetsize, char *);
811 me->presets[me->npresets] = preset;
812 me->preset_names[me->npresets] = dupstr(name);
821 void midend_fetch_preset(midend_data *me, int n,
822 char **name, game_params **params)
824 assert(n >= 0 && n < me->npresets);
825 *name = me->preset_names[n];
826 *params = me->presets[n];
829 int midend_wants_statusbar(midend_data *me)
831 return me->ourgame->wants_statusbar();
834 void midend_supersede_game_desc(midend_data *me, char *desc, char *privdesc)
838 me->desc = dupstr(desc);
839 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
842 config_item *midend_get_config(midend_data *me, int which, char **wintitle)
844 char *titlebuf, *parstr, *rest;
849 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
853 sprintf(titlebuf, "%s configuration", me->ourgame->name);
854 *wintitle = titlebuf;
855 return me->ourgame->configure(me->params);
858 if (!me->curparams) {
862 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
863 which == CFG_SEED ? "random" : "game");
864 *wintitle = titlebuf;
866 ret = snewn(2, config_item);
868 ret[0].type = C_STRING;
869 if (which == CFG_SEED)
870 ret[0].name = "Game random seed";
872 ret[0].name = "Game ID";
875 * For CFG_DESC the text going in here will be a string
876 * encoding of the restricted parameters, plus a colon,
877 * plus the game description. For CFG_SEED it will be the
878 * full parameters, plus a hash, plus the random seed data.
879 * Either of these is a valid full game ID (although only
880 * the former is likely to persist across many code
883 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
885 if (which == CFG_DESC) {
886 rest = me->desc ? me->desc : "";
889 rest = me->seedstr ? me->seedstr : "";
892 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
893 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
897 ret[1].name = ret[1].sval = NULL;
903 assert(!"We shouldn't be here");
907 static char *midend_game_id_int(midend_data *me, char *id, int defmode)
909 char *error, *par, *desc, *seed;
910 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
913 seed = strchr(id, '#');
914 desc = strchr(id, ':');
916 if (desc && (!seed || desc < seed)) {
918 * We have a colon separating parameters from game
919 * description. So `par' now points to the parameters
920 * string, and `desc' to the description string.
925 } else if (seed && (!desc || seed < desc)) {
927 * We have a hash separating parameters from random seed.
928 * So `par' now points to the parameters string, and `seed'
929 * to the seed string.
936 * We only have one string. Depending on `defmode', we take
937 * it to be either parameters, seed or description.
939 if (defmode == DEF_SEED) {
942 } else if (defmode == DEF_DESC) {
952 * We must be reasonably careful here not to modify anything in
953 * `me' until we have finished validating things. This function
954 * must either return an error and do nothing to the midend, or
955 * return success and do everything; nothing in between is
958 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
961 newcurparams = me->ourgame->dup_params(me->params);
962 me->ourgame->decode_params(newcurparams, par);
963 error = me->ourgame->validate_params(newcurparams, desc == NULL);
965 me->ourgame->free_params(newcurparams);
968 oldparams1 = me->curparams;
971 * Now filter only the persistent parts of this state into
972 * the long-term params structure, unless we've _only_
973 * received a params string in which case the whole lot is
976 oldparams2 = me->params;
980 newparams = me->ourgame->dup_params(me->params);
982 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
983 me->ourgame->decode_params(newparams, tmpstr);
987 newparams = me->ourgame->dup_params(newcurparams);
991 newcurparams = me->curparams;
992 newparams = me->params;
997 error = me->ourgame->validate_desc(newparams, desc);
1001 me->ourgame->free_params(newcurparams);
1003 me->ourgame->free_params(newparams);
1010 * Now we've got past all possible error points. Update the
1013 me->params = newparams;
1014 me->curparams = newcurparams;
1016 me->ourgame->free_params(oldparams1);
1018 me->ourgame->free_params(oldparams2);
1021 sfree(me->privdesc);
1022 me->desc = me->privdesc = NULL;
1027 me->desc = dupstr(desc);
1028 me->genmode = GOT_DESC;
1029 sfree(me->aux_info);
1030 me->aux_info = NULL;
1034 me->seedstr = dupstr(seed);
1035 me->genmode = GOT_SEED;
1041 char *midend_game_id(midend_data *me, char *id)
1043 return midend_game_id_int(me, id, DEF_PARAMS);
1046 char *midend_set_config(midend_data *me, int which, config_item *cfg)
1049 game_params *params;
1053 params = me->ourgame->custom_params(cfg);
1054 error = me->ourgame->validate_params(params, TRUE);
1057 me->ourgame->free_params(params);
1061 me->ourgame->free_params(me->params);
1062 me->params = params;
1067 error = midend_game_id_int(me, cfg[0].sval,
1068 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1077 char *midend_text_format(midend_data *me)
1079 if (me->ourgame->can_format_as_text && me->statepos > 0)
1080 return me->ourgame->text_format(me->states[me->statepos-1].state);
1085 char *midend_solve(midend_data *me)
1088 char *msg, *movestr;
1090 if (!me->ourgame->can_solve)
1091 return "This game does not support the Solve operation";
1093 if (me->statepos < 1)
1094 return "No game set up to solve"; /* _shouldn't_ happen! */
1096 msg = "Solve operation failed"; /* game _should_ overwrite on error */
1097 movestr = me->ourgame->solve(me->states[0].state,
1098 me->states[me->statepos-1].state,
1099 me->aux_info, &msg);
1102 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1106 * Now enter the solved state as the next move.
1108 midend_stop_anim(me);
1109 while (me->nstates > me->statepos)
1110 me->ourgame->free_game(me->states[--me->nstates].state);
1112 me->states[me->nstates].state = s;
1113 me->states[me->nstates].movestr = movestr;
1114 me->states[me->nstates].movetype = SOLVE;
1115 me->statepos = ++me->nstates;
1117 me->ourgame->changed_state(me->ui,
1118 me->states[me->statepos-2].state,
1119 me->states[me->statepos-1].state);
1120 me->anim_time = 0.0;
1121 midend_finish_move(me);
1123 midend_set_timer(me);
1127 char *midend_rewrite_statusbar(midend_data *me, char *text)
1130 * An important special case is that we are occasionally called
1131 * with our own laststatus, to update the timer.
1133 if (me->laststatus != text) {
1134 sfree(me->laststatus);
1135 me->laststatus = dupstr(text);
1138 if (me->ourgame->is_timed) {
1139 char timebuf[100], *ret;
1145 sprintf(timebuf, "[%d:%02d] ", min, sec);
1147 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1148 strcpy(ret, timebuf);
1153 return dupstr(text);
1157 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1158 #define SERIALISE_VERSION "1"
1160 void midend_serialise(midend_data *me,
1161 void (*write)(void *ctx, void *buf, int len),
1167 * Each line of the save file contains three components. First
1168 * exactly 8 characters of header word indicating what type of
1169 * data is contained on the line; then a colon followed by a
1170 * decimal integer giving the length of the main string on the
1171 * line; then a colon followed by the string itself (exactly as
1172 * many bytes as previously specified, no matter what they
1173 * contain). Then a newline (of reasonably flexible form).
1175 #define wr(h,s) do { \
1178 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1179 write(wctx, hbuf, strlen(hbuf)); \
1180 write(wctx, str, strlen(str)); \
1181 write(wctx, "\n", 1); \
1185 * Magic string identifying the file, and version number of the
1188 wr("SAVEFILE", SERIALISE_MAGIC);
1189 wr("VERSION", SERIALISE_VERSION);
1192 * The game name. (Copied locally to avoid const annoyance.)
1195 char *s = dupstr(me->ourgame->name);
1201 * The current long-term parameters structure, in full.
1204 char *s = me->ourgame->encode_params(me->params, TRUE);
1210 * The current short-term parameters structure, in full.
1212 if (me->curparams) {
1213 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1219 * The current game description, the privdesc, and the random seed.
1222 wr("SEED", me->seedstr);
1224 wr("DESC", me->desc);
1226 wr("PRIVDESC", me->privdesc);
1229 * The game's aux_info. We obfuscate this to prevent spoilers
1230 * (people are likely to run `head' or similar on a saved game
1231 * file simply to find out what it is, and don't necessarily
1232 * want to be told the answer to the puzzle!)
1239 len = strlen(me->aux_info);
1240 s1 = snewn(len, unsigned char);
1241 memcpy(s1, me->aux_info, len);
1242 obfuscate_bitmap(s1, len*8, FALSE);
1243 s2 = bin2hex(s1, len);
1252 * Any required serialisation of the game_ui.
1255 char *s = me->ourgame->encode_ui(me->ui);
1263 * The game time, if it's a timed game.
1265 if (me->ourgame->is_timed) {
1267 sprintf(buf, "%g", me->elapsed);
1272 * The length of, and position in, the states list.
1276 sprintf(buf, "%d", me->nstates);
1278 sprintf(buf, "%d", me->statepos);
1279 wr("STATEPOS", buf);
1283 * For each state after the initial one (which we know is
1284 * constructed from either privdesc or desc), enough
1285 * information for execute_move() to reconstruct it from the
1288 for (i = 1; i < me->nstates; i++) {
1289 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1290 switch (me->states[i].movetype) {
1292 wr("MOVE", me->states[i].movestr);
1295 wr("SOLVE", me->states[i].movestr);
1298 wr("RESTART", me->states[i].movestr);
1307 * This function returns NULL on success, or an error message.
1309 char *midend_deserialise(midend_data *me,
1310 int (*read)(void *ctx, void *buf, int len),
1313 int nstates = 0, statepos = -1, gotstates = 0;
1314 int started = FALSE;
1318 /* Initially all errors give the same report */
1319 char *ret = "Data does not appear to be a saved game file";
1322 * We construct all the new state in local variables while we
1323 * check its sanity. Only once we have finished reading the
1324 * serialised data and detected no errors at all do we start
1325 * modifying stuff in the midend_data passed in.
1327 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1328 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1329 float elapsed = 0.0F;
1330 game_params *params = NULL, *cparams = NULL;
1332 struct midend_state_entry *states = NULL;
1335 * Loop round and round reading one key/value pair at a time
1336 * from the serialised stream, until we have enough game states
1339 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1344 if (!read(rctx, key, 1)) {
1345 /* unexpected EOF */
1348 } while (key[0] == '\r' || key[0] == '\n');
1350 if (!read(rctx, key+1, 8)) {
1351 /* unexpected EOF */
1355 if (key[8] != ':') {
1357 ret = "Data was incorrectly formatted for a saved game file";
1360 len = strcspn(key, ": ");
1366 if (!read(rctx, &c, 1)) {
1367 /* unexpected EOF */
1373 } else if (c >= '0' && c <= '9') {
1374 len = (len * 10) + (c - '0');
1377 ret = "Data was incorrectly formatted for a"
1383 val = snewn(len+1, char);
1384 if (!read(rctx, val, len)) {
1391 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1392 /* ret already has the right message in it */
1395 /* Now most errors are this one, unless otherwise specified */
1396 ret = "Saved data ended unexpectedly";
1399 if (!strcmp(key, "VERSION")) {
1400 if (strcmp(val, SERIALISE_VERSION)) {
1401 ret = "Cannot handle this version of the saved game"
1405 } else if (!strcmp(key, "GAME")) {
1406 if (strcmp(val, me->ourgame->name)) {
1407 ret = "Save file is from a different game";
1410 } else if (!strcmp(key, "PARAMS")) {
1414 } else if (!strcmp(key, "CPARAMS")) {
1418 } else if (!strcmp(key, "SEED")) {
1422 } else if (!strcmp(key, "DESC")) {
1426 } else if (!strcmp(key, "PRIVDESC")) {
1430 } else if (!strcmp(key, "AUXINFO")) {
1432 int len = strlen(val) / 2; /* length in bytes */
1433 tmp = hex2bin(val, len);
1434 obfuscate_bitmap(tmp, len*8, TRUE);
1437 auxinfo = snewn(len + 1, char);
1438 memcpy(auxinfo, tmp, len);
1439 auxinfo[len] = '\0';
1441 } else if (!strcmp(key, "UI")) {
1445 } else if (!strcmp(key, "TIME")) {
1446 elapsed = atof(val);
1447 } else if (!strcmp(key, "NSTATES")) {
1448 nstates = atoi(val);
1450 ret = "Number of states in save file was negative";
1454 ret = "Two state counts provided in save file";
1457 states = snewn(nstates, struct midend_state_entry);
1458 for (i = 0; i < nstates; i++) {
1459 states[i].state = NULL;
1460 states[i].movestr = NULL;
1461 states[i].movetype = NEWGAME;
1463 } else if (!strcmp(key, "STATEPOS")) {
1464 statepos = atoi(val);
1465 } else if (!strcmp(key, "MOVE")) {
1467 states[gotstates].movetype = MOVE;
1468 states[gotstates].movestr = val;
1470 } else if (!strcmp(key, "SOLVE")) {
1472 states[gotstates].movetype = SOLVE;
1473 states[gotstates].movestr = val;
1475 } else if (!strcmp(key, "RESTART")) {
1477 states[gotstates].movetype = RESTART;
1478 states[gotstates].movestr = val;
1487 params = me->ourgame->default_params();
1488 me->ourgame->decode_params(params, parstr);
1489 if (me->ourgame->validate_params(params, TRUE)) {
1490 ret = "Long-term parameters in save file are invalid";
1493 cparams = me->ourgame->default_params();
1494 me->ourgame->decode_params(cparams, cparstr);
1495 if (me->ourgame->validate_params(cparams, FALSE)) {
1496 ret = "Short-term parameters in save file are invalid";
1499 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1501 * The seed's no use with this version, but we can perfectly
1502 * well use the rest of the data.
1508 ret = "Game description in save file is missing";
1510 } else if (me->ourgame->validate_desc(params, desc)) {
1511 ret = "Game description in save file is invalid";
1514 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1515 ret = "Game private description in save file is invalid";
1518 if (statepos < 0 || statepos >= nstates) {
1519 ret = "Game position in save file is out of range";
1522 states[0].state = me->ourgame->new_game(me, params,
1523 privdesc ? privdesc : desc);
1524 for (i = 1; i < nstates; i++) {
1525 assert(states[i].movetype != NEWGAME);
1526 switch (states[i].movetype) {
1529 states[i].state = me->ourgame->execute_move(states[i-1].state,
1531 if (states[i].state == NULL) {
1532 ret = "Save file contained an invalid move";
1537 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1538 ret = "Save file contained an invalid restart move";
1541 states[i].state = me->ourgame->new_game(me, params,
1547 ui = me->ourgame->new_ui(states[0].state);
1548 me->ourgame->decode_ui(ui, uistr);
1551 * Now we've run out of possible error conditions, so we're
1552 * ready to start overwriting the real data in the current
1553 * midend. We'll do this by swapping things with the local
1554 * variables, so that the same cleanup code will free the old
1565 me->privdesc = privdesc;
1573 me->aux_info = auxinfo;
1577 me->genmode = GOT_NOTHING;
1579 me->statesize = nstates;
1580 nstates = me->nstates;
1581 me->nstates = me->statesize;
1583 struct midend_state_entry *tmp;
1585 me->states = states;
1588 me->statepos = statepos;
1594 me->params = params;
1597 tmp = me->curparams;
1598 me->curparams = cparams;
1602 me->oldstate = NULL;
1603 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1614 me->elapsed = elapsed;
1615 me->pressed_mouse_button = 0;
1617 midend_set_timer(me);
1620 me->ourgame->free_drawstate(me->drawstate);
1622 me->ourgame->new_drawstate(me->states[me->statepos-1].state);
1623 midend_size_new_drawstate(me);
1625 ret = NULL; /* success! */
1637 me->ourgame->free_params(params);
1639 me->ourgame->free_params(cparams);
1641 me->ourgame->free_ui(ui);
1645 for (i = 0; i < nstates; i++) {
1646 if (states[i].state)
1647 me->ourgame->free_game(states[i].state);
1648 sfree(states[i].movestr);