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
;
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();
109 me
->curparams
= NULL
;
110 me
->desc
= me
->privdesc
= NULL
;
113 me
->genmode
= GOT_NOTHING
;
114 me
->drawstate
= NULL
;
117 me
->preset_names
= NULL
;
118 me
->npresets
= me
->presetsize
= 0;
119 me
->anim_time
= me
->anim_pos
= 0.0F
;
120 me
->flash_time
= me
->flash_pos
= 0.0F
;
123 me
->pressed_mouse_button
= 0;
124 me
->laststatus
= NULL
;
127 me
->tilesize
= me
->winwidth
= me
->winheight
= 0;
129 me
->drawing
= drawing_new(drapi
, me
, drhandle
);
133 me
->preferred_tilesize
= ourgame
->preferred_tilesize
;
136 * Allow an environment-based override for the default tile
137 * size by defining a variable along the lines of
144 sprintf(buf
, "%s_TILESIZE", me
->ourgame
->name
);
145 for (j
= k
= 0; buf
[j
]; j
++)
146 if (!isspace((unsigned char)buf
[j
]))
147 buf
[k
++] = toupper((unsigned char)buf
[j
]);
149 if ((e
= getenv(buf
)) != NULL
&& sscanf(e
, "%d", &ts
) == 1 && ts
> 0)
150 me
->preferred_tilesize
= ts
;
158 static void midend_free_game(midend
*me
)
160 while (me
->nstates
> 0) {
162 me
->ourgame
->free_game(me
->states
[me
->nstates
].state
);
163 sfree(me
->states
[me
->nstates
].movestr
);
167 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
170 void midend_free(midend
*me
)
174 midend_free_game(me
);
177 drawing_free(me
->drawing
);
178 random_free(me
->random
);
184 me
->ourgame
->free_params(me
->params
);
186 for (i
= 0; i
< me
->npresets
; i
++) {
187 sfree(me
->presets
[i
]);
188 sfree(me
->preset_names
[i
]);
191 sfree(me
->preset_names
);
194 me
->ourgame
->free_ui(me
->ui
);
196 me
->ourgame
->free_params(me
->curparams
);
197 sfree(me
->laststatus
);
201 static void midend_size_new_drawstate(midend
*me
)
204 * Don't even bother, if we haven't worked out our tile size
207 if (me
->tilesize
> 0) {
208 me
->ourgame
->compute_size(me
->params
, me
->tilesize
,
209 &me
->winwidth
, &me
->winheight
);
210 me
->ourgame
->set_size(me
->drawing
, me
->drawstate
,
211 me
->params
, me
->tilesize
);
215 void midend_size(midend
*me
, int *x
, int *y
, int expand
)
221 * We can't set the size on the same drawstate twice. So if
222 * we've already sized one drawstate, we must throw it away and
225 if (me
->drawstate
&& me
->tilesize
> 0) {
226 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
227 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
228 me
->states
[0].state
);
232 * Find the tile size that best fits within the given space. If
233 * `expand' is TRUE, we must actually find the _largest_ such
234 * tile size; otherwise, we bound above at the game's preferred
241 me
->ourgame
->compute_size(me
->params
, max
, &rx
, &ry
);
242 } while (rx
<= *x
&& ry
<= *y
);
244 max
= me
->preferred_tilesize
+ 1;
248 * Now binary-search between min and max. We're looking for a
249 * boundary rather than a value: the point at which tile sizes
250 * stop fitting within the given dimensions. Thus, we stop when
251 * max and min differ by exactly 1.
253 while (max
- min
> 1) {
254 int mid
= (max
+ min
) / 2;
255 me
->ourgame
->compute_size(me
->params
, mid
, &rx
, &ry
);
256 if (rx
<= *x
&& ry
<= *y
)
263 * Now `min' is a valid size, and `max' isn't. So use `min'.
267 midend_size_new_drawstate(me
);
272 void midend_set_params(midend
*me
, game_params
*params
)
274 me
->ourgame
->free_params(me
->params
);
275 me
->params
= me
->ourgame
->dup_params(params
);
278 game_params
*midend_get_params(midend
*me
)
280 return me
->ourgame
->dup_params(me
->params
);
283 static void midend_set_timer(midend
*me
)
285 me
->timing
= (me
->ourgame
->is_timed
&&
286 me
->ourgame
->timing_state(me
->states
[me
->statepos
-1].state
,
288 if (me
->timing
|| me
->flash_time
|| me
->anim_time
)
289 activate_timer(me
->frontend
);
291 deactivate_timer(me
->frontend
);
294 void midend_force_redraw(midend
*me
)
297 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
298 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
299 me
->states
[0].state
);
300 midend_size_new_drawstate(me
);
304 void midend_new_game(midend
*me
)
306 midend_free_game(me
);
308 assert(me
->nstates
== 0);
310 if (me
->genmode
== GOT_DESC
) {
311 me
->genmode
= GOT_NOTHING
;
315 if (me
->genmode
== GOT_SEED
) {
316 me
->genmode
= GOT_NOTHING
;
319 * Generate a new random seed. 15 digits comes to about
320 * 48 bits, which should be more than enough.
322 * I'll avoid putting a leading zero on the number,
323 * just in case it confuses anybody who thinks it's
324 * processed as an integer rather than a string.
329 newseed
[0] = '1' + random_upto(me
->random
, 9);
330 for (i
= 1; i
< 15; i
++)
331 newseed
[i
] = '0' + random_upto(me
->random
, 10);
333 me
->seedstr
= dupstr(newseed
);
336 me
->ourgame
->free_params(me
->curparams
);
337 me
->curparams
= me
->ourgame
->dup_params(me
->params
);
345 rs
= random_new(me
->seedstr
, strlen(me
->seedstr
));
347 * If this midend has been instantiated without providing a
348 * drawing API, it is non-interactive. This means that it's
349 * being used for bulk game generation, and hence we should
350 * pass the non-interactive flag to new_desc.
352 me
->desc
= me
->ourgame
->new_desc(me
->curparams
, rs
,
353 &me
->aux_info
, (me
->drawing
!= NULL
));
361 * It might seem a bit odd that we're using me->params to
362 * create the initial game state, rather than me->curparams
363 * which is better tailored to this specific game and which we
366 * It's supposed to be an invariant in the midend that
367 * me->params and me->curparams differ in no aspect that is
368 * important after generation (i.e. after new_desc()). By
369 * deliberately passing the _less_ specific of these two
370 * parameter sets, we provoke play-time misbehaviour in the
371 * case where a game has failed to encode a play-time parameter
372 * in the non-full version of encode_params().
374 me
->states
[me
->nstates
].state
=
375 me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
377 me
->states
[me
->nstates
].movestr
= NULL
;
378 me
->states
[me
->nstates
].movetype
= NEWGAME
;
381 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
382 me
->states
[0].state
);
383 midend_size_new_drawstate(me
);
386 me
->ourgame
->free_ui(me
->ui
);
387 me
->ui
= me
->ourgame
->new_ui(me
->states
[0].state
);
388 midend_set_timer(me
);
389 me
->pressed_mouse_button
= 0;
392 static int midend_undo(midend
*me
)
394 if (me
->statepos
> 1) {
396 me
->ourgame
->changed_state(me
->ui
,
397 me
->states
[me
->statepos
-1].state
,
398 me
->states
[me
->statepos
-2].state
);
406 static int midend_redo(midend
*me
)
408 if (me
->statepos
< me
->nstates
) {
410 me
->ourgame
->changed_state(me
->ui
,
411 me
->states
[me
->statepos
-1].state
,
412 me
->states
[me
->statepos
].state
);
420 static void midend_finish_move(midend
*me
)
425 * We do not flash if the later of the two states is special.
426 * This covers both forward Solve moves and backward (undone)
429 if ((me
->oldstate
|| me
->statepos
> 1) &&
430 ((me
->dir
> 0 && !special(me
->states
[me
->statepos
-1].movetype
)) ||
431 (me
->dir
< 0 && me
->statepos
< me
->nstates
&&
432 !special(me
->states
[me
->statepos
].movetype
)))) {
433 flashtime
= me
->ourgame
->flash_length(me
->oldstate ? me
->oldstate
:
434 me
->states
[me
->statepos
-2].state
,
435 me
->states
[me
->statepos
-1].state
,
436 me
->oldstate ? me
->dir
: +1,
439 me
->flash_pos
= 0.0F
;
440 me
->flash_time
= flashtime
;
445 me
->ourgame
->free_game(me
->oldstate
);
447 me
->anim_pos
= me
->anim_time
= 0;
450 midend_set_timer(me
);
453 void midend_stop_anim(midend
*me
)
455 if (me
->oldstate
|| me
->anim_time
!= 0) {
456 midend_finish_move(me
);
461 void midend_restart_game(midend
*me
)
465 midend_stop_anim(me
);
467 assert(me
->statepos
>= 1);
468 if (me
->statepos
== 1)
469 return; /* no point doing anything at all! */
472 * During restart, we reconstruct the game from the (public)
473 * game description rather than from states[0], because that
474 * way Mines gets slightly more sensible behaviour (restart
475 * goes to _after_ the first click so you don't have to
476 * remember where you clicked).
478 s
= me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
481 * Now enter the restarted state as the next move.
483 midend_stop_anim(me
);
484 while (me
->nstates
> me
->statepos
)
485 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
487 me
->states
[me
->nstates
].state
= s
;
488 me
->states
[me
->nstates
].movestr
= dupstr(me
->desc
);
489 me
->states
[me
->nstates
].movetype
= RESTART
;
490 me
->statepos
= ++me
->nstates
;
492 me
->ourgame
->changed_state(me
->ui
,
493 me
->states
[me
->statepos
-2].state
,
494 me
->states
[me
->statepos
-1].state
);
496 midend_finish_move(me
);
498 midend_set_timer(me
);
501 static int midend_really_process_key(midend
*me
, int x
, int y
, int button
)
503 game_state
*oldstate
=
504 me
->ourgame
->dup_game(me
->states
[me
->statepos
- 1].state
);
505 int type
= MOVE
, gottype
= FALSE
, ret
= 1;
511 me
->ourgame
->interpret_move(me
->states
[me
->statepos
-1].state
,
512 me
->ui
, me
->drawstate
, x
, y
, button
);
515 if (button
== 'n' || button
== 'N' || button
== '\x0E') {
516 midend_stop_anim(me
);
519 goto done
; /* never animate */
520 } else if (button
== 'u' || button
== 'u' ||
521 button
== '\x1A' || button
== '\x1F') {
522 midend_stop_anim(me
);
523 type
= me
->states
[me
->statepos
-1].movetype
;
525 if (!midend_undo(me
))
527 } else if (button
== 'r' || button
== 'R' ||
528 button
== '\x12' || button
== '\x19') {
529 midend_stop_anim(me
);
530 if (!midend_redo(me
))
532 } else if (button
== 'q' || button
== 'Q' || button
== '\x11') {
539 s
= me
->states
[me
->statepos
-1].state
;
541 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
546 if (s
== me
->states
[me
->statepos
-1].state
) {
548 * make_move() is allowed to return its input state to
549 * indicate that although no move has been made, the UI
550 * state has been updated and a redraw is called for.
555 midend_stop_anim(me
);
556 while (me
->nstates
> me
->statepos
)
557 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
559 assert(movestr
!= NULL
);
560 me
->states
[me
->nstates
].state
= s
;
561 me
->states
[me
->nstates
].movestr
= movestr
;
562 me
->states
[me
->nstates
].movetype
= MOVE
;
563 me
->statepos
= ++me
->nstates
;
566 me
->ourgame
->changed_state(me
->ui
,
567 me
->states
[me
->statepos
-2].state
,
568 me
->states
[me
->statepos
-1].state
);
575 type
= me
->states
[me
->statepos
-1].movetype
;
578 * See if this move requires an animation.
580 if (special(type
) && !(type
== SOLVE
&&
581 (me
->ourgame
->flags
& SOLVE_ANIMATES
))) {
584 anim_time
= me
->ourgame
->anim_length(oldstate
,
585 me
->states
[me
->statepos
-1].state
,
589 me
->oldstate
= oldstate
; oldstate
= NULL
;
591 me
->anim_time
= anim_time
;
594 midend_finish_move(me
);
600 midend_set_timer(me
);
603 if (oldstate
) me
->ourgame
->free_game(oldstate
);
607 int midend_process_key(midend
*me
, int x
, int y
, int button
)
612 * Harmonise mouse drag and release messages.
614 * Some front ends might accidentally switch from sending, say,
615 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
616 * drag. (This can happen on the Mac, for example, since
617 * RIGHT_DRAG is usually done using Command+drag, and if the
618 * user accidentally releases Command half way through the drag
619 * then there will be trouble.)
621 * It would be an O(number of front ends) annoyance to fix this
622 * in the front ends, but an O(number of back ends) annoyance
623 * to have each game capable of dealing with it. Therefore, we
624 * fix it _here_ in the common midend code so that it only has
627 * The possible ways in which things can go screwy in the front
630 * - in a system containing multiple physical buttons button
631 * presses can inadvertently overlap. We can see ABab (caps
632 * meaning button-down and lowercase meaning button-up) when
633 * the user had semantically intended AaBb.
635 * - in a system where one button is simulated by means of a
636 * modifier key and another button, buttons can mutate
637 * between press and release (possibly during drag). So we
638 * can see Ab instead of Aa.
640 * Definite requirements are:
642 * - button _presses_ must never be invented or destroyed. If
643 * the user presses two buttons in succession, the button
644 * presses must be transferred to the backend unchanged. So
645 * if we see AaBb , that's fine; if we see ABab (the button
646 * presses inadvertently overlapped) we must somehow
647 * `correct' it to AaBb.
649 * - every mouse action must end up looking like a press, zero
650 * or more drags, then a release. This allows back ends to
651 * make the _assumption_ that incoming mouse data will be
652 * sane in this regard, and not worry about the details.
654 * So my policy will be:
656 * - treat any button-up as a button-up for the currently
657 * pressed button, or ignore it if there is no currently
660 * - treat any drag as a drag for the currently pressed
661 * button, or ignore it if there is no currently pressed
664 * - if we see a button-down while another button is currently
665 * pressed, invent a button-up for the first one and then
666 * pass the button-down through as before.
668 * 2005-05-31: An addendum to the above. Some games might want
669 * a `priority order' among buttons, such that if one button is
670 * pressed while another is down then a fixed one of the
671 * buttons takes priority no matter what order they're pressed
672 * in. Mines, in particular, wants to treat a left+right click
673 * like a left click for the benefit of users of other
674 * implementations. So the last of the above points is modified
675 * in the presence of an (optional) button priority order.
677 if (IS_MOUSE_DRAG(button
) || IS_MOUSE_RELEASE(button
)) {
678 if (me
->pressed_mouse_button
) {
679 if (IS_MOUSE_DRAG(button
)) {
680 button
= me
->pressed_mouse_button
+
681 (LEFT_DRAG
- LEFT_BUTTON
);
683 button
= me
->pressed_mouse_button
+
684 (LEFT_RELEASE
- LEFT_BUTTON
);
687 return ret
; /* ignore it */
688 } else if (IS_MOUSE_DOWN(button
) && me
->pressed_mouse_button
) {
690 * If the new button has lower priority than the old one,
691 * don't bother doing this.
693 if (me
->ourgame
->flags
&
694 BUTTON_BEATS(me
->pressed_mouse_button
, button
))
695 return ret
; /* just ignore it */
698 * Fabricate a button-up for the previously pressed button.
700 ret
= ret
&& midend_really_process_key
701 (me
, x
, y
, (me
->pressed_mouse_button
+
702 (LEFT_RELEASE
- LEFT_BUTTON
)));
706 * Now send on the event we originally received.
708 ret
= ret
&& midend_really_process_key(me
, x
, y
, button
);
711 * And update the currently pressed button.
713 if (IS_MOUSE_RELEASE(button
))
714 me
->pressed_mouse_button
= 0;
715 else if (IS_MOUSE_DOWN(button
))
716 me
->pressed_mouse_button
= button
;
721 void midend_redraw(midend
*me
)
725 if (me
->statepos
> 0 && me
->drawstate
) {
726 start_draw(me
->drawing
);
727 if (me
->oldstate
&& me
->anim_time
> 0 &&
728 me
->anim_pos
< me
->anim_time
) {
729 assert(me
->dir
!= 0);
730 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, me
->oldstate
,
731 me
->states
[me
->statepos
-1].state
, me
->dir
,
732 me
->ui
, me
->anim_pos
, me
->flash_pos
);
734 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, NULL
,
735 me
->states
[me
->statepos
-1].state
, +1 /*shrug*/,
736 me
->ui
, 0.0, me
->flash_pos
);
738 end_draw(me
->drawing
);
742 void midend_timer(midend
*me
, float tplus
)
744 me
->anim_pos
+= tplus
;
745 if (me
->anim_pos
>= me
->anim_time
||
746 me
->anim_time
== 0 || !me
->oldstate
) {
747 if (me
->anim_time
> 0)
748 midend_finish_move(me
);
751 me
->flash_pos
+= tplus
;
752 if (me
->flash_pos
>= me
->flash_time
|| me
->flash_time
== 0) {
753 me
->flash_pos
= me
->flash_time
= 0;
759 float oldelapsed
= me
->elapsed
;
760 me
->elapsed
+= tplus
;
761 if ((int)oldelapsed
!= (int)me
->elapsed
)
762 status_bar(me
->drawing
, me
->laststatus ? me
->laststatus
: "");
765 midend_set_timer(me
);
768 float *midend_colours(midend
*me
, int *ncolours
)
772 ret
= me
->ourgame
->colours(me
->frontend
, ncolours
);
778 * Allow environment-based overrides for the standard
779 * colours by defining variables along the lines of
780 * `NET_COLOUR_4=6000c0'.
783 for (i
= 0; i
< *ncolours
; i
++) {
785 unsigned int r
, g
, b
;
788 sprintf(buf
, "%s_COLOUR_%d", me
->ourgame
->name
, i
);
789 for (j
= k
= 0; buf
[j
]; j
++)
790 if (!isspace((unsigned char)buf
[j
]))
791 buf
[k
++] = toupper((unsigned char)buf
[j
]);
793 if ((e
= getenv(buf
)) != NULL
&&
794 sscanf(e
, "%2x%2x%2x", &r
, &g
, &b
) == 3) {
795 ret
[i
*3 + 0] = r
/ 255.0;
796 ret
[i
*3 + 1] = g
/ 255.0;
797 ret
[i
*3 + 2] = b
/ 255.0;
805 int midend_num_presets(midend
*me
)
811 while (me
->ourgame
->fetch_preset(me
->npresets
, &name
, &preset
)) {
812 if (me
->presetsize
<= me
->npresets
) {
813 me
->presetsize
= me
->npresets
+ 10;
814 me
->presets
= sresize(me
->presets
, me
->presetsize
,
816 me
->preset_names
= sresize(me
->preset_names
, me
->presetsize
,
820 me
->presets
[me
->npresets
] = preset
;
821 me
->preset_names
[me
->npresets
] = name
;
828 * Allow environment-based extensions to the preset list by
829 * defining a variable along the lines of `SOLO_PRESETS=2x3
830 * Advanced:2x3da'. Colon-separated list of items,
831 * alternating between textual titles in the menu and
832 * encoded parameter strings.
834 char buf
[80], *e
, *p
;
837 sprintf(buf
, "%s_PRESETS", me
->ourgame
->name
);
838 for (j
= k
= 0; buf
[j
]; j
++)
839 if (!isspace((unsigned char)buf
[j
]))
840 buf
[k
++] = toupper((unsigned char)buf
[j
]);
843 if ((e
= getenv(buf
)) != NULL
) {
851 while (*p
&& *p
!= ':') p
++;
854 while (*p
&& *p
!= ':') p
++;
857 preset
= me
->ourgame
->default_params();
858 me
->ourgame
->decode_params(preset
, val
);
860 if (me
->ourgame
->validate_params(preset
, TRUE
)) {
861 /* Drop this one from the list. */
862 me
->ourgame
->free_params(preset
);
866 if (me
->presetsize
<= me
->npresets
) {
867 me
->presetsize
= me
->npresets
+ 10;
868 me
->presets
= sresize(me
->presets
, me
->presetsize
,
870 me
->preset_names
= sresize(me
->preset_names
,
871 me
->presetsize
, char *);
874 me
->presets
[me
->npresets
] = preset
;
875 me
->preset_names
[me
->npresets
] = dupstr(name
);
884 void midend_fetch_preset(midend
*me
, int n
,
885 char **name
, game_params
**params
)
887 assert(n
>= 0 && n
< me
->npresets
);
888 *name
= me
->preset_names
[n
];
889 *params
= me
->presets
[n
];
892 int midend_wants_statusbar(midend
*me
)
894 return me
->ourgame
->wants_statusbar
;
897 void midend_supersede_game_desc(midend
*me
, char *desc
, char *privdesc
)
901 me
->desc
= dupstr(desc
);
902 me
->privdesc
= privdesc ?
dupstr(privdesc
) : NULL
;
905 config_item
*midend_get_config(midend
*me
, int which
, char **wintitle
)
907 char *titlebuf
, *parstr
, *rest
;
912 titlebuf
= snewn(40 + strlen(me
->ourgame
->name
), char);
916 sprintf(titlebuf
, "%s configuration", me
->ourgame
->name
);
917 *wintitle
= titlebuf
;
918 return me
->ourgame
->configure(me
->params
);
921 if (!me
->curparams
) {
925 sprintf(titlebuf
, "%s %s selection", me
->ourgame
->name
,
926 which
== CFG_SEED ?
"random" : "game");
927 *wintitle
= titlebuf
;
929 ret
= snewn(2, config_item
);
931 ret
[0].type
= C_STRING
;
932 if (which
== CFG_SEED
)
933 ret
[0].name
= "Game random seed";
935 ret
[0].name
= "Game ID";
938 * For CFG_DESC the text going in here will be a string
939 * encoding of the restricted parameters, plus a colon,
940 * plus the game description. For CFG_SEED it will be the
941 * full parameters, plus a hash, plus the random seed data.
942 * Either of these is a valid full game ID (although only
943 * the former is likely to persist across many code
946 parstr
= me
->ourgame
->encode_params(me
->curparams
, which
== CFG_SEED
);
948 if (which
== CFG_DESC
) {
949 rest
= me
->desc ? me
->desc
: "";
952 rest
= me
->seedstr ? me
->seedstr
: "";
955 ret
[0].sval
= snewn(strlen(parstr
) + strlen(rest
) + 2, char);
956 sprintf(ret
[0].sval
, "%s%c%s", parstr
, sep
, rest
);
960 ret
[1].name
= ret
[1].sval
= NULL
;
966 assert(!"We shouldn't be here");
970 static char *midend_game_id_int(midend
*me
, char *id
, int defmode
)
972 char *error
, *par
, *desc
, *seed
;
973 game_params
*newcurparams
, *newparams
, *oldparams1
, *oldparams2
;
976 seed
= strchr(id
, '#');
977 desc
= strchr(id
, ':');
979 if (desc
&& (!seed
|| desc
< seed
)) {
981 * We have a colon separating parameters from game
982 * description. So `par' now points to the parameters
983 * string, and `desc' to the description string.
988 } else if (seed
&& (!desc
|| seed
< desc
)) {
990 * We have a hash separating parameters from random seed.
991 * So `par' now points to the parameters string, and `seed'
992 * to the seed string.
999 * We only have one string. Depending on `defmode', we take
1000 * it to be either parameters, seed or description.
1002 if (defmode
== DEF_SEED
) {
1005 } else if (defmode
== DEF_DESC
) {
1015 * We must be reasonably careful here not to modify anything in
1016 * `me' until we have finished validating things. This function
1017 * must either return an error and do nothing to the midend, or
1018 * return success and do everything; nothing in between is
1021 newcurparams
= newparams
= oldparams1
= oldparams2
= NULL
;
1024 newcurparams
= me
->ourgame
->dup_params(me
->params
);
1025 me
->ourgame
->decode_params(newcurparams
, par
);
1026 error
= me
->ourgame
->validate_params(newcurparams
, desc
== NULL
);
1028 me
->ourgame
->free_params(newcurparams
);
1031 oldparams1
= me
->curparams
;
1034 * Now filter only the persistent parts of this state into
1035 * the long-term params structure, unless we've _only_
1036 * received a params string in which case the whole lot is
1039 oldparams2
= me
->params
;
1043 newparams
= me
->ourgame
->dup_params(me
->params
);
1045 tmpstr
= me
->ourgame
->encode_params(newcurparams
, FALSE
);
1046 me
->ourgame
->decode_params(newparams
, tmpstr
);
1050 newparams
= me
->ourgame
->dup_params(newcurparams
);
1054 newcurparams
= me
->curparams
;
1055 newparams
= me
->params
;
1056 free_params
= FALSE
;
1060 error
= me
->ourgame
->validate_desc(newparams
, desc
);
1064 me
->ourgame
->free_params(newcurparams
);
1066 me
->ourgame
->free_params(newparams
);
1073 * Now we've got past all possible error points. Update the
1076 me
->params
= newparams
;
1077 me
->curparams
= newcurparams
;
1079 me
->ourgame
->free_params(oldparams1
);
1081 me
->ourgame
->free_params(oldparams2
);
1084 sfree(me
->privdesc
);
1085 me
->desc
= me
->privdesc
= NULL
;
1090 me
->desc
= dupstr(desc
);
1091 me
->genmode
= GOT_DESC
;
1092 sfree(me
->aux_info
);
1093 me
->aux_info
= NULL
;
1097 me
->seedstr
= dupstr(seed
);
1098 me
->genmode
= GOT_SEED
;
1104 char *midend_game_id(midend
*me
, char *id
)
1106 return midend_game_id_int(me
, id
, DEF_PARAMS
);
1109 char *midend_get_game_id(midend
*me
)
1113 parstr
= me
->ourgame
->encode_params(me
->curparams
, FALSE
);
1116 ret
= snewn(strlen(parstr
) + strlen(me
->desc
) + 2, char);
1117 sprintf(ret
, "%s:%s", parstr
, me
->desc
);
1122 char *midend_set_config(midend
*me
, int which
, config_item
*cfg
)
1125 game_params
*params
;
1129 params
= me
->ourgame
->custom_params(cfg
);
1130 error
= me
->ourgame
->validate_params(params
, TRUE
);
1133 me
->ourgame
->free_params(params
);
1137 me
->ourgame
->free_params(me
->params
);
1138 me
->params
= params
;
1143 error
= midend_game_id_int(me
, cfg
[0].sval
,
1144 (which
== CFG_SEED ? DEF_SEED
: DEF_DESC
));
1153 char *midend_text_format(midend
*me
)
1155 if (me
->ourgame
->can_format_as_text
&& me
->statepos
> 0)
1156 return me
->ourgame
->text_format(me
->states
[me
->statepos
-1].state
);
1161 char *midend_solve(midend
*me
)
1164 char *msg
, *movestr
;
1166 if (!me
->ourgame
->can_solve
)
1167 return "This game does not support the Solve operation";
1169 if (me
->statepos
< 1)
1170 return "No game set up to solve"; /* _shouldn't_ happen! */
1173 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1174 me
->states
[me
->statepos
-1].state
,
1175 me
->aux_info
, &msg
);
1178 msg
= "Solve operation failed"; /* _shouldn't_ happen, but can */
1181 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
, movestr
);
1185 * Now enter the solved state as the next move.
1187 midend_stop_anim(me
);
1188 while (me
->nstates
> me
->statepos
) {
1189 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
1190 if (me
->states
[me
->nstates
].movestr
)
1191 sfree(me
->states
[me
->nstates
].movestr
);
1194 me
->states
[me
->nstates
].state
= s
;
1195 me
->states
[me
->nstates
].movestr
= movestr
;
1196 me
->states
[me
->nstates
].movetype
= SOLVE
;
1197 me
->statepos
= ++me
->nstates
;
1199 me
->ourgame
->changed_state(me
->ui
,
1200 me
->states
[me
->statepos
-2].state
,
1201 me
->states
[me
->statepos
-1].state
);
1203 if (me
->ourgame
->flags
& SOLVE_ANIMATES
) {
1204 me
->oldstate
= me
->ourgame
->dup_game(me
->states
[me
->statepos
-2].state
);
1206 me
->ourgame
->anim_length(me
->states
[me
->statepos
-2].state
,
1207 me
->states
[me
->statepos
-1].state
,
1211 me
->anim_time
= 0.0;
1212 midend_finish_move(me
);
1215 midend_set_timer(me
);
1219 char *midend_rewrite_statusbar(midend
*me
, char *text
)
1222 * An important special case is that we are occasionally called
1223 * with our own laststatus, to update the timer.
1225 if (me
->laststatus
!= text
) {
1226 sfree(me
->laststatus
);
1227 me
->laststatus
= dupstr(text
);
1230 if (me
->ourgame
->is_timed
) {
1231 char timebuf
[100], *ret
;
1237 sprintf(timebuf
, "[%d:%02d] ", min
, sec
);
1239 ret
= snewn(strlen(timebuf
) + strlen(text
) + 1, char);
1240 strcpy(ret
, timebuf
);
1245 return dupstr(text
);
1249 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1250 #define SERIALISE_VERSION "1"
1252 void midend_serialise(midend
*me
,
1253 void (*write
)(void *ctx
, void *buf
, int len
),
1259 * Each line of the save file contains three components. First
1260 * exactly 8 characters of header word indicating what type of
1261 * data is contained on the line; then a colon followed by a
1262 * decimal integer giving the length of the main string on the
1263 * line; then a colon followed by the string itself (exactly as
1264 * many bytes as previously specified, no matter what they
1265 * contain). Then a newline (of reasonably flexible form).
1267 #define wr(h,s) do { \
1270 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1271 write(wctx, hbuf, strlen(hbuf)); \
1272 write(wctx, str, strlen(str)); \
1273 write(wctx, "\n", 1); \
1277 * Magic string identifying the file, and version number of the
1280 wr("SAVEFILE", SERIALISE_MAGIC
);
1281 wr("VERSION", SERIALISE_VERSION
);
1284 * The game name. (Copied locally to avoid const annoyance.)
1287 char *s
= dupstr(me
->ourgame
->name
);
1293 * The current long-term parameters structure, in full.
1296 char *s
= me
->ourgame
->encode_params(me
->params
, TRUE
);
1302 * The current short-term parameters structure, in full.
1304 if (me
->curparams
) {
1305 char *s
= me
->ourgame
->encode_params(me
->curparams
, TRUE
);
1311 * The current game description, the privdesc, and the random seed.
1314 wr("SEED", me
->seedstr
);
1316 wr("DESC", me
->desc
);
1318 wr("PRIVDESC", me
->privdesc
);
1321 * The game's aux_info. We obfuscate this to prevent spoilers
1322 * (people are likely to run `head' or similar on a saved game
1323 * file simply to find out what it is, and don't necessarily
1324 * want to be told the answer to the puzzle!)
1331 len
= strlen(me
->aux_info
);
1332 s1
= snewn(len
, unsigned char);
1333 memcpy(s1
, me
->aux_info
, len
);
1334 obfuscate_bitmap(s1
, len
*8, FALSE
);
1335 s2
= bin2hex(s1
, len
);
1344 * Any required serialisation of the game_ui.
1347 char *s
= me
->ourgame
->encode_ui(me
->ui
);
1355 * The game time, if it's a timed game.
1357 if (me
->ourgame
->is_timed
) {
1359 sprintf(buf
, "%g", me
->elapsed
);
1364 * The length of, and position in, the states list.
1368 sprintf(buf
, "%d", me
->nstates
);
1370 sprintf(buf
, "%d", me
->statepos
);
1371 wr("STATEPOS", buf
);
1375 * For each state after the initial one (which we know is
1376 * constructed from either privdesc or desc), enough
1377 * information for execute_move() to reconstruct it from the
1380 for (i
= 1; i
< me
->nstates
; i
++) {
1381 assert(me
->states
[i
].movetype
!= NEWGAME
); /* only state 0 */
1382 switch (me
->states
[i
].movetype
) {
1384 wr("MOVE", me
->states
[i
].movestr
);
1387 wr("SOLVE", me
->states
[i
].movestr
);
1390 wr("RESTART", me
->states
[i
].movestr
);
1399 * This function returns NULL on success, or an error message.
1401 char *midend_deserialise(midend
*me
,
1402 int (*read
)(void *ctx
, void *buf
, int len
),
1405 int nstates
= 0, statepos
= -1, gotstates
= 0;
1406 int started
= FALSE
;
1410 /* Initially all errors give the same report */
1411 char *ret
= "Data does not appear to be a saved game file";
1414 * We construct all the new state in local variables while we
1415 * check its sanity. Only once we have finished reading the
1416 * serialised data and detected no errors at all do we start
1417 * modifying stuff in the midend passed in.
1419 char *seed
= NULL
, *parstr
= NULL
, *desc
= NULL
, *privdesc
= NULL
;
1420 char *auxinfo
= NULL
, *uistr
= NULL
, *cparstr
= NULL
;
1421 float elapsed
= 0.0F
;
1422 game_params
*params
= NULL
, *cparams
= NULL
;
1424 struct midend_state_entry
*states
= NULL
;
1427 * Loop round and round reading one key/value pair at a time
1428 * from the serialised stream, until we have enough game states
1431 while (nstates
<= 0 || statepos
< 0 || gotstates
< nstates
-1) {
1436 if (!read(rctx
, key
, 1)) {
1437 /* unexpected EOF */
1440 } while (key
[0] == '\r' || key
[0] == '\n');
1442 if (!read(rctx
, key
+1, 8)) {
1443 /* unexpected EOF */
1447 if (key
[8] != ':') {
1449 ret
= "Data was incorrectly formatted for a saved game file";
1452 len
= strcspn(key
, ": ");
1458 if (!read(rctx
, &c
, 1)) {
1459 /* unexpected EOF */
1465 } else if (c
>= '0' && c
<= '9') {
1466 len
= (len
* 10) + (c
- '0');
1469 ret
= "Data was incorrectly formatted for a"
1475 val
= snewn(len
+1, char);
1476 if (!read(rctx
, val
, len
)) {
1483 if (strcmp(key
, "SAVEFILE") || strcmp(val
, SERIALISE_MAGIC
)) {
1484 /* ret already has the right message in it */
1487 /* Now most errors are this one, unless otherwise specified */
1488 ret
= "Saved data ended unexpectedly";
1491 if (!strcmp(key
, "VERSION")) {
1492 if (strcmp(val
, SERIALISE_VERSION
)) {
1493 ret
= "Cannot handle this version of the saved game"
1497 } else if (!strcmp(key
, "GAME")) {
1498 if (strcmp(val
, me
->ourgame
->name
)) {
1499 ret
= "Save file is from a different game";
1502 } else if (!strcmp(key
, "PARAMS")) {
1506 } else if (!strcmp(key
, "CPARAMS")) {
1510 } else if (!strcmp(key
, "SEED")) {
1514 } else if (!strcmp(key
, "DESC")) {
1518 } else if (!strcmp(key
, "PRIVDESC")) {
1522 } else if (!strcmp(key
, "AUXINFO")) {
1524 int len
= strlen(val
) / 2; /* length in bytes */
1525 tmp
= hex2bin(val
, len
);
1526 obfuscate_bitmap(tmp
, len
*8, TRUE
);
1529 auxinfo
= snewn(len
+ 1, char);
1530 memcpy(auxinfo
, tmp
, len
);
1531 auxinfo
[len
] = '\0';
1533 } else if (!strcmp(key
, "UI")) {
1537 } else if (!strcmp(key
, "TIME")) {
1538 elapsed
= atof(val
);
1539 } else if (!strcmp(key
, "NSTATES")) {
1540 nstates
= atoi(val
);
1542 ret
= "Number of states in save file was negative";
1546 ret
= "Two state counts provided in save file";
1549 states
= snewn(nstates
, struct midend_state_entry
);
1550 for (i
= 0; i
< nstates
; i
++) {
1551 states
[i
].state
= NULL
;
1552 states
[i
].movestr
= NULL
;
1553 states
[i
].movetype
= NEWGAME
;
1555 } else if (!strcmp(key
, "STATEPOS")) {
1556 statepos
= atoi(val
);
1557 } else if (!strcmp(key
, "MOVE")) {
1559 states
[gotstates
].movetype
= MOVE
;
1560 states
[gotstates
].movestr
= val
;
1562 } else if (!strcmp(key
, "SOLVE")) {
1564 states
[gotstates
].movetype
= SOLVE
;
1565 states
[gotstates
].movestr
= val
;
1567 } else if (!strcmp(key
, "RESTART")) {
1569 states
[gotstates
].movetype
= RESTART
;
1570 states
[gotstates
].movestr
= val
;
1579 params
= me
->ourgame
->default_params();
1580 me
->ourgame
->decode_params(params
, parstr
);
1581 if (me
->ourgame
->validate_params(params
, TRUE
)) {
1582 ret
= "Long-term parameters in save file are invalid";
1585 cparams
= me
->ourgame
->default_params();
1586 me
->ourgame
->decode_params(cparams
, cparstr
);
1587 if (me
->ourgame
->validate_params(cparams
, FALSE
)) {
1588 ret
= "Short-term parameters in save file are invalid";
1591 if (seed
&& me
->ourgame
->validate_params(cparams
, TRUE
)) {
1593 * The seed's no use with this version, but we can perfectly
1594 * well use the rest of the data.
1600 ret
= "Game description in save file is missing";
1602 } else if (me
->ourgame
->validate_desc(params
, desc
)) {
1603 ret
= "Game description in save file is invalid";
1606 if (privdesc
&& me
->ourgame
->validate_desc(params
, privdesc
)) {
1607 ret
= "Game private description in save file is invalid";
1610 if (statepos
< 0 || statepos
>= nstates
) {
1611 ret
= "Game position in save file is out of range";
1614 states
[0].state
= me
->ourgame
->new_game(me
, params
,
1615 privdesc ? privdesc
: desc
);
1616 for (i
= 1; i
< nstates
; i
++) {
1617 assert(states
[i
].movetype
!= NEWGAME
);
1618 switch (states
[i
].movetype
) {
1621 states
[i
].state
= me
->ourgame
->execute_move(states
[i
-1].state
,
1623 if (states
[i
].state
== NULL
) {
1624 ret
= "Save file contained an invalid move";
1629 if (me
->ourgame
->validate_desc(params
, states
[i
].movestr
)) {
1630 ret
= "Save file contained an invalid restart move";
1633 states
[i
].state
= me
->ourgame
->new_game(me
, params
,
1639 ui
= me
->ourgame
->new_ui(states
[0].state
);
1640 me
->ourgame
->decode_ui(ui
, uistr
);
1643 * Now we've run out of possible error conditions, so we're
1644 * ready to start overwriting the real data in the current
1645 * midend. We'll do this by swapping things with the local
1646 * variables, so that the same cleanup code will free the old
1657 me
->privdesc
= privdesc
;
1665 me
->aux_info
= auxinfo
;
1669 me
->genmode
= GOT_NOTHING
;
1671 me
->statesize
= nstates
;
1672 nstates
= me
->nstates
;
1673 me
->nstates
= me
->statesize
;
1675 struct midend_state_entry
*tmp
;
1677 me
->states
= states
;
1680 me
->statepos
= statepos
;
1686 me
->params
= params
;
1689 tmp
= me
->curparams
;
1690 me
->curparams
= cparams
;
1694 me
->oldstate
= NULL
;
1695 me
->anim_time
= me
->anim_pos
= me
->flash_time
= me
->flash_pos
= 0.0F
;
1706 me
->elapsed
= elapsed
;
1707 me
->pressed_mouse_button
= 0;
1709 midend_set_timer(me
);
1712 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
1714 me
->ourgame
->new_drawstate(me
->drawing
,
1715 me
->states
[me
->statepos
-1].state
);
1716 midend_size_new_drawstate(me
);
1718 ret
= NULL
; /* success! */
1730 me
->ourgame
->free_params(params
);
1732 me
->ourgame
->free_params(cparams
);
1734 me
->ourgame
->free_ui(ui
);
1738 for (i
= 0; i
< nstates
; i
++) {
1739 if (states
[i
].state
)
1740 me
->ourgame
->free_game(states
[i
].state
);
1741 sfree(states
[i
].movestr
);
1749 char *midend_print_puzzle(midend
*me
, document
*doc
, int with_soln
)
1751 game_state
*soln
= NULL
;
1753 if (me
->statepos
< 1)
1754 return "No game set up to print";/* _shouldn't_ happen! */
1757 char *msg
, *movestr
;
1759 if (!me
->ourgame
->can_solve
)
1760 return "This game does not support the Solve operation";
1762 msg
= "Solve operation failed";/* game _should_ overwrite on error */
1763 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1764 me
->states
[me
->statepos
-1].state
,
1765 me
->aux_info
, &msg
);
1768 soln
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
1777 * This call passes over ownership of the two game_states and
1778 * the game_params. Hence we duplicate the ones we want to
1779 * keep, and we don't have to bother freeing soln if it was
1782 document_add_puzzle(doc
, me
->ourgame
,
1783 me
->ourgame
->dup_params(me
->curparams
),
1784 me
->ourgame
->dup_game(me
->states
[0].state
), soln
);