2 * midend.c: general middle fragment sitting between the
3 * platform-specific front end and game-specific back end.
4 * Maintains a move list, takes care of Undo and Redo commands, and
5 * processes standard keystrokes for undo/redo/new/quit.
16 enum { DEF_PARAMS, DEF_SEED, DEF_DESC }; /* for midend_game_id_int */
18 enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
20 #define special(type) ( (type) != MOVE )
22 struct midend_state_entry {
33 game_params **presets;
34 char **preset_names, **preset_encodings;
35 int npresets, presetsize;
38 * `desc' and `privdesc' deserve a comment.
40 * `desc' is the game description as presented to the user when
41 * they ask for Game -> Specific. `privdesc', if non-NULL, is a
42 * different game description used to reconstruct the initial
43 * game_state when de-serialising. If privdesc is NULL, `desc'
46 * For almost all games, `privdesc' is NULL and never used. The
47 * exception (as usual) is Mines: the initial game state has no
48 * squares open at all, but after the first click `desc' is
49 * rewritten to describe a game state with an initial click and
50 * thus a bunch of squares open. If we used that desc to
51 * serialise and deserialise, then the initial game state after
52 * deserialisation would look unlike the initial game state
53 * beforehand, and worse still execute_move() might fail on the
54 * attempted first click. So `privdesc' is also used in this
55 * case, to provide a game description describing the same
56 * fixed mine layout _but_ no initial click. (These game IDs
57 * may also be typed directly into Mines if you like.)
59 char *desc, *privdesc, *seedstr;
61 enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
63 int nstates, statesize, statepos;
64 struct midend_state_entry *states;
66 game_params *params, *curparams;
67 game_drawstate *drawstate;
71 float anim_time, anim_pos;
72 float flash_time, flash_pos;
81 int pressed_mouse_button;
83 int preferred_tilesize, tilesize, winwidth, winheight;
85 void (*game_id_change_notify_function)(void *);
86 void *game_id_change_notify_ctx;
89 #define ensure(me) do { \
90 if ((me)->nstates >= (me)->statesize) { \
91 (me)->statesize = (me)->nstates + 128; \
92 (me)->states = sresize((me)->states, (me)->statesize, \
93 struct midend_state_entry); \
97 void midend_reset_tilesize(midend *me)
99 me->preferred_tilesize = me->ourgame->preferred_tilesize;
102 * Allow an environment-based override for the default tile
103 * size by defining a variable along the lines of
110 sprintf(buf, "%s_TILESIZE", me->ourgame->name);
111 for (j = k = 0; buf[j]; j++)
112 if (!isspace((unsigned char)buf[j]))
113 buf[k++] = toupper((unsigned char)buf[j]);
115 if ((e = getenv(buf)) != NULL && sscanf(e, "%d", &ts) == 1 && ts > 0)
116 me->preferred_tilesize = ts;
120 midend *midend_new(frontend *fe, const game *ourgame,
121 const drawing_api *drapi, void *drhandle)
123 midend *me = snew(midend);
127 get_random_seed(&randseed, &randseedsize);
130 me->ourgame = ourgame;
131 me->random = random_new(randseed, randseedsize);
132 me->nstates = me->statesize = me->statepos = 0;
134 me->params = ourgame->default_params();
135 me->game_id_change_notify_function = NULL;
136 me->game_id_change_notify_ctx = NULL;
139 * Allow environment-based changing of the default settings by
140 * defining a variable along the lines of `NET_DEFAULT=25x25w'
141 * in which the value is an encoded parameter string.
146 sprintf(buf, "%s_DEFAULT", me->ourgame->name);
147 for (j = k = 0; buf[j]; j++)
148 if (!isspace((unsigned char)buf[j]))
149 buf[k++] = toupper((unsigned char)buf[j]);
151 if ((e = getenv(buf)) != NULL)
152 me->ourgame->decode_params(me->params, e);
154 me->curparams = NULL;
155 me->desc = me->privdesc = NULL;
158 me->genmode = GOT_NOTHING;
159 me->drawstate = NULL;
162 me->preset_names = NULL;
163 me->preset_encodings = NULL;
164 me->npresets = me->presetsize = 0;
165 me->anim_time = me->anim_pos = 0.0F;
166 me->flash_time = me->flash_pos = 0.0F;
169 me->pressed_mouse_button = 0;
170 me->laststatus = NULL;
173 me->tilesize = me->winwidth = me->winheight = 0;
175 me->drawing = drawing_new(drapi, me, drhandle);
179 midend_reset_tilesize(me);
186 const game *midend_which_game(midend *me)
191 static void midend_purge_states(midend *me)
193 while (me->nstates > me->statepos) {
194 me->ourgame->free_game(me->states[--me->nstates].state);
195 if (me->states[me->nstates].movestr)
196 sfree(me->states[me->nstates].movestr);
200 static void midend_free_game(midend *me)
202 while (me->nstates > 0) {
204 me->ourgame->free_game(me->states[me->nstates].state);
205 sfree(me->states[me->nstates].movestr);
209 me->ourgame->free_drawstate(me->drawing, me->drawstate);
212 void midend_free(midend *me)
216 midend_free_game(me);
219 drawing_free(me->drawing);
220 random_free(me->random);
226 me->ourgame->free_params(me->params);
228 for (i = 0; i < me->npresets; i++) {
229 sfree(me->presets[i]);
230 sfree(me->preset_names[i]);
231 sfree(me->preset_encodings[i]);
234 sfree(me->preset_names);
235 sfree(me->preset_encodings);
238 me->ourgame->free_ui(me->ui);
240 me->ourgame->free_params(me->curparams);
241 sfree(me->laststatus);
245 static void midend_size_new_drawstate(midend *me)
248 * Don't even bother, if we haven't worked out our tile size
251 if (me->tilesize > 0) {
252 me->ourgame->compute_size(me->params, me->tilesize,
253 &me->winwidth, &me->winheight);
254 me->ourgame->set_size(me->drawing, me->drawstate,
255 me->params, me->tilesize);
259 void midend_size(midend *me, int *x, int *y, int user_size)
265 * We can't set the size on the same drawstate twice. So if
266 * we've already sized one drawstate, we must throw it away and
269 if (me->drawstate && me->tilesize > 0) {
270 me->ourgame->free_drawstate(me->drawing, me->drawstate);
271 me->drawstate = me->ourgame->new_drawstate(me->drawing,
272 me->states[0].state);
276 * Find the tile size that best fits within the given space. If
277 * `user_size' is TRUE, we must actually find the _largest_ such
278 * tile size, in order to get as close to the user's explicit
279 * request as possible; otherwise, we bound above at the game's
280 * preferred tile size, so that the game gets what it wants
281 * provided that this doesn't break the constraint from the
282 * front-end (which is likely to be a screen size or similar).
288 me->ourgame->compute_size(me->params, max, &rx, &ry);
289 } while (rx <= *x && ry <= *y);
291 max = me->preferred_tilesize + 1;
295 * Now binary-search between min and max. We're looking for a
296 * boundary rather than a value: the point at which tile sizes
297 * stop fitting within the given dimensions. Thus, we stop when
298 * max and min differ by exactly 1.
300 while (max - min > 1) {
301 int mid = (max + min) / 2;
302 me->ourgame->compute_size(me->params, mid, &rx, &ry);
303 if (rx <= *x && ry <= *y)
310 * Now `min' is a valid size, and `max' isn't. So use `min'.
315 /* If the user requested a change in size, make it permanent. */
316 me->preferred_tilesize = me->tilesize;
317 midend_size_new_drawstate(me);
322 int midend_tilesize(midend *me) { return me->tilesize; }
324 void midend_set_params(midend *me, game_params *params)
326 me->ourgame->free_params(me->params);
327 me->params = me->ourgame->dup_params(params);
330 game_params *midend_get_params(midend *me)
332 return me->ourgame->dup_params(me->params);
335 static void midend_set_timer(midend *me)
337 me->timing = (me->ourgame->is_timed &&
338 me->ourgame->timing_state(me->states[me->statepos-1].state,
340 if (me->timing || me->flash_time || me->anim_time)
341 activate_timer(me->frontend);
343 deactivate_timer(me->frontend);
346 void midend_force_redraw(midend *me)
349 me->ourgame->free_drawstate(me->drawing, me->drawstate);
350 me->drawstate = me->ourgame->new_drawstate(me->drawing,
351 me->states[0].state);
352 midend_size_new_drawstate(me);
356 void midend_new_game(midend *me)
358 midend_stop_anim(me);
359 midend_free_game(me);
361 assert(me->nstates == 0);
363 if (me->genmode == GOT_DESC) {
364 me->genmode = GOT_NOTHING;
368 if (me->genmode == GOT_SEED) {
369 me->genmode = GOT_NOTHING;
372 * Generate a new random seed. 15 digits comes to about
373 * 48 bits, which should be more than enough.
375 * I'll avoid putting a leading zero on the number,
376 * just in case it confuses anybody who thinks it's
377 * processed as an integer rather than a string.
382 newseed[0] = '1' + (char)random_upto(me->random, 9);
383 for (i = 1; i < 15; i++)
384 newseed[i] = '0' + (char)random_upto(me->random, 10);
386 me->seedstr = dupstr(newseed);
389 me->ourgame->free_params(me->curparams);
390 me->curparams = me->ourgame->dup_params(me->params);
398 rs = random_new(me->seedstr, strlen(me->seedstr));
400 * If this midend has been instantiated without providing a
401 * drawing API, it is non-interactive. This means that it's
402 * being used for bulk game generation, and hence we should
403 * pass the non-interactive flag to new_desc.
405 me->desc = me->ourgame->new_desc(me->curparams, rs,
406 &me->aux_info, (me->drawing != NULL));
414 * It might seem a bit odd that we're using me->params to
415 * create the initial game state, rather than me->curparams
416 * which is better tailored to this specific game and which we
419 * It's supposed to be an invariant in the midend that
420 * me->params and me->curparams differ in no aspect that is
421 * important after generation (i.e. after new_desc()). By
422 * deliberately passing the _less_ specific of these two
423 * parameter sets, we provoke play-time misbehaviour in the
424 * case where a game has failed to encode a play-time parameter
425 * in the non-full version of encode_params().
427 me->states[me->nstates].state =
428 me->ourgame->new_game(me, me->params, me->desc);
431 * As part of our commitment to self-testing, test the aux
432 * string to make sure nothing ghastly went wrong.
434 if (me->ourgame->can_solve && me->aux_info) {
439 movestr = me->ourgame->solve(me->states[0].state,
442 assert(movestr && !msg);
443 s = me->ourgame->execute_move(me->states[0].state, movestr);
445 me->ourgame->free_game(s);
449 me->states[me->nstates].movestr = NULL;
450 me->states[me->nstates].movetype = NEWGAME;
453 me->drawstate = me->ourgame->new_drawstate(me->drawing,
454 me->states[0].state);
455 midend_size_new_drawstate(me);
458 me->ourgame->free_ui(me->ui);
459 me->ui = me->ourgame->new_ui(me->states[0].state);
460 midend_set_timer(me);
461 me->pressed_mouse_button = 0;
463 if (me->game_id_change_notify_function)
464 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
467 int midend_can_undo(midend *me)
469 return (me->statepos > 1);
472 int midend_can_redo(midend *me)
474 return (me->statepos < me->nstates);
477 static int midend_undo(midend *me)
479 if (me->statepos > 1) {
481 me->ourgame->changed_state(me->ui,
482 me->states[me->statepos-1].state,
483 me->states[me->statepos-2].state);
491 static int midend_redo(midend *me)
493 if (me->statepos < me->nstates) {
495 me->ourgame->changed_state(me->ui,
496 me->states[me->statepos-1].state,
497 me->states[me->statepos].state);
505 static void midend_finish_move(midend *me)
510 * We do not flash if the later of the two states is special.
511 * This covers both forward Solve moves and backward (undone)
514 if ((me->oldstate || me->statepos > 1) &&
515 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
516 (me->dir < 0 && me->statepos < me->nstates &&
517 !special(me->states[me->statepos].movetype)))) {
518 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
519 me->states[me->statepos-2].state,
520 me->states[me->statepos-1].state,
521 me->oldstate ? me->dir : +1,
524 me->flash_pos = 0.0F;
525 me->flash_time = flashtime;
530 me->ourgame->free_game(me->oldstate);
532 me->anim_pos = me->anim_time = 0;
535 midend_set_timer(me);
538 void midend_stop_anim(midend *me)
540 if (me->oldstate || me->anim_time != 0) {
541 midend_finish_move(me);
546 void midend_restart_game(midend *me)
550 assert(me->statepos >= 1);
551 if (me->statepos == 1)
552 return; /* no point doing anything at all! */
555 * During restart, we reconstruct the game from the (public)
556 * game description rather than from states[0], because that
557 * way Mines gets slightly more sensible behaviour (restart
558 * goes to _after_ the first click so you don't have to
559 * remember where you clicked).
561 s = me->ourgame->new_game(me, me->params, me->desc);
564 * Now enter the restarted state as the next move.
566 midend_stop_anim(me);
567 midend_purge_states(me);
569 me->states[me->nstates].state = s;
570 me->states[me->nstates].movestr = dupstr(me->desc);
571 me->states[me->nstates].movetype = RESTART;
572 me->statepos = ++me->nstates;
574 me->ourgame->changed_state(me->ui,
575 me->states[me->statepos-2].state,
576 me->states[me->statepos-1].state);
577 midend_finish_move(me);
579 midend_set_timer(me);
582 static int midend_really_process_key(midend *me, int x, int y, int button)
584 game_state *oldstate =
585 me->ourgame->dup_game(me->states[me->statepos - 1].state);
586 int type = MOVE, gottype = FALSE, ret = 1;
592 me->ourgame->interpret_move(me->states[me->statepos-1].state,
593 me->ui, me->drawstate, x, y, button);
596 if (button == 'n' || button == 'N' || button == '\x0E') {
599 goto done; /* never animate */
600 } else if (button == 'u' || button == 'U' ||
601 button == '\x1A' || button == '\x1F') {
602 midend_stop_anim(me);
603 type = me->states[me->statepos-1].movetype;
605 if (!midend_undo(me))
607 } else if (button == 'r' || button == 'R' ||
608 button == '\x12' || button == '\x19') {
609 midend_stop_anim(me);
610 if (!midend_redo(me))
612 } else if (button == '\x13' && me->ourgame->can_solve) {
613 if (midend_solve(me))
615 } else if (button == 'q' || button == 'Q' || button == '\x11') {
622 s = me->states[me->statepos-1].state;
624 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
629 if (s == me->states[me->statepos-1].state) {
631 * make_move() is allowed to return its input state to
632 * indicate that although no move has been made, the UI
633 * state has been updated and a redraw is called for.
636 midend_set_timer(me);
639 midend_stop_anim(me);
640 midend_purge_states(me);
642 assert(movestr != NULL);
643 me->states[me->nstates].state = s;
644 me->states[me->nstates].movestr = movestr;
645 me->states[me->nstates].movetype = MOVE;
646 me->statepos = ++me->nstates;
649 me->ourgame->changed_state(me->ui,
650 me->states[me->statepos-2].state,
651 me->states[me->statepos-1].state);
658 type = me->states[me->statepos-1].movetype;
661 * See if this move requires an animation.
663 if (special(type) && !(type == SOLVE &&
664 (me->ourgame->flags & SOLVE_ANIMATES))) {
667 anim_time = me->ourgame->anim_length(oldstate,
668 me->states[me->statepos-1].state,
672 me->oldstate = oldstate; oldstate = NULL;
674 me->anim_time = anim_time;
677 midend_finish_move(me);
683 midend_set_timer(me);
686 if (oldstate) me->ourgame->free_game(oldstate);
690 int midend_process_key(midend *me, int x, int y, int button)
695 * Harmonise mouse drag and release messages.
697 * Some front ends might accidentally switch from sending, say,
698 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
699 * drag. (This can happen on the Mac, for example, since
700 * RIGHT_DRAG is usually done using Command+drag, and if the
701 * user accidentally releases Command half way through the drag
702 * then there will be trouble.)
704 * It would be an O(number of front ends) annoyance to fix this
705 * in the front ends, but an O(number of back ends) annoyance
706 * to have each game capable of dealing with it. Therefore, we
707 * fix it _here_ in the common midend code so that it only has
710 * The possible ways in which things can go screwy in the front
713 * - in a system containing multiple physical buttons button
714 * presses can inadvertently overlap. We can see ABab (caps
715 * meaning button-down and lowercase meaning button-up) when
716 * the user had semantically intended AaBb.
718 * - in a system where one button is simulated by means of a
719 * modifier key and another button, buttons can mutate
720 * between press and release (possibly during drag). So we
721 * can see Ab instead of Aa.
723 * Definite requirements are:
725 * - button _presses_ must never be invented or destroyed. If
726 * the user presses two buttons in succession, the button
727 * presses must be transferred to the backend unchanged. So
728 * if we see AaBb , that's fine; if we see ABab (the button
729 * presses inadvertently overlapped) we must somehow
730 * `correct' it to AaBb.
732 * - every mouse action must end up looking like a press, zero
733 * or more drags, then a release. This allows back ends to
734 * make the _assumption_ that incoming mouse data will be
735 * sane in this regard, and not worry about the details.
737 * So my policy will be:
739 * - treat any button-up as a button-up for the currently
740 * pressed button, or ignore it if there is no currently
743 * - treat any drag as a drag for the currently pressed
744 * button, or ignore it if there is no currently pressed
747 * - if we see a button-down while another button is currently
748 * pressed, invent a button-up for the first one and then
749 * pass the button-down through as before.
751 * 2005-05-31: An addendum to the above. Some games might want
752 * a `priority order' among buttons, such that if one button is
753 * pressed while another is down then a fixed one of the
754 * buttons takes priority no matter what order they're pressed
755 * in. Mines, in particular, wants to treat a left+right click
756 * like a left click for the benefit of users of other
757 * implementations. So the last of the above points is modified
758 * in the presence of an (optional) button priority order.
760 * A further addition: we translate certain keyboard presses to
761 * cursor key 'select' buttons, so that a) frontends don't have
762 * to translate these themselves (like they do for CURSOR_UP etc),
763 * and b) individual games don't have to hard-code button presses
764 * of '\n' etc for keyboard-based cursors. The choice of buttons
765 * here could eventually be controlled by a runtime configuration
768 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
769 if (me->pressed_mouse_button) {
770 if (IS_MOUSE_DRAG(button)) {
771 button = me->pressed_mouse_button +
772 (LEFT_DRAG - LEFT_BUTTON);
774 button = me->pressed_mouse_button +
775 (LEFT_RELEASE - LEFT_BUTTON);
778 return ret; /* ignore it */
779 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
781 * If the new button has lower priority than the old one,
782 * don't bother doing this.
784 if (me->ourgame->flags &
785 BUTTON_BEATS(me->pressed_mouse_button, button))
786 return ret; /* just ignore it */
789 * Fabricate a button-up for the previously pressed button.
791 ret = ret && midend_really_process_key
792 (me, x, y, (me->pressed_mouse_button +
793 (LEFT_RELEASE - LEFT_BUTTON)));
797 * Translate keyboard presses to cursor selection.
799 if (button == '\n' || button == '\r')
800 button = CURSOR_SELECT;
802 button = CURSOR_SELECT2;
805 * Normalise both backspace characters (8 and 127) to \b. Easier
806 * to do this once, here, than to require all front ends to
807 * carefully generate the same one - now each front end can
808 * generate whichever is easiest.
810 if (button == '\177')
814 * Now send on the event we originally received.
816 ret = ret && midend_really_process_key(me, x, y, button);
819 * And update the currently pressed button.
821 if (IS_MOUSE_RELEASE(button))
822 me->pressed_mouse_button = 0;
823 else if (IS_MOUSE_DOWN(button))
824 me->pressed_mouse_button = button;
829 void midend_redraw(midend *me)
833 if (me->statepos > 0 && me->drawstate) {
834 start_draw(me->drawing);
835 if (me->oldstate && me->anim_time > 0 &&
836 me->anim_pos < me->anim_time) {
837 assert(me->dir != 0);
838 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
839 me->states[me->statepos-1].state, me->dir,
840 me->ui, me->anim_pos, me->flash_pos);
842 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
843 me->states[me->statepos-1].state, +1 /*shrug*/,
844 me->ui, 0.0, me->flash_pos);
846 end_draw(me->drawing);
851 * Nasty hacky function used to implement the --redo option in
852 * gtk.c. Only used for generating the puzzles' icons.
854 void midend_freeze_timer(midend *me, float tprop)
856 me->anim_pos = me->anim_time * tprop;
858 deactivate_timer(me->frontend);
861 void midend_timer(midend *me, float tplus)
863 int need_redraw = (me->anim_time > 0 || me->flash_time > 0);
865 me->anim_pos += tplus;
866 if (me->anim_pos >= me->anim_time ||
867 me->anim_time == 0 || !me->oldstate) {
868 if (me->anim_time > 0)
869 midend_finish_move(me);
872 me->flash_pos += tplus;
873 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
874 me->flash_pos = me->flash_time = 0;
881 float oldelapsed = me->elapsed;
882 me->elapsed += tplus;
883 if ((int)oldelapsed != (int)me->elapsed)
884 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
887 midend_set_timer(me);
890 float *midend_colours(midend *me, int *ncolours)
894 ret = me->ourgame->colours(me->frontend, ncolours);
900 * Allow environment-based overrides for the standard
901 * colours by defining variables along the lines of
902 * `NET_COLOUR_4=6000c0'.
905 for (i = 0; i < *ncolours; i++) {
907 unsigned int r, g, b;
910 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
911 for (j = k = 0; buf[j]; j++)
912 if (!isspace((unsigned char)buf[j]))
913 buf[k++] = toupper((unsigned char)buf[j]);
915 if ((e = getenv(buf)) != NULL &&
916 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
917 ret[i*3 + 0] = r / 255.0F;
918 ret[i*3 + 1] = g / 255.0F;
919 ret[i*3 + 2] = b / 255.0F;
927 int midend_num_presets(midend *me)
933 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
934 if (me->presetsize <= me->npresets) {
935 me->presetsize = me->npresets + 10;
936 me->presets = sresize(me->presets, me->presetsize,
938 me->preset_names = sresize(me->preset_names, me->presetsize,
940 me->preset_encodings = sresize(me->preset_encodings,
941 me->presetsize, char *);
944 me->presets[me->npresets] = preset;
945 me->preset_names[me->npresets] = name;
946 me->preset_encodings[me->npresets] =
947 me->ourgame->encode_params(preset, TRUE);;
954 * Allow environment-based extensions to the preset list by
955 * defining a variable along the lines of `SOLO_PRESETS=2x3
956 * Advanced:2x3da'. Colon-separated list of items,
957 * alternating between textual titles in the menu and
958 * encoded parameter strings.
960 char buf[80], *e, *p;
963 sprintf(buf, "%s_PRESETS", me->ourgame->name);
964 for (j = k = 0; buf[j]; j++)
965 if (!isspace((unsigned char)buf[j]))
966 buf[k++] = toupper((unsigned char)buf[j]);
969 if ((e = getenv(buf)) != NULL) {
977 while (*p && *p != ':') p++;
980 while (*p && *p != ':') p++;
983 preset = me->ourgame->default_params();
984 me->ourgame->decode_params(preset, val);
986 if (me->ourgame->validate_params(preset, TRUE)) {
987 /* Drop this one from the list. */
988 me->ourgame->free_params(preset);
992 if (me->presetsize <= me->npresets) {
993 me->presetsize = me->npresets + 10;
994 me->presets = sresize(me->presets, me->presetsize,
996 me->preset_names = sresize(me->preset_names,
997 me->presetsize, char *);
998 me->preset_encodings = sresize(me->preset_encodings,
999 me->presetsize, char *);
1002 me->presets[me->npresets] = preset;
1003 me->preset_names[me->npresets] = dupstr(name);
1004 me->preset_encodings[me->npresets] =
1005 me->ourgame->encode_params(preset, TRUE);
1012 return me->npresets;
1015 void midend_fetch_preset(midend *me, int n,
1016 char **name, game_params **params)
1018 assert(n >= 0 && n < me->npresets);
1019 *name = me->preset_names[n];
1020 *params = me->presets[n];
1023 int midend_which_preset(midend *me)
1025 char *encoding = me->ourgame->encode_params(me->params, TRUE);
1029 for (i = 0; i < me->npresets; i++)
1030 if (!strcmp(encoding, me->preset_encodings[i])) {
1039 int midend_wants_statusbar(midend *me)
1041 return me->ourgame->wants_statusbar;
1044 void midend_request_id_changes(midend *me, void (*notify)(void *), void *ctx)
1046 me->game_id_change_notify_function = notify;
1047 me->game_id_change_notify_ctx = ctx;
1050 void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
1053 sfree(me->privdesc);
1054 me->desc = dupstr(desc);
1055 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
1056 if (me->game_id_change_notify_function)
1057 me->game_id_change_notify_function(me->game_id_change_notify_ctx);
1060 config_item *midend_get_config(midend *me, int which, char **wintitle)
1062 char *titlebuf, *parstr, *rest;
1067 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
1071 sprintf(titlebuf, "%s configuration", me->ourgame->name);
1072 *wintitle = titlebuf;
1073 return me->ourgame->configure(me->params);
1076 if (!me->curparams) {
1080 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1081 which == CFG_SEED ? "random" : "game");
1082 *wintitle = titlebuf;
1084 ret = snewn(2, config_item);
1086 ret[0].type = C_STRING;
1087 if (which == CFG_SEED)
1088 ret[0].name = "Game random seed";
1090 ret[0].name = "Game ID";
1093 * For CFG_DESC the text going in here will be a string
1094 * encoding of the restricted parameters, plus a colon,
1095 * plus the game description. For CFG_SEED it will be the
1096 * full parameters, plus a hash, plus the random seed data.
1097 * Either of these is a valid full game ID (although only
1098 * the former is likely to persist across many code
1101 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
1103 if (which == CFG_DESC) {
1104 rest = me->desc ? me->desc : "";
1107 rest = me->seedstr ? me->seedstr : "";
1110 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
1111 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
1114 ret[1].type = C_END;
1115 ret[1].name = ret[1].sval = NULL;
1121 assert(!"We shouldn't be here");
1125 static char *midend_game_id_int(midend *me, char *id, int defmode)
1127 char *error, *par, *desc, *seed;
1128 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
1131 seed = strchr(id, '#');
1132 desc = strchr(id, ':');
1134 if (desc && (!seed || desc < seed)) {
1136 * We have a colon separating parameters from game
1137 * description. So `par' now points to the parameters
1138 * string, and `desc' to the description string.
1143 } else if (seed && (!desc || seed < desc)) {
1145 * We have a hash separating parameters from random seed.
1146 * So `par' now points to the parameters string, and `seed'
1147 * to the seed string.
1154 * We only have one string. Depending on `defmode', we take
1155 * it to be either parameters, seed or description.
1157 if (defmode == DEF_SEED) {
1160 } else if (defmode == DEF_DESC) {
1170 * We must be reasonably careful here not to modify anything in
1171 * `me' until we have finished validating things. This function
1172 * must either return an error and do nothing to the midend, or
1173 * return success and do everything; nothing in between is
1176 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
1180 * The params string may underspecify the game parameters, so
1181 * we must first initialise newcurparams with a full set of
1182 * params from somewhere else before we decode_params the
1183 * input string over the top.
1185 * But which set? It depends on what other data we have.
1187 * If we've been given a _descriptive_ game id, then that may
1188 * well underspecify by design, e.g. Solo game descriptions
1189 * often start just '3x3:' without specifying one of Solo's
1190 * difficulty settings, because it isn't necessary once a game
1191 * has been generated (and you might not even know it, if
1192 * you're manually transcribing a game description). In that
1193 * situation, I've always felt that the best thing to set the
1194 * difficulty to (for use if the user hits 'New Game' after
1195 * pasting in that game id) is whatever it was previously set
1196 * to. That is, we use whatever is already in me->params as
1197 * the basis for our decoding of this input string.
1199 * A random-seed based game id, however, should use the real,
1200 * built-in default params, and not even check the
1201 * <game>_DEFAULT environment setting, because when people
1202 * paste each other random seeds - whether it's two users
1203 * arranging to generate the same game at the same time to
1204 * race solving them, or a user sending a bug report upstream
1205 * - the whole point is for the random game id to always be
1206 * interpreted the same way, even if it does underspecify.
1208 * A parameter string typed in on its own, with no seed _or_
1209 * description, gets treated the same way as a random seed,
1210 * because again I think the most likely reason for doing that
1211 * is to have a portable representation of a set of params.
1214 newcurparams = me->ourgame->dup_params(me->params);
1216 newcurparams = me->ourgame->default_params();
1218 me->ourgame->decode_params(newcurparams, par);
1219 error = me->ourgame->validate_params(newcurparams, desc == NULL);
1221 me->ourgame->free_params(newcurparams);
1224 oldparams1 = me->curparams;
1227 * Now filter only the persistent parts of this state into
1228 * the long-term params structure, unless we've _only_
1229 * received a params string in which case the whole lot is
1232 oldparams2 = me->params;
1236 newparams = me->ourgame->dup_params(me->params);
1238 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1239 me->ourgame->decode_params(newparams, tmpstr);
1243 newparams = me->ourgame->dup_params(newcurparams);
1247 newcurparams = me->curparams;
1248 newparams = me->params;
1249 free_params = FALSE;
1253 error = me->ourgame->validate_desc(newparams, desc);
1257 me->ourgame->free_params(newcurparams);
1259 me->ourgame->free_params(newparams);
1266 * Now we've got past all possible error points. Update the
1269 me->params = newparams;
1270 me->curparams = newcurparams;
1272 me->ourgame->free_params(oldparams1);
1274 me->ourgame->free_params(oldparams2);
1277 sfree(me->privdesc);
1278 me->desc = me->privdesc = NULL;
1283 me->desc = dupstr(desc);
1284 me->genmode = GOT_DESC;
1285 sfree(me->aux_info);
1286 me->aux_info = NULL;
1290 me->seedstr = dupstr(seed);
1291 me->genmode = GOT_SEED;
1297 char *midend_game_id(midend *me, char *id)
1299 return midend_game_id_int(me, id, DEF_PARAMS);
1302 char *midend_get_game_id(midend *me)
1306 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1309 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1310 sprintf(ret, "%s:%s", parstr, me->desc);
1315 char *midend_get_random_seed(midend *me)
1322 parstr = me->ourgame->encode_params(me->curparams, TRUE);
1324 ret = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
1325 sprintf(ret, "%s#%s", parstr, me->seedstr);
1330 char *midend_set_config(midend *me, int which, config_item *cfg)
1333 game_params *params;
1337 params = me->ourgame->custom_params(cfg);
1338 error = me->ourgame->validate_params(params, TRUE);
1341 me->ourgame->free_params(params);
1345 me->ourgame->free_params(me->params);
1346 me->params = params;
1351 error = midend_game_id_int(me, cfg[0].sval,
1352 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
1361 int midend_can_format_as_text_now(midend *me)
1363 if (me->ourgame->can_format_as_text_ever)
1364 return me->ourgame->can_format_as_text_now(me->params);
1369 char *midend_text_format(midend *me)
1371 if (me->ourgame->can_format_as_text_ever && me->statepos > 0 &&
1372 me->ourgame->can_format_as_text_now(me->params))
1373 return me->ourgame->text_format(me->states[me->statepos-1].state);
1378 char *midend_solve(midend *me)
1381 char *msg, *movestr;
1383 if (!me->ourgame->can_solve)
1384 return "This game does not support the Solve operation";
1386 if (me->statepos < 1)
1387 return "No game set up to solve"; /* _shouldn't_ happen! */
1390 movestr = me->ourgame->solve(me->states[0].state,
1391 me->states[me->statepos-1].state,
1392 me->aux_info, &msg);
1395 msg = "Solve operation failed"; /* _shouldn't_ happen, but can */
1398 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1402 * Now enter the solved state as the next move.
1404 midend_stop_anim(me);
1405 midend_purge_states(me);
1407 me->states[me->nstates].state = s;
1408 me->states[me->nstates].movestr = movestr;
1409 me->states[me->nstates].movetype = SOLVE;
1410 me->statepos = ++me->nstates;
1412 me->ourgame->changed_state(me->ui,
1413 me->states[me->statepos-2].state,
1414 me->states[me->statepos-1].state);
1416 if (me->ourgame->flags & SOLVE_ANIMATES) {
1417 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1419 me->ourgame->anim_length(me->states[me->statepos-2].state,
1420 me->states[me->statepos-1].state,
1424 me->anim_time = 0.0;
1425 midend_finish_move(me);
1429 midend_set_timer(me);
1433 int midend_status(midend *me)
1436 * We should probably never be called when the state stack has no
1437 * states on it at all - ideally, midends should never be left in
1438 * that state for long enough to get put down and forgotten about.
1439 * But if we are, I think we return _true_ - pedantically speaking
1440 * a midend in that state is 'vacuously solved', and more
1441 * practically, a user whose midend has been left in that state
1442 * probably _does_ want the 'new game' option to be prominent.
1444 if (me->statepos == 0)
1447 return me->ourgame->status(me->states[me->statepos-1].state);
1450 char *midend_rewrite_statusbar(midend *me, char *text)
1453 * An important special case is that we are occasionally called
1454 * with our own laststatus, to update the timer.
1456 if (me->laststatus != text) {
1457 sfree(me->laststatus);
1458 me->laststatus = dupstr(text);
1461 if (me->ourgame->is_timed) {
1462 char timebuf[100], *ret;
1465 sec = (int)me->elapsed;
1468 sprintf(timebuf, "[%d:%02d] ", min, sec);
1470 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1471 strcpy(ret, timebuf);
1476 return dupstr(text);
1480 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1481 #define SERIALISE_VERSION "1"
1483 void midend_serialise(midend *me,
1484 void (*write)(void *ctx, void *buf, int len),
1490 * Each line of the save file contains three components. First
1491 * exactly 8 characters of header word indicating what type of
1492 * data is contained on the line; then a colon followed by a
1493 * decimal integer giving the length of the main string on the
1494 * line; then a colon followed by the string itself (exactly as
1495 * many bytes as previously specified, no matter what they
1496 * contain). Then a newline (of reasonably flexible form).
1498 #define wr(h,s) do { \
1501 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1502 write(wctx, hbuf, strlen(hbuf)); \
1503 write(wctx, str, strlen(str)); \
1504 write(wctx, "\n", 1); \
1508 * Magic string identifying the file, and version number of the
1511 wr("SAVEFILE", SERIALISE_MAGIC);
1512 wr("VERSION", SERIALISE_VERSION);
1515 * The game name. (Copied locally to avoid const annoyance.)
1518 char *s = dupstr(me->ourgame->name);
1524 * The current long-term parameters structure, in full.
1527 char *s = me->ourgame->encode_params(me->params, TRUE);
1533 * The current short-term parameters structure, in full.
1535 if (me->curparams) {
1536 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1542 * The current game description, the privdesc, and the random seed.
1545 wr("SEED", me->seedstr);
1547 wr("DESC", me->desc);
1549 wr("PRIVDESC", me->privdesc);
1552 * The game's aux_info. We obfuscate this to prevent spoilers
1553 * (people are likely to run `head' or similar on a saved game
1554 * file simply to find out what it is, and don't necessarily
1555 * want to be told the answer to the puzzle!)
1562 len = strlen(me->aux_info);
1563 s1 = snewn(len, unsigned char);
1564 memcpy(s1, me->aux_info, len);
1565 obfuscate_bitmap(s1, len*8, FALSE);
1566 s2 = bin2hex(s1, len);
1575 * Any required serialisation of the game_ui.
1578 char *s = me->ourgame->encode_ui(me->ui);
1586 * The game time, if it's a timed game.
1588 if (me->ourgame->is_timed) {
1590 sprintf(buf, "%g", me->elapsed);
1595 * The length of, and position in, the states list.
1599 sprintf(buf, "%d", me->nstates);
1601 sprintf(buf, "%d", me->statepos);
1602 wr("STATEPOS", buf);
1606 * For each state after the initial one (which we know is
1607 * constructed from either privdesc or desc), enough
1608 * information for execute_move() to reconstruct it from the
1611 for (i = 1; i < me->nstates; i++) {
1612 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1613 switch (me->states[i].movetype) {
1615 wr("MOVE", me->states[i].movestr);
1618 wr("SOLVE", me->states[i].movestr);
1621 wr("RESTART", me->states[i].movestr);
1630 * This function returns NULL on success, or an error message.
1632 char *midend_deserialise(midend *me,
1633 int (*read)(void *ctx, void *buf, int len),
1636 int nstates = 0, statepos = -1, gotstates = 0;
1637 int started = FALSE;
1641 /* Initially all errors give the same report */
1642 char *ret = "Data does not appear to be a saved game file";
1645 * We construct all the new state in local variables while we
1646 * check its sanity. Only once we have finished reading the
1647 * serialised data and detected no errors at all do we start
1648 * modifying stuff in the midend passed in.
1650 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1651 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1652 float elapsed = 0.0F;
1653 game_params *params = NULL, *cparams = NULL;
1655 struct midend_state_entry *states = NULL;
1658 * Loop round and round reading one key/value pair at a time
1659 * from the serialised stream, until we have enough game states
1662 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1667 if (!read(rctx, key, 1)) {
1668 /* unexpected EOF */
1671 } while (key[0] == '\r' || key[0] == '\n');
1673 if (!read(rctx, key+1, 8)) {
1674 /* unexpected EOF */
1678 if (key[8] != ':') {
1680 ret = "Data was incorrectly formatted for a saved game file";
1683 len = strcspn(key, ": ");
1689 if (!read(rctx, &c, 1)) {
1690 /* unexpected EOF */
1696 } else if (c >= '0' && c <= '9') {
1697 len = (len * 10) + (c - '0');
1700 ret = "Data was incorrectly formatted for a"
1706 val = snewn(len+1, char);
1707 if (!read(rctx, val, len)) {
1714 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1715 /* ret already has the right message in it */
1718 /* Now most errors are this one, unless otherwise specified */
1719 ret = "Saved data ended unexpectedly";
1722 if (!strcmp(key, "VERSION")) {
1723 if (strcmp(val, SERIALISE_VERSION)) {
1724 ret = "Cannot handle this version of the saved game"
1728 } else if (!strcmp(key, "GAME")) {
1729 if (strcmp(val, me->ourgame->name)) {
1730 ret = "Save file is from a different game";
1733 } else if (!strcmp(key, "PARAMS")) {
1737 } else if (!strcmp(key, "CPARAMS")) {
1741 } else if (!strcmp(key, "SEED")) {
1745 } else if (!strcmp(key, "DESC")) {
1749 } else if (!strcmp(key, "PRIVDESC")) {
1753 } else if (!strcmp(key, "AUXINFO")) {
1755 int len = strlen(val) / 2; /* length in bytes */
1756 tmp = hex2bin(val, len);
1757 obfuscate_bitmap(tmp, len*8, TRUE);
1760 auxinfo = snewn(len + 1, char);
1761 memcpy(auxinfo, tmp, len);
1762 auxinfo[len] = '\0';
1764 } else if (!strcmp(key, "UI")) {
1768 } else if (!strcmp(key, "TIME")) {
1769 elapsed = (float)atof(val);
1770 } else if (!strcmp(key, "NSTATES")) {
1771 nstates = atoi(val);
1773 ret = "Number of states in save file was negative";
1777 ret = "Two state counts provided in save file";
1780 states = snewn(nstates, struct midend_state_entry);
1781 for (i = 0; i < nstates; i++) {
1782 states[i].state = NULL;
1783 states[i].movestr = NULL;
1784 states[i].movetype = NEWGAME;
1786 } else if (!strcmp(key, "STATEPOS")) {
1787 statepos = atoi(val);
1788 } else if (!strcmp(key, "MOVE")) {
1790 states[gotstates].movetype = MOVE;
1791 states[gotstates].movestr = val;
1793 } else if (!strcmp(key, "SOLVE")) {
1795 states[gotstates].movetype = SOLVE;
1796 states[gotstates].movestr = val;
1798 } else if (!strcmp(key, "RESTART")) {
1800 states[gotstates].movetype = RESTART;
1801 states[gotstates].movestr = val;
1810 params = me->ourgame->default_params();
1811 me->ourgame->decode_params(params, parstr);
1812 if (me->ourgame->validate_params(params, TRUE)) {
1813 ret = "Long-term parameters in save file are invalid";
1816 cparams = me->ourgame->default_params();
1817 me->ourgame->decode_params(cparams, cparstr);
1818 if (me->ourgame->validate_params(cparams, FALSE)) {
1819 ret = "Short-term parameters in save file are invalid";
1822 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1824 * The seed's no use with this version, but we can perfectly
1825 * well use the rest of the data.
1831 ret = "Game description in save file is missing";
1833 } else if (me->ourgame->validate_desc(params, desc)) {
1834 ret = "Game description in save file is invalid";
1837 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1838 ret = "Game private description in save file is invalid";
1841 if (statepos < 0 || statepos >= nstates) {
1842 ret = "Game position in save file is out of range";
1845 states[0].state = me->ourgame->new_game(me, params,
1846 privdesc ? privdesc : desc);
1847 for (i = 1; i < nstates; i++) {
1848 assert(states[i].movetype != NEWGAME);
1849 switch (states[i].movetype) {
1852 states[i].state = me->ourgame->execute_move(states[i-1].state,
1854 if (states[i].state == NULL) {
1855 ret = "Save file contained an invalid move";
1860 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1861 ret = "Save file contained an invalid restart move";
1864 states[i].state = me->ourgame->new_game(me, params,
1870 ui = me->ourgame->new_ui(states[0].state);
1871 me->ourgame->decode_ui(ui, uistr);
1874 * Now we've run out of possible error conditions, so we're
1875 * ready to start overwriting the real data in the current
1876 * midend. We'll do this by swapping things with the local
1877 * variables, so that the same cleanup code will free the old
1888 me->privdesc = privdesc;
1896 me->aux_info = auxinfo;
1900 me->genmode = GOT_NOTHING;
1902 me->statesize = nstates;
1903 nstates = me->nstates;
1904 me->nstates = me->statesize;
1906 struct midend_state_entry *tmp;
1908 me->states = states;
1911 me->statepos = statepos;
1917 me->params = params;
1920 tmp = me->curparams;
1921 me->curparams = cparams;
1925 me->oldstate = NULL;
1926 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1937 me->elapsed = elapsed;
1938 me->pressed_mouse_button = 0;
1940 midend_set_timer(me);
1943 me->ourgame->free_drawstate(me->drawing, me->drawstate);
1945 me->ourgame->new_drawstate(me->drawing,
1946 me->states[me->statepos-1].state);
1947 midend_size_new_drawstate(me);
1949 ret = NULL; /* success! */
1961 me->ourgame->free_params(params);
1963 me->ourgame->free_params(cparams);
1965 me->ourgame->free_ui(ui);
1969 for (i = 0; i < nstates; i++) {
1970 if (states[i].state)
1971 me->ourgame->free_game(states[i].state);
1972 sfree(states[i].movestr);
1981 * This function examines a saved game file just far enough to
1982 * determine which game type it contains. It returns NULL on success
1983 * and the game name string in 'name' (which will be dynamically
1984 * allocated and should be caller-freed), or an error message on
1987 char *identify_game(char **name, int (*read)(void *ctx, void *buf, int len),
1990 int nstates = 0, statepos = -1, gotstates = 0;
1991 int started = FALSE;
1994 /* Initially all errors give the same report */
1995 char *ret = "Data does not appear to be a saved game file";
2000 * Loop round and round reading one key/value pair at a time from
2001 * the serialised stream, until we've found the game name.
2003 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
2008 if (!read(rctx, key, 1)) {
2009 /* unexpected EOF */
2012 } while (key[0] == '\r' || key[0] == '\n');
2014 if (!read(rctx, key+1, 8)) {
2015 /* unexpected EOF */
2019 if (key[8] != ':') {
2021 ret = "Data was incorrectly formatted for a saved game file";
2024 len = strcspn(key, ": ");
2030 if (!read(rctx, &c, 1)) {
2031 /* unexpected EOF */
2037 } else if (c >= '0' && c <= '9') {
2038 len = (len * 10) + (c - '0');
2041 ret = "Data was incorrectly formatted for a"
2047 val = snewn(len+1, char);
2048 if (!read(rctx, val, len)) {
2055 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
2056 /* ret already has the right message in it */
2059 /* Now most errors are this one, unless otherwise specified */
2060 ret = "Saved data ended unexpectedly";
2063 if (!strcmp(key, "VERSION")) {
2064 if (strcmp(val, SERIALISE_VERSION)) {
2065 ret = "Cannot handle this version of the saved game"
2069 } else if (!strcmp(key, "GAME")) {
2070 *name = dupstr(val);
2085 char *midend_print_puzzle(midend *me, document *doc, int with_soln)
2087 game_state *soln = NULL;
2089 if (me->statepos < 1)
2090 return "No game set up to print";/* _shouldn't_ happen! */
2093 char *msg, *movestr;
2095 if (!me->ourgame->can_solve)
2096 return "This game does not support the Solve operation";
2098 msg = "Solve operation failed";/* game _should_ overwrite on error */
2099 movestr = me->ourgame->solve(me->states[0].state,
2100 me->states[me->statepos-1].state,
2101 me->aux_info, &msg);
2104 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
2113 * This call passes over ownership of the two game_states and
2114 * the game_params. Hence we duplicate the ones we want to
2115 * keep, and we don't have to bother freeing soln if it was
2118 document_add_puzzle(doc, me->ourgame,
2119 me->ourgame->dup_params(me->curparams),
2120 me->ourgame->dup_game(me->states[0].state), soln);