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;
86 #define ensure(me) do { \
87 if ((me)->nstates >= (me)->statesize) { \
88 (me)->statesize = (me)->nstates + 128; \
89 (me)->states = sresize((me)->states, (me)->statesize, \
90 struct midend_state_entry); \
94 midend *midend_new(frontend *fe, const game *ourgame,
95 const drawing_api *drapi, void *drhandle)
97 midend *me = snew(midend);
101 get_random_seed(&randseed, &randseedsize);
104 me->ourgame = ourgame;
105 me->random = random_new(randseed, randseedsize);
106 me->nstates = me->statesize = me->statepos = 0;
108 me->params = ourgame->default_params();
110 * Allow environment-based changing of the default settings by
111 * defining a variable along the lines of `NET_DEFAULT=25x25w'
112 * in which the value is an encoded parameter string.
117 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
118 for (j = k = 0; buf[j]; j++)
119 if (!isspace((unsigned char)buf[j]))
120 buf[k++] = toupper((unsigned char)buf[j]);
122 if ((e = getenv(buf)) != NULL)
123 me->ourgame->decode_params(me->params, e);
125 me->curparams = NULL;
126 me->desc = me->privdesc = NULL;
129 me->genmode = GOT_NOTHING;
130 me->drawstate = NULL;
133 me->preset_names = NULL;
134 me->preset_encodings = NULL;
135 me->npresets = me->presetsize = 0;
136 me->anim_time = me->anim_pos = 0.0F;
137 me->flash_time = me->flash_pos = 0.0F;
140 me->pressed_mouse_button = 0;
141 me->laststatus = NULL;
144 me->tilesize = me->winwidth = me->winheight = 0;
146 me->drawing = drawing_new(drapi, me, drhandle);
150 me->preferred_tilesize = ourgame->preferred_tilesize;
153 * Allow an environment-based override for the default tile
154 * size by defining a variable along the lines of
161 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
162 for (j = k = 0; buf[j]; j++)
163 if (!isspace((unsigned char)buf[j]))
164 buf[k++] = toupper((unsigned char)buf[j]);
166 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
167 me->preferred_tilesize = ts;
175 static void midend_purge_states(midend *me)
177 while (me->nstates > me->statepos) {
178 me->ourgame->free_game(me->states[--me->nstates].state);
179 if (me->states[me->nstates].movestr)
180 sfree(me->states[me->nstates].movestr);
184 static void midend_free_game(midend *me)
186 while (me->nstates > 0) {
188 me->ourgame->free_game(me->states[me->nstates].state);
189 sfree(me->states[me->nstates].movestr);
193 me->ourgame->free_drawstate(me->drawing, me->drawstate);
196 void midend_free(midend *me)
200 midend_free_game(me);
203 drawing_free(me->drawing);
204 random_free(me->random);
210 me->ourgame->free_params(me->params);
212 for (i = 0; i < me->npresets; i++) {
213 sfree(me->presets[i]);
214 sfree(me->preset_names[i]);
215 sfree(me->preset_encodings[i]);
218 sfree(me->preset_names);
219 sfree(me->preset_encodings);
222 me->ourgame->free_ui(me->ui);
224 me->ourgame->free_params(me->curparams);
225 sfree(me->laststatus);
229 static void midend_size_new_drawstate(midend *me)
232 * Don't even bother, if we haven't worked out our tile size
235 if (me->tilesize > 0) {
236 me->ourgame->compute_size(me->params, me->tilesize,
237 &me->winwidth, &me->winheight);
238 me->ourgame->set_size(me->drawing, me->drawstate,
239 me->params, me->tilesize);
243 void midend_size(midend *me, int *x, int *y, int user_size)
249 * We can't set the size on the same drawstate twice. So if
250 * we've already sized one drawstate, we must throw it away and
253 if (me->drawstate && me->tilesize > 0) {
254 me->ourgame->free_drawstate(me->drawing, me->drawstate);
255 me->drawstate = me->ourgame->new_drawstate(me->drawing,
256 me->states[0].state);
260 * Find the tile size that best fits within the given space. If
261 * `user_size' is TRUE, we must actually find the _largest_ such
262 * tile size, in order to get as close to the user's explicit
263 * request as possible; otherwise, we bound above at the game's
264 * preferred tile size, so that the game gets what it wants
265 * provided that this doesn't break the constraint from the
266 * front-end (which is likely to be a screen size or similar).
272 me->ourgame->compute_size(me->params, max, &rx, &ry);
273 } while (rx <= *x && ry <= *y);
275 max = me->preferred_tilesize + 1;
279 * Now binary-search between min and max. We're looking for a
280 * boundary rather than a value: the point at which tile sizes
281 * stop fitting within the given dimensions. Thus, we stop when
282 * max and min differ by exactly 1.
284 while (max - min > 1) {
285 int mid = (max + min) / 2;
286 me->ourgame->compute_size(me->params, mid, &rx, &ry);
287 if (rx <= *x && ry <= *y)
294 * Now `min' is a valid size, and `max' isn't. So use `min'.
299 /* If the user requested a change in size, make it permanent. */
300 me->preferred_tilesize = me->tilesize;
301 midend_size_new_drawstate(me);
306 int midend_tilesize(midend *me) { return me->tilesize; }
308 void midend_set_params(midend *me, game_params *params)
310 me->ourgame->free_params(me->params);
311 me->params = me->ourgame->dup_params(params);
314 game_params *midend_get_params(midend *me)
316 return me->ourgame->dup_params(me->params);
319 static void midend_set_timer(midend *me)
321 me->timing = (me->ourgame->is_timed &&
322 me->ourgame->timing_state(me->states[me->statepos-1].state,
324 if (me->timing || me->flash_time || me->anim_time)
325 activate_timer(me->frontend);
327 deactivate_timer(me->frontend);
330 void midend_force_redraw(midend *me)
333 me->ourgame->free_drawstate(me->drawing, me->drawstate);
334 me->drawstate = me->ourgame->new_drawstate(me->drawing,
335 me->states[0].state);
336 midend_size_new_drawstate(me);
340 void midend_new_game(midend *me)
342 midend_free_game(me);
344 assert(me->nstates == 0);
346 if (me->genmode == GOT_DESC) {
347 me->genmode = GOT_NOTHING;
351 if (me->genmode == GOT_SEED) {
352 me->genmode = GOT_NOTHING;
355 * Generate a new random seed. 15 digits comes to about
356 * 48 bits, which should be more than enough.
358 * I'll avoid putting a leading zero on the number,
359 * just in case it confuses anybody who thinks it's
360 * processed as an integer rather than a string.
365 newseed[0] = '1' + (char)random_upto(me->random, 9);
366 for (i = 1; i < 15; i++)
367 newseed[i] = '0' + (char)random_upto(me->random, 10);
369 me->seedstr = dupstr(newseed);
372 me->ourgame->free_params(me->curparams);
373 me->curparams = me->ourgame->dup_params(me->params);
381 rs = random_new(me->seedstr, strlen(me->seedstr));
383 * If this midend has been instantiated without providing a
384 * drawing API, it is non-interactive. This means that it's
385 * being used for bulk game generation, and hence we should
386 * pass the non-interactive flag to new_desc.
388 me->desc = me->ourgame->new_desc(me->curparams, rs,
389 &me->aux_info, (me->drawing != NULL));
397 * It might seem a bit odd that we're using me->params to
398 * create the initial game state, rather than me->curparams
399 * which is better tailored to this specific game and which we
402 * It's supposed to be an invariant in the midend that
403 * me->params and me->curparams differ in no aspect that is
404 * important after generation (i.e. after new_desc()). By
405 * deliberately passing the _less_ specific of these two
406 * parameter sets, we provoke play-time misbehaviour in the
407 * case where a game has failed to encode a play-time parameter
408 * in the non-full version of encode_params().
410 me->states[me->nstates].state =
411 me->ourgame->new_game(me, me->params, me->desc);
414 * As part of our commitment to self-testing, test the aux
415 * string to make sure nothing ghastly went wrong.
417 if (me->ourgame->can_solve && me->aux_info) {
422 movestr = me->ourgame->solve(me->states[0].state,
425 assert(movestr && !msg);
426 s = me->ourgame->execute_move(me->states[0].state, movestr);
428 me->ourgame->free_game(s);
433 * Soak test, enabled by setting <gamename>_TESTSOLVE in the
434 * environment. This causes an immediate attempt to re-solve the
435 * game without benefit of aux_info. The effect is that (at least
436 * on Unix) you can run 'FOO_TESTSOLVE=1 foo --generate 10000
437 * <params>#12345' and it will generate a lot of game ids and
438 * instantly pass each one back to the solver.
440 * (It's worth putting in an explicit seed in any such test, so
441 * you can repeat it to diagnose a problem if one comes up!)
446 static int doing_test_solve = -1;
447 if (doing_test_solve < 0) {
448 sprintf(buf, "%s_TESTSOLVE", me->ourgame->name);
449 for (j = k = 0; buf[j]; j++)
450 if (!isspace((unsigned char)buf[j]))
451 buf[k++] = toupper((unsigned char)buf[j]);
455 * Since this is used for correctness testing, it's
456 * helpful to have a visual acknowledgment that the
457 * user hasn't mistyped the environment variable name.
459 fprintf(stderr, "Running solver soak tests\n");
460 doing_test_solve = TRUE;
462 doing_test_solve = FALSE;
465 if (doing_test_solve) {
470 movestr = me->ourgame->solve(me->states[0].state,
473 assert(movestr && !msg);
474 s = me->ourgame->execute_move(me->states[0].state, movestr);
476 me->ourgame->free_game(s);
481 me->states[me->nstates].movestr = NULL;
482 me->states[me->nstates].movetype = NEWGAME;
485 me->drawstate = me->ourgame->new_drawstate(me->drawing,
486 me->states[0].state);
487 midend_size_new_drawstate(me);
490 me->ourgame->free_ui(me->ui);
491 me->ui = me->ourgame->new_ui(me->states[0].state);
492 midend_set_timer(me);
493 me->pressed_mouse_button = 0;
496 int midend_can_undo(midend *me)
498 return (me->statepos > 1);
501 int midend_can_redo(midend *me)
503 return (me->statepos < me->nstates);
506 static int midend_undo(midend *me)
508 if (me->statepos > 1) {
510 me->ourgame->changed_state(me->ui,
511 me->states[me->statepos-1].state,
512 me->states[me->statepos-2].state);
520 static int midend_redo(midend *me)
522 if (me->statepos < me->nstates) {
524 me->ourgame->changed_state(me->ui,
525 me->states[me->statepos-1].state,
526 me->states[me->statepos].state);
534 static void midend_finish_move(midend *me)
539 * We do not flash if the later of the two states is special.
540 * This covers both forward Solve moves and backward (undone)
543 if ((me->oldstate || me->statepos > 1) &&
544 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
545 (me->dir < 0 && me->statepos < me->nstates &&
546 !special(me->states[me->statepos].movetype)))) {
547 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
548 me->states[me->statepos-2].state,
549 me->states[me->statepos-1].state,
550 me->oldstate ? me->dir : +1,
553 me->flash_pos = 0.0F;
554 me->flash_time = flashtime;
559 me->ourgame->free_game(me->oldstate);
561 me->anim_pos = me->anim_time = 0;
564 midend_set_timer(me);
567 void midend_stop_anim(midend *me)
569 if (me->oldstate || me->anim_time != 0) {
570 midend_finish_move(me);
575 void midend_restart_game(midend *me)
579 midend_stop_anim(me);
581 assert(me->statepos >= 1);
582 if (me->statepos == 1)
583 return; /* no point doing anything at all! */
586 * During restart, we reconstruct the game from the (public)
587 * game description rather than from states[0], because that
588 * way Mines gets slightly more sensible behaviour (restart
589 * goes to _after_ the first click so you don't have to
590 * remember where you clicked).
592 s = me->ourgame->new_game(me, me->params, me->desc);
595 * Now enter the restarted state as the next move.
597 midend_stop_anim(me);
598 midend_purge_states(me);
600 me->states[me->nstates].state = s;
601 me->states[me->nstates].movestr = dupstr(me->desc);
602 me->states[me->nstates].movetype = RESTART;
603 me->statepos = ++me->nstates;
605 me->ourgame->changed_state(me->ui,
606 me->states[me->statepos-2].state,
607 me->states[me->statepos-1].state);
609 midend_finish_move(me);
611 midend_set_timer(me);
614 static int midend_really_process_key(midend *me, int x, int y, int button)
616 game_state *oldstate =
617 me->ourgame->dup_game(me->states[me->statepos - 1].state);
618 int type = MOVE, gottype = FALSE, ret = 1;
624 me->ourgame->interpret_move(me->states[me->statepos-1].state,
625 me->ui, me->drawstate, x, y, button);
628 if (button == 'n' || button == 'N' || button == '\x0E') {
629 midend_stop_anim(me);
632 goto done; /* never animate */
633 } else if (button == 'u' || button == 'u' ||
634 button == '\x1A' || button == '\x1F') {
635 midend_stop_anim(me);
636 type = me->states[me->statepos-1].movetype;
638 if (!midend_undo(me))
640 } else if (button == 'r' || button == 'R' ||
641 button == '\x12' || button == '\x19') {
642 midend_stop_anim(me);
643 if (!midend_redo(me))
645 } else if (button == '\x13' && me->ourgame->can_solve) {
646 if (midend_solve(me))
648 } else if (button == 'q' || button == 'Q' || button == '\x11') {
655 s = me->states[me->statepos-1].state;
657 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
662 if (s == me->states[me->statepos-1].state) {
664 * make_move() is allowed to return its input state to
665 * indicate that although no move has been made, the UI
666 * state has been updated and a redraw is called for.
669 midend_set_timer(me);
672 midend_stop_anim(me);
673 midend_purge_states(me);
675 assert(movestr != NULL);
676 me->states[me->nstates].state = s;
677 me->states[me->nstates].movestr = movestr;
678 me->states[me->nstates].movetype = MOVE;
679 me->statepos = ++me->nstates;
682 me->ourgame->changed_state(me->ui,
683 me->states[me->statepos-2].state,
684 me->states[me->statepos-1].state);
691 type = me->states[me->statepos-1].movetype;
694 * See if this move requires an animation.
696 if (special(type) && !(type == SOLVE &&
697 (me->ourgame->flags & SOLVE_ANIMATES))) {
700 anim_time = me->ourgame->anim_length(oldstate,
701 me->states[me->statepos-1].state,
705 me->oldstate = oldstate; oldstate = NULL;
707 me->anim_time = anim_time;
710 midend_finish_move(me);
716 midend_set_timer(me);
719 if (oldstate) me->ourgame->free_game(oldstate);
723 int midend_process_key(midend *me, int x, int y, int button)
728 * Harmonise mouse drag and release messages.
730 * Some front ends might accidentally switch from sending, say,
731 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
732 * drag. (This can happen on the Mac, for example, since
733 * RIGHT_DRAG is usually done using Command+drag, and if the
734 * user accidentally releases Command half way through the drag
735 * then there will be trouble.)
737 * It would be an O(number of front ends) annoyance to fix this
738 * in the front ends, but an O(number of back ends) annoyance
739 * to have each game capable of dealing with it. Therefore, we
740 * fix it _here_ in the common midend code so that it only has
743 * The possible ways in which things can go screwy in the front
746 * - in a system containing multiple physical buttons button
747 * presses can inadvertently overlap. We can see ABab (caps
748 * meaning button-down and lowercase meaning button-up) when
749 * the user had semantically intended AaBb.
751 * - in a system where one button is simulated by means of a
752 * modifier key and another button, buttons can mutate
753 * between press and release (possibly during drag). So we
754 * can see Ab instead of Aa.
756 * Definite requirements are:
758 * - button _presses_ must never be invented or destroyed. If
759 * the user presses two buttons in succession, the button
760 * presses must be transferred to the backend unchanged. So
761 * if we see AaBb , that's fine; if we see ABab (the button
762 * presses inadvertently overlapped) we must somehow
763 * `correct' it to AaBb.
765 * - every mouse action must end up looking like a press, zero
766 * or more drags, then a release. This allows back ends to
767 * make the _assumption_ that incoming mouse data will be
768 * sane in this regard, and not worry about the details.
770 * So my policy will be:
772 * - treat any button-up as a button-up for the currently
773 * pressed button, or ignore it if there is no currently
776 * - treat any drag as a drag for the currently pressed
777 * button, or ignore it if there is no currently pressed
780 * - if we see a button-down while another button is currently
781 * pressed, invent a button-up for the first one and then
782 * pass the button-down through as before.
784 * 2005-05-31: An addendum to the above. Some games might want
785 * a `priority order' among buttons, such that if one button is
786 * pressed while another is down then a fixed one of the
787 * buttons takes priority no matter what order they're pressed
788 * in. Mines, in particular, wants to treat a left+right click
789 * like a left click for the benefit of users of other
790 * implementations. So the last of the above points is modified
791 * in the presence of an (optional) button priority order.
793 * A further addition: we translate certain keyboard presses to
794 * cursor key 'select' buttons, so that a) frontends don't have
795 * to translate these themselves (like they do for CURSOR_UP etc),
796 * and b) individual games don't have to hard-code button presses
797 * of '\n' etc for keyboard-based cursors. The choice of buttons
798 * here could eventually be controlled by a runtime configuration
801 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
802 if (me->pressed_mouse_button) {
803 if (IS_MOUSE_DRAG(button)) {
804 button = me->pressed_mouse_button +
805 (LEFT_DRAG - LEFT_BUTTON);
807 button = me->pressed_mouse_button +
808 (LEFT_RELEASE - LEFT_BUTTON);
811 return ret; /* ignore it */
812 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
814 * If the new button has lower priority than the old one,
815 * don't bother doing this.
817 if (me->ourgame->flags &
818 BUTTON_BEATS(me->pressed_mouse_button, button))
819 return ret; /* just ignore it */
822 * Fabricate a button-up for the previously pressed button.
824 ret = ret && midend_really_process_key
825 (me, x, y, (me->pressed_mouse_button +
826 (LEFT_RELEASE - LEFT_BUTTON)));
830 * Translate keyboard presses to cursor selection.
832 if (button == '\n' || button == '\r')
833 button = CURSOR_SELECT;
835 button = CURSOR_SELECT2;
838 * Normalise both backspace characters (8 and 127) to \b. Easier
839 * to do this once, here, than to require all front ends to
840 * carefully generate the same one - now each front end can
841 * generate whichever is easiest.
843 if (button == '\177')
847 * Now send on the event we originally received.
849 ret = ret && midend_really_process_key(me, x, y, button);
852 * And update the currently pressed button.
854 if (IS_MOUSE_RELEASE(button))
855 me->pressed_mouse_button = 0;
856 else if (IS_MOUSE_DOWN(button))
857 me->pressed_mouse_button = button;
862 void midend_redraw(midend *me)
866 if (me->statepos > 0 && me->drawstate) {
867 start_draw(me->drawing);
868 if (me->oldstate && me->anim_time > 0 &&
869 me->anim_pos < me->anim_time) {
870 assert(me->dir != 0);
871 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
872 me->states[me->statepos-1].state, me->dir,
873 me->ui, me->anim_pos, me->flash_pos);
875 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
876 me->states[me->statepos-1].state, +1 /*shrug*/,
877 me->ui, 0.0, me->flash_pos);
879 end_draw(me->drawing);
884 * Nasty hacky function used to implement the --redo option in
885 * gtk.c. Only used for generating the puzzles' icons.
887 void midend_freeze_timer(midend *me, float tprop)
889 me->anim_pos = me->anim_time * tprop;
891 deactivate_timer(me->frontend);
894 void midend_timer(midend *me, float tplus)
896 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
898 me->anim_pos += tplus;
899 if (me->anim_pos >= me->anim_time ||
900 me->anim_time == 0 || !me->oldstate) {
901 if (me->anim_time > 0)
902 midend_finish_move(me);
905 me->flash_pos += tplus;
906 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
907 me->flash_pos = me->flash_time = 0;
914 float oldelapsed = me->elapsed;
915 me->elapsed += tplus;
916 if ((int)oldelapsed != (int)me->elapsed)
917 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
920 midend_set_timer(me);
923 float *midend_colours(midend *me, int *ncolours)
927 ret = me->ourgame->colours(me->frontend, ncolours);
933 * Allow environment-based overrides for the standard
934 * colours by defining variables along the lines of
935 * `NET_COLOUR_4=6000c0'.
938 for (i = 0; i < *ncolours; i++) {
940 unsigned int r, g, b;
943 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
944 for (j = k = 0; buf[j]; j++)
945 if (!isspace((unsigned char)buf[j]))
946 buf[k++] = toupper((unsigned char)buf[j]);
948 if ((e = getenv(buf)) != NULL &&
949 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
950 ret[i*3 + 0] = r / 255.0F;
951 ret[i*3 + 1] = g / 255.0F;
952 ret[i*3 + 2] = b / 255.0F;
960 int midend_num_presets(midend *me)
966 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
967 if (me->presetsize <= me->npresets) {
968 me->presetsize = me->npresets + 10;
969 me->presets = sresize(me->presets, me->presetsize,
971 me->preset_names = sresize(me->preset_names, me->presetsize,
973 me->preset_encodings = sresize(me->preset_encodings,
974 me->presetsize, char *);
977 me->presets[me->npresets] = preset;
978 me->preset_names[me->npresets] = name;
979 me->preset_encodings[me->npresets] =
980 me->ourgame->encode_params(preset, TRUE);;
987 * Allow environment-based extensions to the preset list by
988 * defining a variable along the lines of `SOLO_PRESETS=2x3
989 * Advanced:2x3da'. Colon-separated list of items,
990 * alternating between textual titles in the menu and
991 * encoded parameter strings.
993 char buf[80], *e, *p;
996 sprintf(buf, "%s_PRESETS", me->ourgame->name);
997 for (j = k = 0; buf[j]; j++)
998 if (!isspace((unsigned char)buf[j]))
999 buf[k++] = toupper((unsigned char)buf[j]);
1002 if ((e = getenv(buf)) != NULL) {
1007 game_params *preset;
1010 while (*p && *p != ':') p++;
1011 if (*p) *p++ = '\0';
1013 while (*p && *p != ':') p++;
1014 if (*p) *p++ = '\0';
1016 preset = me->ourgame->default_params();
1017 me->ourgame->decode_params(preset, val);
1019 if (me->ourgame->validate_params(preset, TRUE)) {
1020 /* Drop this one from the list. */
1021 me->ourgame->free_params(preset);
1025 if (me->presetsize <= me->npresets) {
1026 me->presetsize = me->npresets + 10;
1027 me->presets = sresize(me->presets, me->presetsize,
1029 me->preset_names = sresize(me->preset_names,
1030 me->presetsize, char *);
1031 me->preset_encodings = sresize(me->preset_encodings,
1032 me->presetsize, char *);
1035 me->presets[me->npresets] = preset;
1036 me->preset_names[me->npresets] = dupstr(name);
1037 me->preset_encodings[me->npresets] =
1038 me->ourgame->encode_params(preset, TRUE);
1045 return me->npresets;
1048 void midend_fetch_preset(midend *me, int n,
1049 char **name, game_params **params)
1051 assert(n >= 0 && n < me->npresets);
1052 *name = me->preset_names[n];
1053 *params = me->presets[n];
1056 int midend_which_preset(midend *me)
1058 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1062 for (i = 0; i < me->npresets; i++)
1063 if (!strcmp(encoding, me->preset_encodings[i])) {
1072 int midend_wants_statusbar(midend *me)
1074 return me->ourgame->wants_statusbar;
1077 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1080 sfree(me->privdesc);
1081 me->desc = dupstr(desc);
1082 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1085 config_item *midend_get_config(midend *me, int which, char **wintitle)
1087 char *titlebuf, *parstr, *rest;
1092 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1096 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1097 *wintitle = titlebuf;
1098 return me->ourgame->configure(me->params);
1101 if (!me->curparams) {
1105 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1106 which == CFG_SEED ? "random" : "game");
1107 *wintitle = titlebuf;
1109 ret = snewn(2, config_item);
1111 ret[0].type = C_STRING;
1112 if (which == CFG_SEED)
1113 ret[0].name = "Game random seed";
1115 ret[0].name = "Game ID";
1118 * For CFG_DESC the text going in here will be a string
1119 * encoding of the restricted parameters, plus a colon,
1120 * plus the game description. For CFG_SEED it will be the
1121 * full parameters, plus a hash, plus the random seed data.
1122 * Either of these is a valid full game ID (although only
1123 * the former is likely to persist across many code
1126 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1128 if (which == CFG_DESC) {
1129 rest = me->desc ? me->desc : "";
1132 rest = me->seedstr ? me->seedstr : "";
1135 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1136 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1139 ret[1].type = C_END;
1140 ret[1].name = ret[1].sval = NULL;
1146 assert(!"We shouldn't be here");
1150 static char *midend_game_id_int(midend *me, char *id, int defmode)
1152 char *error, *par, *desc, *seed;
1153 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1156 seed = strchr(id, '#');
1157 desc = strchr(id, ':');
1159 if (desc && (!seed || desc < seed)) {
1161 * We have a colon separating parameters from game
1162 * description. So `par' now points to the parameters
1163 * string, and `desc' to the description string.
1168 } else if (seed && (!desc || seed < desc)) {
1170 * We have a hash separating parameters from random seed.
1171 * So `par' now points to the parameters string, and `seed'
1172 * to the seed string.
1179 * We only have one string. Depending on `defmode', we take
1180 * it to be either parameters, seed or description.
1182 if (defmode == DEF_SEED) {
1185 } else if (defmode == DEF_DESC) {
1195 * We must be reasonably careful here not to modify anything in
1196 * `me' until we have finished validating things. This function
1197 * must either return an error and do nothing to the midend, or
1198 * return success and do everything; nothing in between is
1201 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1204 newcurparams = me->ourgame->dup_params(me->params);
1205 me->ourgame->decode_params(newcurparams, par);
1206 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1208 me->ourgame->free_params(newcurparams);
1211 oldparams1 = me->curparams;
1214 * Now filter only the persistent parts of this state into
1215 * the long-term params structure, unless we've _only_
1216 * received a params string in which case the whole lot is
1219 oldparams2 = me->params;
1223 newparams = me->ourgame->dup_params(me->params);
1225 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1226 me->ourgame->decode_params(newparams, tmpstr);
1230 newparams = me->ourgame->dup_params(newcurparams);
1234 newcurparams = me->curparams;
1235 newparams = me->params;
1236 free_params = FALSE;
1240 error = me->ourgame->validate_desc(newparams, desc);
1244 me->ourgame->free_params(newcurparams);
1246 me->ourgame->free_params(newparams);
1253 * Now we've got past all possible error points. Update the
1256 me->params = newparams;
1257 me->curparams = newcurparams;
1259 me->ourgame->free_params(oldparams1);
1261 me->ourgame->free_params(oldparams2);
1264 sfree(me->privdesc);
1265 me->desc = me->privdesc = NULL;
1270 me->desc = dupstr(desc);
1271 me->genmode = GOT_DESC;
1272 sfree(me->aux_info);
1273 me->aux_info = NULL;
1277 me->seedstr = dupstr(seed);
1278 me->genmode = GOT_SEED;
1284 char *midend_game_id(midend *me, char *id)
1286 return midend_game_id_int(me, id, DEF_PARAMS);
1289 char *midend_get_game_id(midend *me)
1293 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1296 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1297 sprintf(ret, "%s:%s", parstr, me->desc);
1302 char *midend_set_config(midend *me, int which, config_item *cfg)
1305 game_params *params;
1309 params = me->ourgame->custom_params(cfg);
1310 error = me->ourgame->validate_params(params, TRUE);
1313 me->ourgame->free_params(params);
1317 me->ourgame->free_params(me->params);
1318 me->params = params;
1323 error = midend_game_id_int(me, cfg[0].sval,
1324 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1333 int midend_can_format_as_text_now(midend *me)
1335 if (me->ourgame->can_format_as_text_ever)
1336 return me->ourgame->can_format_as_text_now(me->params);
1341 char *midend_text_format(midend *me)
1343 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1344 me->ourgame->can_format_as_text_now(me->params))
1345 return me->ourgame->text_format(me->states[me->statepos-1].state);
1350 char *midend_solve(midend *me)
1353 char *msg, *movestr;
1355 if (!me->ourgame->can_solve)
1356 return "This game does not support the Solve operation";
1358 if (me->statepos < 1)
1359 return "No game set up to solve"; /* _shouldn't_ happen! */
1362 movestr = me->ourgame->solve(me->states[0].state,
1363 me->states[me->statepos-1].state,
1364 me->aux_info, &msg);
1367 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1370 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1374 * Now enter the solved state as the next move.
1376 midend_stop_anim(me);
1377 midend_purge_states(me);
1379 me->states[me->nstates].state = s;
1380 me->states[me->nstates].movestr = movestr;
1381 me->states[me->nstates].movetype = SOLVE;
1382 me->statepos = ++me->nstates;
1384 me->ourgame->changed_state(me->ui,
1385 me->states[me->statepos-2].state,
1386 me->states[me->statepos-1].state);
1388 if (me->ourgame->flags & SOLVE_ANIMATES) {
1389 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1391 me->ourgame->anim_length(me->states[me->statepos-2].state,
1392 me->states[me->statepos-1].state,
1396 me->anim_time = 0.0;
1397 midend_finish_move(me);
1401 midend_set_timer(me);
1405 int midend_status(midend *me)
1408 * We should probably never be called when the state stack has no
1409 * states on it at all - ideally, midends should never be left in
1410 * that state for long enough to get put down and forgotten about.
1411 * But if we are, I think we return _true_ - pedantically speaking
1412 * a midend in that state is 'vacuously solved', and more
1413 * practically, a user whose midend has been left in that state
1414 * probably _does_ want the 'new game' option to be prominent.
1416 if (me->statepos == 0)
1419 return me->ourgame->status(me->states[me->statepos-1].state);
1422 char *midend_rewrite_statusbar(midend *me, char *text)
1425 * An important special case is that we are occasionally called
1426 * with our own laststatus, to update the timer.
1428 if (me->laststatus != text) {
1429 sfree(me->laststatus);
1430 me->laststatus = dupstr(text);
1433 if (me->ourgame->is_timed) {
1434 char timebuf[100], *ret;
1437 sec = (int)me->elapsed;
1440 sprintf(timebuf, "[%d:%02d] ", min, sec);
1442 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1443 strcpy(ret, timebuf);
1448 return dupstr(text);
1452 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1453 #define SERIALISE_VERSION "1"
1455 void midend_serialise(midend *me,
1456 void (*write)(void *ctx, void *buf, int len),
1462 * Each line of the save file contains three components. First
1463 * exactly 8 characters of header word indicating what type of
1464 * data is contained on the line; then a colon followed by a
1465 * decimal integer giving the length of the main string on the
1466 * line; then a colon followed by the string itself (exactly as
1467 * many bytes as previously specified, no matter what they
1468 * contain). Then a newline (of reasonably flexible form).
1470 #define wr(h,s) do { \
1473 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1474 write(wctx, hbuf, strlen(hbuf)); \
1475 write(wctx, str, strlen(str)); \
1476 write(wctx, "\n", 1); \
1480 * Magic string identifying the file, and version number of the
1483 wr("SAVEFILE", SERIALISE_MAGIC);
1484 wr("VERSION", SERIALISE_VERSION);
1487 * The game name. (Copied locally to avoid const annoyance.)
1490 char *s = dupstr(me->ourgame->name);
1496 * The current long-term parameters structure, in full.
1499 char *s = me->ourgame->encode_params(me->params, TRUE);
1505 * The current short-term parameters structure, in full.
1507 if (me->curparams) {
1508 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1514 * The current game description, the privdesc, and the random seed.
1517 wr("SEED", me->seedstr);
1519 wr("DESC", me->desc);
1521 wr("PRIVDESC", me->privdesc);
1524 * The game's aux_info. We obfuscate this to prevent spoilers
1525 * (people are likely to run `head' or similar on a saved game
1526 * file simply to find out what it is, and don't necessarily
1527 * want to be told the answer to the puzzle!)
1534 len = strlen(me->aux_info);
1535 s1 = snewn(len, unsigned char);
1536 memcpy(s1, me->aux_info, len);
1537 obfuscate_bitmap(s1, len*8, FALSE);
1538 s2 = bin2hex(s1, len);
1547 * Any required serialisation of the game_ui.
1550 char *s = me->ourgame->encode_ui(me->ui);
1558 * The game time, if it's a timed game.
1560 if (me->ourgame->is_timed) {
1562 sprintf(buf, "%g", me->elapsed);
1567 * The length of, and position in, the states list.
1571 sprintf(buf, "%d", me->nstates);
1573 sprintf(buf, "%d", me->statepos);
1574 wr("STATEPOS", buf);
1578 * For each state after the initial one (which we know is
1579 * constructed from either privdesc or desc), enough
1580 * information for execute_move() to reconstruct it from the
1583 for (i = 1; i < me->nstates; i++) {
1584 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1585 switch (me->states[i].movetype) {
1587 wr("MOVE", me->states[i].movestr);
1590 wr("SOLVE", me->states[i].movestr);
1593 wr("RESTART", me->states[i].movestr);
1602 * This function returns NULL on success, or an error message.
1604 char *midend_deserialise(midend *me,
1605 int (*read)(void *ctx, void *buf, int len),
1608 int nstates = 0, statepos = -1, gotstates = 0;
1609 int started = FALSE;
1613 /* Initially all errors give the same report */
1614 char *ret = "Data does not appear to be a saved game file";
1617 * We construct all the new state in local variables while we
1618 * check its sanity. Only once we have finished reading the
1619 * serialised data and detected no errors at all do we start
1620 * modifying stuff in the midend passed in.
1622 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1623 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1624 float elapsed = 0.0F;
1625 game_params *params = NULL, *cparams = NULL;
1627 struct midend_state_entry *states = NULL;
1630 * Loop round and round reading one key/value pair at a time
1631 * from the serialised stream, until we have enough game states
1634 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1639 if (!read(rctx, key, 1)) {
1640 /* unexpected EOF */
1643 } while (key[0] == '\r' || key[0] == '\n');
1645 if (!read(rctx, key+1, 8)) {
1646 /* unexpected EOF */
1650 if (key[8] != ':') {
1652 ret = "Data was incorrectly formatted for a saved game file";
1655 len = strcspn(key, ": ");
1661 if (!read(rctx, &c, 1)) {
1662 /* unexpected EOF */
1668 } else if (c >= '0' && c <= '9') {
1669 len = (len * 10) + (c - '0');
1672 ret = "Data was incorrectly formatted for a"
1678 val = snewn(len+1, char);
1679 if (!read(rctx, val, len)) {
1686 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1687 /* ret already has the right message in it */
1690 /* Now most errors are this one, unless otherwise specified */
1691 ret = "Saved data ended unexpectedly";
1694 if (!strcmp(key, "VERSION")) {
1695 if (strcmp(val, SERIALISE_VERSION)) {
1696 ret = "Cannot handle this version of the saved game"
1700 } else if (!strcmp(key, "GAME")) {
1701 if (strcmp(val, me->ourgame->name)) {
1702 ret = "Save file is from a different game";
1705 } else if (!strcmp(key, "PARAMS")) {
1709 } else if (!strcmp(key, "CPARAMS")) {
1713 } else if (!strcmp(key, "SEED")) {
1717 } else if (!strcmp(key, "DESC")) {
1721 } else if (!strcmp(key, "PRIVDESC")) {
1725 } else if (!strcmp(key, "AUXINFO")) {
1727 int len = strlen(val) / 2; /* length in bytes */
1728 tmp = hex2bin(val, len);
1729 obfuscate_bitmap(tmp, len*8, TRUE);
1732 auxinfo = snewn(len + 1, char);
1733 memcpy(auxinfo, tmp, len);
1734 auxinfo[len] = '\0';
1736 } else if (!strcmp(key, "UI")) {
1740 } else if (!strcmp(key, "TIME")) {
1741 elapsed = (float)atof(val);
1742 } else if (!strcmp(key, "NSTATES")) {
1743 nstates = atoi(val);
1745 ret = "Number of states in save file was negative";
1749 ret = "Two state counts provided in save file";
1752 states = snewn(nstates, struct midend_state_entry);
1753 for (i = 0; i < nstates; i++) {
1754 states[i].state = NULL;
1755 states[i].movestr = NULL;
1756 states[i].movetype = NEWGAME;
1758 } else if (!strcmp(key, "STATEPOS")) {
1759 statepos = atoi(val);
1760 } else if (!strcmp(key, "MOVE")) {
1762 states[gotstates].movetype = MOVE;
1763 states[gotstates].movestr = val;
1765 } else if (!strcmp(key, "SOLVE")) {
1767 states[gotstates].movetype = SOLVE;
1768 states[gotstates].movestr = val;
1770 } else if (!strcmp(key, "RESTART")) {
1772 states[gotstates].movetype = RESTART;
1773 states[gotstates].movestr = val;
1782 params = me->ourgame->default_params();
1783 me->ourgame->decode_params(params, parstr);
1784 if (me->ourgame->validate_params(params, TRUE)) {
1785 ret = "Long-term parameters in save file are invalid";
1788 cparams = me->ourgame->default_params();
1789 me->ourgame->decode_params(cparams, cparstr);
1790 if (me->ourgame->validate_params(cparams, FALSE)) {
1791 ret = "Short-term parameters in save file are invalid";
1794 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1796 * The seed's no use with this version, but we can perfectly
1797 * well use the rest of the data.
1803 ret = "Game description in save file is missing";
1805 } else if (me->ourgame->validate_desc(params, desc)) {
1806 ret = "Game description in save file is invalid";
1809 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1810 ret = "Game private description in save file is invalid";
1813 if (statepos < 0 || statepos >= nstates) {
1814 ret = "Game position in save file is out of range";
1817 states[0].state = me->ourgame->new_game(me, params,
1818 privdesc ? privdesc : desc);
1819 for (i = 1; i < nstates; i++) {
1820 assert(states[i].movetype != NEWGAME);
1821 switch (states[i].movetype) {
1824 states[i].state = me->ourgame->execute_move(states[i-1].state,
1826 if (states[i].state == NULL) {
1827 ret = "Save file contained an invalid move";
1832 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1833 ret = "Save file contained an invalid restart move";
1836 states[i].state = me->ourgame->new_game(me, params,
1842 ui = me->ourgame->new_ui(states[0].state);
1843 me->ourgame->decode_ui(ui, uistr);
1846 * Now we've run out of possible error conditions, so we're
1847 * ready to start overwriting the real data in the current
1848 * midend. We'll do this by swapping things with the local
1849 * variables, so that the same cleanup code will free the old
1860 me->privdesc = privdesc;
1868 me->aux_info = auxinfo;
1872 me->genmode = GOT_NOTHING;
1874 me->statesize = nstates;
1875 nstates = me->nstates;
1876 me->nstates = me->statesize;
1878 struct midend_state_entry *tmp;
1880 me->states = states;
1883 me->statepos = statepos;
1889 me->params = params;
1892 tmp = me->curparams;
1893 me->curparams = cparams;
1897 me->oldstate = NULL;
1898 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1909 me->elapsed = elapsed;
1910 me->pressed_mouse_button = 0;
1912 midend_set_timer(me);
1915 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1917 me->ourgame->new_drawstate(me->drawing,
1918 me->states[me->statepos-1].state);
1919 midend_size_new_drawstate(me);
1921 ret = NULL; /* success! */
1933 me->ourgame->free_params(params);
1935 me->ourgame->free_params(cparams);
1937 me->ourgame->free_ui(ui);
1941 for (i = 0; i < nstates; i++) {
1942 if (states[i].state)
1943 me->ourgame->free_game(states[i].state);
1944 sfree(states[i].movestr);
1952 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
1954 game_state *soln = NULL;
1956 if (me->statepos < 1)
1957 return "No game set up to print";/* _shouldn't_ happen! */
1960 char *msg, *movestr;
1962 if (!me->ourgame->can_solve)
1963 return "This game does not support the Solve operation";
1965 msg = "Solve operation failed";/* game _should_ overwrite on error */
1966 movestr = me->ourgame->solve(me->states[0].state,
1967 me->states[me->statepos-1].state,
1968 me->aux_info, &msg);
1971 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
1980 * This call passes over ownership of the two game_states and
1981 * the game_params. Hence we duplicate the ones we want to
1982 * keep, and we don't have to bother freeing soln if it was
1985 document_add_puzzle(doc, me->ourgame,
1986 me->ourgame->dup_params(me->curparams),
1987 me->ourgame->dup_game(me->states[0].state), soln);