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 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->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 void midend_size(midend_data *me, int *x, int *y, int expand)
174 me->ourgame->size(me->params, me->drawstate, x, y, expand);
179 void midend_set_params(midend_data *me, game_params *params)
181 me->ourgame->free_params(me->params);
182 me->params = me->ourgame->dup_params(params);
185 static void midend_set_timer(midend_data *me)
187 me->timing = (me->ourgame->is_timed &&
188 me->ourgame->timing_state(me->states[me->statepos-1].state));
189 if (me->timing || me->flash_time || me->anim_time)
190 activate_timer(me->frontend);
192 deactivate_timer(me->frontend);
195 static void midend_size_new_drawstate(midend_data *me)
197 me->ourgame->size(me->params, me->drawstate, &me->winwidth, &me->winheight,
201 void midend_force_redraw(midend_data *me)
204 me->ourgame->free_drawstate(me->drawstate);
205 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
206 midend_size_new_drawstate(me);
210 void midend_new_game(midend_data *me)
212 midend_free_game(me);
214 assert(me->nstates == 0);
216 if (me->genmode == GOT_DESC) {
217 me->genmode = GOT_NOTHING;
221 if (me->genmode == GOT_SEED) {
222 me->genmode = GOT_NOTHING;
225 * Generate a new random seed. 15 digits comes to about
226 * 48 bits, which should be more than enough.
228 * I'll avoid putting a leading zero on the number,
229 * just in case it confuses anybody who thinks it's
230 * processed as an integer rather than a string.
235 newseed[0] = '1' + random_upto(me->random, 9);
236 for (i = 1; i < 15; i++)
237 newseed[i] = '0' + random_upto(me->random, 10);
239 me->seedstr = dupstr(newseed);
242 me->ourgame->free_params(me->curparams);
243 me->curparams = me->ourgame->dup_params(me->params);
251 rs = random_init(me->seedstr, strlen(me->seedstr));
252 me->desc = me->ourgame->new_desc(me->curparams, rs,
253 &me->aux_info, TRUE);
259 me->states[me->nstates].state =
260 me->ourgame->new_game(me, me->params, me->desc);
261 me->states[me->nstates].movestr = NULL;
262 me->states[me->nstates].movetype = NEWGAME;
265 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
266 midend_size_new_drawstate(me);
268 midend_set_timer(me);
270 me->ourgame->free_ui(me->ui);
271 me->ui = me->ourgame->new_ui(me->states[0].state);
272 me->pressed_mouse_button = 0;
275 static int midend_undo(midend_data *me)
277 if (me->statepos > 1) {
279 me->ourgame->changed_state(me->ui,
280 me->states[me->statepos-1].state,
281 me->states[me->statepos-2].state);
289 static int midend_redo(midend_data *me)
291 if (me->statepos < me->nstates) {
293 me->ourgame->changed_state(me->ui,
294 me->states[me->statepos-1].state,
295 me->states[me->statepos].state);
303 static void midend_finish_move(midend_data *me)
308 * We do not flash if the later of the two states is special.
309 * This covers both forward Solve moves and backward (undone)
312 if ((me->oldstate || me->statepos > 1) &&
313 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
314 (me->dir < 0 && me->statepos < me->nstates &&
315 !special(me->states[me->statepos].movetype)))) {
316 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
317 me->states[me->statepos-2].state,
318 me->states[me->statepos-1].state,
319 me->oldstate ? me->dir : +1,
322 me->flash_pos = 0.0F;
323 me->flash_time = flashtime;
328 me->ourgame->free_game(me->oldstate);
330 me->anim_pos = me->anim_time = 0;
333 midend_set_timer(me);
336 void midend_stop_anim(midend_data *me)
338 if (me->oldstate || me->anim_time) {
339 midend_finish_move(me);
344 void midend_restart_game(midend_data *me)
348 midend_stop_anim(me);
350 assert(me->statepos >= 1);
351 if (me->statepos == 1)
352 return; /* no point doing anything at all! */
355 * During restart, we reconstruct the game from the (public)
356 * game description rather than from states[0], because that
357 * way Mines gets slightly more sensible behaviour (restart
358 * goes to _after_ the first click so you don't have to
359 * remember where you clicked).
361 s = me->ourgame->new_game(me, me->params, me->desc);
364 * Now enter the restarted state as the next move.
366 midend_stop_anim(me);
367 while (me->nstates > me->statepos)
368 me->ourgame->free_game(me->states[--me->nstates].state);
370 me->states[me->nstates].state = s;
371 me->states[me->nstates].movestr = dupstr(me->desc);
372 me->states[me->nstates].movetype = RESTART;
373 me->statepos = ++me->nstates;
375 me->ourgame->changed_state(me->ui,
376 me->states[me->statepos-2].state,
377 me->states[me->statepos-1].state);
379 midend_finish_move(me);
381 midend_set_timer(me);
384 static int midend_really_process_key(midend_data *me, int x, int y, int button)
386 game_state *oldstate =
387 me->ourgame->dup_game(me->states[me->statepos - 1].state);
388 int special = FALSE, gotspecial = FALSE, ret = 1;
394 me->ourgame->interpret_move(me->states[me->statepos-1].state,
395 me->ui, me->drawstate, x, y, button);
398 if (button == 'n' || button == 'N' || button == '\x0E') {
399 midend_stop_anim(me);
402 goto done; /* never animate */
403 } else if (button == 'u' || button == 'u' ||
404 button == '\x1A' || button == '\x1F') {
405 midend_stop_anim(me);
406 special = special(me->states[me->statepos-1].movetype);
408 if (!midend_undo(me))
410 } else if (button == 'r' || button == 'R' ||
411 button == '\x12' || button == '\x19') {
412 midend_stop_anim(me);
413 if (!midend_redo(me))
415 } else if (button == 'q' || button == 'Q' || button == '\x11') {
422 s = me->states[me->statepos-1].state;
424 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
429 if (s == me->states[me->statepos-1].state) {
431 * make_move() is allowed to return its input state to
432 * indicate that although no move has been made, the UI
433 * state has been updated and a redraw is called for.
438 midend_stop_anim(me);
439 while (me->nstates > me->statepos)
440 me->ourgame->free_game(me->states[--me->nstates].state);
442 assert(movestr != NULL);
443 me->states[me->nstates].state = s;
444 me->states[me->nstates].movestr = movestr;
445 me->states[me->nstates].movetype = MOVE;
446 me->statepos = ++me->nstates;
454 special = special(me->states[me->statepos-1].movetype);
457 * See if this move requires an animation.
462 anim_time = me->ourgame->anim_length(oldstate,
463 me->states[me->statepos-1].state,
467 me->oldstate = oldstate; oldstate = NULL;
469 me->anim_time = anim_time;
472 midend_finish_move(me);
478 midend_set_timer(me);
481 if (oldstate) me->ourgame->free_game(oldstate);
485 int midend_process_key(midend_data *me, int x, int y, int button)
490 * Harmonise mouse drag and release messages.
492 * Some front ends might accidentally switch from sending, say,
493 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
494 * drag. (This can happen on the Mac, for example, since
495 * RIGHT_DRAG is usually done using Command+drag, and if the
496 * user accidentally releases Command half way through the drag
497 * then there will be trouble.)
499 * It would be an O(number of front ends) annoyance to fix this
500 * in the front ends, but an O(number of back ends) annoyance
501 * to have each game capable of dealing with it. Therefore, we
502 * fix it _here_ in the common midend code so that it only has
505 * The possible ways in which things can go screwy in the front
508 * - in a system containing multiple physical buttons button
509 * presses can inadvertently overlap. We can see ABab (caps
510 * meaning button-down and lowercase meaning button-up) when
511 * the user had semantically intended AaBb.
513 * - in a system where one button is simulated by means of a
514 * modifier key and another button, buttons can mutate
515 * between press and release (possibly during drag). So we
516 * can see Ab instead of Aa.
518 * Definite requirements are:
520 * - button _presses_ must never be invented or destroyed. If
521 * the user presses two buttons in succession, the button
522 * presses must be transferred to the backend unchanged. So
523 * if we see AaBb , that's fine; if we see ABab (the button
524 * presses inadvertently overlapped) we must somehow
525 * `correct' it to AaBb.
527 * - every mouse action must end up looking like a press, zero
528 * or more drags, then a release. This allows back ends to
529 * make the _assumption_ that incoming mouse data will be
530 * sane in this regard, and not worry about the details.
532 * So my policy will be:
534 * - treat any button-up as a button-up for the currently
535 * pressed button, or ignore it if there is no currently
538 * - treat any drag as a drag for the currently pressed
539 * button, or ignore it if there is no currently pressed
542 * - if we see a button-down while another button is currently
543 * pressed, invent a button-up for the first one and then
544 * pass the button-down through as before.
546 * 2005-05-31: An addendum to the above. Some games might want
547 * a `priority order' among buttons, such that if one button is
548 * pressed while another is down then a fixed one of the
549 * buttons takes priority no matter what order they're pressed
550 * in. Mines, in particular, wants to treat a left+right click
551 * like a left click for the benefit of users of other
552 * implementations. So the last of the above points is modified
553 * in the presence of an (optional) button priority order.
555 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
556 if (me->pressed_mouse_button) {
557 if (IS_MOUSE_DRAG(button)) {
558 button = me->pressed_mouse_button +
559 (LEFT_DRAG - LEFT_BUTTON);
561 button = me->pressed_mouse_button +
562 (LEFT_RELEASE - LEFT_BUTTON);
565 return ret; /* ignore it */
566 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
568 * If the new button has lower priority than the old one,
569 * don't bother doing this.
571 if (me->ourgame->mouse_priorities &
572 BUTTON_BEATS(me->pressed_mouse_button, button))
573 return ret; /* just ignore it */
576 * Fabricate a button-up for the previously pressed button.
578 ret = ret && midend_really_process_key
579 (me, x, y, (me->pressed_mouse_button +
580 (LEFT_RELEASE - LEFT_BUTTON)));
584 * Now send on the event we originally received.
586 ret = ret && midend_really_process_key(me, x, y, button);
589 * And update the currently pressed button.
591 if (IS_MOUSE_RELEASE(button))
592 me->pressed_mouse_button = 0;
593 else if (IS_MOUSE_DOWN(button))
594 me->pressed_mouse_button = button;
599 void midend_redraw(midend_data *me)
601 if (me->statepos > 0 && me->drawstate) {
602 start_draw(me->frontend);
603 if (me->oldstate && me->anim_time > 0 &&
604 me->anim_pos < me->anim_time) {
605 assert(me->dir != 0);
606 me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
607 me->states[me->statepos-1].state, me->dir,
608 me->ui, me->anim_pos, me->flash_pos);
610 me->ourgame->redraw(me->frontend, me->drawstate, NULL,
611 me->states[me->statepos-1].state, +1 /*shrug*/,
612 me->ui, 0.0, me->flash_pos);
614 end_draw(me->frontend);
618 void midend_timer(midend_data *me, float tplus)
620 me->anim_pos += tplus;
621 if (me->anim_pos >= me->anim_time ||
622 me->anim_time == 0 || !me->oldstate) {
623 if (me->anim_time > 0)
624 midend_finish_move(me);
627 me->flash_pos += tplus;
628 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
629 me->flash_pos = me->flash_time = 0;
635 float oldelapsed = me->elapsed;
636 me->elapsed += tplus;
637 if ((int)oldelapsed != (int)me->elapsed)
638 status_bar(me->frontend, me->laststatus ? me->laststatus : "");
641 midend_set_timer(me);
644 float *midend_colours(midend_data *me, int *ncolours)
646 game_state *state = NULL;
649 if (me->nstates == 0) {
651 char *desc = me->ourgame->new_desc(me->params, me->random,
653 state = me->ourgame->new_game(me, me->params, desc);
657 state = me->states[0].state;
659 ret = me->ourgame->colours(me->frontend, state, ncolours);
665 * Allow environment-based overrides for the standard
666 * colours by defining variables along the lines of
667 * `NET_COLOUR_4=6000c0'.
670 for (i = 0; i < *ncolours; i++) {
672 unsigned int r, g, b;
675 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
676 for (j = 0; buf[j]; j++)
677 buf[j] = toupper((unsigned char)buf[j]);
678 if ((e = getenv(buf)) != NULL &&
679 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
680 ret[i*3 + 0] = r / 255.0;
681 ret[i*3 + 1] = g / 255.0;
682 ret[i*3 + 2] = b / 255.0;
687 if (me->nstates == 0)
688 me->ourgame->free_game(state);
693 int midend_num_presets(midend_data *me)
699 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
700 if (me->presetsize <= me->npresets) {
701 me->presetsize = me->npresets + 10;
702 me->presets = sresize(me->presets, me->presetsize,
704 me->preset_names = sresize(me->preset_names, me->presetsize,
708 me->presets[me->npresets] = preset;
709 me->preset_names[me->npresets] = name;
716 * Allow environment-based extensions to the preset list by
717 * defining a variable along the lines of `SOLO_PRESETS=2x3
718 * Advanced:2x3da'. Colon-separated list of items,
719 * alternating between textual titles in the menu and
720 * encoded parameter strings.
722 char buf[80], *e, *p;
725 sprintf(buf, "%s_PRESETS", me->ourgame->name);
726 for (j = 0; buf[j]; j++)
727 buf[j] = toupper((unsigned char)buf[j]);
729 if ((e = getenv(buf)) != NULL) {
737 while (*p && *p != ':') p++;
740 while (*p && *p != ':') p++;
743 preset = me->ourgame->default_params();
744 me->ourgame->decode_params(preset, val);
746 if (me->ourgame->validate_params(preset)) {
747 /* Drop this one from the list. */
748 me->ourgame->free_params(preset);
752 if (me->presetsize <= me->npresets) {
753 me->presetsize = me->npresets + 10;
754 me->presets = sresize(me->presets, me->presetsize,
756 me->preset_names = sresize(me->preset_names,
757 me->presetsize, char *);
760 me->presets[me->npresets] = preset;
761 me->preset_names[me->npresets] = dupstr(name);
770 void midend_fetch_preset(midend_data *me, int n,
771 char **name, game_params **params)
773 assert(n >= 0 && n < me->npresets);
774 *name = me->preset_names[n];
775 *params = me->presets[n];
778 int midend_wants_statusbar(midend_data *me)
780 return me->ourgame->wants_statusbar();
783 void midend_supersede_game_desc(midend_data *me, char *desc, char *privdesc)
787 me->desc = dupstr(desc);
788 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
791 config_item *midend_get_config(midend_data *me, int which, char **wintitle)
793 char *titlebuf, *parstr, *rest;
798 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
802 sprintf(titlebuf, "%s configuration", me->ourgame->name);
803 *wintitle = titlebuf;
804 return me->ourgame->configure(me->params);
807 if (!me->curparams) {
811 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
812 which == CFG_SEED ? "random" : "game");
813 *wintitle = titlebuf;
815 ret = snewn(2, config_item);
817 ret[0].type = C_STRING;
818 if (which == CFG_SEED)
819 ret[0].name = "Game random seed";
821 ret[0].name = "Game ID";
824 * For CFG_DESC the text going in here will be a string
825 * encoding of the restricted parameters, plus a colon,
826 * plus the game description. For CFG_SEED it will be the
827 * full parameters, plus a hash, plus the random seed data.
828 * Either of these is a valid full game ID (although only
829 * the former is likely to persist across many code
832 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
834 if (which == CFG_DESC) {
835 rest = me->desc ? me->desc : "";
838 rest = me->seedstr ? me->seedstr : "";
841 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
842 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
846 ret[1].name = ret[1].sval = NULL;
852 assert(!"We shouldn't be here");
856 static char *midend_game_id_int(midend_data *me, char *id, int defmode)
858 char *error, *par, *desc, *seed;
859 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
862 seed = strchr(id, '#');
863 desc = strchr(id, ':');
865 if (desc && (!seed || desc < seed)) {
867 * We have a colon separating parameters from game
868 * description. So `par' now points to the parameters
869 * string, and `desc' to the description string.
874 } else if (seed && (!desc || seed < desc)) {
876 * We have a hash separating parameters from random seed.
877 * So `par' now points to the parameters string, and `seed'
878 * to the seed string.
885 * We only have one string. Depending on `defmode', we take
886 * it to be either parameters, seed or description.
888 if (defmode == DEF_SEED) {
891 } else if (defmode == DEF_DESC) {
901 * We must be reasonably careful here not to modify anything in
902 * `me' until we have finished validating things. This function
903 * must either return an error and do nothing to the midend, or
904 * return success and do everything; nothing in between is
907 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
910 newcurparams = me->ourgame->dup_params(me->params);
911 me->ourgame->decode_params(newcurparams, par);
912 error = me->ourgame->validate_params(newcurparams);
914 me->ourgame->free_params(newcurparams);
917 oldparams1 = me->curparams;
920 * Now filter only the persistent parts of this state into
921 * the long-term params structure, unless we've _only_
922 * received a params string in which case the whole lot is
925 oldparams2 = me->params;
929 newparams = me->ourgame->dup_params(me->params);
931 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
932 me->ourgame->decode_params(newparams, tmpstr);
936 newparams = me->ourgame->dup_params(newcurparams);
940 newcurparams = me->curparams;
941 newparams = me->params;
946 error = me->ourgame->validate_desc(newparams, desc);
950 me->ourgame->free_params(newcurparams);
952 me->ourgame->free_params(newparams);
959 * Now we've got past all possible error points. Update the
962 me->params = newparams;
963 me->curparams = newcurparams;
965 me->ourgame->free_params(oldparams1);
967 me->ourgame->free_params(oldparams2);
971 me->desc = me->privdesc = NULL;
976 me->desc = dupstr(desc);
977 me->genmode = GOT_DESC;
983 me->seedstr = dupstr(seed);
984 me->genmode = GOT_SEED;
990 char *midend_game_id(midend_data *me, char *id)
992 return midend_game_id_int(me, id, DEF_PARAMS);
995 char *midend_set_config(midend_data *me, int which, config_item *cfg)
1002 params = me->ourgame->custom_params(cfg);
1003 error = me->ourgame->validate_params(params);
1006 me->ourgame->free_params(params);
1010 me->ourgame->free_params(me->params);
1011 me->params = params;
1016 error = midend_game_id_int(me, cfg[0].sval,
1017 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1026 char *midend_text_format(midend_data *me)
1028 if (me->ourgame->can_format_as_text && me->statepos > 0)
1029 return me->ourgame->text_format(me->states[me->statepos-1].state);
1034 char *midend_solve(midend_data *me)
1037 char *msg, *movestr;
1039 if (!me->ourgame->can_solve)
1040 return "This game does not support the Solve operation";
1042 if (me->statepos < 1)
1043 return "No game set up to solve"; /* _shouldn't_ happen! */
1045 msg = "Solve operation failed"; /* game _should_ overwrite on error */
1046 movestr = me->ourgame->solve(me->states[0].state,
1047 me->states[me->statepos-1].state,
1048 me->aux_info, &msg);
1051 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1055 * Now enter the solved state as the next move.
1057 midend_stop_anim(me);
1058 while (me->nstates > me->statepos)
1059 me->ourgame->free_game(me->states[--me->nstates].state);
1061 me->states[me->nstates].state = s;
1062 me->states[me->nstates].movestr = movestr;
1063 me->states[me->nstates].movetype = SOLVE;
1064 me->statepos = ++me->nstates;
1066 me->ourgame->changed_state(me->ui,
1067 me->states[me->statepos-2].state,
1068 me->states[me->statepos-1].state);
1069 me->anim_time = 0.0;
1070 midend_finish_move(me);
1072 midend_set_timer(me);
1076 char *midend_rewrite_statusbar(midend_data *me, char *text)
1079 * An important special case is that we are occasionally called
1080 * with our own laststatus, to update the timer.
1082 if (me->laststatus != text) {
1083 sfree(me->laststatus);
1084 me->laststatus = dupstr(text);
1087 if (me->ourgame->is_timed) {
1088 char timebuf[100], *ret;
1094 sprintf(timebuf, "[%d:%02d] ", min, sec);
1096 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1097 strcpy(ret, timebuf);
1102 return dupstr(text);
1106 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1107 #define SERIALISE_VERSION "1"
1109 void midend_serialise(midend_data *me,
1110 void (*write)(void *ctx, void *buf, int len),
1116 * Each line of the save file contains three components. First
1117 * exactly 8 characters of header word indicating what type of
1118 * data is contained on the line; then a colon followed by a
1119 * decimal integer giving the length of the main string on the
1120 * line; then a colon followed by the string itself (exactly as
1121 * many bytes as previously specified, no matter what they
1122 * contain). Then a newline (of reasonably flexible form).
1124 #define wr(h,s) do { \
1127 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1128 write(wctx, hbuf, strlen(hbuf)); \
1129 write(wctx, str, strlen(str)); \
1130 write(wctx, "\n", 1); \
1134 * Magic string identifying the file, and version number of the
1137 wr("SAVEFILE", SERIALISE_MAGIC);
1138 wr("VERSION", SERIALISE_VERSION);
1141 * The game name. (Copied locally to avoid const annoyance.)
1144 char *s = dupstr(me->ourgame->name);
1150 * The current long-term parameters structure, in full.
1153 char *s = me->ourgame->encode_params(me->params, TRUE);
1159 * The current short-term parameters structure, in full.
1161 if (me->curparams) {
1162 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1168 * The current game description, the privdesc, and the random seed.
1171 wr("SEED", me->seedstr);
1173 wr("DESC", me->desc);
1175 wr("PRIVDESC", me->privdesc);
1178 * The game's aux_info. We obfuscate this to prevent spoilers
1179 * (people are likely to run `head' or similar on a saved game
1180 * file simply to find out what it is, and don't necessarily
1181 * want to be told the answer to the puzzle!)
1188 len = strlen(me->aux_info);
1189 s1 = snewn(len, unsigned char);
1190 memcpy(s1, me->aux_info, len);
1191 obfuscate_bitmap(s1, len*8, FALSE);
1192 s2 = bin2hex(s1, len);
1201 * Any required serialisation of the game_ui.
1204 char *s = me->ourgame->encode_ui(me->ui);
1212 * The game time, if it's a timed game.
1214 if (me->ourgame->is_timed) {
1216 sprintf(buf, "%g", me->elapsed);
1221 * The length of, and position in, the states list.
1225 sprintf(buf, "%d", me->nstates);
1227 sprintf(buf, "%d", me->statepos);
1228 wr("STATEPOS", buf);
1232 * For each state after the initial one (which we know is
1233 * constructed from either privdesc or desc), enough
1234 * information for execute_move() to reconstruct it from the
1237 for (i = 1; i < me->nstates; i++) {
1238 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1239 switch (me->states[i].movetype) {
1241 wr("MOVE", me->states[i].movestr);
1244 wr("SOLVE", me->states[i].movestr);
1247 wr("RESTART", me->states[i].movestr);
1256 * This function returns NULL on success, or an error message.
1258 char *midend_deserialise(midend_data *me,
1259 int (*read)(void *ctx, void *buf, int len),
1262 int nstates = 0, statepos = -1, gotstates = 0;
1263 int started = FALSE;
1267 /* Initially all errors give the same report */
1268 char *ret = "Data does not appear to be a saved game file";
1271 * We construct all the new state in local variables while we
1272 * check its sanity. Only once we have finished reading the
1273 * serialised data and detected no errors at all do we start
1274 * modifying stuff in the midend_data passed in.
1276 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1277 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1278 float elapsed = 0.0F;
1279 game_params *params = NULL, *cparams = NULL;
1281 struct midend_state_entry *states = NULL;
1284 * Loop round and round reading one key/value pair at a time
1285 * from the serialised stream, until we have enough game states
1288 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1293 if (!read(rctx, key, 1)) {
1294 /* unexpected EOF */
1297 } while (key[0] == '\r' || key[0] == '\n');
1299 if (!read(rctx, key+1, 8)) {
1300 /* unexpected EOF */
1304 if (key[8] != ':') {
1306 ret = "Data was incorrectly formatted for a saved game file";
1308 len = strcspn(key, ": ");
1314 if (!read(rctx, &c, 1)) {
1315 /* unexpected EOF */
1321 } else if (c >= '0' && c <= '9') {
1322 len = (len * 10) + (c - '0');
1325 ret = "Data was incorrectly formatted for a"
1331 val = snewn(len+1, char);
1332 if (!read(rctx, val, len)) {
1339 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1340 /* ret already has the right message in it */
1343 /* Now most errors are this one, unless otherwise specified */
1344 ret = "Saved data ended unexpectedly";
1347 if (!strcmp(key, "VERSION")) {
1348 if (strcmp(val, SERIALISE_VERSION)) {
1349 ret = "Cannot handle this version of the saved game"
1353 } else if (!strcmp(key, "GAME")) {
1354 if (strcmp(val, me->ourgame->name)) {
1355 ret = "Save file is from a different game";
1358 } else if (!strcmp(key, "PARAMS")) {
1362 } else if (!strcmp(key, "CPARAMS")) {
1366 } else if (!strcmp(key, "SEED")) {
1370 } else if (!strcmp(key, "DESC")) {
1374 } else if (!strcmp(key, "PRIVDESC")) {
1378 } else if (!strcmp(key, "AUXINFO")) {
1380 int len = strlen(val) / 2; /* length in bytes */
1381 tmp = hex2bin(val, len);
1382 obfuscate_bitmap(tmp, len*8, TRUE);
1385 auxinfo = snewn(len + 1, char);
1386 memcpy(auxinfo, tmp, len);
1387 auxinfo[len] = '\0';
1389 } else if (!strcmp(key, "UI")) {
1393 } else if (!strcmp(key, "TIME")) {
1394 elapsed = atof(val);
1395 } else if (!strcmp(key, "NSTATES")) {
1396 nstates = atoi(val);
1398 ret = "Number of states in save file was negative";
1402 ret = "Two state counts provided in save file";
1405 states = snewn(nstates, struct midend_state_entry);
1406 for (i = 0; i < nstates; i++) {
1407 states[i].state = NULL;
1408 states[i].movestr = NULL;
1409 states[i].movetype = NEWGAME;
1411 } else if (!strcmp(key, "STATEPOS")) {
1412 statepos = atoi(val);
1413 } else if (!strcmp(key, "MOVE")) {
1415 states[gotstates].movetype = MOVE;
1416 states[gotstates].movestr = val;
1418 } else if (!strcmp(key, "SOLVE")) {
1420 states[gotstates].movetype = SOLVE;
1421 states[gotstates].movestr = val;
1423 } else if (!strcmp(key, "RESTART")) {
1425 states[gotstates].movetype = RESTART;
1426 states[gotstates].movestr = val;
1435 params = me->ourgame->default_params();
1436 me->ourgame->decode_params(params, parstr);
1437 if (me->ourgame->validate_params(params)) {
1438 ret = "Long-term parameters in save file are invalid";
1441 cparams = me->ourgame->default_params();
1442 me->ourgame->decode_params(cparams, cparstr);
1443 if (me->ourgame->validate_params(cparams)) {
1444 ret = "Short-term parameters in save file are invalid";
1448 ret = "Game description in save file is missing";
1450 } else if (me->ourgame->validate_desc(params, desc)) {
1451 ret = "Game description in save file is invalid";
1454 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1455 ret = "Game private description in save file is invalid";
1458 if (statepos < 0 || statepos >= nstates) {
1459 ret = "Game position in save file is out of range";
1462 states[0].state = me->ourgame->new_game(me, params,
1463 privdesc ? privdesc : desc);
1464 for (i = 1; i < nstates; i++) {
1465 assert(states[i].movetype != NEWGAME);
1466 switch (states[i].movetype) {
1469 states[i].state = me->ourgame->execute_move(states[i-1].state,
1471 if (states[i].state == NULL) {
1472 ret = "Save file contained an invalid move";
1477 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1478 ret = "Save file contained an invalid restart move";
1481 states[i].state = me->ourgame->new_game(me, params,
1487 ui = me->ourgame->new_ui(states[0].state);
1488 me->ourgame->decode_ui(ui, uistr);
1491 * Now we've run out of possible error conditions, so we're
1492 * ready to start overwriting the real data in the current
1493 * midend. We'll do this by swapping things with the local
1494 * variables, so that the same cleanup code will free the old
1505 me->privdesc = privdesc;
1513 me->aux_info = auxinfo;
1517 me->genmode = GOT_NOTHING;
1519 me->statesize = nstates;
1520 nstates = me->nstates;
1521 me->nstates = me->statesize;
1523 struct midend_state_entry *tmp;
1525 me->states = states;
1528 me->statepos = statepos;
1534 me->params = params;
1537 tmp = me->curparams;
1538 me->curparams = cparams;
1542 me->oldstate = NULL;
1543 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1554 me->elapsed = elapsed;
1555 me->pressed_mouse_button = 0;
1557 midend_set_timer(me);
1560 me->ourgame->free_drawstate(me->drawstate);
1562 me->ourgame->new_drawstate(me->states[me->statepos-1].state);
1563 midend_size_new_drawstate(me);
1565 ret = NULL; /* success! */
1577 me->ourgame->free_params(params);
1579 me->ourgame->free_params(cparams);
1581 me->ourgame->free_ui(ui);
1585 for (i = 0; i < nstates; i++) {
1586 if (states[i].state)
1587 me->ourgame->free_game(states[i].state);
1588 sfree(states[i].movestr);