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 midend *midend_new(frontend *fe, const game *ourgame,
98 const drawing_api *drapi, void *drhandle)
100 midend *me = snew(midend);
104 get_random_seed(&randseed, &randseedsize);
107 me->ourgame = ourgame;
108 me->random = random_new(randseed, randseedsize);
109 me->nstates = me->statesize = me->statepos = 0;
111 me->params = ourgame->default_params();
112 me->game_id_change_notify_function = NULL;
113 me->game_id_change_notify_ctx = NULL;
116 * Allow environment-based changing of the default settings by
117 * defining a variable along the lines of `NET_DEFAULT=25x25w'
118 * in which the value is an encoded parameter string.
123 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
124 for (j = k = 0; buf[j]; j++)
125 if (!isspace((unsigned char)buf[j]))
126 buf[k++] = toupper((unsigned char)buf[j]);
128 if ((e = getenv(buf)) != NULL)
129 me->ourgame->decode_params(me->params, e);
131 me->curparams = NULL;
132 me->desc = me->privdesc = NULL;
135 me->genmode = GOT_NOTHING;
136 me->drawstate = NULL;
139 me->preset_names = NULL;
140 me->preset_encodings = NULL;
141 me->npresets = me->presetsize = 0;
142 me->anim_time = me->anim_pos = 0.0F;
143 me->flash_time = me->flash_pos = 0.0F;
146 me->pressed_mouse_button = 0;
147 me->laststatus = NULL;
150 me->tilesize = me->winwidth = me->winheight = 0;
152 me->drawing = drawing_new(drapi, me, drhandle);
156 me->preferred_tilesize = ourgame->preferred_tilesize;
159 * Allow an environment-based override for the default tile
160 * size by defining a variable along the lines of
167 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
168 for (j = k = 0; buf[j]; j++)
169 if (!isspace((unsigned char)buf[j]))
170 buf[k++] = toupper((unsigned char)buf[j]);
172 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
173 me->preferred_tilesize = ts;
181 const game *midend_which_game(midend *me)
186 static void midend_purge_states(midend *me)
188 while (me->nstates > me->statepos) {
189 me->ourgame->free_game(me->states[--me->nstates].state);
190 if (me->states[me->nstates].movestr)
191 sfree(me->states[me->nstates].movestr);
195 static void midend_free_game(midend *me)
197 while (me->nstates > 0) {
199 me->ourgame->free_game(me->states[me->nstates].state);
200 sfree(me->states[me->nstates].movestr);
204 me->ourgame->free_drawstate(me->drawing, me->drawstate);
207 void midend_free(midend *me)
211 midend_free_game(me);
214 drawing_free(me->drawing);
215 random_free(me->random);
221 me->ourgame->free_params(me->params);
223 for (i = 0; i < me->npresets; i++) {
224 sfree(me->presets[i]);
225 sfree(me->preset_names[i]);
226 sfree(me->preset_encodings[i]);
229 sfree(me->preset_names);
230 sfree(me->preset_encodings);
233 me->ourgame->free_ui(me->ui);
235 me->ourgame->free_params(me->curparams);
236 sfree(me->laststatus);
240 static void midend_size_new_drawstate(midend *me)
243 * Don't even bother, if we haven't worked out our tile size
246 if (me->tilesize > 0) {
247 me->ourgame->compute_size(me->params, me->tilesize,
248 &me->winwidth, &me->winheight);
249 me->ourgame->set_size(me->drawing, me->drawstate,
250 me->params, me->tilesize);
254 void midend_size(midend *me, int *x, int *y, int user_size)
260 * We can't set the size on the same drawstate twice. So if
261 * we've already sized one drawstate, we must throw it away and
264 if (me->drawstate && me->tilesize > 0) {
265 me->ourgame->free_drawstate(me->drawing, me->drawstate);
266 me->drawstate = me->ourgame->new_drawstate(me->drawing,
267 me->states[0].state);
271 * Find the tile size that best fits within the given space. If
272 * `user_size' is TRUE, we must actually find the _largest_ such
273 * tile size, in order to get as close to the user's explicit
274 * request as possible; otherwise, we bound above at the game's
275 * preferred tile size, so that the game gets what it wants
276 * provided that this doesn't break the constraint from the
277 * front-end (which is likely to be a screen size or similar).
283 me->ourgame->compute_size(me->params, max, &rx, &ry);
284 } while (rx <= *x && ry <= *y);
286 max = me->preferred_tilesize + 1;
290 * Now binary-search between min and max. We're looking for a
291 * boundary rather than a value: the point at which tile sizes
292 * stop fitting within the given dimensions. Thus, we stop when
293 * max and min differ by exactly 1.
295 while (max - min > 1) {
296 int mid = (max + min) / 2;
297 me->ourgame->compute_size(me->params, mid, &rx, &ry);
298 if (rx <= *x && ry <= *y)
305 * Now `min' is a valid size, and `max' isn't. So use `min'.
310 /* If the user requested a change in size, make it permanent. */
311 me->preferred_tilesize = me->tilesize;
312 midend_size_new_drawstate(me);
317 int midend_tilesize(midend *me) { return me->tilesize; }
319 void midend_set_params(midend *me, game_params *params)
321 me->ourgame->free_params(me->params);
322 me->params = me->ourgame->dup_params(params);
325 game_params *midend_get_params(midend *me)
327 return me->ourgame->dup_params(me->params);
330 static void midend_set_timer(midend *me)
332 me->timing = (me->ourgame->is_timed &&
333 me->ourgame->timing_state(me->states[me->statepos-1].state,
335 if (me->timing || me->flash_time || me->anim_time)
336 activate_timer(me->frontend);
338 deactivate_timer(me->frontend);
341 void midend_force_redraw(midend *me)
344 me->ourgame->free_drawstate(me->drawing, me->drawstate);
345 me->drawstate = me->ourgame->new_drawstate(me->drawing,
346 me->states[0].state);
347 midend_size_new_drawstate(me);
351 void midend_new_game(midend *me)
353 midend_free_game(me);
355 assert(me->nstates == 0);
357 if (me->genmode == GOT_DESC) {
358 me->genmode = GOT_NOTHING;
362 if (me->genmode == GOT_SEED) {
363 me->genmode = GOT_NOTHING;
366 * Generate a new random seed. 15 digits comes to about
367 * 48 bits, which should be more than enough.
369 * I'll avoid putting a leading zero on the number,
370 * just in case it confuses anybody who thinks it's
371 * processed as an integer rather than a string.
376 newseed[0] = '1' + (char)random_upto(me->random, 9);
377 for (i = 1; i < 15; i++)
378 newseed[i] = '0' + (char)random_upto(me->random, 10);
380 me->seedstr = dupstr(newseed);
383 me->ourgame->free_params(me->curparams);
384 me->curparams = me->ourgame->dup_params(me->params);
392 rs = random_new(me->seedstr, strlen(me->seedstr));
394 * If this midend has been instantiated without providing a
395 * drawing API, it is non-interactive. This means that it's
396 * being used for bulk game generation, and hence we should
397 * pass the non-interactive flag to new_desc.
399 me->desc = me->ourgame->new_desc(me->curparams, rs,
400 &me->aux_info, (me->drawing != NULL));
408 * It might seem a bit odd that we're using me->params to
409 * create the initial game state, rather than me->curparams
410 * which is better tailored to this specific game and which we
413 * It's supposed to be an invariant in the midend that
414 * me->params and me->curparams differ in no aspect that is
415 * important after generation (i.e. after new_desc()). By
416 * deliberately passing the _less_ specific of these two
417 * parameter sets, we provoke play-time misbehaviour in the
418 * case where a game has failed to encode a play-time parameter
419 * in the non-full version of encode_params().
421 me->states[me->nstates].state =
422 me->ourgame->new_game(me, me->params, me->desc);
425 * As part of our commitment to self-testing, test the aux
426 * string to make sure nothing ghastly went wrong.
428 if (me->ourgame->can_solve && me->aux_info) {
433 movestr = me->ourgame->solve(me->states[0].state,
436 assert(movestr && !msg);
437 s = me->ourgame->execute_move(me->states[0].state, movestr);
439 me->ourgame->free_game(s);
444 * Soak test, enabled by setting <gamename>_TESTSOLVE in the
445 * environment. This causes an immediate attempt to re-solve the
446 * game without benefit of aux_info. The effect is that (at least
447 * on Unix) you can run 'FOO_TESTSOLVE=1 foo --generate 10000
448 * <params>#12345' and it will generate a lot of game ids and
449 * instantly pass each one back to the solver.
451 * (It's worth putting in an explicit seed in any such test, so
452 * you can repeat it to diagnose a problem if one comes up!)
457 static int doing_test_solve = -1;
458 if (doing_test_solve < 0) {
459 sprintf(buf, "%s_TESTSOLVE", me->ourgame->name);
460 for (j = k = 0; buf[j]; j++)
461 if (!isspace((unsigned char)buf[j]))
462 buf[k++] = toupper((unsigned char)buf[j]);
466 * Since this is used for correctness testing, it's
467 * helpful to have a visual acknowledgment that the
468 * user hasn't mistyped the environment variable name.
470 fprintf(stderr, "Running solver soak tests\n");
471 doing_test_solve = TRUE;
473 doing_test_solve = FALSE;
476 if (doing_test_solve) {
481 movestr = me->ourgame->solve(me->states[0].state,
484 assert(movestr && !msg);
485 s = me->ourgame->execute_move(me->states[0].state, movestr);
487 me->ourgame->free_game(s);
492 me->states[me->nstates].movestr = NULL;
493 me->states[me->nstates].movetype = NEWGAME;
496 me->drawstate = me->ourgame->new_drawstate(me->drawing,
497 me->states[0].state);
498 midend_size_new_drawstate(me);
501 me->ourgame->free_ui(me->ui);
502 me->ui = me->ourgame->new_ui(me->states[0].state);
503 midend_set_timer(me);
504 me->pressed_mouse_button = 0;
506 if (me->game_id_change_notify_function)
507 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
510 int midend_can_undo(midend *me)
512 return (me->statepos > 1);
515 int midend_can_redo(midend *me)
517 return (me->statepos < me->nstates);
520 static int midend_undo(midend *me)
522 if (me->statepos > 1) {
524 me->ourgame->changed_state(me->ui,
525 me->states[me->statepos-1].state,
526 me->states[me->statepos-2].state);
534 static int midend_redo(midend *me)
536 if (me->statepos < me->nstates) {
538 me->ourgame->changed_state(me->ui,
539 me->states[me->statepos-1].state,
540 me->states[me->statepos].state);
548 static void midend_finish_move(midend *me)
553 * We do not flash if the later of the two states is special.
554 * This covers both forward Solve moves and backward (undone)
557 if ((me->oldstate || me->statepos > 1) &&
558 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
559 (me->dir < 0 && me->statepos < me->nstates &&
560 !special(me->states[me->statepos].movetype)))) {
561 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
562 me->states[me->statepos-2].state,
563 me->states[me->statepos-1].state,
564 me->oldstate ? me->dir : +1,
567 me->flash_pos = 0.0F;
568 me->flash_time = flashtime;
573 me->ourgame->free_game(me->oldstate);
575 me->anim_pos = me->anim_time = 0;
578 midend_set_timer(me);
581 void midend_stop_anim(midend *me)
583 if (me->oldstate || me->anim_time != 0) {
584 midend_finish_move(me);
589 void midend_restart_game(midend *me)
593 midend_stop_anim(me);
595 assert(me->statepos >= 1);
596 if (me->statepos == 1)
597 return; /* no point doing anything at all! */
600 * During restart, we reconstruct the game from the (public)
601 * game description rather than from states[0], because that
602 * way Mines gets slightly more sensible behaviour (restart
603 * goes to _after_ the first click so you don't have to
604 * remember where you clicked).
606 s = me->ourgame->new_game(me, me->params, me->desc);
609 * Now enter the restarted state as the next move.
611 midend_stop_anim(me);
612 midend_purge_states(me);
614 me->states[me->nstates].state = s;
615 me->states[me->nstates].movestr = dupstr(me->desc);
616 me->states[me->nstates].movetype = RESTART;
617 me->statepos = ++me->nstates;
619 me->ourgame->changed_state(me->ui,
620 me->states[me->statepos-2].state,
621 me->states[me->statepos-1].state);
623 midend_finish_move(me);
625 midend_set_timer(me);
628 static int midend_really_process_key(midend *me, int x, int y, int button)
630 game_state *oldstate =
631 me->ourgame->dup_game(me->states[me->statepos - 1].state);
632 int type = MOVE, gottype = FALSE, ret = 1;
638 me->ourgame->interpret_move(me->states[me->statepos-1].state,
639 me->ui, me->drawstate, x, y, button);
642 if (button == 'n' || button == 'N' || button == '\x0E') {
643 midend_stop_anim(me);
646 goto done; /* never animate */
647 } else if (button == 'u' || button == 'u' ||
648 button == '\x1A' || button == '\x1F') {
649 midend_stop_anim(me);
650 type = me->states[me->statepos-1].movetype;
652 if (!midend_undo(me))
654 } else if (button == 'r' || button == 'R' ||
655 button == '\x12' || button == '\x19') {
656 midend_stop_anim(me);
657 if (!midend_redo(me))
659 } else if (button == '\x13' && me->ourgame->can_solve) {
660 if (midend_solve(me))
662 } else if (button == 'q' || button == 'Q' || button == '\x11') {
669 s = me->states[me->statepos-1].state;
671 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
676 if (s == me->states[me->statepos-1].state) {
678 * make_move() is allowed to return its input state to
679 * indicate that although no move has been made, the UI
680 * state has been updated and a redraw is called for.
683 midend_set_timer(me);
686 midend_stop_anim(me);
687 midend_purge_states(me);
689 assert(movestr != NULL);
690 me->states[me->nstates].state = s;
691 me->states[me->nstates].movestr = movestr;
692 me->states[me->nstates].movetype = MOVE;
693 me->statepos = ++me->nstates;
696 me->ourgame->changed_state(me->ui,
697 me->states[me->statepos-2].state,
698 me->states[me->statepos-1].state);
705 type = me->states[me->statepos-1].movetype;
708 * See if this move requires an animation.
710 if (special(type) && !(type == SOLVE &&
711 (me->ourgame->flags & SOLVE_ANIMATES))) {
714 anim_time = me->ourgame->anim_length(oldstate,
715 me->states[me->statepos-1].state,
719 me->oldstate = oldstate; oldstate = NULL;
721 me->anim_time = anim_time;
724 midend_finish_move(me);
730 midend_set_timer(me);
733 if (oldstate) me->ourgame->free_game(oldstate);
737 int midend_process_key(midend *me, int x, int y, int button)
742 * Harmonise mouse drag and release messages.
744 * Some front ends might accidentally switch from sending, say,
745 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
746 * drag. (This can happen on the Mac, for example, since
747 * RIGHT_DRAG is usually done using Command+drag, and if the
748 * user accidentally releases Command half way through the drag
749 * then there will be trouble.)
751 * It would be an O(number of front ends) annoyance to fix this
752 * in the front ends, but an O(number of back ends) annoyance
753 * to have each game capable of dealing with it. Therefore, we
754 * fix it _here_ in the common midend code so that it only has
757 * The possible ways in which things can go screwy in the front
760 * - in a system containing multiple physical buttons button
761 * presses can inadvertently overlap. We can see ABab (caps
762 * meaning button-down and lowercase meaning button-up) when
763 * the user had semantically intended AaBb.
765 * - in a system where one button is simulated by means of a
766 * modifier key and another button, buttons can mutate
767 * between press and release (possibly during drag). So we
768 * can see Ab instead of Aa.
770 * Definite requirements are:
772 * - button _presses_ must never be invented or destroyed. If
773 * the user presses two buttons in succession, the button
774 * presses must be transferred to the backend unchanged. So
775 * if we see AaBb , that's fine; if we see ABab (the button
776 * presses inadvertently overlapped) we must somehow
777 * `correct' it to AaBb.
779 * - every mouse action must end up looking like a press, zero
780 * or more drags, then a release. This allows back ends to
781 * make the _assumption_ that incoming mouse data will be
782 * sane in this regard, and not worry about the details.
784 * So my policy will be:
786 * - treat any button-up as a button-up for the currently
787 * pressed button, or ignore it if there is no currently
790 * - treat any drag as a drag for the currently pressed
791 * button, or ignore it if there is no currently pressed
794 * - if we see a button-down while another button is currently
795 * pressed, invent a button-up for the first one and then
796 * pass the button-down through as before.
798 * 2005-05-31: An addendum to the above. Some games might want
799 * a `priority order' among buttons, such that if one button is
800 * pressed while another is down then a fixed one of the
801 * buttons takes priority no matter what order they're pressed
802 * in. Mines, in particular, wants to treat a left+right click
803 * like a left click for the benefit of users of other
804 * implementations. So the last of the above points is modified
805 * in the presence of an (optional) button priority order.
807 * A further addition: we translate certain keyboard presses to
808 * cursor key 'select' buttons, so that a) frontends don't have
809 * to translate these themselves (like they do for CURSOR_UP etc),
810 * and b) individual games don't have to hard-code button presses
811 * of '\n' etc for keyboard-based cursors. The choice of buttons
812 * here could eventually be controlled by a runtime configuration
815 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
816 if (me->pressed_mouse_button) {
817 if (IS_MOUSE_DRAG(button)) {
818 button = me->pressed_mouse_button +
819 (LEFT_DRAG - LEFT_BUTTON);
821 button = me->pressed_mouse_button +
822 (LEFT_RELEASE - LEFT_BUTTON);
825 return ret; /* ignore it */
826 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
828 * If the new button has lower priority than the old one,
829 * don't bother doing this.
831 if (me->ourgame->flags &
832 BUTTON_BEATS(me->pressed_mouse_button, button))
833 return ret; /* just ignore it */
836 * Fabricate a button-up for the previously pressed button.
838 ret = ret && midend_really_process_key
839 (me, x, y, (me->pressed_mouse_button +
840 (LEFT_RELEASE - LEFT_BUTTON)));
844 * Translate keyboard presses to cursor selection.
846 if (button == '\n' || button == '\r')
847 button = CURSOR_SELECT;
849 button = CURSOR_SELECT2;
852 * Normalise both backspace characters (8 and 127) to \b. Easier
853 * to do this once, here, than to require all front ends to
854 * carefully generate the same one - now each front end can
855 * generate whichever is easiest.
857 if (button == '\177')
861 * Now send on the event we originally received.
863 ret = ret && midend_really_process_key(me, x, y, button);
866 * And update the currently pressed button.
868 if (IS_MOUSE_RELEASE(button))
869 me->pressed_mouse_button = 0;
870 else if (IS_MOUSE_DOWN(button))
871 me->pressed_mouse_button = button;
876 void midend_redraw(midend *me)
880 if (me->statepos > 0 && me->drawstate) {
881 start_draw(me->drawing);
882 if (me->oldstate && me->anim_time > 0 &&
883 me->anim_pos < me->anim_time) {
884 assert(me->dir != 0);
885 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
886 me->states[me->statepos-1].state, me->dir,
887 me->ui, me->anim_pos, me->flash_pos);
889 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
890 me->states[me->statepos-1].state, +1 /*shrug*/,
891 me->ui, 0.0, me->flash_pos);
893 end_draw(me->drawing);
898 * Nasty hacky function used to implement the --redo option in
899 * gtk.c. Only used for generating the puzzles' icons.
901 void midend_freeze_timer(midend *me, float tprop)
903 me->anim_pos = me->anim_time * tprop;
905 deactivate_timer(me->frontend);
908 void midend_timer(midend *me, float tplus)
910 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
912 me->anim_pos += tplus;
913 if (me->anim_pos >= me->anim_time ||
914 me->anim_time == 0 || !me->oldstate) {
915 if (me->anim_time > 0)
916 midend_finish_move(me);
919 me->flash_pos += tplus;
920 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
921 me->flash_pos = me->flash_time = 0;
928 float oldelapsed = me->elapsed;
929 me->elapsed += tplus;
930 if ((int)oldelapsed != (int)me->elapsed)
931 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
934 midend_set_timer(me);
937 float *midend_colours(midend *me, int *ncolours)
941 ret = me->ourgame->colours(me->frontend, ncolours);
947 * Allow environment-based overrides for the standard
948 * colours by defining variables along the lines of
949 * `NET_COLOUR_4=6000c0'.
952 for (i = 0; i < *ncolours; i++) {
954 unsigned int r, g, b;
957 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
958 for (j = k = 0; buf[j]; j++)
959 if (!isspace((unsigned char)buf[j]))
960 buf[k++] = toupper((unsigned char)buf[j]);
962 if ((e = getenv(buf)) != NULL &&
963 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
964 ret[i*3 + 0] = r / 255.0F;
965 ret[i*3 + 1] = g / 255.0F;
966 ret[i*3 + 2] = b / 255.0F;
974 int midend_num_presets(midend *me)
980 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
981 if (me->presetsize <= me->npresets) {
982 me->presetsize = me->npresets + 10;
983 me->presets = sresize(me->presets, me->presetsize,
985 me->preset_names = sresize(me->preset_names, me->presetsize,
987 me->preset_encodings = sresize(me->preset_encodings,
988 me->presetsize, char *);
991 me->presets[me->npresets] = preset;
992 me->preset_names[me->npresets] = name;
993 me->preset_encodings[me->npresets] =
994 me->ourgame->encode_params(preset, TRUE);;
1001 * Allow environment-based extensions to the preset list by
1002 * defining a variable along the lines of `SOLO_PRESETS=2x3
1003 * Advanced:2x3da'. Colon-separated list of items,
1004 * alternating between textual titles in the menu and
1005 * encoded parameter strings.
1007 char buf[80], *e, *p;
1010 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1011 for (j = k = 0; buf[j]; j++)
1012 if (!isspace((unsigned char)buf[j]))
1013 buf[k++] = toupper((unsigned char)buf[j]);
1016 if ((e = getenv(buf)) != NULL) {
1021 game_params *preset;
1024 while (*p && *p != ':') p++;
1025 if (*p) *p++ = '\0';
1027 while (*p && *p != ':') p++;
1028 if (*p) *p++ = '\0';
1030 preset = me->ourgame->default_params();
1031 me->ourgame->decode_params(preset, val);
1033 if (me->ourgame->validate_params(preset, TRUE)) {
1034 /* Drop this one from the list. */
1035 me->ourgame->free_params(preset);
1039 if (me->presetsize <= me->npresets) {
1040 me->presetsize = me->npresets + 10;
1041 me->presets = sresize(me->presets, me->presetsize,
1043 me->preset_names = sresize(me->preset_names,
1044 me->presetsize, char *);
1045 me->preset_encodings = sresize(me->preset_encodings,
1046 me->presetsize, char *);
1049 me->presets[me->npresets] = preset;
1050 me->preset_names[me->npresets] = dupstr(name);
1051 me->preset_encodings[me->npresets] =
1052 me->ourgame->encode_params(preset, TRUE);
1059 return me->npresets;
1062 void midend_fetch_preset(midend *me, int n,
1063 char **name, game_params **params)
1065 assert(n >= 0 && n < me->npresets);
1066 *name = me->preset_names[n];
1067 *params = me->presets[n];
1070 int midend_which_preset(midend *me)
1072 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1076 for (i = 0; i < me->npresets; i++)
1077 if (!strcmp(encoding, me->preset_encodings[i])) {
1086 int midend_wants_statusbar(midend *me)
1088 return me->ourgame->wants_statusbar;
1091 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1093 me->game_id_change_notify_function = notify;
1094 me->game_id_change_notify_ctx = ctx;
1097 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1100 sfree(me->privdesc);
1101 me->desc = dupstr(desc);
1102 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1103 if (me->game_id_change_notify_function)
1104 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1107 config_item *midend_get_config(midend *me, int which, char **wintitle)
1109 char *titlebuf, *parstr, *rest;
1114 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1118 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1119 *wintitle = titlebuf;
1120 return me->ourgame->configure(me->params);
1123 if (!me->curparams) {
1127 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1128 which == CFG_SEED ? "random" : "game");
1129 *wintitle = titlebuf;
1131 ret = snewn(2, config_item);
1133 ret[0].type = C_STRING;
1134 if (which == CFG_SEED)
1135 ret[0].name = "Game random seed";
1137 ret[0].name = "Game ID";
1140 * For CFG_DESC the text going in here will be a string
1141 * encoding of the restricted parameters, plus a colon,
1142 * plus the game description. For CFG_SEED it will be the
1143 * full parameters, plus a hash, plus the random seed data.
1144 * Either of these is a valid full game ID (although only
1145 * the former is likely to persist across many code
1148 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1150 if (which == CFG_DESC) {
1151 rest = me->desc ? me->desc : "";
1154 rest = me->seedstr ? me->seedstr : "";
1157 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1158 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1161 ret[1].type = C_END;
1162 ret[1].name = ret[1].sval = NULL;
1168 assert(!"We shouldn't be here");
1172 static char *midend_game_id_int(midend *me, char *id, int defmode)
1174 char *error, *par, *desc, *seed;
1175 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1178 seed = strchr(id, '#');
1179 desc = strchr(id, ':');
1181 if (desc && (!seed || desc < seed)) {
1183 * We have a colon separating parameters from game
1184 * description. So `par' now points to the parameters
1185 * string, and `desc' to the description string.
1190 } else if (seed && (!desc || seed < desc)) {
1192 * We have a hash separating parameters from random seed.
1193 * So `par' now points to the parameters string, and `seed'
1194 * to the seed string.
1201 * We only have one string. Depending on `defmode', we take
1202 * it to be either parameters, seed or description.
1204 if (defmode == DEF_SEED) {
1207 } else if (defmode == DEF_DESC) {
1217 * We must be reasonably careful here not to modify anything in
1218 * `me' until we have finished validating things. This function
1219 * must either return an error and do nothing to the midend, or
1220 * return success and do everything; nothing in between is
1223 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1226 newcurparams = me->ourgame->dup_params(me->params);
1227 me->ourgame->decode_params(newcurparams, par);
1228 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1230 me->ourgame->free_params(newcurparams);
1233 oldparams1 = me->curparams;
1236 * Now filter only the persistent parts of this state into
1237 * the long-term params structure, unless we've _only_
1238 * received a params string in which case the whole lot is
1241 oldparams2 = me->params;
1245 newparams = me->ourgame->dup_params(me->params);
1247 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1248 me->ourgame->decode_params(newparams, tmpstr);
1252 newparams = me->ourgame->dup_params(newcurparams);
1256 newcurparams = me->curparams;
1257 newparams = me->params;
1258 free_params = FALSE;
1262 error = me->ourgame->validate_desc(newparams, desc);
1266 me->ourgame->free_params(newcurparams);
1268 me->ourgame->free_params(newparams);
1275 * Now we've got past all possible error points. Update the
1278 me->params = newparams;
1279 me->curparams = newcurparams;
1281 me->ourgame->free_params(oldparams1);
1283 me->ourgame->free_params(oldparams2);
1286 sfree(me->privdesc);
1287 me->desc = me->privdesc = NULL;
1292 me->desc = dupstr(desc);
1293 me->genmode = GOT_DESC;
1294 sfree(me->aux_info);
1295 me->aux_info = NULL;
1299 me->seedstr = dupstr(seed);
1300 me->genmode = GOT_SEED;
1306 char *midend_game_id(midend *me, char *id)
1308 return midend_game_id_int(me, id, DEF_PARAMS);
1311 char *midend_get_game_id(midend *me)
1315 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1318 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1319 sprintf(ret, "%s:%s", parstr, me->desc);
1324 char *midend_get_random_seed(midend *me)
1331 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1333 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1334 sprintf(ret, "%s#%s", parstr, me->seedstr);
1339 char *midend_set_config(midend *me, int which, config_item *cfg)
1342 game_params *params;
1346 params = me->ourgame->custom_params(cfg);
1347 error = me->ourgame->validate_params(params, TRUE);
1350 me->ourgame->free_params(params);
1354 me->ourgame->free_params(me->params);
1355 me->params = params;
1360 error = midend_game_id_int(me, cfg[0].sval,
1361 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1370 int midend_can_format_as_text_now(midend *me)
1372 if (me->ourgame->can_format_as_text_ever)
1373 return me->ourgame->can_format_as_text_now(me->params);
1378 char *midend_text_format(midend *me)
1380 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1381 me->ourgame->can_format_as_text_now(me->params))
1382 return me->ourgame->text_format(me->states[me->statepos-1].state);
1387 char *midend_solve(midend *me)
1390 char *msg, *movestr;
1392 if (!me->ourgame->can_solve)
1393 return "This game does not support the Solve operation";
1395 if (me->statepos < 1)
1396 return "No game set up to solve"; /* _shouldn't_ happen! */
1399 movestr = me->ourgame->solve(me->states[0].state,
1400 me->states[me->statepos-1].state,
1401 me->aux_info, &msg);
1404 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1407 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1411 * Now enter the solved state as the next move.
1413 midend_stop_anim(me);
1414 midend_purge_states(me);
1416 me->states[me->nstates].state = s;
1417 me->states[me->nstates].movestr = movestr;
1418 me->states[me->nstates].movetype = SOLVE;
1419 me->statepos = ++me->nstates;
1421 me->ourgame->changed_state(me->ui,
1422 me->states[me->statepos-2].state,
1423 me->states[me->statepos-1].state);
1425 if (me->ourgame->flags & SOLVE_ANIMATES) {
1426 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1428 me->ourgame->anim_length(me->states[me->statepos-2].state,
1429 me->states[me->statepos-1].state,
1433 me->anim_time = 0.0;
1434 midend_finish_move(me);
1438 midend_set_timer(me);
1442 int midend_status(midend *me)
1445 * We should probably never be called when the state stack has no
1446 * states on it at all - ideally, midends should never be left in
1447 * that state for long enough to get put down and forgotten about.
1448 * But if we are, I think we return _true_ - pedantically speaking
1449 * a midend in that state is 'vacuously solved', and more
1450 * practically, a user whose midend has been left in that state
1451 * probably _does_ want the 'new game' option to be prominent.
1453 if (me->statepos == 0)
1456 return me->ourgame->status(me->states[me->statepos-1].state);
1459 char *midend_rewrite_statusbar(midend *me, char *text)
1462 * An important special case is that we are occasionally called
1463 * with our own laststatus, to update the timer.
1465 if (me->laststatus != text) {
1466 sfree(me->laststatus);
1467 me->laststatus = dupstr(text);
1470 if (me->ourgame->is_timed) {
1471 char timebuf[100], *ret;
1474 sec = (int)me->elapsed;
1477 sprintf(timebuf, "[%d:%02d] ", min, sec);
1479 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1480 strcpy(ret, timebuf);
1485 return dupstr(text);
1489 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1490 #define SERIALISE_VERSION "1"
1492 void midend_serialise(midend *me,
1493 void (*write)(void *ctx, void *buf, int len),
1499 * Each line of the save file contains three components. First
1500 * exactly 8 characters of header word indicating what type of
1501 * data is contained on the line; then a colon followed by a
1502 * decimal integer giving the length of the main string on the
1503 * line; then a colon followed by the string itself (exactly as
1504 * many bytes as previously specified, no matter what they
1505 * contain). Then a newline (of reasonably flexible form).
1507 #define wr(h,s) do { \
1510 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1511 write(wctx, hbuf, strlen(hbuf)); \
1512 write(wctx, str, strlen(str)); \
1513 write(wctx, "\n", 1); \
1517 * Magic string identifying the file, and version number of the
1520 wr("SAVEFILE", SERIALISE_MAGIC);
1521 wr("VERSION", SERIALISE_VERSION);
1524 * The game name. (Copied locally to avoid const annoyance.)
1527 char *s = dupstr(me->ourgame->name);
1533 * The current long-term parameters structure, in full.
1536 char *s = me->ourgame->encode_params(me->params, TRUE);
1542 * The current short-term parameters structure, in full.
1544 if (me->curparams) {
1545 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1551 * The current game description, the privdesc, and the random seed.
1554 wr("SEED", me->seedstr);
1556 wr("DESC", me->desc);
1558 wr("PRIVDESC", me->privdesc);
1561 * The game's aux_info. We obfuscate this to prevent spoilers
1562 * (people are likely to run `head' or similar on a saved game
1563 * file simply to find out what it is, and don't necessarily
1564 * want to be told the answer to the puzzle!)
1571 len = strlen(me->aux_info);
1572 s1 = snewn(len, unsigned char);
1573 memcpy(s1, me->aux_info, len);
1574 obfuscate_bitmap(s1, len*8, FALSE);
1575 s2 = bin2hex(s1, len);
1584 * Any required serialisation of the game_ui.
1587 char *s = me->ourgame->encode_ui(me->ui);
1595 * The game time, if it's a timed game.
1597 if (me->ourgame->is_timed) {
1599 sprintf(buf, "%g", me->elapsed);
1604 * The length of, and position in, the states list.
1608 sprintf(buf, "%d", me->nstates);
1610 sprintf(buf, "%d", me->statepos);
1611 wr("STATEPOS", buf);
1615 * For each state after the initial one (which we know is
1616 * constructed from either privdesc or desc), enough
1617 * information for execute_move() to reconstruct it from the
1620 for (i = 1; i < me->nstates; i++) {
1621 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1622 switch (me->states[i].movetype) {
1624 wr("MOVE", me->states[i].movestr);
1627 wr("SOLVE", me->states[i].movestr);
1630 wr("RESTART", me->states[i].movestr);
1639 * This function returns NULL on success, or an error message.
1641 char *midend_deserialise(midend *me,
1642 int (*read)(void *ctx, void *buf, int len),
1645 int nstates = 0, statepos = -1, gotstates = 0;
1646 int started = FALSE;
1650 /* Initially all errors give the same report */
1651 char *ret = "Data does not appear to be a saved game file";
1654 * We construct all the new state in local variables while we
1655 * check its sanity. Only once we have finished reading the
1656 * serialised data and detected no errors at all do we start
1657 * modifying stuff in the midend passed in.
1659 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1660 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1661 float elapsed = 0.0F;
1662 game_params *params = NULL, *cparams = NULL;
1664 struct midend_state_entry *states = NULL;
1667 * Loop round and round reading one key/value pair at a time
1668 * from the serialised stream, until we have enough game states
1671 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1676 if (!read(rctx, key, 1)) {
1677 /* unexpected EOF */
1680 } while (key[0] == '\r' || key[0] == '\n');
1682 if (!read(rctx, key+1, 8)) {
1683 /* unexpected EOF */
1687 if (key[8] != ':') {
1689 ret = "Data was incorrectly formatted for a saved game file";
1692 len = strcspn(key, ": ");
1698 if (!read(rctx, &c, 1)) {
1699 /* unexpected EOF */
1705 } else if (c >= '0' && c <= '9') {
1706 len = (len * 10) + (c - '0');
1709 ret = "Data was incorrectly formatted for a"
1715 val = snewn(len+1, char);
1716 if (!read(rctx, val, len)) {
1723 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1724 /* ret already has the right message in it */
1727 /* Now most errors are this one, unless otherwise specified */
1728 ret = "Saved data ended unexpectedly";
1731 if (!strcmp(key, "VERSION")) {
1732 if (strcmp(val, SERIALISE_VERSION)) {
1733 ret = "Cannot handle this version of the saved game"
1737 } else if (!strcmp(key, "GAME")) {
1738 if (strcmp(val, me->ourgame->name)) {
1739 ret = "Save file is from a different game";
1742 } else if (!strcmp(key, "PARAMS")) {
1746 } else if (!strcmp(key, "CPARAMS")) {
1750 } else if (!strcmp(key, "SEED")) {
1754 } else if (!strcmp(key, "DESC")) {
1758 } else if (!strcmp(key, "PRIVDESC")) {
1762 } else if (!strcmp(key, "AUXINFO")) {
1764 int len = strlen(val) / 2; /* length in bytes */
1765 tmp = hex2bin(val, len);
1766 obfuscate_bitmap(tmp, len*8, TRUE);
1769 auxinfo = snewn(len + 1, char);
1770 memcpy(auxinfo, tmp, len);
1771 auxinfo[len] = '\0';
1773 } else if (!strcmp(key, "UI")) {
1777 } else if (!strcmp(key, "TIME")) {
1778 elapsed = (float)atof(val);
1779 } else if (!strcmp(key, "NSTATES")) {
1780 nstates = atoi(val);
1782 ret = "Number of states in save file was negative";
1786 ret = "Two state counts provided in save file";
1789 states = snewn(nstates, struct midend_state_entry);
1790 for (i = 0; i < nstates; i++) {
1791 states[i].state = NULL;
1792 states[i].movestr = NULL;
1793 states[i].movetype = NEWGAME;
1795 } else if (!strcmp(key, "STATEPOS")) {
1796 statepos = atoi(val);
1797 } else if (!strcmp(key, "MOVE")) {
1799 states[gotstates].movetype = MOVE;
1800 states[gotstates].movestr = val;
1802 } else if (!strcmp(key, "SOLVE")) {
1804 states[gotstates].movetype = SOLVE;
1805 states[gotstates].movestr = val;
1807 } else if (!strcmp(key, "RESTART")) {
1809 states[gotstates].movetype = RESTART;
1810 states[gotstates].movestr = val;
1819 params = me->ourgame->default_params();
1820 me->ourgame->decode_params(params, parstr);
1821 if (me->ourgame->validate_params(params, TRUE)) {
1822 ret = "Long-term parameters in save file are invalid";
1825 cparams = me->ourgame->default_params();
1826 me->ourgame->decode_params(cparams, cparstr);
1827 if (me->ourgame->validate_params(cparams, FALSE)) {
1828 ret = "Short-term parameters in save file are invalid";
1831 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1833 * The seed's no use with this version, but we can perfectly
1834 * well use the rest of the data.
1840 ret = "Game description in save file is missing";
1842 } else if (me->ourgame->validate_desc(params, desc)) {
1843 ret = "Game description in save file is invalid";
1846 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1847 ret = "Game private description in save file is invalid";
1850 if (statepos < 0 || statepos >= nstates) {
1851 ret = "Game position in save file is out of range";
1854 states[0].state = me->ourgame->new_game(me, params,
1855 privdesc ? privdesc : desc);
1856 for (i = 1; i < nstates; i++) {
1857 assert(states[i].movetype != NEWGAME);
1858 switch (states[i].movetype) {
1861 states[i].state = me->ourgame->execute_move(states[i-1].state,
1863 if (states[i].state == NULL) {
1864 ret = "Save file contained an invalid move";
1869 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1870 ret = "Save file contained an invalid restart move";
1873 states[i].state = me->ourgame->new_game(me, params,
1879 ui = me->ourgame->new_ui(states[0].state);
1880 me->ourgame->decode_ui(ui, uistr);
1883 * Now we've run out of possible error conditions, so we're
1884 * ready to start overwriting the real data in the current
1885 * midend. We'll do this by swapping things with the local
1886 * variables, so that the same cleanup code will free the old
1897 me->privdesc = privdesc;
1905 me->aux_info = auxinfo;
1909 me->genmode = GOT_NOTHING;
1911 me->statesize = nstates;
1912 nstates = me->nstates;
1913 me->nstates = me->statesize;
1915 struct midend_state_entry *tmp;
1917 me->states = states;
1920 me->statepos = statepos;
1926 me->params = params;
1929 tmp = me->curparams;
1930 me->curparams = cparams;
1934 me->oldstate = NULL;
1935 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1946 me->elapsed = elapsed;
1947 me->pressed_mouse_button = 0;
1949 midend_set_timer(me);
1952 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1954 me->ourgame->new_drawstate(me->drawing,
1955 me->states[me->statepos-1].state);
1956 midend_size_new_drawstate(me);
1958 ret = NULL; /* success! */
1970 me->ourgame->free_params(params);
1972 me->ourgame->free_params(cparams);
1974 me->ourgame->free_ui(ui);
1978 for (i = 0; i < nstates; i++) {
1979 if (states[i].state)
1980 me->ourgame->free_game(states[i].state);
1981 sfree(states[i].movestr);
1990 * This function examines a saved game file just far enough to
1991 * determine which game type it contains. It returns NULL on success
1992 * and the game name string in 'name' (which will be dynamically
1993 * allocated and should be caller-freed), or an error message on
1996 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
1999 int nstates = 0, statepos = -1, gotstates = 0;
2000 int started = FALSE;
2003 /* Initially all errors give the same report */
2004 char *ret = "Data does not appear to be a saved game file";
2009 * Loop round and round reading one key/value pair at a time from
2010 * the serialised stream, until we've found the game name.
2012 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2017 if (!read(rctx, key, 1)) {
2018 /* unexpected EOF */
2021 } while (key[0] == '\r' || key[0] == '\n');
2023 if (!read(rctx, key+1, 8)) {
2024 /* unexpected EOF */
2028 if (key[8] != ':') {
2030 ret = "Data was incorrectly formatted for a saved game file";
2033 len = strcspn(key, ": ");
2039 if (!read(rctx, &c, 1)) {
2040 /* unexpected EOF */
2046 } else if (c >= '0' && c <= '9') {
2047 len = (len * 10) + (c - '0');
2050 ret = "Data was incorrectly formatted for a"
2056 val = snewn(len+1, char);
2057 if (!read(rctx, val, len)) {
2064 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2065 /* ret already has the right message in it */
2068 /* Now most errors are this one, unless otherwise specified */
2069 ret = "Saved data ended unexpectedly";
2072 if (!strcmp(key, "VERSION")) {
2073 if (strcmp(val, SERIALISE_VERSION)) {
2074 ret = "Cannot handle this version of the saved game"
2078 } else if (!strcmp(key, "GAME")) {
2079 *name = dupstr(val);
2094 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2096 game_state *soln = NULL;
2098 if (me->statepos < 1)
2099 return "No game set up to print";/* _shouldn't_ happen! */
2102 char *msg, *movestr;
2104 if (!me->ourgame->can_solve)
2105 return "This game does not support the Solve operation";
2107 msg = "Solve operation failed";/* game _should_ overwrite on error */
2108 movestr = me->ourgame->solve(me->states[0].state,
2109 me->states[me->statepos-1].state,
2110 me->aux_info, &msg);
2113 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2122 * This call passes over ownership of the two game_states and
2123 * the game_params. Hence we duplicate the ones we want to
2124 * keep, and we don't have to bother freeing soln if it was
2127 document_add_puzzle(doc, me->ourgame,
2128 me->ourgame->dup_params(me->curparams),
2129 me->ourgame->dup_game(me->states[0].state), soln);