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;
34 char **preset_names, **preset_encodings;
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 preferred_tilesize, tilesize, winwidth, winheight;
85 void (*game_id_change_notify_function)(void *);
86 void *game_id_change_notify_ctx;
89 #define ensure(me) do { \
90 if ((me)->nstates >= (me)->statesize) { \
91 (me)->statesize = (me)->nstates + 128; \
92 (me)->states = sresize((me)->states, (me)->statesize, \
93 struct midend_state_entry); \
97 void midend_reset_tilesize(midend *me)
99 me->preferred_tilesize = me->ourgame->preferred_tilesize;
102 * Allow an environment-based override for the default tile
103 * size by defining a variable along the lines of
110 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
111 for (j = k = 0; buf[j]; j++)
112 if (!isspace((unsigned char)buf[j]))
113 buf[k++] = toupper((unsigned char)buf[j]);
115 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
116 me->preferred_tilesize = ts;
120 midend *midend_new(frontend *fe, const game *ourgame,
121 const drawing_api *drapi, void *drhandle)
123 midend *me = snew(midend);
127 get_random_seed(&randseed, &randseedsize);
130 me->ourgame = ourgame;
131 me->random = random_new(randseed, randseedsize);
132 me->nstates = me->statesize = me->statepos = 0;
134 me->params = ourgame->default_params();
135 me->game_id_change_notify_function = NULL;
136 me->game_id_change_notify_ctx = NULL;
139 * Allow environment-based changing of the default settings by
140 * defining a variable along the lines of `NET_DEFAULT=25x25w'
141 * in which the value is an encoded parameter string.
146 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
147 for (j = k = 0; buf[j]; j++)
148 if (!isspace((unsigned char)buf[j]))
149 buf[k++] = toupper((unsigned char)buf[j]);
151 if ((e = getenv(buf)) != NULL)
152 me->ourgame->decode_params(me->params, e);
154 me->curparams = NULL;
155 me->desc = me->privdesc = NULL;
158 me->genmode = GOT_NOTHING;
159 me->drawstate = NULL;
162 me->preset_names = NULL;
163 me->preset_encodings = NULL;
164 me->npresets = me->presetsize = 0;
165 me->anim_time = me->anim_pos = 0.0F;
166 me->flash_time = me->flash_pos = 0.0F;
169 me->pressed_mouse_button = 0;
170 me->laststatus = NULL;
173 me->tilesize = me->winwidth = me->winheight = 0;
175 me->drawing = drawing_new(drapi, me, drhandle);
179 midend_reset_tilesize(me);
186 const game *midend_which_game(midend *me)
191 static void midend_purge_states(midend *me)
193 while (me->nstates > me->statepos) {
194 me->ourgame->free_game(me->states[--me->nstates].state);
195 if (me->states[me->nstates].movestr)
196 sfree(me->states[me->nstates].movestr);
200 static void midend_free_game(midend *me)
202 while (me->nstates > 0) {
204 me->ourgame->free_game(me->states[me->nstates].state);
205 sfree(me->states[me->nstates].movestr);
209 me->ourgame->free_drawstate(me->drawing, me->drawstate);
212 void midend_free(midend *me)
216 midend_free_game(me);
219 drawing_free(me->drawing);
220 random_free(me->random);
226 me->ourgame->free_params(me->params);
228 for (i = 0; i < me->npresets; i++) {
229 sfree(me->presets[i]);
230 sfree(me->preset_names[i]);
231 sfree(me->preset_encodings[i]);
234 sfree(me->preset_names);
235 sfree(me->preset_encodings);
238 me->ourgame->free_ui(me->ui);
240 me->ourgame->free_params(me->curparams);
241 sfree(me->laststatus);
245 static void midend_size_new_drawstate(midend *me)
248 * Don't even bother, if we haven't worked out our tile size
251 if (me->tilesize > 0) {
252 me->ourgame->compute_size(me->params, me->tilesize,
253 &me->winwidth, &me->winheight);
254 me->ourgame->set_size(me->drawing, me->drawstate,
255 me->params, me->tilesize);
259 void midend_size(midend *me, int *x, int *y, int user_size)
265 * We can't set the size on the same drawstate twice. So if
266 * we've already sized one drawstate, we must throw it away and
269 if (me->drawstate && me->tilesize > 0) {
270 me->ourgame->free_drawstate(me->drawing, me->drawstate);
271 me->drawstate = me->ourgame->new_drawstate(me->drawing,
272 me->states[0].state);
276 * Find the tile size that best fits within the given space. If
277 * `user_size' is TRUE, we must actually find the _largest_ such
278 * tile size, in order to get as close to the user's explicit
279 * request as possible; otherwise, we bound above at the game's
280 * preferred tile size, so that the game gets what it wants
281 * provided that this doesn't break the constraint from the
282 * front-end (which is likely to be a screen size or similar).
288 me->ourgame->compute_size(me->params, max, &rx, &ry);
289 } while (rx <= *x && ry <= *y);
291 max = me->preferred_tilesize + 1;
295 * Now binary-search between min and max. We're looking for a
296 * boundary rather than a value: the point at which tile sizes
297 * stop fitting within the given dimensions. Thus, we stop when
298 * max and min differ by exactly 1.
300 while (max - min > 1) {
301 int mid = (max + min) / 2;
302 me->ourgame->compute_size(me->params, mid, &rx, &ry);
303 if (rx <= *x && ry <= *y)
310 * Now `min' is a valid size, and `max' isn't. So use `min'.
315 /* If the user requested a change in size, make it permanent. */
316 me->preferred_tilesize = me->tilesize;
317 midend_size_new_drawstate(me);
322 int midend_tilesize(midend *me) { return me->tilesize; }
324 void midend_set_params(midend *me, game_params *params)
326 me->ourgame->free_params(me->params);
327 me->params = me->ourgame->dup_params(params);
330 game_params *midend_get_params(midend *me)
332 return me->ourgame->dup_params(me->params);
335 static void midend_set_timer(midend *me)
337 me->timing = (me->ourgame->is_timed &&
338 me->ourgame->timing_state(me->states[me->statepos-1].state,
340 if (me->timing || me->flash_time || me->anim_time)
341 activate_timer(me->frontend);
343 deactivate_timer(me->frontend);
346 void midend_force_redraw(midend *me)
349 me->ourgame->free_drawstate(me->drawing, me->drawstate);
350 me->drawstate = me->ourgame->new_drawstate(me->drawing,
351 me->states[0].state);
352 midend_size_new_drawstate(me);
356 void midend_new_game(midend *me)
358 midend_free_game(me);
360 assert(me->nstates == 0);
362 if (me->genmode == GOT_DESC) {
363 me->genmode = GOT_NOTHING;
367 if (me->genmode == GOT_SEED) {
368 me->genmode = GOT_NOTHING;
371 * Generate a new random seed. 15 digits comes to about
372 * 48 bits, which should be more than enough.
374 * I'll avoid putting a leading zero on the number,
375 * just in case it confuses anybody who thinks it's
376 * processed as an integer rather than a string.
381 newseed[0] = '1' + (char)random_upto(me->random, 9);
382 for (i = 1; i < 15; i++)
383 newseed[i] = '0' + (char)random_upto(me->random, 10);
385 me->seedstr = dupstr(newseed);
388 me->ourgame->free_params(me->curparams);
389 me->curparams = me->ourgame->dup_params(me->params);
397 rs = random_new(me->seedstr, strlen(me->seedstr));
399 * If this midend has been instantiated without providing a
400 * drawing API, it is non-interactive. This means that it's
401 * being used for bulk game generation, and hence we should
402 * pass the non-interactive flag to new_desc.
404 me->desc = me->ourgame->new_desc(me->curparams, rs,
405 &me->aux_info, (me->drawing != NULL));
413 * It might seem a bit odd that we're using me->params to
414 * create the initial game state, rather than me->curparams
415 * which is better tailored to this specific game and which we
418 * It's supposed to be an invariant in the midend that
419 * me->params and me->curparams differ in no aspect that is
420 * important after generation (i.e. after new_desc()). By
421 * deliberately passing the _less_ specific of these two
422 * parameter sets, we provoke play-time misbehaviour in the
423 * case where a game has failed to encode a play-time parameter
424 * in the non-full version of encode_params().
426 me->states[me->nstates].state =
427 me->ourgame->new_game(me, me->params, me->desc);
430 * As part of our commitment to self-testing, test the aux
431 * string to make sure nothing ghastly went wrong.
433 if (me->ourgame->can_solve && me->aux_info) {
438 movestr = me->ourgame->solve(me->states[0].state,
441 assert(movestr && !msg);
442 s = me->ourgame->execute_move(me->states[0].state, movestr);
444 me->ourgame->free_game(s);
449 * Soak test, enabled by setting <gamename>_TESTSOLVE in the
450 * environment. This causes an immediate attempt to re-solve the
451 * game without benefit of aux_info. The effect is that (at least
452 * on Unix) you can run 'FOO_TESTSOLVE=1 foo --generate 10000
453 * <params>#12345' and it will generate a lot of game ids and
454 * instantly pass each one back to the solver.
456 * (It's worth putting in an explicit seed in any such test, so
457 * you can repeat it to diagnose a problem if one comes up!)
462 static int doing_test_solve = -1;
463 if (doing_test_solve < 0) {
464 sprintf(buf, "%s_TESTSOLVE", me->ourgame->name);
465 for (j = k = 0; buf[j]; j++)
466 if (!isspace((unsigned char)buf[j]))
467 buf[k++] = toupper((unsigned char)buf[j]);
471 * Since this is used for correctness testing, it's
472 * helpful to have a visual acknowledgment that the
473 * user hasn't mistyped the environment variable name.
475 fprintf(stderr, "Running solver soak tests\n");
476 doing_test_solve = TRUE;
478 doing_test_solve = FALSE;
481 if (doing_test_solve) {
486 movestr = me->ourgame->solve(me->states[0].state,
489 assert(movestr && !msg);
490 s = me->ourgame->execute_move(me->states[0].state, movestr);
492 me->ourgame->free_game(s);
497 me->states[me->nstates].movestr = NULL;
498 me->states[me->nstates].movetype = NEWGAME;
501 me->drawstate = me->ourgame->new_drawstate(me->drawing,
502 me->states[0].state);
503 midend_size_new_drawstate(me);
506 me->ourgame->free_ui(me->ui);
507 me->ui = me->ourgame->new_ui(me->states[0].state);
508 midend_set_timer(me);
509 me->pressed_mouse_button = 0;
511 if (me->game_id_change_notify_function)
512 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
515 int midend_can_undo(midend *me)
517 return (me->statepos > 1);
520 int midend_can_redo(midend *me)
522 return (me->statepos < me->nstates);
525 static int midend_undo(midend *me)
527 if (me->statepos > 1) {
529 me->ourgame->changed_state(me->ui,
530 me->states[me->statepos-1].state,
531 me->states[me->statepos-2].state);
539 static int midend_redo(midend *me)
541 if (me->statepos < me->nstates) {
543 me->ourgame->changed_state(me->ui,
544 me->states[me->statepos-1].state,
545 me->states[me->statepos].state);
553 static void midend_finish_move(midend *me)
558 * We do not flash if the later of the two states is special.
559 * This covers both forward Solve moves and backward (undone)
562 if ((me->oldstate || me->statepos > 1) &&
563 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
564 (me->dir < 0 && me->statepos < me->nstates &&
565 !special(me->states[me->statepos].movetype)))) {
566 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
567 me->states[me->statepos-2].state,
568 me->states[me->statepos-1].state,
569 me->oldstate ? me->dir : +1,
572 me->flash_pos = 0.0F;
573 me->flash_time = flashtime;
578 me->ourgame->free_game(me->oldstate);
580 me->anim_pos = me->anim_time = 0;
583 midend_set_timer(me);
586 void midend_stop_anim(midend *me)
588 if (me->oldstate || me->anim_time != 0) {
589 midend_finish_move(me);
594 void midend_restart_game(midend *me)
598 midend_stop_anim(me);
600 assert(me->statepos >= 1);
601 if (me->statepos == 1)
602 return; /* no point doing anything at all! */
605 * During restart, we reconstruct the game from the (public)
606 * game description rather than from states[0], because that
607 * way Mines gets slightly more sensible behaviour (restart
608 * goes to _after_ the first click so you don't have to
609 * remember where you clicked).
611 s = me->ourgame->new_game(me, me->params, me->desc);
614 * Now enter the restarted state as the next move.
616 midend_stop_anim(me);
617 midend_purge_states(me);
619 me->states[me->nstates].state = s;
620 me->states[me->nstates].movestr = dupstr(me->desc);
621 me->states[me->nstates].movetype = RESTART;
622 me->statepos = ++me->nstates;
624 me->ourgame->changed_state(me->ui,
625 me->states[me->statepos-2].state,
626 me->states[me->statepos-1].state);
628 midend_finish_move(me);
630 midend_set_timer(me);
633 static int midend_really_process_key(midend *me, int x, int y, int button)
635 game_state *oldstate =
636 me->ourgame->dup_game(me->states[me->statepos - 1].state);
637 int type = MOVE, gottype = FALSE, ret = 1;
643 me->ourgame->interpret_move(me->states[me->statepos-1].state,
644 me->ui, me->drawstate, x, y, button);
647 if (button == 'n' || button == 'N' || button == '\x0E') {
648 midend_stop_anim(me);
651 goto done; /* never animate */
652 } else if (button == 'u' || button == 'u' ||
653 button == '\x1A' || button == '\x1F') {
654 midend_stop_anim(me);
655 type = me->states[me->statepos-1].movetype;
657 if (!midend_undo(me))
659 } else if (button == 'r' || button == 'R' ||
660 button == '\x12' || button == '\x19') {
661 midend_stop_anim(me);
662 if (!midend_redo(me))
664 } else if (button == '\x13' && me->ourgame->can_solve) {
665 if (midend_solve(me))
667 } else if (button == 'q' || button == 'Q' || button == '\x11') {
674 s = me->states[me->statepos-1].state;
676 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
681 if (s == me->states[me->statepos-1].state) {
683 * make_move() is allowed to return its input state to
684 * indicate that although no move has been made, the UI
685 * state has been updated and a redraw is called for.
688 midend_set_timer(me);
691 midend_stop_anim(me);
692 midend_purge_states(me);
694 assert(movestr != NULL);
695 me->states[me->nstates].state = s;
696 me->states[me->nstates].movestr = movestr;
697 me->states[me->nstates].movetype = MOVE;
698 me->statepos = ++me->nstates;
701 me->ourgame->changed_state(me->ui,
702 me->states[me->statepos-2].state,
703 me->states[me->statepos-1].state);
710 type = me->states[me->statepos-1].movetype;
713 * See if this move requires an animation.
715 if (special(type) && !(type == SOLVE &&
716 (me->ourgame->flags & SOLVE_ANIMATES))) {
719 anim_time = me->ourgame->anim_length(oldstate,
720 me->states[me->statepos-1].state,
724 me->oldstate = oldstate; oldstate = NULL;
726 me->anim_time = anim_time;
729 midend_finish_move(me);
735 midend_set_timer(me);
738 if (oldstate) me->ourgame->free_game(oldstate);
742 int midend_process_key(midend *me, int x, int y, int button)
747 * Harmonise mouse drag and release messages.
749 * Some front ends might accidentally switch from sending, say,
750 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
751 * drag. (This can happen on the Mac, for example, since
752 * RIGHT_DRAG is usually done using Command+drag, and if the
753 * user accidentally releases Command half way through the drag
754 * then there will be trouble.)
756 * It would be an O(number of front ends) annoyance to fix this
757 * in the front ends, but an O(number of back ends) annoyance
758 * to have each game capable of dealing with it. Therefore, we
759 * fix it _here_ in the common midend code so that it only has
762 * The possible ways in which things can go screwy in the front
765 * - in a system containing multiple physical buttons button
766 * presses can inadvertently overlap. We can see ABab (caps
767 * meaning button-down and lowercase meaning button-up) when
768 * the user had semantically intended AaBb.
770 * - in a system where one button is simulated by means of a
771 * modifier key and another button, buttons can mutate
772 * between press and release (possibly during drag). So we
773 * can see Ab instead of Aa.
775 * Definite requirements are:
777 * - button _presses_ must never be invented or destroyed. If
778 * the user presses two buttons in succession, the button
779 * presses must be transferred to the backend unchanged. So
780 * if we see AaBb , that's fine; if we see ABab (the button
781 * presses inadvertently overlapped) we must somehow
782 * `correct' it to AaBb.
784 * - every mouse action must end up looking like a press, zero
785 * or more drags, then a release. This allows back ends to
786 * make the _assumption_ that incoming mouse data will be
787 * sane in this regard, and not worry about the details.
789 * So my policy will be:
791 * - treat any button-up as a button-up for the currently
792 * pressed button, or ignore it if there is no currently
795 * - treat any drag as a drag for the currently pressed
796 * button, or ignore it if there is no currently pressed
799 * - if we see a button-down while another button is currently
800 * pressed, invent a button-up for the first one and then
801 * pass the button-down through as before.
803 * 2005-05-31: An addendum to the above. Some games might want
804 * a `priority order' among buttons, such that if one button is
805 * pressed while another is down then a fixed one of the
806 * buttons takes priority no matter what order they're pressed
807 * in. Mines, in particular, wants to treat a left+right click
808 * like a left click for the benefit of users of other
809 * implementations. So the last of the above points is modified
810 * in the presence of an (optional) button priority order.
812 * A further addition: we translate certain keyboard presses to
813 * cursor key 'select' buttons, so that a) frontends don't have
814 * to translate these themselves (like they do for CURSOR_UP etc),
815 * and b) individual games don't have to hard-code button presses
816 * of '\n' etc for keyboard-based cursors. The choice of buttons
817 * here could eventually be controlled by a runtime configuration
820 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
821 if (me->pressed_mouse_button) {
822 if (IS_MOUSE_DRAG(button)) {
823 button = me->pressed_mouse_button +
824 (LEFT_DRAG - LEFT_BUTTON);
826 button = me->pressed_mouse_button +
827 (LEFT_RELEASE - LEFT_BUTTON);
830 return ret; /* ignore it */
831 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
833 * If the new button has lower priority than the old one,
834 * don't bother doing this.
836 if (me->ourgame->flags &
837 BUTTON_BEATS(me->pressed_mouse_button, button))
838 return ret; /* just ignore it */
841 * Fabricate a button-up for the previously pressed button.
843 ret = ret && midend_really_process_key
844 (me, x, y, (me->pressed_mouse_button +
845 (LEFT_RELEASE - LEFT_BUTTON)));
849 * Translate keyboard presses to cursor selection.
851 if (button == '\n' || button == '\r')
852 button = CURSOR_SELECT;
854 button = CURSOR_SELECT2;
857 * Normalise both backspace characters (8 and 127) to \b. Easier
858 * to do this once, here, than to require all front ends to
859 * carefully generate the same one - now each front end can
860 * generate whichever is easiest.
862 if (button == '\177')
866 * Now send on the event we originally received.
868 ret = ret && midend_really_process_key(me, x, y, button);
871 * And update the currently pressed button.
873 if (IS_MOUSE_RELEASE(button))
874 me->pressed_mouse_button = 0;
875 else if (IS_MOUSE_DOWN(button))
876 me->pressed_mouse_button = button;
881 void midend_redraw(midend *me)
885 if (me->statepos > 0 && me->drawstate) {
886 start_draw(me->drawing);
887 if (me->oldstate && me->anim_time > 0 &&
888 me->anim_pos < me->anim_time) {
889 assert(me->dir != 0);
890 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
891 me->states[me->statepos-1].state, me->dir,
892 me->ui, me->anim_pos, me->flash_pos);
894 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
895 me->states[me->statepos-1].state, +1 /*shrug*/,
896 me->ui, 0.0, me->flash_pos);
898 end_draw(me->drawing);
903 * Nasty hacky function used to implement the --redo option in
904 * gtk.c. Only used for generating the puzzles' icons.
906 void midend_freeze_timer(midend *me, float tprop)
908 me->anim_pos = me->anim_time * tprop;
910 deactivate_timer(me->frontend);
913 void midend_timer(midend *me, float tplus)
915 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
917 me->anim_pos += tplus;
918 if (me->anim_pos >= me->anim_time ||
919 me->anim_time == 0 || !me->oldstate) {
920 if (me->anim_time > 0)
921 midend_finish_move(me);
924 me->flash_pos += tplus;
925 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
926 me->flash_pos = me->flash_time = 0;
933 float oldelapsed = me->elapsed;
934 me->elapsed += tplus;
935 if ((int)oldelapsed != (int)me->elapsed)
936 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
939 midend_set_timer(me);
942 float *midend_colours(midend *me, int *ncolours)
946 ret = me->ourgame->colours(me->frontend, ncolours);
952 * Allow environment-based overrides for the standard
953 * colours by defining variables along the lines of
954 * `NET_COLOUR_4=6000c0'.
957 for (i = 0; i < *ncolours; i++) {
959 unsigned int r, g, b;
962 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
963 for (j = k = 0; buf[j]; j++)
964 if (!isspace((unsigned char)buf[j]))
965 buf[k++] = toupper((unsigned char)buf[j]);
967 if ((e = getenv(buf)) != NULL &&
968 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
969 ret[i*3 + 0] = r / 255.0F;
970 ret[i*3 + 1] = g / 255.0F;
971 ret[i*3 + 2] = b / 255.0F;
979 int midend_num_presets(midend *me)
985 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
986 if (me->presetsize <= me->npresets) {
987 me->presetsize = me->npresets + 10;
988 me->presets = sresize(me->presets, me->presetsize,
990 me->preset_names = sresize(me->preset_names, me->presetsize,
992 me->preset_encodings = sresize(me->preset_encodings,
993 me->presetsize, char *);
996 me->presets[me->npresets] = preset;
997 me->preset_names[me->npresets] = name;
998 me->preset_encodings[me->npresets] =
999 me->ourgame->encode_params(preset, TRUE);;
1006 * Allow environment-based extensions to the preset list by
1007 * defining a variable along the lines of `SOLO_PRESETS=2x3
1008 * Advanced:2x3da'. Colon-separated list of items,
1009 * alternating between textual titles in the menu and
1010 * encoded parameter strings.
1012 char buf[80], *e, *p;
1015 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1016 for (j = k = 0; buf[j]; j++)
1017 if (!isspace((unsigned char)buf[j]))
1018 buf[k++] = toupper((unsigned char)buf[j]);
1021 if ((e = getenv(buf)) != NULL) {
1026 game_params *preset;
1029 while (*p && *p != ':') p++;
1030 if (*p) *p++ = '\0';
1032 while (*p && *p != ':') p++;
1033 if (*p) *p++ = '\0';
1035 preset = me->ourgame->default_params();
1036 me->ourgame->decode_params(preset, val);
1038 if (me->ourgame->validate_params(preset, TRUE)) {
1039 /* Drop this one from the list. */
1040 me->ourgame->free_params(preset);
1044 if (me->presetsize <= me->npresets) {
1045 me->presetsize = me->npresets + 10;
1046 me->presets = sresize(me->presets, me->presetsize,
1048 me->preset_names = sresize(me->preset_names,
1049 me->presetsize, char *);
1050 me->preset_encodings = sresize(me->preset_encodings,
1051 me->presetsize, char *);
1054 me->presets[me->npresets] = preset;
1055 me->preset_names[me->npresets] = dupstr(name);
1056 me->preset_encodings[me->npresets] =
1057 me->ourgame->encode_params(preset, TRUE);
1064 return me->npresets;
1067 void midend_fetch_preset(midend *me, int n,
1068 char **name, game_params **params)
1070 assert(n >= 0 && n < me->npresets);
1071 *name = me->preset_names[n];
1072 *params = me->presets[n];
1075 int midend_which_preset(midend *me)
1077 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1081 for (i = 0; i < me->npresets; i++)
1082 if (!strcmp(encoding, me->preset_encodings[i])) {
1091 int midend_wants_statusbar(midend *me)
1093 return me->ourgame->wants_statusbar;
1096 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1098 me->game_id_change_notify_function = notify;
1099 me->game_id_change_notify_ctx = ctx;
1102 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1105 sfree(me->privdesc);
1106 me->desc = dupstr(desc);
1107 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1108 if (me->game_id_change_notify_function)
1109 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1112 config_item *midend_get_config(midend *me, int which, char **wintitle)
1114 char *titlebuf, *parstr, *rest;
1119 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1123 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1124 *wintitle = titlebuf;
1125 return me->ourgame->configure(me->params);
1128 if (!me->curparams) {
1132 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1133 which == CFG_SEED ? "random" : "game");
1134 *wintitle = titlebuf;
1136 ret = snewn(2, config_item);
1138 ret[0].type = C_STRING;
1139 if (which == CFG_SEED)
1140 ret[0].name = "Game random seed";
1142 ret[0].name = "Game ID";
1145 * For CFG_DESC the text going in here will be a string
1146 * encoding of the restricted parameters, plus a colon,
1147 * plus the game description. For CFG_SEED it will be the
1148 * full parameters, plus a hash, plus the random seed data.
1149 * Either of these is a valid full game ID (although only
1150 * the former is likely to persist across many code
1153 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1155 if (which == CFG_DESC) {
1156 rest = me->desc ? me->desc : "";
1159 rest = me->seedstr ? me->seedstr : "";
1162 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1163 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1166 ret[1].type = C_END;
1167 ret[1].name = ret[1].sval = NULL;
1173 assert(!"We shouldn't be here");
1177 static char *midend_game_id_int(midend *me, char *id, int defmode)
1179 char *error, *par, *desc, *seed;
1180 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1183 seed = strchr(id, '#');
1184 desc = strchr(id, ':');
1186 if (desc && (!seed || desc < seed)) {
1188 * We have a colon separating parameters from game
1189 * description. So `par' now points to the parameters
1190 * string, and `desc' to the description string.
1195 } else if (seed && (!desc || seed < desc)) {
1197 * We have a hash separating parameters from random seed.
1198 * So `par' now points to the parameters string, and `seed'
1199 * to the seed string.
1206 * We only have one string. Depending on `defmode', we take
1207 * it to be either parameters, seed or description.
1209 if (defmode == DEF_SEED) {
1212 } else if (defmode == DEF_DESC) {
1222 * We must be reasonably careful here not to modify anything in
1223 * `me' until we have finished validating things. This function
1224 * must either return an error and do nothing to the midend, or
1225 * return success and do everything; nothing in between is
1228 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1231 newcurparams = me->ourgame->dup_params(me->params);
1232 me->ourgame->decode_params(newcurparams, par);
1233 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1235 me->ourgame->free_params(newcurparams);
1238 oldparams1 = me->curparams;
1241 * Now filter only the persistent parts of this state into
1242 * the long-term params structure, unless we've _only_
1243 * received a params string in which case the whole lot is
1246 oldparams2 = me->params;
1250 newparams = me->ourgame->dup_params(me->params);
1252 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1253 me->ourgame->decode_params(newparams, tmpstr);
1257 newparams = me->ourgame->dup_params(newcurparams);
1261 newcurparams = me->curparams;
1262 newparams = me->params;
1263 free_params = FALSE;
1267 error = me->ourgame->validate_desc(newparams, desc);
1271 me->ourgame->free_params(newcurparams);
1273 me->ourgame->free_params(newparams);
1280 * Now we've got past all possible error points. Update the
1283 me->params = newparams;
1284 me->curparams = newcurparams;
1286 me->ourgame->free_params(oldparams1);
1288 me->ourgame->free_params(oldparams2);
1291 sfree(me->privdesc);
1292 me->desc = me->privdesc = NULL;
1297 me->desc = dupstr(desc);
1298 me->genmode = GOT_DESC;
1299 sfree(me->aux_info);
1300 me->aux_info = NULL;
1304 me->seedstr = dupstr(seed);
1305 me->genmode = GOT_SEED;
1311 char *midend_game_id(midend *me, char *id)
1313 return midend_game_id_int(me, id, DEF_PARAMS);
1316 char *midend_get_game_id(midend *me)
1320 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1323 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1324 sprintf(ret, "%s:%s", parstr, me->desc);
1329 char *midend_get_random_seed(midend *me)
1336 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1338 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1339 sprintf(ret, "%s#%s", parstr, me->seedstr);
1344 char *midend_set_config(midend *me, int which, config_item *cfg)
1347 game_params *params;
1351 params = me->ourgame->custom_params(cfg);
1352 error = me->ourgame->validate_params(params, TRUE);
1355 me->ourgame->free_params(params);
1359 me->ourgame->free_params(me->params);
1360 me->params = params;
1365 error = midend_game_id_int(me, cfg[0].sval,
1366 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1375 int midend_can_format_as_text_now(midend *me)
1377 if (me->ourgame->can_format_as_text_ever)
1378 return me->ourgame->can_format_as_text_now(me->params);
1383 char *midend_text_format(midend *me)
1385 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1386 me->ourgame->can_format_as_text_now(me->params))
1387 return me->ourgame->text_format(me->states[me->statepos-1].state);
1392 char *midend_solve(midend *me)
1395 char *msg, *movestr;
1397 if (!me->ourgame->can_solve)
1398 return "This game does not support the Solve operation";
1400 if (me->statepos < 1)
1401 return "No game set up to solve"; /* _shouldn't_ happen! */
1404 movestr = me->ourgame->solve(me->states[0].state,
1405 me->states[me->statepos-1].state,
1406 me->aux_info, &msg);
1409 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1412 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1416 * Now enter the solved state as the next move.
1418 midend_stop_anim(me);
1419 midend_purge_states(me);
1421 me->states[me->nstates].state = s;
1422 me->states[me->nstates].movestr = movestr;
1423 me->states[me->nstates].movetype = SOLVE;
1424 me->statepos = ++me->nstates;
1426 me->ourgame->changed_state(me->ui,
1427 me->states[me->statepos-2].state,
1428 me->states[me->statepos-1].state);
1430 if (me->ourgame->flags & SOLVE_ANIMATES) {
1431 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1433 me->ourgame->anim_length(me->states[me->statepos-2].state,
1434 me->states[me->statepos-1].state,
1438 me->anim_time = 0.0;
1439 midend_finish_move(me);
1443 midend_set_timer(me);
1447 int midend_status(midend *me)
1450 * We should probably never be called when the state stack has no
1451 * states on it at all - ideally, midends should never be left in
1452 * that state for long enough to get put down and forgotten about.
1453 * But if we are, I think we return _true_ - pedantically speaking
1454 * a midend in that state is 'vacuously solved', and more
1455 * practically, a user whose midend has been left in that state
1456 * probably _does_ want the 'new game' option to be prominent.
1458 if (me->statepos == 0)
1461 return me->ourgame->status(me->states[me->statepos-1].state);
1464 char *midend_rewrite_statusbar(midend *me, char *text)
1467 * An important special case is that we are occasionally called
1468 * with our own laststatus, to update the timer.
1470 if (me->laststatus != text) {
1471 sfree(me->laststatus);
1472 me->laststatus = dupstr(text);
1475 if (me->ourgame->is_timed) {
1476 char timebuf[100], *ret;
1479 sec = (int)me->elapsed;
1482 sprintf(timebuf, "[%d:%02d] ", min, sec);
1484 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1485 strcpy(ret, timebuf);
1490 return dupstr(text);
1494 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1495 #define SERIALISE_VERSION "1"
1497 void midend_serialise(midend *me,
1498 void (*write)(void *ctx, void *buf, int len),
1504 * Each line of the save file contains three components. First
1505 * exactly 8 characters of header word indicating what type of
1506 * data is contained on the line; then a colon followed by a
1507 * decimal integer giving the length of the main string on the
1508 * line; then a colon followed by the string itself (exactly as
1509 * many bytes as previously specified, no matter what they
1510 * contain). Then a newline (of reasonably flexible form).
1512 #define wr(h,s) do { \
1515 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1516 write(wctx, hbuf, strlen(hbuf)); \
1517 write(wctx, str, strlen(str)); \
1518 write(wctx, "\n", 1); \
1522 * Magic string identifying the file, and version number of the
1525 wr("SAVEFILE", SERIALISE_MAGIC);
1526 wr("VERSION", SERIALISE_VERSION);
1529 * The game name. (Copied locally to avoid const annoyance.)
1532 char *s = dupstr(me->ourgame->name);
1538 * The current long-term parameters structure, in full.
1541 char *s = me->ourgame->encode_params(me->params, TRUE);
1547 * The current short-term parameters structure, in full.
1549 if (me->curparams) {
1550 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1556 * The current game description, the privdesc, and the random seed.
1559 wr("SEED", me->seedstr);
1561 wr("DESC", me->desc);
1563 wr("PRIVDESC", me->privdesc);
1566 * The game's aux_info. We obfuscate this to prevent spoilers
1567 * (people are likely to run `head' or similar on a saved game
1568 * file simply to find out what it is, and don't necessarily
1569 * want to be told the answer to the puzzle!)
1576 len = strlen(me->aux_info);
1577 s1 = snewn(len, unsigned char);
1578 memcpy(s1, me->aux_info, len);
1579 obfuscate_bitmap(s1, len*8, FALSE);
1580 s2 = bin2hex(s1, len);
1589 * Any required serialisation of the game_ui.
1592 char *s = me->ourgame->encode_ui(me->ui);
1600 * The game time, if it's a timed game.
1602 if (me->ourgame->is_timed) {
1604 sprintf(buf, "%g", me->elapsed);
1609 * The length of, and position in, the states list.
1613 sprintf(buf, "%d", me->nstates);
1615 sprintf(buf, "%d", me->statepos);
1616 wr("STATEPOS", buf);
1620 * For each state after the initial one (which we know is
1621 * constructed from either privdesc or desc), enough
1622 * information for execute_move() to reconstruct it from the
1625 for (i = 1; i < me->nstates; i++) {
1626 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1627 switch (me->states[i].movetype) {
1629 wr("MOVE", me->states[i].movestr);
1632 wr("SOLVE", me->states[i].movestr);
1635 wr("RESTART", me->states[i].movestr);
1644 * This function returns NULL on success, or an error message.
1646 char *midend_deserialise(midend *me,
1647 int (*read)(void *ctx, void *buf, int len),
1650 int nstates = 0, statepos = -1, gotstates = 0;
1651 int started = FALSE;
1655 /* Initially all errors give the same report */
1656 char *ret = "Data does not appear to be a saved game file";
1659 * We construct all the new state in local variables while we
1660 * check its sanity. Only once we have finished reading the
1661 * serialised data and detected no errors at all do we start
1662 * modifying stuff in the midend passed in.
1664 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1665 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1666 float elapsed = 0.0F;
1667 game_params *params = NULL, *cparams = NULL;
1669 struct midend_state_entry *states = NULL;
1672 * Loop round and round reading one key/value pair at a time
1673 * from the serialised stream, until we have enough game states
1676 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1681 if (!read(rctx, key, 1)) {
1682 /* unexpected EOF */
1685 } while (key[0] == '\r' || key[0] == '\n');
1687 if (!read(rctx, key+1, 8)) {
1688 /* unexpected EOF */
1692 if (key[8] != ':') {
1694 ret = "Data was incorrectly formatted for a saved game file";
1697 len = strcspn(key, ": ");
1703 if (!read(rctx, &c, 1)) {
1704 /* unexpected EOF */
1710 } else if (c >= '0' && c <= '9') {
1711 len = (len * 10) + (c - '0');
1714 ret = "Data was incorrectly formatted for a"
1720 val = snewn(len+1, char);
1721 if (!read(rctx, val, len)) {
1728 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1729 /* ret already has the right message in it */
1732 /* Now most errors are this one, unless otherwise specified */
1733 ret = "Saved data ended unexpectedly";
1736 if (!strcmp(key, "VERSION")) {
1737 if (strcmp(val, SERIALISE_VERSION)) {
1738 ret = "Cannot handle this version of the saved game"
1742 } else if (!strcmp(key, "GAME")) {
1743 if (strcmp(val, me->ourgame->name)) {
1744 ret = "Save file is from a different game";
1747 } else if (!strcmp(key, "PARAMS")) {
1751 } else if (!strcmp(key, "CPARAMS")) {
1755 } else if (!strcmp(key, "SEED")) {
1759 } else if (!strcmp(key, "DESC")) {
1763 } else if (!strcmp(key, "PRIVDESC")) {
1767 } else if (!strcmp(key, "AUXINFO")) {
1769 int len = strlen(val) / 2; /* length in bytes */
1770 tmp = hex2bin(val, len);
1771 obfuscate_bitmap(tmp, len*8, TRUE);
1774 auxinfo = snewn(len + 1, char);
1775 memcpy(auxinfo, tmp, len);
1776 auxinfo[len] = '\0';
1778 } else if (!strcmp(key, "UI")) {
1782 } else if (!strcmp(key, "TIME")) {
1783 elapsed = (float)atof(val);
1784 } else if (!strcmp(key, "NSTATES")) {
1785 nstates = atoi(val);
1787 ret = "Number of states in save file was negative";
1791 ret = "Two state counts provided in save file";
1794 states = snewn(nstates, struct midend_state_entry);
1795 for (i = 0; i < nstates; i++) {
1796 states[i].state = NULL;
1797 states[i].movestr = NULL;
1798 states[i].movetype = NEWGAME;
1800 } else if (!strcmp(key, "STATEPOS")) {
1801 statepos = atoi(val);
1802 } else if (!strcmp(key, "MOVE")) {
1804 states[gotstates].movetype = MOVE;
1805 states[gotstates].movestr = val;
1807 } else if (!strcmp(key, "SOLVE")) {
1809 states[gotstates].movetype = SOLVE;
1810 states[gotstates].movestr = val;
1812 } else if (!strcmp(key, "RESTART")) {
1814 states[gotstates].movetype = RESTART;
1815 states[gotstates].movestr = val;
1824 params = me->ourgame->default_params();
1825 me->ourgame->decode_params(params, parstr);
1826 if (me->ourgame->validate_params(params, TRUE)) {
1827 ret = "Long-term parameters in save file are invalid";
1830 cparams = me->ourgame->default_params();
1831 me->ourgame->decode_params(cparams, cparstr);
1832 if (me->ourgame->validate_params(cparams, FALSE)) {
1833 ret = "Short-term parameters in save file are invalid";
1836 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1838 * The seed's no use with this version, but we can perfectly
1839 * well use the rest of the data.
1845 ret = "Game description in save file is missing";
1847 } else if (me->ourgame->validate_desc(params, desc)) {
1848 ret = "Game description in save file is invalid";
1851 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1852 ret = "Game private description in save file is invalid";
1855 if (statepos < 0 || statepos >= nstates) {
1856 ret = "Game position in save file is out of range";
1859 states[0].state = me->ourgame->new_game(me, params,
1860 privdesc ? privdesc : desc);
1861 for (i = 1; i < nstates; i++) {
1862 assert(states[i].movetype != NEWGAME);
1863 switch (states[i].movetype) {
1866 states[i].state = me->ourgame->execute_move(states[i-1].state,
1868 if (states[i].state == NULL) {
1869 ret = "Save file contained an invalid move";
1874 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1875 ret = "Save file contained an invalid restart move";
1878 states[i].state = me->ourgame->new_game(me, params,
1884 ui = me->ourgame->new_ui(states[0].state);
1885 me->ourgame->decode_ui(ui, uistr);
1888 * Now we've run out of possible error conditions, so we're
1889 * ready to start overwriting the real data in the current
1890 * midend. We'll do this by swapping things with the local
1891 * variables, so that the same cleanup code will free the old
1902 me->privdesc = privdesc;
1910 me->aux_info = auxinfo;
1914 me->genmode = GOT_NOTHING;
1916 me->statesize = nstates;
1917 nstates = me->nstates;
1918 me->nstates = me->statesize;
1920 struct midend_state_entry *tmp;
1922 me->states = states;
1925 me->statepos = statepos;
1931 me->params = params;
1934 tmp = me->curparams;
1935 me->curparams = cparams;
1939 me->oldstate = NULL;
1940 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1951 me->elapsed = elapsed;
1952 me->pressed_mouse_button = 0;
1954 midend_set_timer(me);
1957 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1959 me->ourgame->new_drawstate(me->drawing,
1960 me->states[me->statepos-1].state);
1961 midend_size_new_drawstate(me);
1963 ret = NULL; /* success! */
1975 me->ourgame->free_params(params);
1977 me->ourgame->free_params(cparams);
1979 me->ourgame->free_ui(ui);
1983 for (i = 0; i < nstates; i++) {
1984 if (states[i].state)
1985 me->ourgame->free_game(states[i].state);
1986 sfree(states[i].movestr);
1995 * This function examines a saved game file just far enough to
1996 * determine which game type it contains. It returns NULL on success
1997 * and the game name string in 'name' (which will be dynamically
1998 * allocated and should be caller-freed), or an error message on
2001 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
2004 int nstates = 0, statepos = -1, gotstates = 0;
2005 int started = FALSE;
2008 /* Initially all errors give the same report */
2009 char *ret = "Data does not appear to be a saved game file";
2014 * Loop round and round reading one key/value pair at a time from
2015 * the serialised stream, until we've found the game name.
2017 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2022 if (!read(rctx, key, 1)) {
2023 /* unexpected EOF */
2026 } while (key[0] == '\r' || key[0] == '\n');
2028 if (!read(rctx, key+1, 8)) {
2029 /* unexpected EOF */
2033 if (key[8] != ':') {
2035 ret = "Data was incorrectly formatted for a saved game file";
2038 len = strcspn(key, ": ");
2044 if (!read(rctx, &c, 1)) {
2045 /* unexpected EOF */
2051 } else if (c >= '0' && c <= '9') {
2052 len = (len * 10) + (c - '0');
2055 ret = "Data was incorrectly formatted for a"
2061 val = snewn(len+1, char);
2062 if (!read(rctx, val, len)) {
2069 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2070 /* ret already has the right message in it */
2073 /* Now most errors are this one, unless otherwise specified */
2074 ret = "Saved data ended unexpectedly";
2077 if (!strcmp(key, "VERSION")) {
2078 if (strcmp(val, SERIALISE_VERSION)) {
2079 ret = "Cannot handle this version of the saved game"
2083 } else if (!strcmp(key, "GAME")) {
2084 *name = dupstr(val);
2099 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2101 game_state *soln = NULL;
2103 if (me->statepos < 1)
2104 return "No game set up to print";/* _shouldn't_ happen! */
2107 char *msg, *movestr;
2109 if (!me->ourgame->can_solve)
2110 return "This game does not support the Solve operation";
2112 msg = "Solve operation failed";/* game _should_ overwrite on error */
2113 movestr = me->ourgame->solve(me->states[0].state,
2114 me->states[me->statepos-1].state,
2115 me->aux_info, &msg);
2118 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2127 * This call passes over ownership of the two game_states and
2128 * the game_params. Hence we duplicate the ones we want to
2129 * keep, and we don't have to bother freeing soln if it was
2132 document_add_puzzle(doc, me->ourgame,
2133 me->ourgame->dup_params(me->curparams),
2134 me->ourgame->dup_game(me->states[0].state), soln);