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();
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
->preset_encodings
= NULL
;
119 me
->npresets
= me
->presetsize
= 0;
120 me
->anim_time
= me
->anim_pos
= 0.0F
;
121 me
->flash_time
= me
->flash_pos
= 0.0F
;
124 me
->pressed_mouse_button
= 0;
125 me
->laststatus
= NULL
;
128 me
->tilesize
= me
->winwidth
= me
->winheight
= 0;
130 me
->drawing
= drawing_new(drapi
, me
, drhandle
);
134 me
->preferred_tilesize
= ourgame
->preferred_tilesize
;
137 * Allow an environment-based override for the default tile
138 * size by defining a variable along the lines of
145 sprintf(buf
, "%s_TILESIZE", me
->ourgame
->name
);
146 for (j
= k
= 0; buf
[j
]; j
++)
147 if (!isspace((unsigned char)buf
[j
]))
148 buf
[k
++] = toupper((unsigned char)buf
[j
]);
150 if ((e
= getenv(buf
)) != NULL
&& sscanf(e
, "%d", &ts
) == 1 && ts
> 0)
151 me
->preferred_tilesize
= ts
;
159 static void midend_purge_states(midend
*me
)
161 while (me
->nstates
> me
->statepos
) {
162 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
163 if (me
->states
[me
->nstates
].movestr
)
164 sfree(me
->states
[me
->nstates
].movestr
);
168 static void midend_free_game(midend
*me
)
170 while (me
->nstates
> 0) {
172 me
->ourgame
->free_game(me
->states
[me
->nstates
].state
);
173 sfree(me
->states
[me
->nstates
].movestr
);
177 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
180 void midend_free(midend
*me
)
184 midend_free_game(me
);
187 drawing_free(me
->drawing
);
188 random_free(me
->random
);
194 me
->ourgame
->free_params(me
->params
);
196 for (i
= 0; i
< me
->npresets
; i
++) {
197 sfree(me
->presets
[i
]);
198 sfree(me
->preset_names
[i
]);
199 sfree(me
->preset_encodings
[i
]);
202 sfree(me
->preset_names
);
203 sfree(me
->preset_encodings
);
206 me
->ourgame
->free_ui(me
->ui
);
208 me
->ourgame
->free_params(me
->curparams
);
209 sfree(me
->laststatus
);
213 static void midend_size_new_drawstate(midend
*me
)
216 * Don't even bother, if we haven't worked out our tile size
219 if (me
->tilesize
> 0) {
220 me
->ourgame
->compute_size(me
->params
, me
->tilesize
,
221 &me
->winwidth
, &me
->winheight
);
222 me
->ourgame
->set_size(me
->drawing
, me
->drawstate
,
223 me
->params
, me
->tilesize
);
227 void midend_size(midend
*me
, int *x
, int *y
, int user_size
)
233 * We can't set the size on the same drawstate twice. So if
234 * we've already sized one drawstate, we must throw it away and
237 if (me
->drawstate
&& me
->tilesize
> 0) {
238 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
239 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
240 me
->states
[0].state
);
244 * Find the tile size that best fits within the given space. If
245 * `user_size' is TRUE, we must actually find the _largest_ such
246 * tile size, in order to get as close to the user's explicit
247 * request as possible; otherwise, we bound above at the game's
248 * preferred tile size, so that the game gets what it wants
249 * provided that this doesn't break the constraint from the
250 * front-end (which is likely to be a screen size or similar).
256 me
->ourgame
->compute_size(me
->params
, max
, &rx
, &ry
);
257 } while (rx
<= *x
&& ry
<= *y
);
259 max
= me
->preferred_tilesize
+ 1;
263 * Now binary-search between min and max. We're looking for a
264 * boundary rather than a value: the point at which tile sizes
265 * stop fitting within the given dimensions. Thus, we stop when
266 * max and min differ by exactly 1.
268 while (max
- min
> 1) {
269 int mid
= (max
+ min
) / 2;
270 me
->ourgame
->compute_size(me
->params
, mid
, &rx
, &ry
);
271 if (rx
<= *x
&& ry
<= *y
)
278 * Now `min' is a valid size, and `max' isn't. So use `min'.
283 /* If the user requested a change in size, make it permanent. */
284 me
->preferred_tilesize
= me
->tilesize
;
285 midend_size_new_drawstate(me
);
290 int midend_tilesize(midend
*me
) { return me
->tilesize
; }
292 void midend_set_params(midend
*me
, game_params
*params
)
294 me
->ourgame
->free_params(me
->params
);
295 me
->params
= me
->ourgame
->dup_params(params
);
298 game_params
*midend_get_params(midend
*me
)
300 return me
->ourgame
->dup_params(me
->params
);
303 static void midend_set_timer(midend
*me
)
305 me
->timing
= (me
->ourgame
->is_timed
&&
306 me
->ourgame
->timing_state(me
->states
[me
->statepos
-1].state
,
308 if (me
->timing
|| me
->flash_time
|| me
->anim_time
)
309 activate_timer(me
->frontend
);
311 deactivate_timer(me
->frontend
);
314 void midend_force_redraw(midend
*me
)
317 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
318 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
319 me
->states
[0].state
);
320 midend_size_new_drawstate(me
);
324 void midend_new_game(midend
*me
)
326 midend_free_game(me
);
328 assert(me
->nstates
== 0);
330 if (me
->genmode
== GOT_DESC
) {
331 me
->genmode
= GOT_NOTHING
;
335 if (me
->genmode
== GOT_SEED
) {
336 me
->genmode
= GOT_NOTHING
;
339 * Generate a new random seed. 15 digits comes to about
340 * 48 bits, which should be more than enough.
342 * I'll avoid putting a leading zero on the number,
343 * just in case it confuses anybody who thinks it's
344 * processed as an integer rather than a string.
349 newseed
[0] = '1' + (char)random_upto(me
->random
, 9);
350 for (i
= 1; i
< 15; i
++)
351 newseed
[i
] = '0' + (char)random_upto(me
->random
, 10);
353 me
->seedstr
= dupstr(newseed
);
356 me
->ourgame
->free_params(me
->curparams
);
357 me
->curparams
= me
->ourgame
->dup_params(me
->params
);
365 rs
= random_new(me
->seedstr
, strlen(me
->seedstr
));
367 * If this midend has been instantiated without providing a
368 * drawing API, it is non-interactive. This means that it's
369 * being used for bulk game generation, and hence we should
370 * pass the non-interactive flag to new_desc.
372 me
->desc
= me
->ourgame
->new_desc(me
->curparams
, rs
,
373 &me
->aux_info
, (me
->drawing
!= NULL
));
381 * It might seem a bit odd that we're using me->params to
382 * create the initial game state, rather than me->curparams
383 * which is better tailored to this specific game and which we
386 * It's supposed to be an invariant in the midend that
387 * me->params and me->curparams differ in no aspect that is
388 * important after generation (i.e. after new_desc()). By
389 * deliberately passing the _less_ specific of these two
390 * parameter sets, we provoke play-time misbehaviour in the
391 * case where a game has failed to encode a play-time parameter
392 * in the non-full version of encode_params().
394 me
->states
[me
->nstates
].state
=
395 me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
398 * As part of our commitment to self-testing, test the aux
399 * string to make sure nothing ghastly went wrong.
401 if (me
->ourgame
->can_solve
&& me
->aux_info
) {
406 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
409 assert(movestr
&& !msg
);
410 s
= me
->ourgame
->execute_move(me
->states
[0].state
, movestr
);
412 me
->ourgame
->free_game(s
);
416 me
->states
[me
->nstates
].movestr
= NULL
;
417 me
->states
[me
->nstates
].movetype
= NEWGAME
;
420 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
421 me
->states
[0].state
);
422 midend_size_new_drawstate(me
);
425 me
->ourgame
->free_ui(me
->ui
);
426 me
->ui
= me
->ourgame
->new_ui(me
->states
[0].state
);
427 midend_set_timer(me
);
428 me
->pressed_mouse_button
= 0;
431 static int midend_undo(midend
*me
)
433 if (me
->statepos
> 1) {
435 me
->ourgame
->changed_state(me
->ui
,
436 me
->states
[me
->statepos
-1].state
,
437 me
->states
[me
->statepos
-2].state
);
445 static int midend_redo(midend
*me
)
447 if (me
->statepos
< me
->nstates
) {
449 me
->ourgame
->changed_state(me
->ui
,
450 me
->states
[me
->statepos
-1].state
,
451 me
->states
[me
->statepos
].state
);
459 static void midend_finish_move(midend
*me
)
464 * We do not flash if the later of the two states is special.
465 * This covers both forward Solve moves and backward (undone)
468 if ((me
->oldstate
|| me
->statepos
> 1) &&
469 ((me
->dir
> 0 && !special(me
->states
[me
->statepos
-1].movetype
)) ||
470 (me
->dir
< 0 && me
->statepos
< me
->nstates
&&
471 !special(me
->states
[me
->statepos
].movetype
)))) {
472 flashtime
= me
->ourgame
->flash_length(me
->oldstate ? me
->oldstate
:
473 me
->states
[me
->statepos
-2].state
,
474 me
->states
[me
->statepos
-1].state
,
475 me
->oldstate ? me
->dir
: +1,
478 me
->flash_pos
= 0.0F
;
479 me
->flash_time
= flashtime
;
484 me
->ourgame
->free_game(me
->oldstate
);
486 me
->anim_pos
= me
->anim_time
= 0;
489 midend_set_timer(me
);
492 void midend_stop_anim(midend
*me
)
494 if (me
->oldstate
|| me
->anim_time
!= 0) {
495 midend_finish_move(me
);
500 void midend_restart_game(midend
*me
)
504 midend_stop_anim(me
);
506 assert(me
->statepos
>= 1);
507 if (me
->statepos
== 1)
508 return; /* no point doing anything at all! */
511 * During restart, we reconstruct the game from the (public)
512 * game description rather than from states[0], because that
513 * way Mines gets slightly more sensible behaviour (restart
514 * goes to _after_ the first click so you don't have to
515 * remember where you clicked).
517 s
= me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
520 * Now enter the restarted state as the next move.
522 midend_stop_anim(me
);
523 midend_purge_states(me
);
525 me
->states
[me
->nstates
].state
= s
;
526 me
->states
[me
->nstates
].movestr
= dupstr(me
->desc
);
527 me
->states
[me
->nstates
].movetype
= RESTART
;
528 me
->statepos
= ++me
->nstates
;
530 me
->ourgame
->changed_state(me
->ui
,
531 me
->states
[me
->statepos
-2].state
,
532 me
->states
[me
->statepos
-1].state
);
534 midend_finish_move(me
);
536 midend_set_timer(me
);
539 static int midend_really_process_key(midend
*me
, int x
, int y
, int button
)
541 game_state
*oldstate
=
542 me
->ourgame
->dup_game(me
->states
[me
->statepos
- 1].state
);
543 int type
= MOVE
, gottype
= FALSE
, ret
= 1;
549 me
->ourgame
->interpret_move(me
->states
[me
->statepos
-1].state
,
550 me
->ui
, me
->drawstate
, x
, y
, button
);
553 if (button
== 'n' || button
== 'N' || button
== '\x0E') {
554 midend_stop_anim(me
);
557 goto done
; /* never animate */
558 } else if (button
== 'u' || button
== 'u' ||
559 button
== '\x1A' || button
== '\x1F') {
560 midend_stop_anim(me
);
561 type
= me
->states
[me
->statepos
-1].movetype
;
563 if (!midend_undo(me
))
565 } else if (button
== 'r' || button
== 'R' ||
566 button
== '\x12' || button
== '\x19') {
567 midend_stop_anim(me
);
568 if (!midend_redo(me
))
570 } else if (button
== '\x13' && me
->ourgame
->can_solve
) {
571 if (midend_solve(me
))
573 } else if (button
== 'q' || button
== 'Q' || button
== '\x11') {
580 s
= me
->states
[me
->statepos
-1].state
;
582 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
587 if (s
== me
->states
[me
->statepos
-1].state
) {
589 * make_move() is allowed to return its input state to
590 * indicate that although no move has been made, the UI
591 * state has been updated and a redraw is called for.
594 midend_set_timer(me
);
597 midend_stop_anim(me
);
598 midend_purge_states(me
);
600 assert(movestr
!= NULL
);
601 me
->states
[me
->nstates
].state
= s
;
602 me
->states
[me
->nstates
].movestr
= movestr
;
603 me
->states
[me
->nstates
].movetype
= MOVE
;
604 me
->statepos
= ++me
->nstates
;
607 me
->ourgame
->changed_state(me
->ui
,
608 me
->states
[me
->statepos
-2].state
,
609 me
->states
[me
->statepos
-1].state
);
616 type
= me
->states
[me
->statepos
-1].movetype
;
619 * See if this move requires an animation.
621 if (special(type
) && !(type
== SOLVE
&&
622 (me
->ourgame
->flags
& SOLVE_ANIMATES
))) {
625 anim_time
= me
->ourgame
->anim_length(oldstate
,
626 me
->states
[me
->statepos
-1].state
,
630 me
->oldstate
= oldstate
; oldstate
= NULL
;
632 me
->anim_time
= anim_time
;
635 midend_finish_move(me
);
641 midend_set_timer(me
);
644 if (oldstate
) me
->ourgame
->free_game(oldstate
);
648 int midend_process_key(midend
*me
, int x
, int y
, int button
)
653 * Harmonise mouse drag and release messages.
655 * Some front ends might accidentally switch from sending, say,
656 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
657 * drag. (This can happen on the Mac, for example, since
658 * RIGHT_DRAG is usually done using Command+drag, and if the
659 * user accidentally releases Command half way through the drag
660 * then there will be trouble.)
662 * It would be an O(number of front ends) annoyance to fix this
663 * in the front ends, but an O(number of back ends) annoyance
664 * to have each game capable of dealing with it. Therefore, we
665 * fix it _here_ in the common midend code so that it only has
668 * The possible ways in which things can go screwy in the front
671 * - in a system containing multiple physical buttons button
672 * presses can inadvertently overlap. We can see ABab (caps
673 * meaning button-down and lowercase meaning button-up) when
674 * the user had semantically intended AaBb.
676 * - in a system where one button is simulated by means of a
677 * modifier key and another button, buttons can mutate
678 * between press and release (possibly during drag). So we
679 * can see Ab instead of Aa.
681 * Definite requirements are:
683 * - button _presses_ must never be invented or destroyed. If
684 * the user presses two buttons in succession, the button
685 * presses must be transferred to the backend unchanged. So
686 * if we see AaBb , that's fine; if we see ABab (the button
687 * presses inadvertently overlapped) we must somehow
688 * `correct' it to AaBb.
690 * - every mouse action must end up looking like a press, zero
691 * or more drags, then a release. This allows back ends to
692 * make the _assumption_ that incoming mouse data will be
693 * sane in this regard, and not worry about the details.
695 * So my policy will be:
697 * - treat any button-up as a button-up for the currently
698 * pressed button, or ignore it if there is no currently
701 * - treat any drag as a drag for the currently pressed
702 * button, or ignore it if there is no currently pressed
705 * - if we see a button-down while another button is currently
706 * pressed, invent a button-up for the first one and then
707 * pass the button-down through as before.
709 * 2005-05-31: An addendum to the above. Some games might want
710 * a `priority order' among buttons, such that if one button is
711 * pressed while another is down then a fixed one of the
712 * buttons takes priority no matter what order they're pressed
713 * in. Mines, in particular, wants to treat a left+right click
714 * like a left click for the benefit of users of other
715 * implementations. So the last of the above points is modified
716 * in the presence of an (optional) button priority order.
718 * A further addition: we translate certain keyboard presses to
719 * cursor key 'select' buttons, so that a) frontends don't have
720 * to translate these themselves (like they do for CURSOR_UP etc),
721 * and b) individual games don't have to hard-code button presses
722 * of '\n' etc for keyboard-based cursors. The choice of buttons
723 * here could eventually be controlled by a runtime configuration
726 if (IS_MOUSE_DRAG(button
) || IS_MOUSE_RELEASE(button
)) {
727 if (me
->pressed_mouse_button
) {
728 if (IS_MOUSE_DRAG(button
)) {
729 button
= me
->pressed_mouse_button
+
730 (LEFT_DRAG
- LEFT_BUTTON
);
732 button
= me
->pressed_mouse_button
+
733 (LEFT_RELEASE
- LEFT_BUTTON
);
736 return ret
; /* ignore it */
737 } else if (IS_MOUSE_DOWN(button
) && me
->pressed_mouse_button
) {
739 * If the new button has lower priority than the old one,
740 * don't bother doing this.
742 if (me
->ourgame
->flags
&
743 BUTTON_BEATS(me
->pressed_mouse_button
, button
))
744 return ret
; /* just ignore it */
747 * Fabricate a button-up for the previously pressed button.
749 ret
= ret
&& midend_really_process_key
750 (me
, x
, y
, (me
->pressed_mouse_button
+
751 (LEFT_RELEASE
- LEFT_BUTTON
)));
755 * Translate keyboard presses to cursor selection.
757 if (button
== '\n' || button
== '\r')
758 button
= CURSOR_SELECT
;
760 button
= CURSOR_SELECT2
;
763 * Normalise both backspace characters (8 and 127) to \b. Easier
764 * to do this once, here, than to require all front ends to
765 * carefully generate the same one - now each front end can
766 * generate whichever is easiest.
768 if (button
== '\177')
772 * Now send on the event we originally received.
774 ret
= ret
&& midend_really_process_key(me
, x
, y
, button
);
777 * And update the currently pressed button.
779 if (IS_MOUSE_RELEASE(button
))
780 me
->pressed_mouse_button
= 0;
781 else if (IS_MOUSE_DOWN(button
))
782 me
->pressed_mouse_button
= button
;
787 void midend_redraw(midend
*me
)
791 if (me
->statepos
> 0 && me
->drawstate
) {
792 start_draw(me
->drawing
);
793 if (me
->oldstate
&& me
->anim_time
> 0 &&
794 me
->anim_pos
< me
->anim_time
) {
795 assert(me
->dir
!= 0);
796 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, me
->oldstate
,
797 me
->states
[me
->statepos
-1].state
, me
->dir
,
798 me
->ui
, me
->anim_pos
, me
->flash_pos
);
800 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, NULL
,
801 me
->states
[me
->statepos
-1].state
, +1 /*shrug*/,
802 me
->ui
, 0.0, me
->flash_pos
);
804 end_draw(me
->drawing
);
809 * Nasty hacky function used to implement the --redo option in
810 * gtk.c. Only used for generating the puzzles' icons.
812 void midend_freeze_timer(midend
*me
, float tprop
)
814 me
->anim_pos
= me
->anim_time
* tprop
;
816 deactivate_timer(me
->frontend
);
819 void midend_timer(midend
*me
, float tplus
)
821 int need_redraw
= (me
->anim_time
> 0 || me
->flash_time
> 0);
823 me
->anim_pos
+= tplus
;
824 if (me
->anim_pos
>= me
->anim_time
||
825 me
->anim_time
== 0 || !me
->oldstate
) {
826 if (me
->anim_time
> 0)
827 midend_finish_move(me
);
830 me
->flash_pos
+= tplus
;
831 if (me
->flash_pos
>= me
->flash_time
|| me
->flash_time
== 0) {
832 me
->flash_pos
= me
->flash_time
= 0;
839 float oldelapsed
= me
->elapsed
;
840 me
->elapsed
+= tplus
;
841 if ((int)oldelapsed
!= (int)me
->elapsed
)
842 status_bar(me
->drawing
, me
->laststatus ? me
->laststatus
: "");
845 midend_set_timer(me
);
848 float *midend_colours(midend
*me
, int *ncolours
)
852 ret
= me
->ourgame
->colours(me
->frontend
, ncolours
);
858 * Allow environment-based overrides for the standard
859 * colours by defining variables along the lines of
860 * `NET_COLOUR_4=6000c0'.
863 for (i
= 0; i
< *ncolours
; i
++) {
865 unsigned int r
, g
, b
;
868 sprintf(buf
, "%s_COLOUR_%d", me
->ourgame
->name
, i
);
869 for (j
= k
= 0; buf
[j
]; j
++)
870 if (!isspace((unsigned char)buf
[j
]))
871 buf
[k
++] = toupper((unsigned char)buf
[j
]);
873 if ((e
= getenv(buf
)) != NULL
&&
874 sscanf(e
, "%2x%2x%2x", &r
, &g
, &b
) == 3) {
875 ret
[i
*3 + 0] = r
/ 255.0F
;
876 ret
[i
*3 + 1] = g
/ 255.0F
;
877 ret
[i
*3 + 2] = b
/ 255.0F
;
885 int midend_num_presets(midend
*me
)
891 while (me
->ourgame
->fetch_preset(me
->npresets
, &name
, &preset
)) {
892 if (me
->presetsize
<= me
->npresets
) {
893 me
->presetsize
= me
->npresets
+ 10;
894 me
->presets
= sresize(me
->presets
, me
->presetsize
,
896 me
->preset_names
= sresize(me
->preset_names
, me
->presetsize
,
898 me
->preset_encodings
= sresize(me
->preset_encodings
,
899 me
->presetsize
, char *);
902 me
->presets
[me
->npresets
] = preset
;
903 me
->preset_names
[me
->npresets
] = name
;
904 me
->preset_encodings
[me
->npresets
] =
905 me
->ourgame
->encode_params(preset
, TRUE
);;
912 * Allow environment-based extensions to the preset list by
913 * defining a variable along the lines of `SOLO_PRESETS=2x3
914 * Advanced:2x3da'. Colon-separated list of items,
915 * alternating between textual titles in the menu and
916 * encoded parameter strings.
918 char buf
[80], *e
, *p
;
921 sprintf(buf
, "%s_PRESETS", me
->ourgame
->name
);
922 for (j
= k
= 0; buf
[j
]; j
++)
923 if (!isspace((unsigned char)buf
[j
]))
924 buf
[k
++] = toupper((unsigned char)buf
[j
]);
927 if ((e
= getenv(buf
)) != NULL
) {
935 while (*p
&& *p
!= ':') p
++;
938 while (*p
&& *p
!= ':') p
++;
941 preset
= me
->ourgame
->default_params();
942 me
->ourgame
->decode_params(preset
, val
);
944 if (me
->ourgame
->validate_params(preset
, TRUE
)) {
945 /* Drop this one from the list. */
946 me
->ourgame
->free_params(preset
);
950 if (me
->presetsize
<= me
->npresets
) {
951 me
->presetsize
= me
->npresets
+ 10;
952 me
->presets
= sresize(me
->presets
, me
->presetsize
,
954 me
->preset_names
= sresize(me
->preset_names
,
955 me
->presetsize
, char *);
956 me
->preset_encodings
= sresize(me
->preset_encodings
,
957 me
->presetsize
, char *);
960 me
->presets
[me
->npresets
] = preset
;
961 me
->preset_names
[me
->npresets
] = dupstr(name
);
962 me
->preset_encodings
[me
->npresets
] =
963 me
->ourgame
->encode_params(preset
, TRUE
);
973 void midend_fetch_preset(midend
*me
, int n
,
974 char **name
, game_params
**params
)
976 assert(n
>= 0 && n
< me
->npresets
);
977 *name
= me
->preset_names
[n
];
978 *params
= me
->presets
[n
];
981 int midend_which_preset(midend
*me
)
983 char *encoding
= me
->ourgame
->encode_params(me
->params
, TRUE
);
987 for (i
= 0; i
< me
->npresets
; i
++)
988 if (!strcmp(encoding
, me
->preset_encodings
[i
])) {
997 int midend_wants_statusbar(midend
*me
)
999 return me
->ourgame
->wants_statusbar
;
1002 void midend_supersede_game_desc(midend
*me
, char *desc
, char *privdesc
)
1005 sfree(me
->privdesc
);
1006 me
->desc
= dupstr(desc
);
1007 me
->privdesc
= privdesc ?
dupstr(privdesc
) : NULL
;
1010 config_item
*midend_get_config(midend
*me
, int which
, char **wintitle
)
1012 char *titlebuf
, *parstr
, *rest
;
1017 titlebuf
= snewn(40 + strlen(me
->ourgame
->name
), char);
1021 sprintf(titlebuf
, "%s configuration", me
->ourgame
->name
);
1022 *wintitle
= titlebuf
;
1023 return me
->ourgame
->configure(me
->params
);
1026 if (!me
->curparams
) {
1030 sprintf(titlebuf
, "%s %s selection", me
->ourgame
->name
,
1031 which
== CFG_SEED ?
"random" : "game");
1032 *wintitle
= titlebuf
;
1034 ret
= snewn(2, config_item
);
1036 ret
[0].type
= C_STRING
;
1037 if (which
== CFG_SEED
)
1038 ret
[0].name
= "Game random seed";
1040 ret
[0].name
= "Game ID";
1043 * For CFG_DESC the text going in here will be a string
1044 * encoding of the restricted parameters, plus a colon,
1045 * plus the game description. For CFG_SEED it will be the
1046 * full parameters, plus a hash, plus the random seed data.
1047 * Either of these is a valid full game ID (although only
1048 * the former is likely to persist across many code
1051 parstr
= me
->ourgame
->encode_params(me
->curparams
, which
== CFG_SEED
);
1053 if (which
== CFG_DESC
) {
1054 rest
= me
->desc ? me
->desc
: "";
1057 rest
= me
->seedstr ? me
->seedstr
: "";
1060 ret
[0].sval
= snewn(strlen(parstr
) + strlen(rest
) + 2, char);
1061 sprintf(ret
[0].sval
, "%s%c%s", parstr
, sep
, rest
);
1064 ret
[1].type
= C_END
;
1065 ret
[1].name
= ret
[1].sval
= NULL
;
1071 assert(!"We shouldn't be here");
1075 static char *midend_game_id_int(midend
*me
, char *id
, int defmode
)
1077 char *error
, *par
, *desc
, *seed
;
1078 game_params
*newcurparams
, *newparams
, *oldparams1
, *oldparams2
;
1081 seed
= strchr(id
, '#');
1082 desc
= strchr(id
, ':');
1084 if (desc
&& (!seed
|| desc
< seed
)) {
1086 * We have a colon separating parameters from game
1087 * description. So `par' now points to the parameters
1088 * string, and `desc' to the description string.
1093 } else if (seed
&& (!desc
|| seed
< desc
)) {
1095 * We have a hash separating parameters from random seed.
1096 * So `par' now points to the parameters string, and `seed'
1097 * to the seed string.
1104 * We only have one string. Depending on `defmode', we take
1105 * it to be either parameters, seed or description.
1107 if (defmode
== DEF_SEED
) {
1110 } else if (defmode
== DEF_DESC
) {
1120 * We must be reasonably careful here not to modify anything in
1121 * `me' until we have finished validating things. This function
1122 * must either return an error and do nothing to the midend, or
1123 * return success and do everything; nothing in between is
1126 newcurparams
= newparams
= oldparams1
= oldparams2
= NULL
;
1129 newcurparams
= me
->ourgame
->dup_params(me
->params
);
1130 me
->ourgame
->decode_params(newcurparams
, par
);
1131 error
= me
->ourgame
->validate_params(newcurparams
, desc
== NULL
);
1133 me
->ourgame
->free_params(newcurparams
);
1136 oldparams1
= me
->curparams
;
1139 * Now filter only the persistent parts of this state into
1140 * the long-term params structure, unless we've _only_
1141 * received a params string in which case the whole lot is
1144 oldparams2
= me
->params
;
1148 newparams
= me
->ourgame
->dup_params(me
->params
);
1150 tmpstr
= me
->ourgame
->encode_params(newcurparams
, FALSE
);
1151 me
->ourgame
->decode_params(newparams
, tmpstr
);
1155 newparams
= me
->ourgame
->dup_params(newcurparams
);
1159 newcurparams
= me
->curparams
;
1160 newparams
= me
->params
;
1161 free_params
= FALSE
;
1165 error
= me
->ourgame
->validate_desc(newparams
, desc
);
1169 me
->ourgame
->free_params(newcurparams
);
1171 me
->ourgame
->free_params(newparams
);
1178 * Now we've got past all possible error points. Update the
1181 me
->params
= newparams
;
1182 me
->curparams
= newcurparams
;
1184 me
->ourgame
->free_params(oldparams1
);
1186 me
->ourgame
->free_params(oldparams2
);
1189 sfree(me
->privdesc
);
1190 me
->desc
= me
->privdesc
= NULL
;
1195 me
->desc
= dupstr(desc
);
1196 me
->genmode
= GOT_DESC
;
1197 sfree(me
->aux_info
);
1198 me
->aux_info
= NULL
;
1202 me
->seedstr
= dupstr(seed
);
1203 me
->genmode
= GOT_SEED
;
1209 char *midend_game_id(midend
*me
, char *id
)
1211 return midend_game_id_int(me
, id
, DEF_PARAMS
);
1214 char *midend_get_game_id(midend
*me
)
1218 parstr
= me
->ourgame
->encode_params(me
->curparams
, FALSE
);
1221 ret
= snewn(strlen(parstr
) + strlen(me
->desc
) + 2, char);
1222 sprintf(ret
, "%s:%s", parstr
, me
->desc
);
1227 char *midend_set_config(midend
*me
, int which
, config_item
*cfg
)
1230 game_params
*params
;
1234 params
= me
->ourgame
->custom_params(cfg
);
1235 error
= me
->ourgame
->validate_params(params
, TRUE
);
1238 me
->ourgame
->free_params(params
);
1242 me
->ourgame
->free_params(me
->params
);
1243 me
->params
= params
;
1248 error
= midend_game_id_int(me
, cfg
[0].sval
,
1249 (which
== CFG_SEED ? DEF_SEED
: DEF_DESC
));
1258 int midend_can_format_as_text_now(midend
*me
)
1260 if (me
->ourgame
->can_format_as_text_ever
)
1261 return me
->ourgame
->can_format_as_text_now(me
->params
);
1266 char *midend_text_format(midend
*me
)
1268 if (me
->ourgame
->can_format_as_text_ever
&& me
->statepos
> 0 &&
1269 me
->ourgame
->can_format_as_text_now(me
->params
))
1270 return me
->ourgame
->text_format(me
->states
[me
->statepos
-1].state
);
1275 char *midend_solve(midend
*me
)
1278 char *msg
, *movestr
;
1280 if (!me
->ourgame
->can_solve
)
1281 return "This game does not support the Solve operation";
1283 if (me
->statepos
< 1)
1284 return "No game set up to solve"; /* _shouldn't_ happen! */
1287 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1288 me
->states
[me
->statepos
-1].state
,
1289 me
->aux_info
, &msg
);
1292 msg
= "Solve operation failed"; /* _shouldn't_ happen, but can */
1295 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
, movestr
);
1299 * Now enter the solved state as the next move.
1301 midend_stop_anim(me
);
1302 midend_purge_states(me
);
1304 me
->states
[me
->nstates
].state
= s
;
1305 me
->states
[me
->nstates
].movestr
= movestr
;
1306 me
->states
[me
->nstates
].movetype
= SOLVE
;
1307 me
->statepos
= ++me
->nstates
;
1309 me
->ourgame
->changed_state(me
->ui
,
1310 me
->states
[me
->statepos
-2].state
,
1311 me
->states
[me
->statepos
-1].state
);
1313 if (me
->ourgame
->flags
& SOLVE_ANIMATES
) {
1314 me
->oldstate
= me
->ourgame
->dup_game(me
->states
[me
->statepos
-2].state
);
1316 me
->ourgame
->anim_length(me
->states
[me
->statepos
-2].state
,
1317 me
->states
[me
->statepos
-1].state
,
1321 me
->anim_time
= 0.0;
1322 midend_finish_move(me
);
1325 midend_set_timer(me
);
1329 char *midend_rewrite_statusbar(midend
*me
, char *text
)
1332 * An important special case is that we are occasionally called
1333 * with our own laststatus, to update the timer.
1335 if (me
->laststatus
!= text
) {
1336 sfree(me
->laststatus
);
1337 me
->laststatus
= dupstr(text
);
1340 if (me
->ourgame
->is_timed
) {
1341 char timebuf
[100], *ret
;
1344 sec
= (int)me
->elapsed
;
1347 sprintf(timebuf
, "[%d:%02d] ", min
, sec
);
1349 ret
= snewn(strlen(timebuf
) + strlen(text
) + 1, char);
1350 strcpy(ret
, timebuf
);
1355 return dupstr(text
);
1359 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1360 #define SERIALISE_VERSION "1"
1362 void midend_serialise(midend
*me
,
1363 void (*write
)(void *ctx
, void *buf
, int len
),
1369 * Each line of the save file contains three components. First
1370 * exactly 8 characters of header word indicating what type of
1371 * data is contained on the line; then a colon followed by a
1372 * decimal integer giving the length of the main string on the
1373 * line; then a colon followed by the string itself (exactly as
1374 * many bytes as previously specified, no matter what they
1375 * contain). Then a newline (of reasonably flexible form).
1377 #define wr(h,s) do { \
1380 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1381 write(wctx, hbuf, strlen(hbuf)); \
1382 write(wctx, str, strlen(str)); \
1383 write(wctx, "\n", 1); \
1387 * Magic string identifying the file, and version number of the
1390 wr("SAVEFILE", SERIALISE_MAGIC
);
1391 wr("VERSION", SERIALISE_VERSION
);
1394 * The game name. (Copied locally to avoid const annoyance.)
1397 char *s
= dupstr(me
->ourgame
->name
);
1403 * The current long-term parameters structure, in full.
1406 char *s
= me
->ourgame
->encode_params(me
->params
, TRUE
);
1412 * The current short-term parameters structure, in full.
1414 if (me
->curparams
) {
1415 char *s
= me
->ourgame
->encode_params(me
->curparams
, TRUE
);
1421 * The current game description, the privdesc, and the random seed.
1424 wr("SEED", me
->seedstr
);
1426 wr("DESC", me
->desc
);
1428 wr("PRIVDESC", me
->privdesc
);
1431 * The game's aux_info. We obfuscate this to prevent spoilers
1432 * (people are likely to run `head' or similar on a saved game
1433 * file simply to find out what it is, and don't necessarily
1434 * want to be told the answer to the puzzle!)
1441 len
= strlen(me
->aux_info
);
1442 s1
= snewn(len
, unsigned char);
1443 memcpy(s1
, me
->aux_info
, len
);
1444 obfuscate_bitmap(s1
, len
*8, FALSE
);
1445 s2
= bin2hex(s1
, len
);
1454 * Any required serialisation of the game_ui.
1457 char *s
= me
->ourgame
->encode_ui(me
->ui
);
1465 * The game time, if it's a timed game.
1467 if (me
->ourgame
->is_timed
) {
1469 sprintf(buf
, "%g", me
->elapsed
);
1474 * The length of, and position in, the states list.
1478 sprintf(buf
, "%d", me
->nstates
);
1480 sprintf(buf
, "%d", me
->statepos
);
1481 wr("STATEPOS", buf
);
1485 * For each state after the initial one (which we know is
1486 * constructed from either privdesc or desc), enough
1487 * information for execute_move() to reconstruct it from the
1490 for (i
= 1; i
< me
->nstates
; i
++) {
1491 assert(me
->states
[i
].movetype
!= NEWGAME
); /* only state 0 */
1492 switch (me
->states
[i
].movetype
) {
1494 wr("MOVE", me
->states
[i
].movestr
);
1497 wr("SOLVE", me
->states
[i
].movestr
);
1500 wr("RESTART", me
->states
[i
].movestr
);
1509 * This function returns NULL on success, or an error message.
1511 char *midend_deserialise(midend
*me
,
1512 int (*read
)(void *ctx
, void *buf
, int len
),
1515 int nstates
= 0, statepos
= -1, gotstates
= 0;
1516 int started
= FALSE
;
1520 /* Initially all errors give the same report */
1521 char *ret
= "Data does not appear to be a saved game file";
1524 * We construct all the new state in local variables while we
1525 * check its sanity. Only once we have finished reading the
1526 * serialised data and detected no errors at all do we start
1527 * modifying stuff in the midend passed in.
1529 char *seed
= NULL
, *parstr
= NULL
, *desc
= NULL
, *privdesc
= NULL
;
1530 char *auxinfo
= NULL
, *uistr
= NULL
, *cparstr
= NULL
;
1531 float elapsed
= 0.0F
;
1532 game_params
*params
= NULL
, *cparams
= NULL
;
1534 struct midend_state_entry
*states
= NULL
;
1537 * Loop round and round reading one key/value pair at a time
1538 * from the serialised stream, until we have enough game states
1541 while (nstates
<= 0 || statepos
< 0 || gotstates
< nstates
-1) {
1546 if (!read(rctx
, key
, 1)) {
1547 /* unexpected EOF */
1550 } while (key
[0] == '\r' || key
[0] == '\n');
1552 if (!read(rctx
, key
+1, 8)) {
1553 /* unexpected EOF */
1557 if (key
[8] != ':') {
1559 ret
= "Data was incorrectly formatted for a saved game file";
1562 len
= strcspn(key
, ": ");
1568 if (!read(rctx
, &c
, 1)) {
1569 /* unexpected EOF */
1575 } else if (c
>= '0' && c
<= '9') {
1576 len
= (len
* 10) + (c
- '0');
1579 ret
= "Data was incorrectly formatted for a"
1585 val
= snewn(len
+1, char);
1586 if (!read(rctx
, val
, len
)) {
1593 if (strcmp(key
, "SAVEFILE") || strcmp(val
, SERIALISE_MAGIC
)) {
1594 /* ret already has the right message in it */
1597 /* Now most errors are this one, unless otherwise specified */
1598 ret
= "Saved data ended unexpectedly";
1601 if (!strcmp(key
, "VERSION")) {
1602 if (strcmp(val
, SERIALISE_VERSION
)) {
1603 ret
= "Cannot handle this version of the saved game"
1607 } else if (!strcmp(key
, "GAME")) {
1608 if (strcmp(val
, me
->ourgame
->name
)) {
1609 ret
= "Save file is from a different game";
1612 } else if (!strcmp(key
, "PARAMS")) {
1616 } else if (!strcmp(key
, "CPARAMS")) {
1620 } else if (!strcmp(key
, "SEED")) {
1624 } else if (!strcmp(key
, "DESC")) {
1628 } else if (!strcmp(key
, "PRIVDESC")) {
1632 } else if (!strcmp(key
, "AUXINFO")) {
1634 int len
= strlen(val
) / 2; /* length in bytes */
1635 tmp
= hex2bin(val
, len
);
1636 obfuscate_bitmap(tmp
, len
*8, TRUE
);
1639 auxinfo
= snewn(len
+ 1, char);
1640 memcpy(auxinfo
, tmp
, len
);
1641 auxinfo
[len
] = '\0';
1643 } else if (!strcmp(key
, "UI")) {
1647 } else if (!strcmp(key
, "TIME")) {
1648 elapsed
= (float)atof(val
);
1649 } else if (!strcmp(key
, "NSTATES")) {
1650 nstates
= atoi(val
);
1652 ret
= "Number of states in save file was negative";
1656 ret
= "Two state counts provided in save file";
1659 states
= snewn(nstates
, struct midend_state_entry
);
1660 for (i
= 0; i
< nstates
; i
++) {
1661 states
[i
].state
= NULL
;
1662 states
[i
].movestr
= NULL
;
1663 states
[i
].movetype
= NEWGAME
;
1665 } else if (!strcmp(key
, "STATEPOS")) {
1666 statepos
= atoi(val
);
1667 } else if (!strcmp(key
, "MOVE")) {
1669 states
[gotstates
].movetype
= MOVE
;
1670 states
[gotstates
].movestr
= val
;
1672 } else if (!strcmp(key
, "SOLVE")) {
1674 states
[gotstates
].movetype
= SOLVE
;
1675 states
[gotstates
].movestr
= val
;
1677 } else if (!strcmp(key
, "RESTART")) {
1679 states
[gotstates
].movetype
= RESTART
;
1680 states
[gotstates
].movestr
= val
;
1689 params
= me
->ourgame
->default_params();
1690 me
->ourgame
->decode_params(params
, parstr
);
1691 if (me
->ourgame
->validate_params(params
, TRUE
)) {
1692 ret
= "Long-term parameters in save file are invalid";
1695 cparams
= me
->ourgame
->default_params();
1696 me
->ourgame
->decode_params(cparams
, cparstr
);
1697 if (me
->ourgame
->validate_params(cparams
, FALSE
)) {
1698 ret
= "Short-term parameters in save file are invalid";
1701 if (seed
&& me
->ourgame
->validate_params(cparams
, TRUE
)) {
1703 * The seed's no use with this version, but we can perfectly
1704 * well use the rest of the data.
1710 ret
= "Game description in save file is missing";
1712 } else if (me
->ourgame
->validate_desc(params
, desc
)) {
1713 ret
= "Game description in save file is invalid";
1716 if (privdesc
&& me
->ourgame
->validate_desc(params
, privdesc
)) {
1717 ret
= "Game private description in save file is invalid";
1720 if (statepos
< 0 || statepos
>= nstates
) {
1721 ret
= "Game position in save file is out of range";
1724 states
[0].state
= me
->ourgame
->new_game(me
, params
,
1725 privdesc ? privdesc
: desc
);
1726 for (i
= 1; i
< nstates
; i
++) {
1727 assert(states
[i
].movetype
!= NEWGAME
);
1728 switch (states
[i
].movetype
) {
1731 states
[i
].state
= me
->ourgame
->execute_move(states
[i
-1].state
,
1733 if (states
[i
].state
== NULL
) {
1734 ret
= "Save file contained an invalid move";
1739 if (me
->ourgame
->validate_desc(params
, states
[i
].movestr
)) {
1740 ret
= "Save file contained an invalid restart move";
1743 states
[i
].state
= me
->ourgame
->new_game(me
, params
,
1749 ui
= me
->ourgame
->new_ui(states
[0].state
);
1750 me
->ourgame
->decode_ui(ui
, uistr
);
1753 * Now we've run out of possible error conditions, so we're
1754 * ready to start overwriting the real data in the current
1755 * midend. We'll do this by swapping things with the local
1756 * variables, so that the same cleanup code will free the old
1767 me
->privdesc
= privdesc
;
1775 me
->aux_info
= auxinfo
;
1779 me
->genmode
= GOT_NOTHING
;
1781 me
->statesize
= nstates
;
1782 nstates
= me
->nstates
;
1783 me
->nstates
= me
->statesize
;
1785 struct midend_state_entry
*tmp
;
1787 me
->states
= states
;
1790 me
->statepos
= statepos
;
1796 me
->params
= params
;
1799 tmp
= me
->curparams
;
1800 me
->curparams
= cparams
;
1804 me
->oldstate
= NULL
;
1805 me
->anim_time
= me
->anim_pos
= me
->flash_time
= me
->flash_pos
= 0.0F
;
1816 me
->elapsed
= elapsed
;
1817 me
->pressed_mouse_button
= 0;
1819 midend_set_timer(me
);
1822 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
1824 me
->ourgame
->new_drawstate(me
->drawing
,
1825 me
->states
[me
->statepos
-1].state
);
1826 midend_size_new_drawstate(me
);
1828 ret
= NULL
; /* success! */
1840 me
->ourgame
->free_params(params
);
1842 me
->ourgame
->free_params(cparams
);
1844 me
->ourgame
->free_ui(ui
);
1848 for (i
= 0; i
< nstates
; i
++) {
1849 if (states
[i
].state
)
1850 me
->ourgame
->free_game(states
[i
].state
);
1851 sfree(states
[i
].movestr
);
1859 char *midend_print_puzzle(midend
*me
, document
*doc
, int with_soln
)
1861 game_state
*soln
= NULL
;
1863 if (me
->statepos
< 1)
1864 return "No game set up to print";/* _shouldn't_ happen! */
1867 char *msg
, *movestr
;
1869 if (!me
->ourgame
->can_solve
)
1870 return "This game does not support the Solve operation";
1872 msg
= "Solve operation failed";/* game _should_ overwrite on error */
1873 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1874 me
->states
[me
->statepos
-1].state
,
1875 me
->aux_info
, &msg
);
1878 soln
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
1887 * This call passes over ownership of the two game_states and
1888 * the game_params. Hence we duplicate the ones we want to
1889 * keep, and we don't have to bother freeing soln if it was
1892 document_add_puzzle(doc
, me
->ourgame
,
1893 me
->ourgame
->dup_params(me
->curparams
),
1894 me
->ourgame
->dup_game(me
->states
[0].state
), soln
);