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 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_init(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_init(drapi
, drhandle
);
138 static void midend_free_game(midend
*me
)
140 while (me
->nstates
> 0) {
142 me
->ourgame
->free_game(me
->states
[me
->nstates
].state
);
143 sfree(me
->states
[me
->nstates
].movestr
);
147 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
150 void midend_free(midend
*me
)
154 midend_free_game(me
);
157 drawing_free(me
->drawing
);
158 random_free(me
->random
);
164 me
->ourgame
->free_params(me
->params
);
166 for (i
= 0; i
< me
->npresets
; i
++) {
167 sfree(me
->presets
[i
]);
168 sfree(me
->preset_names
[i
]);
171 sfree(me
->preset_names
);
174 me
->ourgame
->free_ui(me
->ui
);
176 me
->ourgame
->free_params(me
->curparams
);
177 sfree(me
->laststatus
);
181 static void midend_size_new_drawstate(midend
*me
)
184 * Don't even bother, if we haven't worked out our tile size
187 if (me
->tilesize
> 0) {
188 me
->ourgame
->compute_size(me
->params
, me
->tilesize
,
189 &me
->winwidth
, &me
->winheight
);
190 me
->ourgame
->set_size(me
->drawing
, me
->drawstate
,
191 me
->params
, me
->tilesize
);
195 void midend_size(midend
*me
, int *x
, int *y
, int expand
)
201 * Find the tile size that best fits within the given space. If
202 * `expand' is TRUE, we must actually find the _largest_ such
203 * tile size; otherwise, we bound above at the game's preferred
210 me
->ourgame
->compute_size(me
->params
, max
, &rx
, &ry
);
211 } while (rx
<= *x
&& ry
<= *y
);
213 max
= me
->ourgame
->preferred_tilesize
+ 1;
217 * Now binary-search between min and max. We're looking for a
218 * boundary rather than a value: the point at which tile sizes
219 * stop fitting within the given dimensions. Thus, we stop when
220 * max and min differ by exactly 1.
222 while (max
- min
> 1) {
223 int mid
= (max
+ min
) / 2;
224 me
->ourgame
->compute_size(me
->params
, mid
, &rx
, &ry
);
225 if (rx
<= *x
&& ry
<= *y
)
232 * Now `min' is a valid size, and `max' isn't. So use `min'.
236 midend_size_new_drawstate(me
);
241 void midend_set_params(midend
*me
, game_params
*params
)
243 me
->ourgame
->free_params(me
->params
);
244 me
->params
= me
->ourgame
->dup_params(params
);
247 static void midend_set_timer(midend
*me
)
249 me
->timing
= (me
->ourgame
->is_timed
&&
250 me
->ourgame
->timing_state(me
->states
[me
->statepos
-1].state
,
252 if (me
->timing
|| me
->flash_time
|| me
->anim_time
)
253 activate_timer(me
->frontend
);
255 deactivate_timer(me
->frontend
);
258 void midend_force_redraw(midend
*me
)
261 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
262 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
263 me
->states
[0].state
);
264 midend_size_new_drawstate(me
);
268 void midend_new_game(midend
*me
)
270 midend_free_game(me
);
272 assert(me
->nstates
== 0);
274 if (me
->genmode
== GOT_DESC
) {
275 me
->genmode
= GOT_NOTHING
;
279 if (me
->genmode
== GOT_SEED
) {
280 me
->genmode
= GOT_NOTHING
;
283 * Generate a new random seed. 15 digits comes to about
284 * 48 bits, which should be more than enough.
286 * I'll avoid putting a leading zero on the number,
287 * just in case it confuses anybody who thinks it's
288 * processed as an integer rather than a string.
293 newseed
[0] = '1' + random_upto(me
->random
, 9);
294 for (i
= 1; i
< 15; i
++)
295 newseed
[i
] = '0' + random_upto(me
->random
, 10);
297 me
->seedstr
= dupstr(newseed
);
300 me
->ourgame
->free_params(me
->curparams
);
301 me
->curparams
= me
->ourgame
->dup_params(me
->params
);
309 rs
= random_init(me
->seedstr
, strlen(me
->seedstr
));
311 * If this midend has been instantiated without providing a
312 * drawing API, it is non-interactive. This means that it's
313 * being used for bulk game generation, and hence we should
314 * pass the non-interactive flag to new_desc.
316 me
->desc
= me
->ourgame
->new_desc(me
->curparams
, rs
,
317 &me
->aux_info
, (me
->drawing
!= NULL
));
323 me
->states
[me
->nstates
].state
=
324 me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
325 me
->states
[me
->nstates
].movestr
= NULL
;
326 me
->states
[me
->nstates
].movetype
= NEWGAME
;
329 me
->drawstate
= me
->ourgame
->new_drawstate(me
->drawing
,
330 me
->states
[0].state
);
331 midend_size_new_drawstate(me
);
334 me
->ourgame
->free_ui(me
->ui
);
335 me
->ui
= me
->ourgame
->new_ui(me
->states
[0].state
);
336 midend_set_timer(me
);
337 me
->pressed_mouse_button
= 0;
340 static int midend_undo(midend
*me
)
342 if (me
->statepos
> 1) {
344 me
->ourgame
->changed_state(me
->ui
,
345 me
->states
[me
->statepos
-1].state
,
346 me
->states
[me
->statepos
-2].state
);
354 static int midend_redo(midend
*me
)
356 if (me
->statepos
< me
->nstates
) {
358 me
->ourgame
->changed_state(me
->ui
,
359 me
->states
[me
->statepos
-1].state
,
360 me
->states
[me
->statepos
].state
);
368 static void midend_finish_move(midend
*me
)
373 * We do not flash if the later of the two states is special.
374 * This covers both forward Solve moves and backward (undone)
377 if ((me
->oldstate
|| me
->statepos
> 1) &&
378 ((me
->dir
> 0 && !special(me
->states
[me
->statepos
-1].movetype
)) ||
379 (me
->dir
< 0 && me
->statepos
< me
->nstates
&&
380 !special(me
->states
[me
->statepos
].movetype
)))) {
381 flashtime
= me
->ourgame
->flash_length(me
->oldstate ? me
->oldstate
:
382 me
->states
[me
->statepos
-2].state
,
383 me
->states
[me
->statepos
-1].state
,
384 me
->oldstate ? me
->dir
: +1,
387 me
->flash_pos
= 0.0F
;
388 me
->flash_time
= flashtime
;
393 me
->ourgame
->free_game(me
->oldstate
);
395 me
->anim_pos
= me
->anim_time
= 0;
398 midend_set_timer(me
);
401 void midend_stop_anim(midend
*me
)
403 if (me
->oldstate
|| me
->anim_time
!= 0) {
404 midend_finish_move(me
);
409 void midend_restart_game(midend
*me
)
413 midend_stop_anim(me
);
415 assert(me
->statepos
>= 1);
416 if (me
->statepos
== 1)
417 return; /* no point doing anything at all! */
420 * During restart, we reconstruct the game from the (public)
421 * game description rather than from states[0], because that
422 * way Mines gets slightly more sensible behaviour (restart
423 * goes to _after_ the first click so you don't have to
424 * remember where you clicked).
426 s
= me
->ourgame
->new_game(me
, me
->params
, me
->desc
);
429 * Now enter the restarted state as the next move.
431 midend_stop_anim(me
);
432 while (me
->nstates
> me
->statepos
)
433 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
435 me
->states
[me
->nstates
].state
= s
;
436 me
->states
[me
->nstates
].movestr
= dupstr(me
->desc
);
437 me
->states
[me
->nstates
].movetype
= RESTART
;
438 me
->statepos
= ++me
->nstates
;
440 me
->ourgame
->changed_state(me
->ui
,
441 me
->states
[me
->statepos
-2].state
,
442 me
->states
[me
->statepos
-1].state
);
444 midend_finish_move(me
);
446 midend_set_timer(me
);
449 static int midend_really_process_key(midend
*me
, int x
, int y
, int button
)
451 game_state
*oldstate
=
452 me
->ourgame
->dup_game(me
->states
[me
->statepos
- 1].state
);
453 int type
= MOVE
, gottype
= FALSE
, ret
= 1;
459 me
->ourgame
->interpret_move(me
->states
[me
->statepos
-1].state
,
460 me
->ui
, me
->drawstate
, x
, y
, button
);
463 if (button
== 'n' || button
== 'N' || button
== '\x0E') {
464 midend_stop_anim(me
);
467 goto done
; /* never animate */
468 } else if (button
== 'u' || button
== 'u' ||
469 button
== '\x1A' || button
== '\x1F') {
470 midend_stop_anim(me
);
471 type
= me
->states
[me
->statepos
-1].movetype
;
473 if (!midend_undo(me
))
475 } else if (button
== 'r' || button
== 'R' ||
476 button
== '\x12' || button
== '\x19') {
477 midend_stop_anim(me
);
478 if (!midend_redo(me
))
480 } else if (button
== 'q' || button
== 'Q' || button
== '\x11') {
487 s
= me
->states
[me
->statepos
-1].state
;
489 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
494 if (s
== me
->states
[me
->statepos
-1].state
) {
496 * make_move() is allowed to return its input state to
497 * indicate that although no move has been made, the UI
498 * state has been updated and a redraw is called for.
503 midend_stop_anim(me
);
504 while (me
->nstates
> me
->statepos
)
505 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
507 assert(movestr
!= NULL
);
508 me
->states
[me
->nstates
].state
= s
;
509 me
->states
[me
->nstates
].movestr
= movestr
;
510 me
->states
[me
->nstates
].movetype
= MOVE
;
511 me
->statepos
= ++me
->nstates
;
514 me
->ourgame
->changed_state(me
->ui
,
515 me
->states
[me
->statepos
-2].state
,
516 me
->states
[me
->statepos
-1].state
);
523 type
= me
->states
[me
->statepos
-1].movetype
;
526 * See if this move requires an animation.
528 if (special(type
) && !(type
== SOLVE
&&
529 (me
->ourgame
->mouse_priorities
& SOLVE_ANIMATES
))) {
532 anim_time
= me
->ourgame
->anim_length(oldstate
,
533 me
->states
[me
->statepos
-1].state
,
537 me
->oldstate
= oldstate
; oldstate
= NULL
;
539 me
->anim_time
= anim_time
;
542 midend_finish_move(me
);
548 midend_set_timer(me
);
551 if (oldstate
) me
->ourgame
->free_game(oldstate
);
555 int midend_process_key(midend
*me
, int x
, int y
, int button
)
560 * Harmonise mouse drag and release messages.
562 * Some front ends might accidentally switch from sending, say,
563 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
564 * drag. (This can happen on the Mac, for example, since
565 * RIGHT_DRAG is usually done using Command+drag, and if the
566 * user accidentally releases Command half way through the drag
567 * then there will be trouble.)
569 * It would be an O(number of front ends) annoyance to fix this
570 * in the front ends, but an O(number of back ends) annoyance
571 * to have each game capable of dealing with it. Therefore, we
572 * fix it _here_ in the common midend code so that it only has
575 * The possible ways in which things can go screwy in the front
578 * - in a system containing multiple physical buttons button
579 * presses can inadvertently overlap. We can see ABab (caps
580 * meaning button-down and lowercase meaning button-up) when
581 * the user had semantically intended AaBb.
583 * - in a system where one button is simulated by means of a
584 * modifier key and another button, buttons can mutate
585 * between press and release (possibly during drag). So we
586 * can see Ab instead of Aa.
588 * Definite requirements are:
590 * - button _presses_ must never be invented or destroyed. If
591 * the user presses two buttons in succession, the button
592 * presses must be transferred to the backend unchanged. So
593 * if we see AaBb , that's fine; if we see ABab (the button
594 * presses inadvertently overlapped) we must somehow
595 * `correct' it to AaBb.
597 * - every mouse action must end up looking like a press, zero
598 * or more drags, then a release. This allows back ends to
599 * make the _assumption_ that incoming mouse data will be
600 * sane in this regard, and not worry about the details.
602 * So my policy will be:
604 * - treat any button-up as a button-up for the currently
605 * pressed button, or ignore it if there is no currently
608 * - treat any drag as a drag for the currently pressed
609 * button, or ignore it if there is no currently pressed
612 * - if we see a button-down while another button is currently
613 * pressed, invent a button-up for the first one and then
614 * pass the button-down through as before.
616 * 2005-05-31: An addendum to the above. Some games might want
617 * a `priority order' among buttons, such that if one button is
618 * pressed while another is down then a fixed one of the
619 * buttons takes priority no matter what order they're pressed
620 * in. Mines, in particular, wants to treat a left+right click
621 * like a left click for the benefit of users of other
622 * implementations. So the last of the above points is modified
623 * in the presence of an (optional) button priority order.
625 if (IS_MOUSE_DRAG(button
) || IS_MOUSE_RELEASE(button
)) {
626 if (me
->pressed_mouse_button
) {
627 if (IS_MOUSE_DRAG(button
)) {
628 button
= me
->pressed_mouse_button
+
629 (LEFT_DRAG
- LEFT_BUTTON
);
631 button
= me
->pressed_mouse_button
+
632 (LEFT_RELEASE
- LEFT_BUTTON
);
635 return ret
; /* ignore it */
636 } else if (IS_MOUSE_DOWN(button
) && me
->pressed_mouse_button
) {
638 * If the new button has lower priority than the old one,
639 * don't bother doing this.
641 if (me
->ourgame
->mouse_priorities
&
642 BUTTON_BEATS(me
->pressed_mouse_button
, button
))
643 return ret
; /* just ignore it */
646 * Fabricate a button-up for the previously pressed button.
648 ret
= ret
&& midend_really_process_key
649 (me
, x
, y
, (me
->pressed_mouse_button
+
650 (LEFT_RELEASE
- LEFT_BUTTON
)));
654 * Now send on the event we originally received.
656 ret
= ret
&& midend_really_process_key(me
, x
, y
, button
);
659 * And update the currently pressed button.
661 if (IS_MOUSE_RELEASE(button
))
662 me
->pressed_mouse_button
= 0;
663 else if (IS_MOUSE_DOWN(button
))
664 me
->pressed_mouse_button
= button
;
669 void midend_redraw(midend
*me
)
673 if (me
->statepos
> 0 && me
->drawstate
) {
674 start_draw(me
->drawing
);
675 if (me
->oldstate
&& me
->anim_time
> 0 &&
676 me
->anim_pos
< me
->anim_time
) {
677 assert(me
->dir
!= 0);
678 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, me
->oldstate
,
679 me
->states
[me
->statepos
-1].state
, me
->dir
,
680 me
->ui
, me
->anim_pos
, me
->flash_pos
);
682 me
->ourgame
->redraw(me
->drawing
, me
->drawstate
, NULL
,
683 me
->states
[me
->statepos
-1].state
, +1 /*shrug*/,
684 me
->ui
, 0.0, me
->flash_pos
);
686 end_draw(me
->drawing
);
690 void midend_timer(midend
*me
, float tplus
)
692 me
->anim_pos
+= tplus
;
693 if (me
->anim_pos
>= me
->anim_time
||
694 me
->anim_time
== 0 || !me
->oldstate
) {
695 if (me
->anim_time
> 0)
696 midend_finish_move(me
);
699 me
->flash_pos
+= tplus
;
700 if (me
->flash_pos
>= me
->flash_time
|| me
->flash_time
== 0) {
701 me
->flash_pos
= me
->flash_time
= 0;
707 float oldelapsed
= me
->elapsed
;
708 me
->elapsed
+= tplus
;
709 if ((int)oldelapsed
!= (int)me
->elapsed
)
710 status_bar(me
->drawing
, me
->laststatus ? me
->laststatus
: "");
713 midend_set_timer(me
);
716 float *midend_colours(midend
*me
, int *ncolours
)
718 game_state
*state
= NULL
;
721 if (me
->nstates
== 0) {
723 char *desc
= me
->ourgame
->new_desc(me
->params
, me
->random
,
725 state
= me
->ourgame
->new_game(me
, me
->params
, desc
);
729 state
= me
->states
[0].state
;
731 ret
= me
->ourgame
->colours(me
->frontend
, state
, ncolours
);
737 * Allow environment-based overrides for the standard
738 * colours by defining variables along the lines of
739 * `NET_COLOUR_4=6000c0'.
742 for (i
= 0; i
< *ncolours
; i
++) {
744 unsigned int r
, g
, b
;
747 sprintf(buf
, "%s_COLOUR_%d", me
->ourgame
->name
, i
);
748 for (j
= k
= 0; buf
[j
]; j
++)
749 if (!isspace((unsigned char)buf
[j
]))
750 buf
[k
++] = toupper((unsigned char)buf
[j
]);
752 if ((e
= getenv(buf
)) != NULL
&&
753 sscanf(e
, "%2x%2x%2x", &r
, &g
, &b
) == 3) {
754 ret
[i
*3 + 0] = r
/ 255.0;
755 ret
[i
*3 + 1] = g
/ 255.0;
756 ret
[i
*3 + 2] = b
/ 255.0;
761 if (me
->nstates
== 0)
762 me
->ourgame
->free_game(state
);
767 int midend_num_presets(midend
*me
)
773 while (me
->ourgame
->fetch_preset(me
->npresets
, &name
, &preset
)) {
774 if (me
->presetsize
<= me
->npresets
) {
775 me
->presetsize
= me
->npresets
+ 10;
776 me
->presets
= sresize(me
->presets
, me
->presetsize
,
778 me
->preset_names
= sresize(me
->preset_names
, me
->presetsize
,
782 me
->presets
[me
->npresets
] = preset
;
783 me
->preset_names
[me
->npresets
] = name
;
790 * Allow environment-based extensions to the preset list by
791 * defining a variable along the lines of `SOLO_PRESETS=2x3
792 * Advanced:2x3da'. Colon-separated list of items,
793 * alternating between textual titles in the menu and
794 * encoded parameter strings.
796 char buf
[80], *e
, *p
;
799 sprintf(buf
, "%s_PRESETS", me
->ourgame
->name
);
800 for (j
= k
= 0; buf
[j
]; j
++)
801 if (!isspace((unsigned char)buf
[j
]))
802 buf
[k
++] = toupper((unsigned char)buf
[j
]);
805 if ((e
= getenv(buf
)) != NULL
) {
813 while (*p
&& *p
!= ':') p
++;
816 while (*p
&& *p
!= ':') p
++;
819 preset
= me
->ourgame
->default_params();
820 me
->ourgame
->decode_params(preset
, val
);
822 if (me
->ourgame
->validate_params(preset
, TRUE
)) {
823 /* Drop this one from the list. */
824 me
->ourgame
->free_params(preset
);
828 if (me
->presetsize
<= me
->npresets
) {
829 me
->presetsize
= me
->npresets
+ 10;
830 me
->presets
= sresize(me
->presets
, me
->presetsize
,
832 me
->preset_names
= sresize(me
->preset_names
,
833 me
->presetsize
, char *);
836 me
->presets
[me
->npresets
] = preset
;
837 me
->preset_names
[me
->npresets
] = dupstr(name
);
846 void midend_fetch_preset(midend
*me
, int n
,
847 char **name
, game_params
**params
)
849 assert(n
>= 0 && n
< me
->npresets
);
850 *name
= me
->preset_names
[n
];
851 *params
= me
->presets
[n
];
854 int midend_wants_statusbar(midend
*me
)
856 return me
->ourgame
->wants_statusbar();
859 void midend_supersede_game_desc(midend
*me
, char *desc
, char *privdesc
)
863 me
->desc
= dupstr(desc
);
864 me
->privdesc
= privdesc ?
dupstr(privdesc
) : NULL
;
867 config_item
*midend_get_config(midend
*me
, int which
, char **wintitle
)
869 char *titlebuf
, *parstr
, *rest
;
874 titlebuf
= snewn(40 + strlen(me
->ourgame
->name
), char);
878 sprintf(titlebuf
, "%s configuration", me
->ourgame
->name
);
879 *wintitle
= titlebuf
;
880 return me
->ourgame
->configure(me
->params
);
883 if (!me
->curparams
) {
887 sprintf(titlebuf
, "%s %s selection", me
->ourgame
->name
,
888 which
== CFG_SEED ?
"random" : "game");
889 *wintitle
= titlebuf
;
891 ret
= snewn(2, config_item
);
893 ret
[0].type
= C_STRING
;
894 if (which
== CFG_SEED
)
895 ret
[0].name
= "Game random seed";
897 ret
[0].name
= "Game ID";
900 * For CFG_DESC the text going in here will be a string
901 * encoding of the restricted parameters, plus a colon,
902 * plus the game description. For CFG_SEED it will be the
903 * full parameters, plus a hash, plus the random seed data.
904 * Either of these is a valid full game ID (although only
905 * the former is likely to persist across many code
908 parstr
= me
->ourgame
->encode_params(me
->curparams
, which
== CFG_SEED
);
910 if (which
== CFG_DESC
) {
911 rest
= me
->desc ? me
->desc
: "";
914 rest
= me
->seedstr ? me
->seedstr
: "";
917 ret
[0].sval
= snewn(strlen(parstr
) + strlen(rest
) + 2, char);
918 sprintf(ret
[0].sval
, "%s%c%s", parstr
, sep
, rest
);
922 ret
[1].name
= ret
[1].sval
= NULL
;
928 assert(!"We shouldn't be here");
932 static char *midend_game_id_int(midend
*me
, char *id
, int defmode
)
934 char *error
, *par
, *desc
, *seed
;
935 game_params
*newcurparams
, *newparams
, *oldparams1
, *oldparams2
;
938 seed
= strchr(id
, '#');
939 desc
= strchr(id
, ':');
941 if (desc
&& (!seed
|| desc
< seed
)) {
943 * We have a colon separating parameters from game
944 * description. So `par' now points to the parameters
945 * string, and `desc' to the description string.
950 } else if (seed
&& (!desc
|| seed
< desc
)) {
952 * We have a hash separating parameters from random seed.
953 * So `par' now points to the parameters string, and `seed'
954 * to the seed string.
961 * We only have one string. Depending on `defmode', we take
962 * it to be either parameters, seed or description.
964 if (defmode
== DEF_SEED
) {
967 } else if (defmode
== DEF_DESC
) {
977 * We must be reasonably careful here not to modify anything in
978 * `me' until we have finished validating things. This function
979 * must either return an error and do nothing to the midend, or
980 * return success and do everything; nothing in between is
983 newcurparams
= newparams
= oldparams1
= oldparams2
= NULL
;
986 newcurparams
= me
->ourgame
->dup_params(me
->params
);
987 me
->ourgame
->decode_params(newcurparams
, par
);
988 error
= me
->ourgame
->validate_params(newcurparams
, desc
== NULL
);
990 me
->ourgame
->free_params(newcurparams
);
993 oldparams1
= me
->curparams
;
996 * Now filter only the persistent parts of this state into
997 * the long-term params structure, unless we've _only_
998 * received a params string in which case the whole lot is
1001 oldparams2
= me
->params
;
1005 newparams
= me
->ourgame
->dup_params(me
->params
);
1007 tmpstr
= me
->ourgame
->encode_params(newcurparams
, FALSE
);
1008 me
->ourgame
->decode_params(newparams
, tmpstr
);
1012 newparams
= me
->ourgame
->dup_params(newcurparams
);
1016 newcurparams
= me
->curparams
;
1017 newparams
= me
->params
;
1018 free_params
= FALSE
;
1022 error
= me
->ourgame
->validate_desc(newparams
, desc
);
1026 me
->ourgame
->free_params(newcurparams
);
1028 me
->ourgame
->free_params(newparams
);
1035 * Now we've got past all possible error points. Update the
1038 me
->params
= newparams
;
1039 me
->curparams
= newcurparams
;
1041 me
->ourgame
->free_params(oldparams1
);
1043 me
->ourgame
->free_params(oldparams2
);
1046 sfree(me
->privdesc
);
1047 me
->desc
= me
->privdesc
= NULL
;
1052 me
->desc
= dupstr(desc
);
1053 me
->genmode
= GOT_DESC
;
1054 sfree(me
->aux_info
);
1055 me
->aux_info
= NULL
;
1059 me
->seedstr
= dupstr(seed
);
1060 me
->genmode
= GOT_SEED
;
1066 char *midend_game_id(midend
*me
, char *id
)
1068 return midend_game_id_int(me
, id
, DEF_PARAMS
);
1071 char *midend_get_game_id(midend
*me
)
1075 parstr
= me
->ourgame
->encode_params(me
->curparams
, FALSE
);
1078 ret
= snewn(strlen(parstr
) + strlen(me
->desc
) + 2, char);
1079 sprintf(ret
, "%s:%s", parstr
, me
->desc
);
1084 char *midend_set_config(midend
*me
, int which
, config_item
*cfg
)
1087 game_params
*params
;
1091 params
= me
->ourgame
->custom_params(cfg
);
1092 error
= me
->ourgame
->validate_params(params
, TRUE
);
1095 me
->ourgame
->free_params(params
);
1099 me
->ourgame
->free_params(me
->params
);
1100 me
->params
= params
;
1105 error
= midend_game_id_int(me
, cfg
[0].sval
,
1106 (which
== CFG_SEED ? DEF_SEED
: DEF_DESC
));
1115 char *midend_text_format(midend
*me
)
1117 if (me
->ourgame
->can_format_as_text
&& me
->statepos
> 0)
1118 return me
->ourgame
->text_format(me
->states
[me
->statepos
-1].state
);
1123 char *midend_solve(midend
*me
)
1126 char *msg
, *movestr
;
1128 if (!me
->ourgame
->can_solve
)
1129 return "This game does not support the Solve operation";
1131 if (me
->statepos
< 1)
1132 return "No game set up to solve"; /* _shouldn't_ happen! */
1134 msg
= "Solve operation failed"; /* game _should_ overwrite on error */
1135 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1136 me
->states
[me
->statepos
-1].state
,
1137 me
->aux_info
, &msg
);
1140 s
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
, movestr
);
1144 * Now enter the solved state as the next move.
1146 midend_stop_anim(me
);
1147 while (me
->nstates
> me
->statepos
)
1148 me
->ourgame
->free_game(me
->states
[--me
->nstates
].state
);
1150 me
->states
[me
->nstates
].state
= s
;
1151 me
->states
[me
->nstates
].movestr
= movestr
;
1152 me
->states
[me
->nstates
].movetype
= SOLVE
;
1153 me
->statepos
= ++me
->nstates
;
1155 me
->ourgame
->changed_state(me
->ui
,
1156 me
->states
[me
->statepos
-2].state
,
1157 me
->states
[me
->statepos
-1].state
);
1159 if (me
->ourgame
->mouse_priorities
& SOLVE_ANIMATES
) {
1160 me
->oldstate
= me
->ourgame
->dup_game(me
->states
[me
->statepos
-2].state
);
1162 me
->ourgame
->anim_length(me
->states
[me
->statepos
-2].state
,
1163 me
->states
[me
->statepos
-1].state
,
1167 me
->anim_time
= 0.0;
1168 midend_finish_move(me
);
1171 midend_set_timer(me
);
1175 char *midend_rewrite_statusbar(midend
*me
, char *text
)
1178 * An important special case is that we are occasionally called
1179 * with our own laststatus, to update the timer.
1181 if (me
->laststatus
!= text
) {
1182 sfree(me
->laststatus
);
1183 me
->laststatus
= dupstr(text
);
1186 if (me
->ourgame
->is_timed
) {
1187 char timebuf
[100], *ret
;
1193 sprintf(timebuf
, "[%d:%02d] ", min
, sec
);
1195 ret
= snewn(strlen(timebuf
) + strlen(text
) + 1, char);
1196 strcpy(ret
, timebuf
);
1201 return dupstr(text
);
1205 #define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1206 #define SERIALISE_VERSION "1"
1208 void midend_serialise(midend
*me
,
1209 void (*write
)(void *ctx
, void *buf
, int len
),
1215 * Each line of the save file contains three components. First
1216 * exactly 8 characters of header word indicating what type of
1217 * data is contained on the line; then a colon followed by a
1218 * decimal integer giving the length of the main string on the
1219 * line; then a colon followed by the string itself (exactly as
1220 * many bytes as previously specified, no matter what they
1221 * contain). Then a newline (of reasonably flexible form).
1223 #define wr(h,s) do { \
1226 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
1227 write(wctx, hbuf, strlen(hbuf)); \
1228 write(wctx, str, strlen(str)); \
1229 write(wctx, "\n", 1); \
1233 * Magic string identifying the file, and version number of the
1236 wr("SAVEFILE", SERIALISE_MAGIC
);
1237 wr("VERSION", SERIALISE_VERSION
);
1240 * The game name. (Copied locally to avoid const annoyance.)
1243 char *s
= dupstr(me
->ourgame
->name
);
1249 * The current long-term parameters structure, in full.
1252 char *s
= me
->ourgame
->encode_params(me
->params
, TRUE
);
1258 * The current short-term parameters structure, in full.
1260 if (me
->curparams
) {
1261 char *s
= me
->ourgame
->encode_params(me
->curparams
, TRUE
);
1267 * The current game description, the privdesc, and the random seed.
1270 wr("SEED", me
->seedstr
);
1272 wr("DESC", me
->desc
);
1274 wr("PRIVDESC", me
->privdesc
);
1277 * The game's aux_info. We obfuscate this to prevent spoilers
1278 * (people are likely to run `head' or similar on a saved game
1279 * file simply to find out what it is, and don't necessarily
1280 * want to be told the answer to the puzzle!)
1287 len
= strlen(me
->aux_info
);
1288 s1
= snewn(len
, unsigned char);
1289 memcpy(s1
, me
->aux_info
, len
);
1290 obfuscate_bitmap(s1
, len
*8, FALSE
);
1291 s2
= bin2hex(s1
, len
);
1300 * Any required serialisation of the game_ui.
1303 char *s
= me
->ourgame
->encode_ui(me
->ui
);
1311 * The game time, if it's a timed game.
1313 if (me
->ourgame
->is_timed
) {
1315 sprintf(buf
, "%g", me
->elapsed
);
1320 * The length of, and position in, the states list.
1324 sprintf(buf
, "%d", me
->nstates
);
1326 sprintf(buf
, "%d", me
->statepos
);
1327 wr("STATEPOS", buf
);
1331 * For each state after the initial one (which we know is
1332 * constructed from either privdesc or desc), enough
1333 * information for execute_move() to reconstruct it from the
1336 for (i
= 1; i
< me
->nstates
; i
++) {
1337 assert(me
->states
[i
].movetype
!= NEWGAME
); /* only state 0 */
1338 switch (me
->states
[i
].movetype
) {
1340 wr("MOVE", me
->states
[i
].movestr
);
1343 wr("SOLVE", me
->states
[i
].movestr
);
1346 wr("RESTART", me
->states
[i
].movestr
);
1355 * This function returns NULL on success, or an error message.
1357 char *midend_deserialise(midend
*me
,
1358 int (*read
)(void *ctx
, void *buf
, int len
),
1361 int nstates
= 0, statepos
= -1, gotstates
= 0;
1362 int started
= FALSE
;
1366 /* Initially all errors give the same report */
1367 char *ret
= "Data does not appear to be a saved game file";
1370 * We construct all the new state in local variables while we
1371 * check its sanity. Only once we have finished reading the
1372 * serialised data and detected no errors at all do we start
1373 * modifying stuff in the midend passed in.
1375 char *seed
= NULL
, *parstr
= NULL
, *desc
= NULL
, *privdesc
= NULL
;
1376 char *auxinfo
= NULL
, *uistr
= NULL
, *cparstr
= NULL
;
1377 float elapsed
= 0.0F
;
1378 game_params
*params
= NULL
, *cparams
= NULL
;
1380 struct midend_state_entry
*states
= NULL
;
1383 * Loop round and round reading one key/value pair at a time
1384 * from the serialised stream, until we have enough game states
1387 while (nstates
<= 0 || statepos
< 0 || gotstates
< nstates
-1) {
1392 if (!read(rctx
, key
, 1)) {
1393 /* unexpected EOF */
1396 } while (key
[0] == '\r' || key
[0] == '\n');
1398 if (!read(rctx
, key
+1, 8)) {
1399 /* unexpected EOF */
1403 if (key
[8] != ':') {
1405 ret
= "Data was incorrectly formatted for a saved game file";
1408 len
= strcspn(key
, ": ");
1414 if (!read(rctx
, &c
, 1)) {
1415 /* unexpected EOF */
1421 } else if (c
>= '0' && c
<= '9') {
1422 len
= (len
* 10) + (c
- '0');
1425 ret
= "Data was incorrectly formatted for a"
1431 val
= snewn(len
+1, char);
1432 if (!read(rctx
, val
, len
)) {
1439 if (strcmp(key
, "SAVEFILE") || strcmp(val
, SERIALISE_MAGIC
)) {
1440 /* ret already has the right message in it */
1443 /* Now most errors are this one, unless otherwise specified */
1444 ret
= "Saved data ended unexpectedly";
1447 if (!strcmp(key
, "VERSION")) {
1448 if (strcmp(val
, SERIALISE_VERSION
)) {
1449 ret
= "Cannot handle this version of the saved game"
1453 } else if (!strcmp(key
, "GAME")) {
1454 if (strcmp(val
, me
->ourgame
->name
)) {
1455 ret
= "Save file is from a different game";
1458 } else if (!strcmp(key
, "PARAMS")) {
1462 } else if (!strcmp(key
, "CPARAMS")) {
1466 } else if (!strcmp(key
, "SEED")) {
1470 } else if (!strcmp(key
, "DESC")) {
1474 } else if (!strcmp(key
, "PRIVDESC")) {
1478 } else if (!strcmp(key
, "AUXINFO")) {
1480 int len
= strlen(val
) / 2; /* length in bytes */
1481 tmp
= hex2bin(val
, len
);
1482 obfuscate_bitmap(tmp
, len
*8, TRUE
);
1485 auxinfo
= snewn(len
+ 1, char);
1486 memcpy(auxinfo
, tmp
, len
);
1487 auxinfo
[len
] = '\0';
1489 } else if (!strcmp(key
, "UI")) {
1493 } else if (!strcmp(key
, "TIME")) {
1494 elapsed
= atof(val
);
1495 } else if (!strcmp(key
, "NSTATES")) {
1496 nstates
= atoi(val
);
1498 ret
= "Number of states in save file was negative";
1502 ret
= "Two state counts provided in save file";
1505 states
= snewn(nstates
, struct midend_state_entry
);
1506 for (i
= 0; i
< nstates
; i
++) {
1507 states
[i
].state
= NULL
;
1508 states
[i
].movestr
= NULL
;
1509 states
[i
].movetype
= NEWGAME
;
1511 } else if (!strcmp(key
, "STATEPOS")) {
1512 statepos
= atoi(val
);
1513 } else if (!strcmp(key
, "MOVE")) {
1515 states
[gotstates
].movetype
= MOVE
;
1516 states
[gotstates
].movestr
= val
;
1518 } else if (!strcmp(key
, "SOLVE")) {
1520 states
[gotstates
].movetype
= SOLVE
;
1521 states
[gotstates
].movestr
= val
;
1523 } else if (!strcmp(key
, "RESTART")) {
1525 states
[gotstates
].movetype
= RESTART
;
1526 states
[gotstates
].movestr
= val
;
1535 params
= me
->ourgame
->default_params();
1536 me
->ourgame
->decode_params(params
, parstr
);
1537 if (me
->ourgame
->validate_params(params
, TRUE
)) {
1538 ret
= "Long-term parameters in save file are invalid";
1541 cparams
= me
->ourgame
->default_params();
1542 me
->ourgame
->decode_params(cparams
, cparstr
);
1543 if (me
->ourgame
->validate_params(cparams
, FALSE
)) {
1544 ret
= "Short-term parameters in save file are invalid";
1547 if (seed
&& me
->ourgame
->validate_params(cparams
, TRUE
)) {
1549 * The seed's no use with this version, but we can perfectly
1550 * well use the rest of the data.
1556 ret
= "Game description in save file is missing";
1558 } else if (me
->ourgame
->validate_desc(params
, desc
)) {
1559 ret
= "Game description in save file is invalid";
1562 if (privdesc
&& me
->ourgame
->validate_desc(params
, privdesc
)) {
1563 ret
= "Game private description in save file is invalid";
1566 if (statepos
< 0 || statepos
>= nstates
) {
1567 ret
= "Game position in save file is out of range";
1570 states
[0].state
= me
->ourgame
->new_game(me
, params
,
1571 privdesc ? privdesc
: desc
);
1572 for (i
= 1; i
< nstates
; i
++) {
1573 assert(states
[i
].movetype
!= NEWGAME
);
1574 switch (states
[i
].movetype
) {
1577 states
[i
].state
= me
->ourgame
->execute_move(states
[i
-1].state
,
1579 if (states
[i
].state
== NULL
) {
1580 ret
= "Save file contained an invalid move";
1585 if (me
->ourgame
->validate_desc(params
, states
[i
].movestr
)) {
1586 ret
= "Save file contained an invalid restart move";
1589 states
[i
].state
= me
->ourgame
->new_game(me
, params
,
1595 ui
= me
->ourgame
->new_ui(states
[0].state
);
1596 me
->ourgame
->decode_ui(ui
, uistr
);
1599 * Now we've run out of possible error conditions, so we're
1600 * ready to start overwriting the real data in the current
1601 * midend. We'll do this by swapping things with the local
1602 * variables, so that the same cleanup code will free the old
1613 me
->privdesc
= privdesc
;
1621 me
->aux_info
= auxinfo
;
1625 me
->genmode
= GOT_NOTHING
;
1627 me
->statesize
= nstates
;
1628 nstates
= me
->nstates
;
1629 me
->nstates
= me
->statesize
;
1631 struct midend_state_entry
*tmp
;
1633 me
->states
= states
;
1636 me
->statepos
= statepos
;
1642 me
->params
= params
;
1645 tmp
= me
->curparams
;
1646 me
->curparams
= cparams
;
1650 me
->oldstate
= NULL
;
1651 me
->anim_time
= me
->anim_pos
= me
->flash_time
= me
->flash_pos
= 0.0F
;
1662 me
->elapsed
= elapsed
;
1663 me
->pressed_mouse_button
= 0;
1665 midend_set_timer(me
);
1668 me
->ourgame
->free_drawstate(me
->drawing
, me
->drawstate
);
1670 me
->ourgame
->new_drawstate(me
->drawing
,
1671 me
->states
[me
->statepos
-1].state
);
1672 midend_size_new_drawstate(me
);
1674 ret
= NULL
; /* success! */
1686 me
->ourgame
->free_params(params
);
1688 me
->ourgame
->free_params(cparams
);
1690 me
->ourgame
->free_ui(ui
);
1694 for (i
= 0; i
< nstates
; i
++) {
1695 if (states
[i
].state
)
1696 me
->ourgame
->free_game(states
[i
].state
);
1697 sfree(states
[i
].movestr
);
1705 char *midend_print_puzzle(midend
*me
, document
*doc
, int with_soln
)
1707 game_state
*soln
= NULL
;
1709 if (me
->statepos
< 1)
1710 return "No game set up to print";/* _shouldn't_ happen! */
1713 char *msg
, *movestr
;
1715 if (!me
->ourgame
->can_solve
)
1716 return "This game does not support the Solve operation";
1718 msg
= "Solve operation failed";/* game _should_ overwrite on error */
1719 movestr
= me
->ourgame
->solve(me
->states
[0].state
,
1720 me
->states
[me
->statepos
-1].state
,
1721 me
->aux_info
, &msg
);
1724 soln
= me
->ourgame
->execute_move(me
->states
[me
->statepos
-1].state
,
1733 * This call passes over ownership of the two game_states and
1734 * the game_params. Hence we duplicate the ones we want to
1735 * keep, and we don't have to bother freeing soln if it was
1738 document_add_puzzle(doc
, me
->ourgame
,
1739 me
->ourgame
->dup_params(me
->curparams
),
1740 me
->ourgame
->dup_game(me
->states
[0].state
), soln
);