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 const game *midend_which_game(midend *me)
180 static void midend_purge_states(midend *me)
182 while (me->nstates > me->statepos) {
183 me->ourgame->free_game(me->states[--me->nstates].state);
184 if (me->states[me->nstates].movestr)
185 sfree(me->states[me->nstates].movestr);
189 static void midend_free_game(midend *me)
191 while (me->nstates > 0) {
193 me->ourgame->free_game(me->states[me->nstates].state);
194 sfree(me->states[me->nstates].movestr);
198 me->ourgame->free_drawstate(me->drawing, me->drawstate);
201 void midend_free(midend *me)
205 midend_free_game(me);
208 drawing_free(me->drawing);
209 random_free(me->random);
215 me->ourgame->free_params(me->params);
217 for (i = 0; i < me->npresets; i++) {
218 sfree(me->presets[i]);
219 sfree(me->preset_names[i]);
220 sfree(me->preset_encodings[i]);
223 sfree(me->preset_names);
224 sfree(me->preset_encodings);
227 me->ourgame->free_ui(me->ui);
229 me->ourgame->free_params(me->curparams);
230 sfree(me->laststatus);
234 static void midend_size_new_drawstate(midend *me)
237 * Don't even bother, if we haven't worked out our tile size
240 if (me->tilesize > 0) {
241 me->ourgame->compute_size(me->params, me->tilesize,
242 &me->winwidth, &me->winheight);
243 me->ourgame->set_size(me->drawing, me->drawstate,
244 me->params, me->tilesize);
248 void midend_size(midend *me, int *x, int *y, int user_size)
254 * We can't set the size on the same drawstate twice. So if
255 * we've already sized one drawstate, we must throw it away and
258 if (me->drawstate && me->tilesize > 0) {
259 me->ourgame->free_drawstate(me->drawing, me->drawstate);
260 me->drawstate = me->ourgame->new_drawstate(me->drawing,
261 me->states[0].state);
265 * Find the tile size that best fits within the given space. If
266 * `user_size' is TRUE, we must actually find the _largest_ such
267 * tile size, in order to get as close to the user's explicit
268 * request as possible; otherwise, we bound above at the game's
269 * preferred tile size, so that the game gets what it wants
270 * provided that this doesn't break the constraint from the
271 * front-end (which is likely to be a screen size or similar).
277 me->ourgame->compute_size(me->params, max, &rx, &ry);
278 } while (rx <= *x && ry <= *y);
280 max = me->preferred_tilesize + 1;
284 * Now binary-search between min and max. We're looking for a
285 * boundary rather than a value: the point at which tile sizes
286 * stop fitting within the given dimensions. Thus, we stop when
287 * max and min differ by exactly 1.
289 while (max - min > 1) {
290 int mid = (max + min) / 2;
291 me->ourgame->compute_size(me->params, mid, &rx, &ry);
292 if (rx <= *x && ry <= *y)
299 * Now `min' is a valid size, and `max' isn't. So use `min'.
304 /* If the user requested a change in size, make it permanent. */
305 me->preferred_tilesize = me->tilesize;
306 midend_size_new_drawstate(me);
311 int midend_tilesize(midend *me) { return me->tilesize; }
313 void midend_set_params(midend *me, game_params *params)
315 me->ourgame->free_params(me->params);
316 me->params = me->ourgame->dup_params(params);
319 game_params *midend_get_params(midend *me)
321 return me->ourgame->dup_params(me->params);
324 static void midend_set_timer(midend *me)
326 me->timing = (me->ourgame->is_timed &&
327 me->ourgame->timing_state(me->states[me->statepos-1].state,
329 if (me->timing || me->flash_time || me->anim_time)
330 activate_timer(me->frontend);
332 deactivate_timer(me->frontend);
335 void midend_force_redraw(midend *me)
338 me->ourgame->free_drawstate(me->drawing, me->drawstate);
339 me->drawstate = me->ourgame->new_drawstate(me->drawing,
340 me->states[0].state);
341 midend_size_new_drawstate(me);
345 void midend_new_game(midend *me)
347 midend_free_game(me);
349 assert(me->nstates == 0);
351 if (me->genmode == GOT_DESC) {
352 me->genmode = GOT_NOTHING;
356 if (me->genmode == GOT_SEED) {
357 me->genmode = GOT_NOTHING;
360 * Generate a new random seed. 15 digits comes to about
361 * 48 bits, which should be more than enough.
363 * I'll avoid putting a leading zero on the number,
364 * just in case it confuses anybody who thinks it's
365 * processed as an integer rather than a string.
370 newseed[0] = '1' + (char)random_upto(me->random, 9);
371 for (i = 1; i < 15; i++)
372 newseed[i] = '0' + (char)random_upto(me->random, 10);
374 me->seedstr = dupstr(newseed);
377 me->ourgame->free_params(me->curparams);
378 me->curparams = me->ourgame->dup_params(me->params);
386 rs = random_new(me->seedstr, strlen(me->seedstr));
388 * If this midend has been instantiated without providing a
389 * drawing API, it is non-interactive. This means that it's
390 * being used for bulk game generation, and hence we should
391 * pass the non-interactive flag to new_desc.
393 me->desc = me->ourgame->new_desc(me->curparams, rs,
394 &me->aux_info, (me->drawing != NULL));
402 * It might seem a bit odd that we're using me->params to
403 * create the initial game state, rather than me->curparams
404 * which is better tailored to this specific game and which we
407 * It's supposed to be an invariant in the midend that
408 * me->params and me->curparams differ in no aspect that is
409 * important after generation (i.e. after new_desc()). By
410 * deliberately passing the _less_ specific of these two
411 * parameter sets, we provoke play-time misbehaviour in the
412 * case where a game has failed to encode a play-time parameter
413 * in the non-full version of encode_params().
415 me->states[me->nstates].state =
416 me->ourgame->new_game(me, me->params, me->desc);
419 * As part of our commitment to self-testing, test the aux
420 * string to make sure nothing ghastly went wrong.
422 if (me->ourgame->can_solve && me->aux_info) {
427 movestr = me->ourgame->solve(me->states[0].state,
430 assert(movestr && !msg);
431 s = me->ourgame->execute_move(me->states[0].state, movestr);
433 me->ourgame->free_game(s);
438 * Soak test, enabled by setting <gamename>_TESTSOLVE in the
439 * environment. This causes an immediate attempt to re-solve the
440 * game without benefit of aux_info. The effect is that (at least
441 * on Unix) you can run 'FOO_TESTSOLVE=1 foo --generate 10000
442 * <params>#12345' and it will generate a lot of game ids and
443 * instantly pass each one back to the solver.
445 * (It's worth putting in an explicit seed in any such test, so
446 * you can repeat it to diagnose a problem if one comes up!)
451 static int doing_test_solve = -1;
452 if (doing_test_solve < 0) {
453 sprintf(buf, "%s_TESTSOLVE", me->ourgame->name);
454 for (j = k = 0; buf[j]; j++)
455 if (!isspace((unsigned char)buf[j]))
456 buf[k++] = toupper((unsigned char)buf[j]);
460 * Since this is used for correctness testing, it's
461 * helpful to have a visual acknowledgment that the
462 * user hasn't mistyped the environment variable name.
464 fprintf(stderr, "Running solver soak tests\n");
465 doing_test_solve = TRUE;
467 doing_test_solve = FALSE;
470 if (doing_test_solve) {
475 movestr = me->ourgame->solve(me->states[0].state,
478 assert(movestr && !msg);
479 s = me->ourgame->execute_move(me->states[0].state, movestr);
481 me->ourgame->free_game(s);
486 me->states[me->nstates].movestr = NULL;
487 me->states[me->nstates].movetype = NEWGAME;
490 me->drawstate = me->ourgame->new_drawstate(me->drawing,
491 me->states[0].state);
492 midend_size_new_drawstate(me);
495 me->ourgame->free_ui(me->ui);
496 me->ui = me->ourgame->new_ui(me->states[0].state);
497 midend_set_timer(me);
498 me->pressed_mouse_button = 0;
501 int midend_can_undo(midend *me)
503 return (me->statepos > 1);
506 int midend_can_redo(midend *me)
508 return (me->statepos < me->nstates);
511 static int midend_undo(midend *me)
513 if (me->statepos > 1) {
515 me->ourgame->changed_state(me->ui,
516 me->states[me->statepos-1].state,
517 me->states[me->statepos-2].state);
525 static int midend_redo(midend *me)
527 if (me->statepos < me->nstates) {
529 me->ourgame->changed_state(me->ui,
530 me->states[me->statepos-1].state,
531 me->states[me->statepos].state);
539 static void midend_finish_move(midend *me)
544 * We do not flash if the later of the two states is special.
545 * This covers both forward Solve moves and backward (undone)
548 if ((me->oldstate || me->statepos > 1) &&
549 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
550 (me->dir < 0 && me->statepos < me->nstates &&
551 !special(me->states[me->statepos].movetype)))) {
552 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
553 me->states[me->statepos-2].state,
554 me->states[me->statepos-1].state,
555 me->oldstate ? me->dir : +1,
558 me->flash_pos = 0.0F;
559 me->flash_time = flashtime;
564 me->ourgame->free_game(me->oldstate);
566 me->anim_pos = me->anim_time = 0;
569 midend_set_timer(me);
572 void midend_stop_anim(midend *me)
574 if (me->oldstate || me->anim_time != 0) {
575 midend_finish_move(me);
580 void midend_restart_game(midend *me)
584 midend_stop_anim(me);
586 assert(me->statepos >= 1);
587 if (me->statepos == 1)
588 return; /* no point doing anything at all! */
591 * During restart, we reconstruct the game from the (public)
592 * game description rather than from states[0], because that
593 * way Mines gets slightly more sensible behaviour (restart
594 * goes to _after_ the first click so you don't have to
595 * remember where you clicked).
597 s = me->ourgame->new_game(me, me->params, me->desc);
600 * Now enter the restarted state as the next move.
602 midend_stop_anim(me);
603 midend_purge_states(me);
605 me->states[me->nstates].state = s;
606 me->states[me->nstates].movestr = dupstr(me->desc);
607 me->states[me->nstates].movetype = RESTART;
608 me->statepos = ++me->nstates;
610 me->ourgame->changed_state(me->ui,
611 me->states[me->statepos-2].state,
612 me->states[me->statepos-1].state);
614 midend_finish_move(me);
616 midend_set_timer(me);
619 static int midend_really_process_key(midend *me, int x, int y, int button)
621 game_state *oldstate =
622 me->ourgame->dup_game(me->states[me->statepos - 1].state);
623 int type = MOVE, gottype = FALSE, ret = 1;
629 me->ourgame->interpret_move(me->states[me->statepos-1].state,
630 me->ui, me->drawstate, x, y, button);
633 if (button == 'n' || button == 'N' || button == '\x0E') {
634 midend_stop_anim(me);
637 goto done; /* never animate */
638 } else if (button == 'u' || button == 'u' ||
639 button == '\x1A' || button == '\x1F') {
640 midend_stop_anim(me);
641 type = me->states[me->statepos-1].movetype;
643 if (!midend_undo(me))
645 } else if (button == 'r' || button == 'R' ||
646 button == '\x12' || button == '\x19') {
647 midend_stop_anim(me);
648 if (!midend_redo(me))
650 } else if (button == '\x13' && me->ourgame->can_solve) {
651 if (midend_solve(me))
653 } else if (button == 'q' || button == 'Q' || button == '\x11') {
660 s = me->states[me->statepos-1].state;
662 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
667 if (s == me->states[me->statepos-1].state) {
669 * make_move() is allowed to return its input state to
670 * indicate that although no move has been made, the UI
671 * state has been updated and a redraw is called for.
674 midend_set_timer(me);
677 midend_stop_anim(me);
678 midend_purge_states(me);
680 assert(movestr != NULL);
681 me->states[me->nstates].state = s;
682 me->states[me->nstates].movestr = movestr;
683 me->states[me->nstates].movetype = MOVE;
684 me->statepos = ++me->nstates;
687 me->ourgame->changed_state(me->ui,
688 me->states[me->statepos-2].state,
689 me->states[me->statepos-1].state);
696 type = me->states[me->statepos-1].movetype;
699 * See if this move requires an animation.
701 if (special(type) && !(type == SOLVE &&
702 (me->ourgame->flags & SOLVE_ANIMATES))) {
705 anim_time = me->ourgame->anim_length(oldstate,
706 me->states[me->statepos-1].state,
710 me->oldstate = oldstate; oldstate = NULL;
712 me->anim_time = anim_time;
715 midend_finish_move(me);
721 midend_set_timer(me);
724 if (oldstate) me->ourgame->free_game(oldstate);
728 int midend_process_key(midend *me, int x, int y, int button)
733 * Harmonise mouse drag and release messages.
735 * Some front ends might accidentally switch from sending, say,
736 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
737 * drag. (This can happen on the Mac, for example, since
738 * RIGHT_DRAG is usually done using Command+drag, and if the
739 * user accidentally releases Command half way through the drag
740 * then there will be trouble.)
742 * It would be an O(number of front ends) annoyance to fix this
743 * in the front ends, but an O(number of back ends) annoyance
744 * to have each game capable of dealing with it. Therefore, we
745 * fix it _here_ in the common midend code so that it only has
748 * The possible ways in which things can go screwy in the front
751 * - in a system containing multiple physical buttons button
752 * presses can inadvertently overlap. We can see ABab (caps
753 * meaning button-down and lowercase meaning button-up) when
754 * the user had semantically intended AaBb.
756 * - in a system where one button is simulated by means of a
757 * modifier key and another button, buttons can mutate
758 * between press and release (possibly during drag). So we
759 * can see Ab instead of Aa.
761 * Definite requirements are:
763 * - button _presses_ must never be invented or destroyed. If
764 * the user presses two buttons in succession, the button
765 * presses must be transferred to the backend unchanged. So
766 * if we see AaBb , that's fine; if we see ABab (the button
767 * presses inadvertently overlapped) we must somehow
768 * `correct' it to AaBb.
770 * - every mouse action must end up looking like a press, zero
771 * or more drags, then a release. This allows back ends to
772 * make the _assumption_ that incoming mouse data will be
773 * sane in this regard, and not worry about the details.
775 * So my policy will be:
777 * - treat any button-up as a button-up for the currently
778 * pressed button, or ignore it if there is no currently
781 * - treat any drag as a drag for the currently pressed
782 * button, or ignore it if there is no currently pressed
785 * - if we see a button-down while another button is currently
786 * pressed, invent a button-up for the first one and then
787 * pass the button-down through as before.
789 * 2005-05-31: An addendum to the above. Some games might want
790 * a `priority order' among buttons, such that if one button is
791 * pressed while another is down then a fixed one of the
792 * buttons takes priority no matter what order they're pressed
793 * in. Mines, in particular, wants to treat a left+right click
794 * like a left click for the benefit of users of other
795 * implementations. So the last of the above points is modified
796 * in the presence of an (optional) button priority order.
798 * A further addition: we translate certain keyboard presses to
799 * cursor key 'select' buttons, so that a) frontends don't have
800 * to translate these themselves (like they do for CURSOR_UP etc),
801 * and b) individual games don't have to hard-code button presses
802 * of '\n' etc for keyboard-based cursors. The choice of buttons
803 * here could eventually be controlled by a runtime configuration
806 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
807 if (me->pressed_mouse_button) {
808 if (IS_MOUSE_DRAG(button)) {
809 button = me->pressed_mouse_button +
810 (LEFT_DRAG - LEFT_BUTTON);
812 button = me->pressed_mouse_button +
813 (LEFT_RELEASE - LEFT_BUTTON);
816 return ret; /* ignore it */
817 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
819 * If the new button has lower priority than the old one,
820 * don't bother doing this.
822 if (me->ourgame->flags &
823 BUTTON_BEATS(me->pressed_mouse_button, button))
824 return ret; /* just ignore it */
827 * Fabricate a button-up for the previously pressed button.
829 ret = ret && midend_really_process_key
830 (me, x, y, (me->pressed_mouse_button +
831 (LEFT_RELEASE - LEFT_BUTTON)));
835 * Translate keyboard presses to cursor selection.
837 if (button == '\n' || button == '\r')
838 button = CURSOR_SELECT;
840 button = CURSOR_SELECT2;
843 * Normalise both backspace characters (8 and 127) to \b. Easier
844 * to do this once, here, than to require all front ends to
845 * carefully generate the same one - now each front end can
846 * generate whichever is easiest.
848 if (button == '\177')
852 * Now send on the event we originally received.
854 ret = ret && midend_really_process_key(me, x, y, button);
857 * And update the currently pressed button.
859 if (IS_MOUSE_RELEASE(button))
860 me->pressed_mouse_button = 0;
861 else if (IS_MOUSE_DOWN(button))
862 me->pressed_mouse_button = button;
867 void midend_redraw(midend *me)
871 if (me->statepos > 0 && me->drawstate) {
872 start_draw(me->drawing);
873 if (me->oldstate && me->anim_time > 0 &&
874 me->anim_pos < me->anim_time) {
875 assert(me->dir != 0);
876 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
877 me->states[me->statepos-1].state, me->dir,
878 me->ui, me->anim_pos, me->flash_pos);
880 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
881 me->states[me->statepos-1].state, +1 /*shrug*/,
882 me->ui, 0.0, me->flash_pos);
884 end_draw(me->drawing);
889 * Nasty hacky function used to implement the --redo option in
890 * gtk.c. Only used for generating the puzzles' icons.
892 void midend_freeze_timer(midend *me, float tprop)
894 me->anim_pos = me->anim_time * tprop;
896 deactivate_timer(me->frontend);
899 void midend_timer(midend *me, float tplus)
901 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
903 me->anim_pos += tplus;
904 if (me->anim_pos >= me->anim_time ||
905 me->anim_time == 0 || !me->oldstate) {
906 if (me->anim_time > 0)
907 midend_finish_move(me);
910 me->flash_pos += tplus;
911 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
912 me->flash_pos = me->flash_time = 0;
919 float oldelapsed = me->elapsed;
920 me->elapsed += tplus;
921 if ((int)oldelapsed != (int)me->elapsed)
922 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
925 midend_set_timer(me);
928 float *midend_colours(midend *me, int *ncolours)
932 ret = me->ourgame->colours(me->frontend, ncolours);
938 * Allow environment-based overrides for the standard
939 * colours by defining variables along the lines of
940 * `NET_COLOUR_4=6000c0'.
943 for (i = 0; i < *ncolours; i++) {
945 unsigned int r, g, b;
948 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
949 for (j = k = 0; buf[j]; j++)
950 if (!isspace((unsigned char)buf[j]))
951 buf[k++] = toupper((unsigned char)buf[j]);
953 if ((e = getenv(buf)) != NULL &&
954 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
955 ret[i*3 + 0] = r / 255.0F;
956 ret[i*3 + 1] = g / 255.0F;
957 ret[i*3 + 2] = b / 255.0F;
965 int midend_num_presets(midend *me)
971 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
972 if (me->presetsize <= me->npresets) {
973 me->presetsize = me->npresets + 10;
974 me->presets = sresize(me->presets, me->presetsize,
976 me->preset_names = sresize(me->preset_names, me->presetsize,
978 me->preset_encodings = sresize(me->preset_encodings,
979 me->presetsize, char *);
982 me->presets[me->npresets] = preset;
983 me->preset_names[me->npresets] = name;
984 me->preset_encodings[me->npresets] =
985 me->ourgame->encode_params(preset, TRUE);;
992 * Allow environment-based extensions to the preset list by
993 * defining a variable along the lines of `SOLO_PRESETS=2x3
994 * Advanced:2x3da'. Colon-separated list of items,
995 * alternating between textual titles in the menu and
996 * encoded parameter strings.
998 char buf[80], *e, *p;
1001 sprintf(buf, "%s_PRESETS", me->ourgame->name);
1002 for (j = k = 0; buf[j]; j++)
1003 if (!isspace((unsigned char)buf[j]))
1004 buf[k++] = toupper((unsigned char)buf[j]);
1007 if ((e = getenv(buf)) != NULL) {
1012 game_params *preset;
1015 while (*p && *p != ':') p++;
1016 if (*p) *p++ = '\0';
1018 while (*p && *p != ':') p++;
1019 if (*p) *p++ = '\0';
1021 preset = me->ourgame->default_params();
1022 me->ourgame->decode_params(preset, val);
1024 if (me->ourgame->validate_params(preset, TRUE)) {
1025 /* Drop this one from the list. */
1026 me->ourgame->free_params(preset);
1030 if (me->presetsize <= me->npresets) {
1031 me->presetsize = me->npresets + 10;
1032 me->presets = sresize(me->presets, me->presetsize,
1034 me->preset_names = sresize(me->preset_names,
1035 me->presetsize, char *);
1036 me->preset_encodings = sresize(me->preset_encodings,
1037 me->presetsize, char *);
1040 me->presets[me->npresets] = preset;
1041 me->preset_names[me->npresets] = dupstr(name);
1042 me->preset_encodings[me->npresets] =
1043 me->ourgame->encode_params(preset, TRUE);
1050 return me->npresets;
1053 void midend_fetch_preset(midend *me, int n,
1054 char **name, game_params **params)
1056 assert(n >= 0 && n < me->npresets);
1057 *name = me->preset_names[n];
1058 *params = me->presets[n];
1061 int midend_which_preset(midend *me)
1063 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1067 for (i = 0; i < me->npresets; i++)
1068 if (!strcmp(encoding, me->preset_encodings[i])) {
1077 int midend_wants_statusbar(midend *me)
1079 return me->ourgame->wants_statusbar;
1082 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1085 sfree(me->privdesc);
1086 me->desc = dupstr(desc);
1087 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1090 config_item *midend_get_config(midend *me, int which, char **wintitle)
1092 char *titlebuf, *parstr, *rest;
1097 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1101 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1102 *wintitle = titlebuf;
1103 return me->ourgame->configure(me->params);
1106 if (!me->curparams) {
1110 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1111 which == CFG_SEED ? "random" : "game");
1112 *wintitle = titlebuf;
1114 ret = snewn(2, config_item);
1116 ret[0].type = C_STRING;
1117 if (which == CFG_SEED)
1118 ret[0].name = "Game random seed";
1120 ret[0].name = "Game ID";
1123 * For CFG_DESC the text going in here will be a string
1124 * encoding of the restricted parameters, plus a colon,
1125 * plus the game description. For CFG_SEED it will be the
1126 * full parameters, plus a hash, plus the random seed data.
1127 * Either of these is a valid full game ID (although only
1128 * the former is likely to persist across many code
1131 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1133 if (which == CFG_DESC) {
1134 rest = me->desc ? me->desc : "";
1137 rest = me->seedstr ? me->seedstr : "";
1140 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1141 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1144 ret[1].type = C_END;
1145 ret[1].name = ret[1].sval = NULL;
1151 assert(!"We shouldn't be here");
1155 static char *midend_game_id_int(midend *me, char *id, int defmode)
1157 char *error, *par, *desc, *seed;
1158 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1161 seed = strchr(id, '#');
1162 desc = strchr(id, ':');
1164 if (desc && (!seed || desc < seed)) {
1166 * We have a colon separating parameters from game
1167 * description. So `par' now points to the parameters
1168 * string, and `desc' to the description string.
1173 } else if (seed && (!desc || seed < desc)) {
1175 * We have a hash separating parameters from random seed.
1176 * So `par' now points to the parameters string, and `seed'
1177 * to the seed string.
1184 * We only have one string. Depending on `defmode', we take
1185 * it to be either parameters, seed or description.
1187 if (defmode == DEF_SEED) {
1190 } else if (defmode == DEF_DESC) {
1200 * We must be reasonably careful here not to modify anything in
1201 * `me' until we have finished validating things. This function
1202 * must either return an error and do nothing to the midend, or
1203 * return success and do everything; nothing in between is
1206 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1209 newcurparams = me->ourgame->dup_params(me->params);
1210 me->ourgame->decode_params(newcurparams, par);
1211 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1213 me->ourgame->free_params(newcurparams);
1216 oldparams1 = me->curparams;
1219 * Now filter only the persistent parts of this state into
1220 * the long-term params structure, unless we've _only_
1221 * received a params string in which case the whole lot is
1224 oldparams2 = me->params;
1228 newparams = me->ourgame->dup_params(me->params);
1230 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1231 me->ourgame->decode_params(newparams, tmpstr);
1235 newparams = me->ourgame->dup_params(newcurparams);
1239 newcurparams = me->curparams;
1240 newparams = me->params;
1241 free_params = FALSE;
1245 error = me->ourgame->validate_desc(newparams, desc);
1249 me->ourgame->free_params(newcurparams);
1251 me->ourgame->free_params(newparams);
1258 * Now we've got past all possible error points. Update the
1261 me->params = newparams;
1262 me->curparams = newcurparams;
1264 me->ourgame->free_params(oldparams1);
1266 me->ourgame->free_params(oldparams2);
1269 sfree(me->privdesc);
1270 me->desc = me->privdesc = NULL;
1275 me->desc = dupstr(desc);
1276 me->genmode = GOT_DESC;
1277 sfree(me->aux_info);
1278 me->aux_info = NULL;
1282 me->seedstr = dupstr(seed);
1283 me->genmode = GOT_SEED;
1289 char *midend_game_id(midend *me, char *id)
1291 return midend_game_id_int(me, id, DEF_PARAMS);
1294 char *midend_get_game_id(midend *me)
1298 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1301 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1302 sprintf(ret, "%s:%s", parstr, me->desc);
1307 char *midend_get_random_seed(midend *me)
1314 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1316 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1317 sprintf(ret, "%s#%s", parstr, me->seedstr);
1322 char *midend_set_config(midend *me, int which, config_item *cfg)
1325 game_params *params;
1329 params = me->ourgame->custom_params(cfg);
1330 error = me->ourgame->validate_params(params, TRUE);
1333 me->ourgame->free_params(params);
1337 me->ourgame->free_params(me->params);
1338 me->params = params;
1343 error = midend_game_id_int(me, cfg[0].sval,
1344 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1353 int midend_can_format_as_text_now(midend *me)
1355 if (me->ourgame->can_format_as_text_ever)
1356 return me->ourgame->can_format_as_text_now(me->params);
1361 char *midend_text_format(midend *me)
1363 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1364 me->ourgame->can_format_as_text_now(me->params))
1365 return me->ourgame->text_format(me->states[me->statepos-1].state);
1370 char *midend_solve(midend *me)
1373 char *msg, *movestr;
1375 if (!me->ourgame->can_solve)
1376 return "This game does not support the Solve operation";
1378 if (me->statepos < 1)
1379 return "No game set up to solve"; /* _shouldn't_ happen! */
1382 movestr = me->ourgame->solve(me->states[0].state,
1383 me->states[me->statepos-1].state,
1384 me->aux_info, &msg);
1387 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1390 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1394 * Now enter the solved state as the next move.
1396 midend_stop_anim(me);
1397 midend_purge_states(me);
1399 me->states[me->nstates].state = s;
1400 me->states[me->nstates].movestr = movestr;
1401 me->states[me->nstates].movetype = SOLVE;
1402 me->statepos = ++me->nstates;
1404 me->ourgame->changed_state(me->ui,
1405 me->states[me->statepos-2].state,
1406 me->states[me->statepos-1].state);
1408 if (me->ourgame->flags & SOLVE_ANIMATES) {
1409 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1411 me->ourgame->anim_length(me->states[me->statepos-2].state,
1412 me->states[me->statepos-1].state,
1416 me->anim_time = 0.0;
1417 midend_finish_move(me);
1421 midend_set_timer(me);
1425 int midend_status(midend *me)
1428 * We should probably never be called when the state stack has no
1429 * states on it at all - ideally, midends should never be left in
1430 * that state for long enough to get put down and forgotten about.
1431 * But if we are, I think we return _true_ - pedantically speaking
1432 * a midend in that state is 'vacuously solved', and more
1433 * practically, a user whose midend has been left in that state
1434 * probably _does_ want the 'new game' option to be prominent.
1436 if (me->statepos == 0)
1439 return me->ourgame->status(me->states[me->statepos-1].state);
1442 char *midend_rewrite_statusbar(midend *me, char *text)
1445 * An important special case is that we are occasionally called
1446 * with our own laststatus, to update the timer.
1448 if (me->laststatus != text) {
1449 sfree(me->laststatus);
1450 me->laststatus = dupstr(text);
1453 if (me->ourgame->is_timed) {
1454 char timebuf[100], *ret;
1457 sec = (int)me->elapsed;
1460 sprintf(timebuf, "[%d:%02d] ", min, sec);
1462 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1463 strcpy(ret, timebuf);
1468 return dupstr(text);
1472 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1473 #define SERIALISE_VERSION "1"
1475 void midend_serialise(midend *me,
1476 void (*write)(void *ctx, void *buf, int len),
1482 * Each line of the save file contains three components. First
1483 * exactly 8 characters of header word indicating what type of
1484 * data is contained on the line; then a colon followed by a
1485 * decimal integer giving the length of the main string on the
1486 * line; then a colon followed by the string itself (exactly as
1487 * many bytes as previously specified, no matter what they
1488 * contain). Then a newline (of reasonably flexible form).
1490 #define wr(h,s) do { \
1493 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1494 write(wctx, hbuf, strlen(hbuf)); \
1495 write(wctx, str, strlen(str)); \
1496 write(wctx, "\n", 1); \
1500 * Magic string identifying the file, and version number of the
1503 wr("SAVEFILE", SERIALISE_MAGIC);
1504 wr("VERSION", SERIALISE_VERSION);
1507 * The game name. (Copied locally to avoid const annoyance.)
1510 char *s = dupstr(me->ourgame->name);
1516 * The current long-term parameters structure, in full.
1519 char *s = me->ourgame->encode_params(me->params, TRUE);
1525 * The current short-term parameters structure, in full.
1527 if (me->curparams) {
1528 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1534 * The current game description, the privdesc, and the random seed.
1537 wr("SEED", me->seedstr);
1539 wr("DESC", me->desc);
1541 wr("PRIVDESC", me->privdesc);
1544 * The game's aux_info. We obfuscate this to prevent spoilers
1545 * (people are likely to run `head' or similar on a saved game
1546 * file simply to find out what it is, and don't necessarily
1547 * want to be told the answer to the puzzle!)
1554 len = strlen(me->aux_info);
1555 s1 = snewn(len, unsigned char);
1556 memcpy(s1, me->aux_info, len);
1557 obfuscate_bitmap(s1, len*8, FALSE);
1558 s2 = bin2hex(s1, len);
1567 * Any required serialisation of the game_ui.
1570 char *s = me->ourgame->encode_ui(me->ui);
1578 * The game time, if it's a timed game.
1580 if (me->ourgame->is_timed) {
1582 sprintf(buf, "%g", me->elapsed);
1587 * The length of, and position in, the states list.
1591 sprintf(buf, "%d", me->nstates);
1593 sprintf(buf, "%d", me->statepos);
1594 wr("STATEPOS", buf);
1598 * For each state after the initial one (which we know is
1599 * constructed from either privdesc or desc), enough
1600 * information for execute_move() to reconstruct it from the
1603 for (i = 1; i < me->nstates; i++) {
1604 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1605 switch (me->states[i].movetype) {
1607 wr("MOVE", me->states[i].movestr);
1610 wr("SOLVE", me->states[i].movestr);
1613 wr("RESTART", me->states[i].movestr);
1622 * This function returns NULL on success, or an error message.
1624 char *midend_deserialise(midend *me,
1625 int (*read)(void *ctx, void *buf, int len),
1628 int nstates = 0, statepos = -1, gotstates = 0;
1629 int started = FALSE;
1633 /* Initially all errors give the same report */
1634 char *ret = "Data does not appear to be a saved game file";
1637 * We construct all the new state in local variables while we
1638 * check its sanity. Only once we have finished reading the
1639 * serialised data and detected no errors at all do we start
1640 * modifying stuff in the midend passed in.
1642 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1643 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1644 float elapsed = 0.0F;
1645 game_params *params = NULL, *cparams = NULL;
1647 struct midend_state_entry *states = NULL;
1650 * Loop round and round reading one key/value pair at a time
1651 * from the serialised stream, until we have enough game states
1654 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1659 if (!read(rctx, key, 1)) {
1660 /* unexpected EOF */
1663 } while (key[0] == '\r' || key[0] == '\n');
1665 if (!read(rctx, key+1, 8)) {
1666 /* unexpected EOF */
1670 if (key[8] != ':') {
1672 ret = "Data was incorrectly formatted for a saved game file";
1675 len = strcspn(key, ": ");
1681 if (!read(rctx, &c, 1)) {
1682 /* unexpected EOF */
1688 } else if (c >= '0' && c <= '9') {
1689 len = (len * 10) + (c - '0');
1692 ret = "Data was incorrectly formatted for a"
1698 val = snewn(len+1, char);
1699 if (!read(rctx, val, len)) {
1706 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1707 /* ret already has the right message in it */
1710 /* Now most errors are this one, unless otherwise specified */
1711 ret = "Saved data ended unexpectedly";
1714 if (!strcmp(key, "VERSION")) {
1715 if (strcmp(val, SERIALISE_VERSION)) {
1716 ret = "Cannot handle this version of the saved game"
1720 } else if (!strcmp(key, "GAME")) {
1721 if (strcmp(val, me->ourgame->name)) {
1722 ret = "Save file is from a different game";
1725 } else if (!strcmp(key, "PARAMS")) {
1729 } else if (!strcmp(key, "CPARAMS")) {
1733 } else if (!strcmp(key, "SEED")) {
1737 } else if (!strcmp(key, "DESC")) {
1741 } else if (!strcmp(key, "PRIVDESC")) {
1745 } else if (!strcmp(key, "AUXINFO")) {
1747 int len = strlen(val) / 2; /* length in bytes */
1748 tmp = hex2bin(val, len);
1749 obfuscate_bitmap(tmp, len*8, TRUE);
1752 auxinfo = snewn(len + 1, char);
1753 memcpy(auxinfo, tmp, len);
1754 auxinfo[len] = '\0';
1756 } else if (!strcmp(key, "UI")) {
1760 } else if (!strcmp(key, "TIME")) {
1761 elapsed = (float)atof(val);
1762 } else if (!strcmp(key, "NSTATES")) {
1763 nstates = atoi(val);
1765 ret = "Number of states in save file was negative";
1769 ret = "Two state counts provided in save file";
1772 states = snewn(nstates, struct midend_state_entry);
1773 for (i = 0; i < nstates; i++) {
1774 states[i].state = NULL;
1775 states[i].movestr = NULL;
1776 states[i].movetype = NEWGAME;
1778 } else if (!strcmp(key, "STATEPOS")) {
1779 statepos = atoi(val);
1780 } else if (!strcmp(key, "MOVE")) {
1782 states[gotstates].movetype = MOVE;
1783 states[gotstates].movestr = val;
1785 } else if (!strcmp(key, "SOLVE")) {
1787 states[gotstates].movetype = SOLVE;
1788 states[gotstates].movestr = val;
1790 } else if (!strcmp(key, "RESTART")) {
1792 states[gotstates].movetype = RESTART;
1793 states[gotstates].movestr = val;
1802 params = me->ourgame->default_params();
1803 me->ourgame->decode_params(params, parstr);
1804 if (me->ourgame->validate_params(params, TRUE)) {
1805 ret = "Long-term parameters in save file are invalid";
1808 cparams = me->ourgame->default_params();
1809 me->ourgame->decode_params(cparams, cparstr);
1810 if (me->ourgame->validate_params(cparams, FALSE)) {
1811 ret = "Short-term parameters in save file are invalid";
1814 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1816 * The seed's no use with this version, but we can perfectly
1817 * well use the rest of the data.
1823 ret = "Game description in save file is missing";
1825 } else if (me->ourgame->validate_desc(params, desc)) {
1826 ret = "Game description in save file is invalid";
1829 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1830 ret = "Game private description in save file is invalid";
1833 if (statepos < 0 || statepos >= nstates) {
1834 ret = "Game position in save file is out of range";
1837 states[0].state = me->ourgame->new_game(me, params,
1838 privdesc ? privdesc : desc);
1839 for (i = 1; i < nstates; i++) {
1840 assert(states[i].movetype != NEWGAME);
1841 switch (states[i].movetype) {
1844 states[i].state = me->ourgame->execute_move(states[i-1].state,
1846 if (states[i].state == NULL) {
1847 ret = "Save file contained an invalid move";
1852 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1853 ret = "Save file contained an invalid restart move";
1856 states[i].state = me->ourgame->new_game(me, params,
1862 ui = me->ourgame->new_ui(states[0].state);
1863 me->ourgame->decode_ui(ui, uistr);
1866 * Now we've run out of possible error conditions, so we're
1867 * ready to start overwriting the real data in the current
1868 * midend. We'll do this by swapping things with the local
1869 * variables, so that the same cleanup code will free the old
1880 me->privdesc = privdesc;
1888 me->aux_info = auxinfo;
1892 me->genmode = GOT_NOTHING;
1894 me->statesize = nstates;
1895 nstates = me->nstates;
1896 me->nstates = me->statesize;
1898 struct midend_state_entry *tmp;
1900 me->states = states;
1903 me->statepos = statepos;
1909 me->params = params;
1912 tmp = me->curparams;
1913 me->curparams = cparams;
1917 me->oldstate = NULL;
1918 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1929 me->elapsed = elapsed;
1930 me->pressed_mouse_button = 0;
1932 midend_set_timer(me);
1935 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1937 me->ourgame->new_drawstate(me->drawing,
1938 me->states[me->statepos-1].state);
1939 midend_size_new_drawstate(me);
1941 ret = NULL; /* success! */
1953 me->ourgame->free_params(params);
1955 me->ourgame->free_params(cparams);
1957 me->ourgame->free_ui(ui);
1961 for (i = 0; i < nstates; i++) {
1962 if (states[i].state)
1963 me->ourgame->free_game(states[i].state);
1964 sfree(states[i].movestr);
1973 * This function examines a saved game file just far enough to
1974 * determine which game type it contains. It returns NULL on success
1975 * and the game name string in 'name' (which will be dynamically
1976 * allocated and should be caller-freed), or an error message on
1979 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
1982 int nstates = 0, statepos = -1, gotstates = 0;
1983 int started = FALSE;
1986 /* Initially all errors give the same report */
1987 char *ret = "Data does not appear to be a saved game file";
1992 * Loop round and round reading one key/value pair at a time from
1993 * the serialised stream, until we've found the game name.
1995 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2000 if (!read(rctx, key, 1)) {
2001 /* unexpected EOF */
2004 } while (key[0] == '\r' || key[0] == '\n');
2006 if (!read(rctx, key+1, 8)) {
2007 /* unexpected EOF */
2011 if (key[8] != ':') {
2013 ret = "Data was incorrectly formatted for a saved game file";
2016 len = strcspn(key, ": ");
2022 if (!read(rctx, &c, 1)) {
2023 /* unexpected EOF */
2029 } else if (c >= '0' && c <= '9') {
2030 len = (len * 10) + (c - '0');
2033 ret = "Data was incorrectly formatted for a"
2039 val = snewn(len+1, char);
2040 if (!read(rctx, val, len)) {
2047 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2048 /* ret already has the right message in it */
2051 /* Now most errors are this one, unless otherwise specified */
2052 ret = "Saved data ended unexpectedly";
2055 if (!strcmp(key, "VERSION")) {
2056 if (strcmp(val, SERIALISE_VERSION)) {
2057 ret = "Cannot handle this version of the saved game"
2061 } else if (!strcmp(key, "GAME")) {
2062 *name = dupstr(val);
2077 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2079 game_state *soln = NULL;
2081 if (me->statepos < 1)
2082 return "No game set up to print";/* _shouldn't_ happen! */
2085 char *msg, *movestr;
2087 if (!me->ourgame->can_solve)
2088 return "This game does not support the Solve operation";
2090 msg = "Solve operation failed";/* game _should_ overwrite on error */
2091 movestr = me->ourgame->solve(me->states[0].state,
2092 me->states[me->statepos-1].state,
2093 me->aux_info, &msg);
2096 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2105 * This call passes over ownership of the two game_states and
2106 * the game_params. Hence we duplicate the ones we want to
2107 * keep, and we don't have to bother freeing soln if it was
2110 document_add_puzzle(doc, me->ourgame,
2111 me->ourgame->dup_params(me->curparams),
2112 me->ourgame->dup_game(me->states[0].state), soln);