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_desc_change_notify_function)(void *);
86 void *game_desc_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();
113 * Allow environment-based changing of the default settings by
114 * defining a variable along the lines of `NET_DEFAULT=25x25w'
115 * in which the value is an encoded parameter string.
120 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
121 for (j = k = 0; buf[j]; j++)
122 if (!isspace((unsigned char)buf[j]))
123 buf[k++] = toupper((unsigned char)buf[j]);
125 if ((e = getenv(buf)) != NULL)
126 me->ourgame->decode_params(me->params, e);
128 me->curparams = NULL;
129 me->desc = me->privdesc = NULL;
132 me->genmode = GOT_NOTHING;
133 me->drawstate = NULL;
136 me->preset_names = NULL;
137 me->preset_encodings = NULL;
138 me->npresets = me->presetsize = 0;
139 me->anim_time = me->anim_pos = 0.0F;
140 me->flash_time = me->flash_pos = 0.0F;
143 me->pressed_mouse_button = 0;
144 me->laststatus = NULL;
147 me->tilesize = me->winwidth = me->winheight = 0;
149 me->drawing = drawing_new(drapi, me, drhandle);
153 me->preferred_tilesize = ourgame->preferred_tilesize;
156 * Allow an environment-based override for the default tile
157 * size by defining a variable along the lines of
164 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
165 for (j = k = 0; buf[j]; j++)
166 if (!isspace((unsigned char)buf[j]))
167 buf[k++] = toupper((unsigned char)buf[j]);
169 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
170 me->preferred_tilesize = ts;
178 const game *midend_which_game(midend *me)
183 static void midend_purge_states(midend *me)
185 while (me->nstates > me->statepos) {
186 me->ourgame->free_game(me->states[--me->nstates].state);
187 if (me->states[me->nstates].movestr)
188 sfree(me->states[me->nstates].movestr);
192 static void midend_free_game(midend *me)
194 while (me->nstates > 0) {
196 me->ourgame->free_game(me->states[me->nstates].state);
197 sfree(me->states[me->nstates].movestr);
201 me->ourgame->free_drawstate(me->drawing, me->drawstate);
204 void midend_free(midend *me)
208 midend_free_game(me);
211 drawing_free(me->drawing);
212 random_free(me->random);
218 me->ourgame->free_params(me->params);
220 for (i = 0; i < me->npresets; i++) {
221 sfree(me->presets[i]);
222 sfree(me->preset_names[i]);
223 sfree(me->preset_encodings[i]);
226 sfree(me->preset_names);
227 sfree(me->preset_encodings);
230 me->ourgame->free_ui(me->ui);
232 me->ourgame->free_params(me->curparams);
233 sfree(me->laststatus);
237 static void midend_size_new_drawstate(midend *me)
240 * Don't even bother, if we haven't worked out our tile size
243 if (me->tilesize > 0) {
244 me->ourgame->compute_size(me->params, me->tilesize,
245 &me->winwidth, &me->winheight);
246 me->ourgame->set_size(me->drawing, me->drawstate,
247 me->params, me->tilesize);
251 void midend_size(midend *me, int *x, int *y, int user_size)
257 * We can't set the size on the same drawstate twice. So if
258 * we've already sized one drawstate, we must throw it away and
261 if (me->drawstate && me->tilesize > 0) {
262 me->ourgame->free_drawstate(me->drawing, me->drawstate);
263 me->drawstate = me->ourgame->new_drawstate(me->drawing,
264 me->states[0].state);
268 * Find the tile size that best fits within the given space. If
269 * `user_size' is TRUE, we must actually find the _largest_ such
270 * tile size, in order to get as close to the user's explicit
271 * request as possible; otherwise, we bound above at the game's
272 * preferred tile size, so that the game gets what it wants
273 * provided that this doesn't break the constraint from the
274 * front-end (which is likely to be a screen size or similar).
280 me->ourgame->compute_size(me->params, max, &rx, &ry);
281 } while (rx <= *x && ry <= *y);
283 max = me->preferred_tilesize + 1;
287 * Now binary-search between min and max. We're looking for a
288 * boundary rather than a value: the point at which tile sizes
289 * stop fitting within the given dimensions. Thus, we stop when
290 * max and min differ by exactly 1.
292 while (max - min > 1) {
293 int mid = (max + min) / 2;
294 me->ourgame->compute_size(me->params, mid, &rx, &ry);
295 if (rx <= *x && ry <= *y)
302 * Now `min' is a valid size, and `max' isn't. So use `min'.
307 /* If the user requested a change in size, make it permanent. */
308 me->preferred_tilesize = me->tilesize;
309 midend_size_new_drawstate(me);
314 int midend_tilesize(midend *me) { return me->tilesize; }
316 void midend_set_params(midend *me, game_params *params)
318 me->ourgame->free_params(me->params);
319 me->params = me->ourgame->dup_params(params);
322 game_params *midend_get_params(midend *me)
324 return me->ourgame->dup_params(me->params);
327 static void midend_set_timer(midend *me)
329 me->timing = (me->ourgame->is_timed &&
330 me->ourgame->timing_state(me->states[me->statepos-1].state,
332 if (me->timing || me->flash_time || me->anim_time)
333 activate_timer(me->frontend);
335 deactivate_timer(me->frontend);
338 void midend_force_redraw(midend *me)
341 me->ourgame->free_drawstate(me->drawing, me->drawstate);
342 me->drawstate = me->ourgame->new_drawstate(me->drawing,
343 me->states[0].state);
344 midend_size_new_drawstate(me);
348 void midend_new_game(midend *me)
350 midend_free_game(me);
352 assert(me->nstates == 0);
354 if (me->genmode == GOT_DESC) {
355 me->genmode = GOT_NOTHING;
359 if (me->genmode == GOT_SEED) {
360 me->genmode = GOT_NOTHING;
363 * Generate a new random seed. 15 digits comes to about
364 * 48 bits, which should be more than enough.
366 * I'll avoid putting a leading zero on the number,
367 * just in case it confuses anybody who thinks it's
368 * processed as an integer rather than a string.
373 newseed[0] = '1' + (char)random_upto(me->random, 9);
374 for (i = 1; i < 15; i++)
375 newseed[i] = '0' + (char)random_upto(me->random, 10);
377 me->seedstr = dupstr(newseed);
380 me->ourgame->free_params(me->curparams);
381 me->curparams = me->ourgame->dup_params(me->params);
389 rs = random_new(me->seedstr, strlen(me->seedstr));
391 * If this midend has been instantiated without providing a
392 * drawing API, it is non-interactive. This means that it's
393 * being used for bulk game generation, and hence we should
394 * pass the non-interactive flag to new_desc.
396 me->desc = me->ourgame->new_desc(me->curparams, rs,
397 &me->aux_info, (me->drawing != NULL));
405 * It might seem a bit odd that we're using me->params to
406 * create the initial game state, rather than me->curparams
407 * which is better tailored to this specific game and which we
410 * It's supposed to be an invariant in the midend that
411 * me->params and me->curparams differ in no aspect that is
412 * important after generation (i.e. after new_desc()). By
413 * deliberately passing the _less_ specific of these two
414 * parameter sets, we provoke play-time misbehaviour in the
415 * case where a game has failed to encode a play-time parameter
416 * in the non-full version of encode_params().
418 me->states[me->nstates].state =
419 me->ourgame->new_game(me, me->params, me->desc);
422 * As part of our commitment to self-testing, test the aux
423 * string to make sure nothing ghastly went wrong.
425 if (me->ourgame->can_solve && me->aux_info) {
430 movestr = me->ourgame->solve(me->states[0].state,
433 assert(movestr && !msg);
434 s = me->ourgame->execute_move(me->states[0].state, movestr);
436 me->ourgame->free_game(s);
441 * Soak test, enabled by setting <gamename>_TESTSOLVE in the
442 * environment. This causes an immediate attempt to re-solve the
443 * game without benefit of aux_info. The effect is that (at least
444 * on Unix) you can run 'FOO_TESTSOLVE=1 foo --generate 10000
445 * <params>#12345' and it will generate a lot of game ids and
446 * instantly pass each one back to the solver.
448 * (It's worth putting in an explicit seed in any such test, so
449 * you can repeat it to diagnose a problem if one comes up!)
454 static int doing_test_solve = -1;
455 if (doing_test_solve < 0) {
456 sprintf(buf, "%s_TESTSOLVE", me->ourgame->name);
457 for (j = k = 0; buf[j]; j++)
458 if (!isspace((unsigned char)buf[j]))
459 buf[k++] = toupper((unsigned char)buf[j]);
463 * Since this is used for correctness testing, it's
464 * helpful to have a visual acknowledgment that the
465 * user hasn't mistyped the environment variable name.
467 fprintf(stderr, "Running solver soak tests\n");
468 doing_test_solve = TRUE;
470 doing_test_solve = FALSE;
473 if (doing_test_solve) {
478 movestr = me->ourgame->solve(me->states[0].state,
481 assert(movestr && !msg);
482 s = me->ourgame->execute_move(me->states[0].state, movestr);
484 me->ourgame->free_game(s);
489 me->states[me->nstates].movestr = NULL;
490 me->states[me->nstates].movetype = NEWGAME;
493 me->drawstate = me->ourgame->new_drawstate(me->drawing,
494 me->states[0].state);
495 midend_size_new_drawstate(me);
498 me->ourgame->free_ui(me->ui);
499 me->ui = me->ourgame->new_ui(me->states[0].state);
500 midend_set_timer(me);
501 me->pressed_mouse_button = 0;
504 int midend_can_undo(midend *me)
506 return (me->statepos > 1);
509 int midend_can_redo(midend *me)
511 return (me->statepos < me->nstates);
514 static int midend_undo(midend *me)
516 if (me->statepos > 1) {
518 me->ourgame->changed_state(me->ui,
519 me->states[me->statepos-1].state,
520 me->states[me->statepos-2].state);
528 static int midend_redo(midend *me)
530 if (me->statepos < me->nstates) {
532 me->ourgame->changed_state(me->ui,
533 me->states[me->statepos-1].state,
534 me->states[me->statepos].state);
542 static void midend_finish_move(midend *me)
547 * We do not flash if the later of the two states is special.
548 * This covers both forward Solve moves and backward (undone)
551 if ((me->oldstate || me->statepos > 1) &&
552 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
553 (me->dir < 0 && me->statepos < me->nstates &&
554 !special(me->states[me->statepos].movetype)))) {
555 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
556 me->states[me->statepos-2].state,
557 me->states[me->statepos-1].state,
558 me->oldstate ? me->dir : +1,
561 me->flash_pos = 0.0F;
562 me->flash_time = flashtime;
567 me->ourgame->free_game(me->oldstate);
569 me->anim_pos = me->anim_time = 0;
572 midend_set_timer(me);
575 void midend_stop_anim(midend *me)
577 if (me->oldstate || me->anim_time != 0) {
578 midend_finish_move(me);
583 void midend_restart_game(midend *me)
587 midend_stop_anim(me);
589 assert(me->statepos >= 1);
590 if (me->statepos == 1)
591 return; /* no point doing anything at all! */
594 * During restart, we reconstruct the game from the (public)
595 * game description rather than from states[0], because that
596 * way Mines gets slightly more sensible behaviour (restart
597 * goes to _after_ the first click so you don't have to
598 * remember where you clicked).
600 s = me->ourgame->new_game(me, me->params, me->desc);
603 * Now enter the restarted state as the next move.
605 midend_stop_anim(me);
606 midend_purge_states(me);
608 me->states[me->nstates].state = s;
609 me->states[me->nstates].movestr = dupstr(me->desc);
610 me->states[me->nstates].movetype = RESTART;
611 me->statepos = ++me->nstates;
613 me->ourgame->changed_state(me->ui,
614 me->states[me->statepos-2].state,
615 me->states[me->statepos-1].state);
617 midend_finish_move(me);
619 midend_set_timer(me);
622 static int midend_really_process_key(midend *me, int x, int y, int button)
624 game_state *oldstate =
625 me->ourgame->dup_game(me->states[me->statepos - 1].state);
626 int type = MOVE, gottype = FALSE, ret = 1;
632 me->ourgame->interpret_move(me->states[me->statepos-1].state,
633 me->ui, me->drawstate, x, y, button);
636 if (button == 'n' || button == 'N' || button == '\x0E') {
637 midend_stop_anim(me);
640 goto done; /* never animate */
641 } else if (button == 'u' || button == 'u' ||
642 button == '\x1A' || button == '\x1F') {
643 midend_stop_anim(me);
644 type = me->states[me->statepos-1].movetype;
646 if (!midend_undo(me))
648 } else if (button == 'r' || button == 'R' ||
649 button == '\x12' || button == '\x19') {
650 midend_stop_anim(me);
651 if (!midend_redo(me))
653 } else if (button == '\x13' && me->ourgame->can_solve) {
654 if (midend_solve(me))
656 } else if (button == 'q' || button == 'Q' || button == '\x11') {
663 s = me->states[me->statepos-1].state;
665 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
670 if (s == me->states[me->statepos-1].state) {
672 * make_move() is allowed to return its input state to
673 * indicate that although no move has been made, the UI
674 * state has been updated and a redraw is called for.
677 midend_set_timer(me);
680 midend_stop_anim(me);
681 midend_purge_states(me);
683 assert(movestr != NULL);
684 me->states[me->nstates].state = s;
685 me->states[me->nstates].movestr = movestr;
686 me->states[me->nstates].movetype = MOVE;
687 me->statepos = ++me->nstates;
690 me->ourgame->changed_state(me->ui,
691 me->states[me->statepos-2].state,
692 me->states[me->statepos-1].state);
699 type = me->states[me->statepos-1].movetype;
702 * See if this move requires an animation.
704 if (special(type) && !(type == SOLVE &&
705 (me->ourgame->flags & SOLVE_ANIMATES))) {
708 anim_time = me->ourgame->anim_length(oldstate,
709 me->states[me->statepos-1].state,
713 me->oldstate = oldstate; oldstate = NULL;
715 me->anim_time = anim_time;
718 midend_finish_move(me);
724 midend_set_timer(me);
727 if (oldstate) me->ourgame->free_game(oldstate);
731 int midend_process_key(midend *me, int x, int y, int button)
736 * Harmonise mouse drag and release messages.
738 * Some front ends might accidentally switch from sending, say,
739 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
740 * drag. (This can happen on the Mac, for example, since
741 * RIGHT_DRAG is usually done using Command+drag, and if the
742 * user accidentally releases Command half way through the drag
743 * then there will be trouble.)
745 * It would be an O(number of front ends) annoyance to fix this
746 * in the front ends, but an O(number of back ends) annoyance
747 * to have each game capable of dealing with it. Therefore, we
748 * fix it _here_ in the common midend code so that it only has
751 * The possible ways in which things can go screwy in the front
754 * - in a system containing multiple physical buttons button
755 * presses can inadvertently overlap. We can see ABab (caps
756 * meaning button-down and lowercase meaning button-up) when
757 * the user had semantically intended AaBb.
759 * - in a system where one button is simulated by means of a
760 * modifier key and another button, buttons can mutate
761 * between press and release (possibly during drag). So we
762 * can see Ab instead of Aa.
764 * Definite requirements are:
766 * - button _presses_ must never be invented or destroyed. If
767 * the user presses two buttons in succession, the button
768 * presses must be transferred to the backend unchanged. So
769 * if we see AaBb , that's fine; if we see ABab (the button
770 * presses inadvertently overlapped) we must somehow
771 * `correct' it to AaBb.
773 * - every mouse action must end up looking like a press, zero
774 * or more drags, then a release. This allows back ends to
775 * make the _assumption_ that incoming mouse data will be
776 * sane in this regard, and not worry about the details.
778 * So my policy will be:
780 * - treat any button-up as a button-up for the currently
781 * pressed button, or ignore it if there is no currently
784 * - treat any drag as a drag for the currently pressed
785 * button, or ignore it if there is no currently pressed
788 * - if we see a button-down while another button is currently
789 * pressed, invent a button-up for the first one and then
790 * pass the button-down through as before.
792 * 2005-05-31: An addendum to the above. Some games might want
793 * a `priority order' among buttons, such that if one button is
794 * pressed while another is down then a fixed one of the
795 * buttons takes priority no matter what order they're pressed
796 * in. Mines, in particular, wants to treat a left+right click
797 * like a left click for the benefit of users of other
798 * implementations. So the last of the above points is modified
799 * in the presence of an (optional) button priority order.
801 * A further addition: we translate certain keyboard presses to
802 * cursor key 'select' buttons, so that a) frontends don't have
803 * to translate these themselves (like they do for CURSOR_UP etc),
804 * and b) individual games don't have to hard-code button presses
805 * of '\n' etc for keyboard-based cursors. The choice of buttons
806 * here could eventually be controlled by a runtime configuration
809 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
810 if (me->pressed_mouse_button) {
811 if (IS_MOUSE_DRAG(button)) {
812 button = me->pressed_mouse_button +
813 (LEFT_DRAG - LEFT_BUTTON);
815 button = me->pressed_mouse_button +
816 (LEFT_RELEASE - LEFT_BUTTON);
819 return ret; /* ignore it */
820 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
822 * If the new button has lower priority than the old one,
823 * don't bother doing this.
825 if (me->ourgame->flags &
826 BUTTON_BEATS(me->pressed_mouse_button, button))
827 return ret; /* just ignore it */
830 * Fabricate a button-up for the previously pressed button.
832 ret = ret && midend_really_process_key
833 (me, x, y, (me->pressed_mouse_button +
834 (LEFT_RELEASE - LEFT_BUTTON)));
838 * Translate keyboard presses to cursor selection.
840 if (button == '\n' || button == '\r')
841 button = CURSOR_SELECT;
843 button = CURSOR_SELECT2;
846 * Normalise both backspace characters (8 and 127) to \b. Easier
847 * to do this once, here, than to require all front ends to
848 * carefully generate the same one - now each front end can
849 * generate whichever is easiest.
851 if (button == '\177')
855 * Now send on the event we originally received.
857 ret = ret && midend_really_process_key(me, x, y, button);
860 * And update the currently pressed button.
862 if (IS_MOUSE_RELEASE(button))
863 me->pressed_mouse_button = 0;
864 else if (IS_MOUSE_DOWN(button))
865 me->pressed_mouse_button = button;
870 void midend_redraw(midend *me)
874 if (me->statepos > 0 && me->drawstate) {
875 start_draw(me->drawing);
876 if (me->oldstate && me->anim_time > 0 &&
877 me->anim_pos < me->anim_time) {
878 assert(me->dir != 0);
879 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
880 me->states[me->statepos-1].state, me->dir,
881 me->ui, me->anim_pos, me->flash_pos);
883 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
884 me->states[me->statepos-1].state, +1 /*shrug*/,
885 me->ui, 0.0, me->flash_pos);
887 end_draw(me->drawing);
892 * Nasty hacky function used to implement the --redo option in
893 * gtk.c. Only used for generating the puzzles' icons.
895 void midend_freeze_timer(midend *me, float tprop)
897 me->anim_pos = me->anim_time * tprop;
899 deactivate_timer(me->frontend);
902 void midend_timer(midend *me, float tplus)
904 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
906 me->anim_pos += tplus;
907 if (me->anim_pos >= me->anim_time ||
908 me->anim_time == 0 || !me->oldstate) {
909 if (me->anim_time > 0)
910 midend_finish_move(me);
913 me->flash_pos += tplus;
914 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
915 me->flash_pos = me->flash_time = 0;
922 float oldelapsed = me->elapsed;
923 me->elapsed += tplus;
924 if ((int)oldelapsed != (int)me->elapsed)
925 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
928 midend_set_timer(me);
931 float *midend_colours(midend *me, int *ncolours)
935 ret = me->ourgame->colours(me->frontend, ncolours);
941 * Allow environment-based overrides for the standard
942 * colours by defining variables along the lines of
943 * `NET_COLOUR_4=6000c0'.
946 for (i = 0; i < *ncolours; i++) {
948 unsigned int r, g, b;
951 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
952 for (j = k = 0; buf[j]; j++)
953 if (!isspace((unsigned char)buf[j]))
954 buf[k++] = toupper((unsigned char)buf[j]);
956 if ((e = getenv(buf)) != NULL &&
957 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
958 ret[i*3 + 0] = r / 255.0F;
959 ret[i*3 + 1] = g / 255.0F;
960 ret[i*3 + 2] = b / 255.0F;
968 int midend_num_presets(midend *me)
974 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
975 if (me->presetsize <= me->npresets) {
976 me->presetsize = me->npresets + 10;
977 me->presets = sresize(me->presets, me->presetsize,
979 me->preset_names = sresize(me->preset_names, me->presetsize,
981 me->preset_encodings = sresize(me->preset_encodings,
982 me->presetsize, char *);
985 me->presets[me->npresets] = preset;
986 me->preset_names[me->npresets] = name;
987 me->preset_encodings[me->npresets] =
988 me->ourgame->encode_params(preset, TRUE);;
995 * Allow environment-based extensions to the preset list by
996 * defining a variable along the lines of `SOLO_PRESETS=2x3
997 * Advanced:2x3da'. Colon-separated list of items,
998 * alternating between textual titles in the menu and
999 * encoded parameter strings.
1001 char buf[80], *e, *p;
1004 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1005 for (j = k = 0; buf[j]; j++)
1006 if (!isspace((unsigned char)buf[j]))
1007 buf[k++] = toupper((unsigned char)buf[j]);
1010 if ((e = getenv(buf)) != NULL) {
1015 game_params *preset;
1018 while (*p && *p != ':') p++;
1019 if (*p) *p++ = '\0';
1021 while (*p && *p != ':') p++;
1022 if (*p) *p++ = '\0';
1024 preset = me->ourgame->default_params();
1025 me->ourgame->decode_params(preset, val);
1027 if (me->ourgame->validate_params(preset, TRUE)) {
1028 /* Drop this one from the list. */
1029 me->ourgame->free_params(preset);
1033 if (me->presetsize <= me->npresets) {
1034 me->presetsize = me->npresets + 10;
1035 me->presets = sresize(me->presets, me->presetsize,
1037 me->preset_names = sresize(me->preset_names,
1038 me->presetsize, char *);
1039 me->preset_encodings = sresize(me->preset_encodings,
1040 me->presetsize, char *);
1043 me->presets[me->npresets] = preset;
1044 me->preset_names[me->npresets] = dupstr(name);
1045 me->preset_encodings[me->npresets] =
1046 me->ourgame->encode_params(preset, TRUE);
1053 return me->npresets;
1056 void midend_fetch_preset(midend *me, int n,
1057 char **name, game_params **params)
1059 assert(n >= 0 && n < me->npresets);
1060 *name = me->preset_names[n];
1061 *params = me->presets[n];
1064 int midend_which_preset(midend *me)
1066 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1070 for (i = 0; i < me->npresets; i++)
1071 if (!strcmp(encoding, me->preset_encodings[i])) {
1080 int midend_wants_statusbar(midend *me)
1082 return me->ourgame->wants_statusbar;
1085 void midend_request_desc_changes(midend *me, void (*notify)(void *), void *ctx)
1087 me->game_desc_change_notify_function = notify;
1088 me->game_desc_change_notify_ctx = ctx;
1091 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1094 sfree(me->privdesc);
1095 me->desc = dupstr(desc);
1096 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1097 if (me->game_desc_change_notify_function)
1098 me->game_desc_change_notify_function(me->game_desc_change_notify_ctx);
1101 config_item *midend_get_config(midend *me, int which, char **wintitle)
1103 char *titlebuf, *parstr, *rest;
1108 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1112 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1113 *wintitle = titlebuf;
1114 return me->ourgame->configure(me->params);
1117 if (!me->curparams) {
1121 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1122 which == CFG_SEED ? "random" : "game");
1123 *wintitle = titlebuf;
1125 ret = snewn(2, config_item);
1127 ret[0].type = C_STRING;
1128 if (which == CFG_SEED)
1129 ret[0].name = "Game random seed";
1131 ret[0].name = "Game ID";
1134 * For CFG_DESC the text going in here will be a string
1135 * encoding of the restricted parameters, plus a colon,
1136 * plus the game description. For CFG_SEED it will be the
1137 * full parameters, plus a hash, plus the random seed data.
1138 * Either of these is a valid full game ID (although only
1139 * the former is likely to persist across many code
1142 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1144 if (which == CFG_DESC) {
1145 rest = me->desc ? me->desc : "";
1148 rest = me->seedstr ? me->seedstr : "";
1151 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1152 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1155 ret[1].type = C_END;
1156 ret[1].name = ret[1].sval = NULL;
1162 assert(!"We shouldn't be here");
1166 static char *midend_game_id_int(midend *me, char *id, int defmode)
1168 char *error, *par, *desc, *seed;
1169 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1172 seed = strchr(id, '#');
1173 desc = strchr(id, ':');
1175 if (desc && (!seed || desc < seed)) {
1177 * We have a colon separating parameters from game
1178 * description. So `par' now points to the parameters
1179 * string, and `desc' to the description string.
1184 } else if (seed && (!desc || seed < desc)) {
1186 * We have a hash separating parameters from random seed.
1187 * So `par' now points to the parameters string, and `seed'
1188 * to the seed string.
1195 * We only have one string. Depending on `defmode', we take
1196 * it to be either parameters, seed or description.
1198 if (defmode == DEF_SEED) {
1201 } else if (defmode == DEF_DESC) {
1211 * We must be reasonably careful here not to modify anything in
1212 * `me' until we have finished validating things. This function
1213 * must either return an error and do nothing to the midend, or
1214 * return success and do everything; nothing in between is
1217 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1220 newcurparams = me->ourgame->dup_params(me->params);
1221 me->ourgame->decode_params(newcurparams, par);
1222 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1224 me->ourgame->free_params(newcurparams);
1227 oldparams1 = me->curparams;
1230 * Now filter only the persistent parts of this state into
1231 * the long-term params structure, unless we've _only_
1232 * received a params string in which case the whole lot is
1235 oldparams2 = me->params;
1239 newparams = me->ourgame->dup_params(me->params);
1241 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1242 me->ourgame->decode_params(newparams, tmpstr);
1246 newparams = me->ourgame->dup_params(newcurparams);
1250 newcurparams = me->curparams;
1251 newparams = me->params;
1252 free_params = FALSE;
1256 error = me->ourgame->validate_desc(newparams, desc);
1260 me->ourgame->free_params(newcurparams);
1262 me->ourgame->free_params(newparams);
1269 * Now we've got past all possible error points. Update the
1272 me->params = newparams;
1273 me->curparams = newcurparams;
1275 me->ourgame->free_params(oldparams1);
1277 me->ourgame->free_params(oldparams2);
1280 sfree(me->privdesc);
1281 me->desc = me->privdesc = NULL;
1286 me->desc = dupstr(desc);
1287 me->genmode = GOT_DESC;
1288 sfree(me->aux_info);
1289 me->aux_info = NULL;
1293 me->seedstr = dupstr(seed);
1294 me->genmode = GOT_SEED;
1300 char *midend_game_id(midend *me, char *id)
1302 return midend_game_id_int(me, id, DEF_PARAMS);
1305 char *midend_get_game_id(midend *me)
1309 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1312 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1313 sprintf(ret, "%s:%s", parstr, me->desc);
1318 char *midend_get_random_seed(midend *me)
1325 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1327 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1328 sprintf(ret, "%s#%s", parstr, me->seedstr);
1333 char *midend_set_config(midend *me, int which, config_item *cfg)
1336 game_params *params;
1340 params = me->ourgame->custom_params(cfg);
1341 error = me->ourgame->validate_params(params, TRUE);
1344 me->ourgame->free_params(params);
1348 me->ourgame->free_params(me->params);
1349 me->params = params;
1354 error = midend_game_id_int(me, cfg[0].sval,
1355 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1364 int midend_can_format_as_text_now(midend *me)
1366 if (me->ourgame->can_format_as_text_ever)
1367 return me->ourgame->can_format_as_text_now(me->params);
1372 char *midend_text_format(midend *me)
1374 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1375 me->ourgame->can_format_as_text_now(me->params))
1376 return me->ourgame->text_format(me->states[me->statepos-1].state);
1381 char *midend_solve(midend *me)
1384 char *msg, *movestr;
1386 if (!me->ourgame->can_solve)
1387 return "This game does not support the Solve operation";
1389 if (me->statepos < 1)
1390 return "No game set up to solve"; /* _shouldn't_ happen! */
1393 movestr = me->ourgame->solve(me->states[0].state,
1394 me->states[me->statepos-1].state,
1395 me->aux_info, &msg);
1398 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1401 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1405 * Now enter the solved state as the next move.
1407 midend_stop_anim(me);
1408 midend_purge_states(me);
1410 me->states[me->nstates].state = s;
1411 me->states[me->nstates].movestr = movestr;
1412 me->states[me->nstates].movetype = SOLVE;
1413 me->statepos = ++me->nstates;
1415 me->ourgame->changed_state(me->ui,
1416 me->states[me->statepos-2].state,
1417 me->states[me->statepos-1].state);
1419 if (me->ourgame->flags & SOLVE_ANIMATES) {
1420 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1422 me->ourgame->anim_length(me->states[me->statepos-2].state,
1423 me->states[me->statepos-1].state,
1427 me->anim_time = 0.0;
1428 midend_finish_move(me);
1432 midend_set_timer(me);
1436 int midend_status(midend *me)
1439 * We should probably never be called when the state stack has no
1440 * states on it at all - ideally, midends should never be left in
1441 * that state for long enough to get put down and forgotten about.
1442 * But if we are, I think we return _true_ - pedantically speaking
1443 * a midend in that state is 'vacuously solved', and more
1444 * practically, a user whose midend has been left in that state
1445 * probably _does_ want the 'new game' option to be prominent.
1447 if (me->statepos == 0)
1450 return me->ourgame->status(me->states[me->statepos-1].state);
1453 char *midend_rewrite_statusbar(midend *me, char *text)
1456 * An important special case is that we are occasionally called
1457 * with our own laststatus, to update the timer.
1459 if (me->laststatus != text) {
1460 sfree(me->laststatus);
1461 me->laststatus = dupstr(text);
1464 if (me->ourgame->is_timed) {
1465 char timebuf[100], *ret;
1468 sec = (int)me->elapsed;
1471 sprintf(timebuf, "[%d:%02d] ", min, sec);
1473 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1474 strcpy(ret, timebuf);
1479 return dupstr(text);
1483 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1484 #define SERIALISE_VERSION "1"
1486 void midend_serialise(midend *me,
1487 void (*write)(void *ctx, void *buf, int len),
1493 * Each line of the save file contains three components. First
1494 * exactly 8 characters of header word indicating what type of
1495 * data is contained on the line; then a colon followed by a
1496 * decimal integer giving the length of the main string on the
1497 * line; then a colon followed by the string itself (exactly as
1498 * many bytes as previously specified, no matter what they
1499 * contain). Then a newline (of reasonably flexible form).
1501 #define wr(h,s) do { \
1504 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1505 write(wctx, hbuf, strlen(hbuf)); \
1506 write(wctx, str, strlen(str)); \
1507 write(wctx, "\n", 1); \
1511 * Magic string identifying the file, and version number of the
1514 wr("SAVEFILE", SERIALISE_MAGIC);
1515 wr("VERSION", SERIALISE_VERSION);
1518 * The game name. (Copied locally to avoid const annoyance.)
1521 char *s = dupstr(me->ourgame->name);
1527 * The current long-term parameters structure, in full.
1530 char *s = me->ourgame->encode_params(me->params, TRUE);
1536 * The current short-term parameters structure, in full.
1538 if (me->curparams) {
1539 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1545 * The current game description, the privdesc, and the random seed.
1548 wr("SEED", me->seedstr);
1550 wr("DESC", me->desc);
1552 wr("PRIVDESC", me->privdesc);
1555 * The game's aux_info. We obfuscate this to prevent spoilers
1556 * (people are likely to run `head' or similar on a saved game
1557 * file simply to find out what it is, and don't necessarily
1558 * want to be told the answer to the puzzle!)
1565 len = strlen(me->aux_info);
1566 s1 = snewn(len, unsigned char);
1567 memcpy(s1, me->aux_info, len);
1568 obfuscate_bitmap(s1, len*8, FALSE);
1569 s2 = bin2hex(s1, len);
1578 * Any required serialisation of the game_ui.
1581 char *s = me->ourgame->encode_ui(me->ui);
1589 * The game time, if it's a timed game.
1591 if (me->ourgame->is_timed) {
1593 sprintf(buf, "%g", me->elapsed);
1598 * The length of, and position in, the states list.
1602 sprintf(buf, "%d", me->nstates);
1604 sprintf(buf, "%d", me->statepos);
1605 wr("STATEPOS", buf);
1609 * For each state after the initial one (which we know is
1610 * constructed from either privdesc or desc), enough
1611 * information for execute_move() to reconstruct it from the
1614 for (i = 1; i < me->nstates; i++) {
1615 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1616 switch (me->states[i].movetype) {
1618 wr("MOVE", me->states[i].movestr);
1621 wr("SOLVE", me->states[i].movestr);
1624 wr("RESTART", me->states[i].movestr);
1633 * This function returns NULL on success, or an error message.
1635 char *midend_deserialise(midend *me,
1636 int (*read)(void *ctx, void *buf, int len),
1639 int nstates = 0, statepos = -1, gotstates = 0;
1640 int started = FALSE;
1644 /* Initially all errors give the same report */
1645 char *ret = "Data does not appear to be a saved game file";
1648 * We construct all the new state in local variables while we
1649 * check its sanity. Only once we have finished reading the
1650 * serialised data and detected no errors at all do we start
1651 * modifying stuff in the midend passed in.
1653 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1654 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1655 float elapsed = 0.0F;
1656 game_params *params = NULL, *cparams = NULL;
1658 struct midend_state_entry *states = NULL;
1661 * Loop round and round reading one key/value pair at a time
1662 * from the serialised stream, until we have enough game states
1665 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1670 if (!read(rctx, key, 1)) {
1671 /* unexpected EOF */
1674 } while (key[0] == '\r' || key[0] == '\n');
1676 if (!read(rctx, key+1, 8)) {
1677 /* unexpected EOF */
1681 if (key[8] != ':') {
1683 ret = "Data was incorrectly formatted for a saved game file";
1686 len = strcspn(key, ": ");
1692 if (!read(rctx, &c, 1)) {
1693 /* unexpected EOF */
1699 } else if (c >= '0' && c <= '9') {
1700 len = (len * 10) + (c - '0');
1703 ret = "Data was incorrectly formatted for a"
1709 val = snewn(len+1, char);
1710 if (!read(rctx, val, len)) {
1717 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1718 /* ret already has the right message in it */
1721 /* Now most errors are this one, unless otherwise specified */
1722 ret = "Saved data ended unexpectedly";
1725 if (!strcmp(key, "VERSION")) {
1726 if (strcmp(val, SERIALISE_VERSION)) {
1727 ret = "Cannot handle this version of the saved game"
1731 } else if (!strcmp(key, "GAME")) {
1732 if (strcmp(val, me->ourgame->name)) {
1733 ret = "Save file is from a different game";
1736 } else if (!strcmp(key, "PARAMS")) {
1740 } else if (!strcmp(key, "CPARAMS")) {
1744 } else if (!strcmp(key, "SEED")) {
1748 } else if (!strcmp(key, "DESC")) {
1752 } else if (!strcmp(key, "PRIVDESC")) {
1756 } else if (!strcmp(key, "AUXINFO")) {
1758 int len = strlen(val) / 2; /* length in bytes */
1759 tmp = hex2bin(val, len);
1760 obfuscate_bitmap(tmp, len*8, TRUE);
1763 auxinfo = snewn(len + 1, char);
1764 memcpy(auxinfo, tmp, len);
1765 auxinfo[len] = '\0';
1767 } else if (!strcmp(key, "UI")) {
1771 } else if (!strcmp(key, "TIME")) {
1772 elapsed = (float)atof(val);
1773 } else if (!strcmp(key, "NSTATES")) {
1774 nstates = atoi(val);
1776 ret = "Number of states in save file was negative";
1780 ret = "Two state counts provided in save file";
1783 states = snewn(nstates, struct midend_state_entry);
1784 for (i = 0; i < nstates; i++) {
1785 states[i].state = NULL;
1786 states[i].movestr = NULL;
1787 states[i].movetype = NEWGAME;
1789 } else if (!strcmp(key, "STATEPOS")) {
1790 statepos = atoi(val);
1791 } else if (!strcmp(key, "MOVE")) {
1793 states[gotstates].movetype = MOVE;
1794 states[gotstates].movestr = val;
1796 } else if (!strcmp(key, "SOLVE")) {
1798 states[gotstates].movetype = SOLVE;
1799 states[gotstates].movestr = val;
1801 } else if (!strcmp(key, "RESTART")) {
1803 states[gotstates].movetype = RESTART;
1804 states[gotstates].movestr = val;
1813 params = me->ourgame->default_params();
1814 me->ourgame->decode_params(params, parstr);
1815 if (me->ourgame->validate_params(params, TRUE)) {
1816 ret = "Long-term parameters in save file are invalid";
1819 cparams = me->ourgame->default_params();
1820 me->ourgame->decode_params(cparams, cparstr);
1821 if (me->ourgame->validate_params(cparams, FALSE)) {
1822 ret = "Short-term parameters in save file are invalid";
1825 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1827 * The seed's no use with this version, but we can perfectly
1828 * well use the rest of the data.
1834 ret = "Game description in save file is missing";
1836 } else if (me->ourgame->validate_desc(params, desc)) {
1837 ret = "Game description in save file is invalid";
1840 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1841 ret = "Game private description in save file is invalid";
1844 if (statepos < 0 || statepos >= nstates) {
1845 ret = "Game position in save file is out of range";
1848 states[0].state = me->ourgame->new_game(me, params,
1849 privdesc ? privdesc : desc);
1850 for (i = 1; i < nstates; i++) {
1851 assert(states[i].movetype != NEWGAME);
1852 switch (states[i].movetype) {
1855 states[i].state = me->ourgame->execute_move(states[i-1].state,
1857 if (states[i].state == NULL) {
1858 ret = "Save file contained an invalid move";
1863 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1864 ret = "Save file contained an invalid restart move";
1867 states[i].state = me->ourgame->new_game(me, params,
1873 ui = me->ourgame->new_ui(states[0].state);
1874 me->ourgame->decode_ui(ui, uistr);
1877 * Now we've run out of possible error conditions, so we're
1878 * ready to start overwriting the real data in the current
1879 * midend. We'll do this by swapping things with the local
1880 * variables, so that the same cleanup code will free the old
1891 me->privdesc = privdesc;
1899 me->aux_info = auxinfo;
1903 me->genmode = GOT_NOTHING;
1905 me->statesize = nstates;
1906 nstates = me->nstates;
1907 me->nstates = me->statesize;
1909 struct midend_state_entry *tmp;
1911 me->states = states;
1914 me->statepos = statepos;
1920 me->params = params;
1923 tmp = me->curparams;
1924 me->curparams = cparams;
1928 me->oldstate = NULL;
1929 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1940 me->elapsed = elapsed;
1941 me->pressed_mouse_button = 0;
1943 midend_set_timer(me);
1946 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1948 me->ourgame->new_drawstate(me->drawing,
1949 me->states[me->statepos-1].state);
1950 midend_size_new_drawstate(me);
1952 ret = NULL; /* success! */
1964 me->ourgame->free_params(params);
1966 me->ourgame->free_params(cparams);
1968 me->ourgame->free_ui(ui);
1972 for (i = 0; i < nstates; i++) {
1973 if (states[i].state)
1974 me->ourgame->free_game(states[i].state);
1975 sfree(states[i].movestr);
1984 * This function examines a saved game file just far enough to
1985 * determine which game type it contains. It returns NULL on success
1986 * and the game name string in 'name' (which will be dynamically
1987 * allocated and should be caller-freed), or an error message on
1990 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
1993 int nstates = 0, statepos = -1, gotstates = 0;
1994 int started = FALSE;
1997 /* Initially all errors give the same report */
1998 char *ret = "Data does not appear to be a saved game file";
2003 * Loop round and round reading one key/value pair at a time from
2004 * the serialised stream, until we've found the game name.
2006 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2011 if (!read(rctx, key, 1)) {
2012 /* unexpected EOF */
2015 } while (key[0] == '\r' || key[0] == '\n');
2017 if (!read(rctx, key+1, 8)) {
2018 /* unexpected EOF */
2022 if (key[8] != ':') {
2024 ret = "Data was incorrectly formatted for a saved game file";
2027 len = strcspn(key, ": ");
2033 if (!read(rctx, &c, 1)) {
2034 /* unexpected EOF */
2040 } else if (c >= '0' && c <= '9') {
2041 len = (len * 10) + (c - '0');
2044 ret = "Data was incorrectly formatted for a"
2050 val = snewn(len+1, char);
2051 if (!read(rctx, val, len)) {
2058 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2059 /* ret already has the right message in it */
2062 /* Now most errors are this one, unless otherwise specified */
2063 ret = "Saved data ended unexpectedly";
2066 if (!strcmp(key, "VERSION")) {
2067 if (strcmp(val, SERIALISE_VERSION)) {
2068 ret = "Cannot handle this version of the saved game"
2072 } else if (!strcmp(key, "GAME")) {
2073 *name = dupstr(val);
2088 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2090 game_state *soln = NULL;
2092 if (me->statepos < 1)
2093 return "No game set up to print";/* _shouldn't_ happen! */
2096 char *msg, *movestr;
2098 if (!me->ourgame->can_solve)
2099 return "This game does not support the Solve operation";
2101 msg = "Solve operation failed";/* game _should_ overwrite on error */
2102 movestr = me->ourgame->solve(me->states[0].state,
2103 me->states[me->statepos-1].state,
2104 me->aux_info, &msg);
2107 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2116 * This call passes over ownership of the two game_states and
2117 * the game_params. Hence we duplicate the ones we want to
2118 * keep, and we don't have to bother freeing soln if it was
2121 document_add_puzzle(doc, me->ourgame,
2122 me->ourgame->dup_params(me->curparams),
2123 me->ourgame->dup_game(me->states[0].state), soln);