Richard B points out a cut and paste error.
[sgt/puzzles] / midend.c
CommitLineData
720a8fb7 1/*
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
7f89707c 5 * processes standard keystrokes for undo/redo/new/quit.
720a8fb7 6 */
7f77ea24 7
8#include <stdio.h>
5928817c 9#include <string.h>
7f77ea24 10#include <assert.h>
813593cc 11#include <stdlib.h>
12#include <ctype.h>
7f77ea24 13
14#include "puzzles.h"
15
1185e3c5 16enum { DEF_PARAMS, DEF_SEED, DEF_DESC }; /* for midend_game_id_int */
17
a4393230 18enum { NEWGAME, MOVE, SOLVE, RESTART };/* for midend_state_entry.movetype */
19
20#define special(type) ( (type) != MOVE )
21
28d0118c 22struct midend_state_entry {
23 game_state *state;
a4393230 24 char *movestr;
25 int movetype;
28d0118c 26};
27
dafd6cf6 28struct midend {
2ef96bd6 29 frontend *frontend;
48d70ca9 30 random_state *random;
be8d5aa1 31 const game *ourgame;
48d70ca9 32
a4393230 33 game_params **presets;
34 char **preset_names;
35 int npresets, presetsize;
36
0a6892db 37 /*
38 * `desc' and `privdesc' deserve a comment.
39 *
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'
44 * is used for both.
45 *
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.)
58 */
59 char *desc, *privdesc, *seedstr;
c566778e 60 char *aux_info;
1185e3c5 61 enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
eb2ad6f1 62
a4393230 63 int nstates, statesize, statepos;
64 struct midend_state_entry *states;
eb2ad6f1 65
f60f7e7c 66 game_params *params, *curparams;
2ef96bd6 67 game_drawstate *drawstate;
74a4e547 68 game_ui *ui;
a4393230 69
70 game_state *oldstate;
2ef96bd6 71 float anim_time, anim_pos;
87ed82be 72 float flash_time, flash_pos;
c822de4a 73 int dir;
6776a950 74
48dcdd62 75 int timing;
76 float elapsed;
77 char *laststatus;
78
dafd6cf6 79 drawing *drawing;
80
6776a950 81 int pressed_mouse_button;
1e3e152d 82
1f3ee4ee 83 int tilesize, winwidth, winheight;
7f77ea24 84};
85
86#define ensure(me) do { \
87 if ((me)->nstates >= (me)->statesize) { \
88 (me)->statesize = (me)->nstates + 128; \
28d0118c 89 (me)->states = sresize((me)->states, (me)->statesize, \
90 struct midend_state_entry); \
7f77ea24 91 } \
92} while (0)
93
dafd6cf6 94midend *midend_new(frontend *fe, const game *ourgame,
95 const drawing_api *drapi, void *drhandle)
7f77ea24 96{
dafd6cf6 97 midend *me = snew(midend);
cbb5549e 98 void *randseed;
99 int randseedsize;
100
101 get_random_seed(&randseed, &randseedsize);
7f77ea24 102
48d70ca9 103 me->frontend = fe;
be8d5aa1 104 me->ourgame = ourgame;
48d70ca9 105 me->random = random_init(randseed, randseedsize);
7f77ea24 106 me->nstates = me->statesize = me->statepos = 0;
107 me->states = NULL;
be8d5aa1 108 me->params = ourgame->default_params();
f60f7e7c 109 me->curparams = NULL;
0a6892db 110 me->desc = me->privdesc = NULL;
1185e3c5 111 me->seedstr = NULL;
6f2d8d7c 112 me->aux_info = NULL;
1185e3c5 113 me->genmode = GOT_NOTHING;
2ef96bd6 114 me->drawstate = NULL;
115 me->oldstate = NULL;
eb2ad6f1 116 me->presets = NULL;
117 me->preset_names = NULL;
118 me->npresets = me->presetsize = 0;
87ed82be 119 me->anim_time = me->anim_pos = 0.0F;
120 me->flash_time = me->flash_pos = 0.0F;
c822de4a 121 me->dir = 0;
74a4e547 122 me->ui = NULL;
6776a950 123 me->pressed_mouse_button = 0;
48dcdd62 124 me->laststatus = NULL;
125 me->timing = FALSE;
126 me->elapsed = 0.0F;
1f3ee4ee 127 me->tilesize = me->winwidth = me->winheight = 0;
dafd6cf6 128 if (drapi)
129 me->drawing = drawing_init(drapi, drhandle);
130 else
131 me->drawing = NULL;
7f77ea24 132
cbb5549e 133 sfree(randseed);
134
7f77ea24 135 return me;
136}
137
dafd6cf6 138static void midend_free_game(midend *me)
ab53eb64 139{
a4393230 140 while (me->nstates > 0) {
141 me->nstates--;
142 me->ourgame->free_game(me->states[me->nstates].state);
143 sfree(me->states[me->nstates].movestr);
144 }
ab53eb64 145
146 if (me->drawstate)
dafd6cf6 147 me->ourgame->free_drawstate(me->drawing, me->drawstate);
ab53eb64 148}
149
dafd6cf6 150void midend_free(midend *me)
7f77ea24 151{
ab53eb64 152 int i;
153
154 midend_free_game(me);
155
dafd6cf6 156 if (me->drawing)
157 drawing_free(me->drawing);
ab53eb64 158 random_free(me->random);
7f77ea24 159 sfree(me->states);
1185e3c5 160 sfree(me->desc);
871bf294 161 sfree(me->privdesc);
1185e3c5 162 sfree(me->seedstr);
c566778e 163 sfree(me->aux_info);
be8d5aa1 164 me->ourgame->free_params(me->params);
ab53eb64 165 if (me->npresets) {
166 for (i = 0; i < me->npresets; i++) {
167 sfree(me->presets[i]);
168 sfree(me->preset_names[i]);
169 }
170 sfree(me->presets);
171 sfree(me->preset_names);
172 }
173 if (me->ui)
174 me->ourgame->free_ui(me->ui);
f60f7e7c 175 if (me->curparams)
176 me->ourgame->free_params(me->curparams);
48dcdd62 177 sfree(me->laststatus);
7f77ea24 178 sfree(me);
179}
180
dafd6cf6 181static void midend_size_new_drawstate(midend *me)
1f3ee4ee 182{
183 /*
184 * Don't even bother, if we haven't worked out our tile size
185 * anyway yet.
186 */
187 if (me->tilesize > 0) {
188 me->ourgame->compute_size(me->params, me->tilesize,
189 &me->winwidth, &me->winheight);
dafd6cf6 190 me->ourgame->set_size(me->drawing, me->drawstate,
191 me->params, me->tilesize);
1f3ee4ee 192 }
193}
194
dafd6cf6 195void midend_size(midend *me, int *x, int *y, int expand)
7f77ea24 196{
1f3ee4ee 197 int min, max;
198 int rx, ry;
199
200 /*
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
204 * tile size.
205 */
206 if (expand) {
207 max = 1;
208 do {
209 max *= 2;
210 me->ourgame->compute_size(me->params, max, &rx, &ry);
211 } while (rx <= *x && ry <= *y);
212 } else
213 max = me->ourgame->preferred_tilesize + 1;
214 min = 1;
215
216 /*
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.
221 */
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)
226 min = mid;
227 else
228 max = mid;
229 }
230
231 /*
232 * Now `min' is a valid size, and `max' isn't. So use `min'.
233 */
234
235 me->tilesize = min;
236 midend_size_new_drawstate(me);
237 *x = me->winwidth;
238 *y = me->winheight;
7f77ea24 239}
240
dafd6cf6 241void midend_set_params(midend *me, game_params *params)
7f77ea24 242{
be8d5aa1 243 me->ourgame->free_params(me->params);
244 me->params = me->ourgame->dup_params(params);
7f77ea24 245}
246
dafd6cf6 247static void midend_set_timer(midend *me)
48dcdd62 248{
249 me->timing = (me->ourgame->is_timed &&
4d08de49 250 me->ourgame->timing_state(me->states[me->statepos-1].state,
251 me->ui));
48dcdd62 252 if (me->timing || me->flash_time || me->anim_time)
253 activate_timer(me->frontend);
254 else
255 deactivate_timer(me->frontend);
256}
257
dafd6cf6 258void midend_force_redraw(midend *me)
008b4378 259{
260 if (me->drawstate)
dafd6cf6 261 me->ourgame->free_drawstate(me->drawing, me->drawstate);
262 me->drawstate = me->ourgame->new_drawstate(me->drawing,
263 me->states[0].state);
1e3e152d 264 midend_size_new_drawstate(me);
008b4378 265 midend_redraw(me);
266}
267
dafd6cf6 268void midend_new_game(midend *me)
7f77ea24 269{
ab53eb64 270 midend_free_game(me);
2ef96bd6 271
7f77ea24 272 assert(me->nstates == 0);
273
1185e3c5 274 if (me->genmode == GOT_DESC) {
275 me->genmode = GOT_NOTHING;
276 } else {
277 random_state *rs;
278
279 if (me->genmode == GOT_SEED) {
280 me->genmode = GOT_NOTHING;
281 } else {
282 /*
283 * Generate a new random seed. 15 digits comes to about
284 * 48 bits, which should be more than enough.
97c44af3 285 *
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.
1185e3c5 289 */
290 char newseed[16];
291 int i;
292 newseed[15] = '\0';
97c44af3 293 newseed[0] = '1' + random_upto(me->random, 9);
294 for (i = 1; i < 15; i++)
1185e3c5 295 newseed[i] = '0' + random_upto(me->random, 10);
296 sfree(me->seedstr);
297 me->seedstr = dupstr(newseed);
f60f7e7c 298
299 if (me->curparams)
300 me->ourgame->free_params(me->curparams);
301 me->curparams = me->ourgame->dup_params(me->params);
1185e3c5 302 }
303
304 sfree(me->desc);
0a6892db 305 sfree(me->privdesc);
c566778e 306 sfree(me->aux_info);
6f2d8d7c 307 me->aux_info = NULL;
1185e3c5 308
309 rs = random_init(me->seedstr, strlen(me->seedstr));
dafd6cf6 310 /*
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.
315 */
6aa6af4c 316 me->desc = me->ourgame->new_desc(me->curparams, rs,
dafd6cf6 317 &me->aux_info, (me->drawing != NULL));
0a6892db 318 me->privdesc = NULL;
1185e3c5 319 random_free(rs);
1185e3c5 320 }
7f77ea24 321
322 ensure(me);
c380832d 323 me->states[me->nstates].state =
324 me->ourgame->new_game(me, me->params, me->desc);
a4393230 325 me->states[me->nstates].movestr = NULL;
326 me->states[me->nstates].movetype = NEWGAME;
28d0118c 327 me->nstates++;
7f77ea24 328 me->statepos = 1;
dafd6cf6 329 me->drawstate = me->ourgame->new_drawstate(me->drawing,
330 me->states[0].state);
1e3e152d 331 midend_size_new_drawstate(me);
48dcdd62 332 me->elapsed = 0.0F;
74a4e547 333 if (me->ui)
be8d5aa1 334 me->ourgame->free_ui(me->ui);
28d0118c 335 me->ui = me->ourgame->new_ui(me->states[0].state);
4d08de49 336 midend_set_timer(me);
6776a950 337 me->pressed_mouse_button = 0;
7f77ea24 338}
339
dafd6cf6 340static int midend_undo(midend *me)
7f77ea24 341{
1482ee76 342 if (me->statepos > 1) {
07dfb697 343 if (me->ui)
344 me->ourgame->changed_state(me->ui,
345 me->states[me->statepos-1].state,
346 me->states[me->statepos-2].state);
7f77ea24 347 me->statepos--;
c822de4a 348 me->dir = -1;
1482ee76 349 return 1;
350 } else
351 return 0;
7f77ea24 352}
353
dafd6cf6 354static int midend_redo(midend *me)
7f77ea24 355{
1482ee76 356 if (me->statepos < me->nstates) {
07dfb697 357 if (me->ui)
358 me->ourgame->changed_state(me->ui,
359 me->states[me->statepos-1].state,
360 me->states[me->statepos].state);
7f77ea24 361 me->statepos++;
c822de4a 362 me->dir = +1;
1482ee76 363 return 1;
364 } else
365 return 0;
7f77ea24 366}
367
dafd6cf6 368static void midend_finish_move(midend *me)
87ed82be 369{
370 float flashtime;
371
28d0118c 372 /*
373 * We do not flash if the later of the two states is special.
374 * This covers both forward Solve moves and backward (undone)
375 * Restart moves.
376 */
377 if ((me->oldstate || me->statepos > 1) &&
a4393230 378 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
28d0118c 379 (me->dir < 0 && me->statepos < me->nstates &&
a4393230 380 !special(me->states[me->statepos].movetype)))) {
be8d5aa1 381 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
28d0118c 382 me->states[me->statepos-2].state,
383 me->states[me->statepos-1].state,
e3f21163 384 me->oldstate ? me->dir : +1,
385 me->ui);
87ed82be 386 if (flashtime > 0) {
387 me->flash_pos = 0.0F;
388 me->flash_time = flashtime;
389 }
390 }
391
392 if (me->oldstate)
be8d5aa1 393 me->ourgame->free_game(me->oldstate);
87ed82be 394 me->oldstate = NULL;
395 me->anim_pos = me->anim_time = 0;
c822de4a 396 me->dir = 0;
87ed82be 397
48dcdd62 398 midend_set_timer(me);
87ed82be 399}
400
dafd6cf6 401void midend_stop_anim(midend *me)
7f77ea24 402{
8317499a 403 if (me->oldstate || me->anim_time != 0) {
87ed82be 404 midend_finish_move(me);
2ef96bd6 405 midend_redraw(me);
406 }
dd216087 407}
408
dafd6cf6 409void midend_restart_game(midend *me)
28d0118c 410{
411 game_state *s;
412
7f89707c 413 midend_stop_anim(me);
414
28d0118c 415 assert(me->statepos >= 1);
416 if (me->statepos == 1)
417 return; /* no point doing anything at all! */
418
0a6892db 419 /*
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).
425 */
426 s = me->ourgame->new_game(me, me->params, me->desc);
28d0118c 427
428 /*
429 * Now enter the restarted state as the next move.
430 */
431 midend_stop_anim(me);
432 while (me->nstates > me->statepos)
433 me->ourgame->free_game(me->states[--me->nstates].state);
434 ensure(me);
435 me->states[me->nstates].state = s;
a4393230 436 me->states[me->nstates].movestr = dupstr(me->desc);
437 me->states[me->nstates].movetype = RESTART;
28d0118c 438 me->statepos = ++me->nstates;
07dfb697 439 if (me->ui)
440 me->ourgame->changed_state(me->ui,
441 me->states[me->statepos-2].state,
442 me->states[me->statepos-1].state);
28d0118c 443 me->anim_time = 0.0;
444 midend_finish_move(me);
445 midend_redraw(me);
48dcdd62 446 midend_set_timer(me);
28d0118c 447}
448
dafd6cf6 449static int midend_really_process_key(midend *me, int x, int y, int button)
dd216087 450{
28d0118c 451 game_state *oldstate =
452 me->ourgame->dup_game(me->states[me->statepos - 1].state);
9d6c3859 453 int type = MOVE, gottype = FALSE, ret = 1;
dd216087 454 float anim_time;
4c692867 455 game_state *s;
456 char *movestr;
457
458 movestr =
459 me->ourgame->interpret_move(me->states[me->statepos-1].state,
460 me->ui, me->drawstate, x, y, button);
7f77ea24 461
4c692867 462 if (!movestr) {
463 if (button == 'n' || button == 'N' || button == '\x0E') {
464 midend_stop_anim(me);
465 midend_new_game(me);
466 midend_redraw(me);
467 goto done; /* never animate */
468 } else if (button == 'u' || button == 'u' ||
469 button == '\x1A' || button == '\x1F') {
470 midend_stop_anim(me);
9d6c3859 471 type = me->states[me->statepos-1].movetype;
472 gottype = TRUE;
4c692867 473 if (!midend_undo(me))
474 goto done;
475 } else if (button == 'r' || button == 'R' ||
476 button == '\x12' || button == '\x19') {
477 midend_stop_anim(me);
478 if (!midend_redo(me))
479 goto done;
480 } else if (button == 'q' || button == 'Q' || button == '\x11') {
481 ret = 0;
482 goto done;
483 } else
ab53eb64 484 goto done;
2ef96bd6 485 } else {
4c692867 486 if (!*movestr)
df11cd4e 487 s = me->states[me->statepos-1].state;
488 else {
489 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
490 movestr);
491 assert(s != NULL);
df11cd4e 492 }
74a4e547 493
28d0118c 494 if (s == me->states[me->statepos-1].state) {
74a4e547 495 /*
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.
499 */
500 midend_redraw(me);
ab53eb64 501 goto done;
74a4e547 502 } else if (s) {
dd216087 503 midend_stop_anim(me);
2ef96bd6 504 while (me->nstates > me->statepos)
28d0118c 505 me->ourgame->free_game(me->states[--me->nstates].state);
2ef96bd6 506 ensure(me);
a4393230 507 assert(movestr != NULL);
28d0118c 508 me->states[me->nstates].state = s;
a4393230 509 me->states[me->nstates].movestr = movestr;
510 me->states[me->nstates].movetype = MOVE;
2ef96bd6 511 me->statepos = ++me->nstates;
c822de4a 512 me->dir = +1;
faff1e07 513 if (me->ui)
514 me->ourgame->changed_state(me->ui,
515 me->states[me->statepos-2].state,
516 me->states[me->statepos-1].state);
2ef96bd6 517 } else {
a4393230 518 goto done;
2ef96bd6 519 }
7f77ea24 520 }
521
9d6c3859 522 if (!gottype)
523 type = me->states[me->statepos-1].movetype;
28d0118c 524
2ef96bd6 525 /*
526 * See if this move requires an animation.
527 */
9d6c3859 528 if (special(type) && !(type == SOLVE &&
529 (me->ourgame->mouse_priorities & SOLVE_ANIMATES))) {
28d0118c 530 anim_time = 0;
531 } else {
532 anim_time = me->ourgame->anim_length(oldstate,
533 me->states[me->statepos-1].state,
e3f21163 534 me->dir, me->ui);
28d0118c 535 }
2ef96bd6 536
ab53eb64 537 me->oldstate = oldstate; oldstate = NULL;
2ef96bd6 538 if (anim_time > 0) {
2ef96bd6 539 me->anim_time = anim_time;
540 } else {
2ef96bd6 541 me->anim_time = 0.0;
87ed82be 542 midend_finish_move(me);
7f77ea24 543 }
2ef96bd6 544 me->anim_pos = 0.0;
545
546 midend_redraw(me);
547
48dcdd62 548 midend_set_timer(me);
7f77ea24 549
ab53eb64 550 done:
551 if (oldstate) me->ourgame->free_game(oldstate);
552 return ret;
7f77ea24 553}
2ef96bd6 554
dafd6cf6 555int midend_process_key(midend *me, int x, int y, int button)
6776a950 556{
557 int ret = 1;
558
559 /*
560 * Harmonise mouse drag and release messages.
561 *
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.)
568 *
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
573 * to be done once.
574 *
eeba2afe 575 * The possible ways in which things can go screwy in the front
576 * end are:
6776a950 577 *
eeba2afe 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.
6776a950 582 *
eeba2afe 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.
6776a950 587 *
eeba2afe 588 * Definite requirements are:
589 *
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.
596 *
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.
601 *
602 * So my policy will be:
603 *
604 * - treat any button-up as a button-up for the currently
605 * pressed button, or ignore it if there is no currently
606 * pressed button.
607 *
608 * - treat any drag as a drag for the currently pressed
609 * button, or ignore it if there is no currently pressed
610 * button.
611 *
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.
6776a950 615 *
93b1da3d 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.
6776a950 624 */
625 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
eeba2afe 626 if (me->pressed_mouse_button) {
627 if (IS_MOUSE_DRAG(button)) {
628 button = me->pressed_mouse_button +
629 (LEFT_DRAG - LEFT_BUTTON);
630 } else {
631 button = me->pressed_mouse_button +
632 (LEFT_RELEASE - LEFT_BUTTON);
6776a950 633 }
eeba2afe 634 } else
635 return ret; /* ignore it */
6776a950 636 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
93b1da3d 637 /*
638 * If the new button has lower priority than the old one,
639 * don't bother doing this.
640 */
641 if (me->ourgame->mouse_priorities &
642 BUTTON_BEATS(me->pressed_mouse_button, button))
643 return ret; /* just ignore it */
644
6776a950 645 /*
646 * Fabricate a button-up for the previously pressed button.
647 */
648 ret = ret && midend_really_process_key
649 (me, x, y, (me->pressed_mouse_button +
650 (LEFT_RELEASE - LEFT_BUTTON)));
651 }
652
653 /*
654 * Now send on the event we originally received.
655 */
656 ret = ret && midend_really_process_key(me, x, y, button);
657
658 /*
659 * And update the currently pressed button.
660 */
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;
665
666 return ret;
667}
668
dafd6cf6 669void midend_redraw(midend *me)
2ef96bd6 670{
dafd6cf6 671 assert(me->drawing);
672
2ef96bd6 673 if (me->statepos > 0 && me->drawstate) {
dafd6cf6 674 start_draw(me->drawing);
2ef96bd6 675 if (me->oldstate && me->anim_time > 0 &&
676 me->anim_pos < me->anim_time) {
c822de4a 677 assert(me->dir != 0);
dafd6cf6 678 me->ourgame->redraw(me->drawing, me->drawstate, me->oldstate,
28d0118c 679 me->states[me->statepos-1].state, me->dir,
be8d5aa1 680 me->ui, me->anim_pos, me->flash_pos);
2ef96bd6 681 } else {
dafd6cf6 682 me->ourgame->redraw(me->drawing, me->drawstate, NULL,
28d0118c 683 me->states[me->statepos-1].state, +1 /*shrug*/,
be8d5aa1 684 me->ui, 0.0, me->flash_pos);
2ef96bd6 685 }
dafd6cf6 686 end_draw(me->drawing);
2ef96bd6 687 }
688}
689
dafd6cf6 690void midend_timer(midend *me, float tplus)
2ef96bd6 691{
692 me->anim_pos += tplus;
693 if (me->anim_pos >= me->anim_time ||
694 me->anim_time == 0 || !me->oldstate) {
87ed82be 695 if (me->anim_time > 0)
696 midend_finish_move(me);
697 }
48dcdd62 698
87ed82be 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;
2ef96bd6 702 }
48dcdd62 703
2ef96bd6 704 midend_redraw(me);
48dcdd62 705
706 if (me->timing) {
707 float oldelapsed = me->elapsed;
708 me->elapsed += tplus;
709 if ((int)oldelapsed != (int)me->elapsed)
dafd6cf6 710 status_bar(me->drawing, me->laststatus ? me->laststatus : "");
48dcdd62 711 }
712
713 midend_set_timer(me);
2ef96bd6 714}
715
dafd6cf6 716float *midend_colours(midend *me, int *ncolours)
2ef96bd6 717{
718 game_state *state = NULL;
719 float *ret;
720
721 if (me->nstates == 0) {
c566778e 722 char *aux = NULL;
6aa6af4c 723 char *desc = me->ourgame->new_desc(me->params, me->random,
724 &aux, TRUE);
c380832d 725 state = me->ourgame->new_game(me, me->params, desc);
1185e3c5 726 sfree(desc);
c566778e 727 sfree(aux);
2ef96bd6 728 } else
28d0118c 729 state = me->states[0].state;
2ef96bd6 730
be8d5aa1 731 ret = me->ourgame->colours(me->frontend, state, ncolours);
2ef96bd6 732
813593cc 733 {
734 int i;
735
736 /*
737 * Allow environment-based overrides for the standard
738 * colours by defining variables along the lines of
739 * `NET_COLOUR_4=6000c0'.
740 */
741
742 for (i = 0; i < *ncolours; i++) {
743 char buf[80], *e;
744 unsigned int r, g, b;
056405ec 745 int j, k;
813593cc 746
747 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
056405ec 748 for (j = k = 0; buf[j]; j++)
749 if (!isspace((unsigned char)buf[j]))
750 buf[k++] = toupper((unsigned char)buf[j]);
751 buf[k] = '\0';
813593cc 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;
757 }
758 }
759 }
760
2ef96bd6 761 if (me->nstates == 0)
be8d5aa1 762 me->ourgame->free_game(state);
2ef96bd6 763
764 return ret;
765}
eb2ad6f1 766
dafd6cf6 767int midend_num_presets(midend *me)
eb2ad6f1 768{
769 if (!me->npresets) {
770 char *name;
771 game_params *preset;
772
be8d5aa1 773 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
eb2ad6f1 774 if (me->presetsize <= me->npresets) {
775 me->presetsize = me->npresets + 10;
776 me->presets = sresize(me->presets, me->presetsize,
777 game_params *);
778 me->preset_names = sresize(me->preset_names, me->presetsize,
779 char *);
780 }
781
782 me->presets[me->npresets] = preset;
783 me->preset_names[me->npresets] = name;
784 me->npresets++;
785 }
786 }
787
813593cc 788 {
789 /*
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.
795 */
796 char buf[80], *e, *p;
056405ec 797 int j, k;
813593cc 798
799 sprintf(buf, "%s_PRESETS", me->ourgame->name);
056405ec 800 for (j = k = 0; buf[j]; j++)
801 if (!isspace((unsigned char)buf[j]))
802 buf[k++] = toupper((unsigned char)buf[j]);
803 buf[k] = '\0';
813593cc 804
805 if ((e = getenv(buf)) != NULL) {
806 p = e = dupstr(e);
807
808 while (*p) {
809 char *name, *val;
810 game_params *preset;
811
812 name = p;
813 while (*p && *p != ':') p++;
814 if (*p) *p++ = '\0';
815 val = p;
816 while (*p && *p != ':') p++;
817 if (*p) *p++ = '\0';
818
819 preset = me->ourgame->default_params();
820 me->ourgame->decode_params(preset, val);
821
3ff276f2 822 if (me->ourgame->validate_params(preset, TRUE)) {
239ba6e6 823 /* Drop this one from the list. */
824 me->ourgame->free_params(preset);
825 continue;
826 }
827
813593cc 828 if (me->presetsize <= me->npresets) {
829 me->presetsize = me->npresets + 10;
830 me->presets = sresize(me->presets, me->presetsize,
831 game_params *);
832 me->preset_names = sresize(me->preset_names,
833 me->presetsize, char *);
834 }
835
836 me->presets[me->npresets] = preset;
cb64d2dd 837 me->preset_names[me->npresets] = dupstr(name);
813593cc 838 me->npresets++;
839 }
840 }
841 }
842
eb2ad6f1 843 return me->npresets;
844}
845
dafd6cf6 846void midend_fetch_preset(midend *me, int n,
eb2ad6f1 847 char **name, game_params **params)
848{
849 assert(n >= 0 && n < me->npresets);
850 *name = me->preset_names[n];
851 *params = me->presets[n];
852}
fd1a1a2b 853
dafd6cf6 854int midend_wants_statusbar(midend *me)
fd1a1a2b 855{
be8d5aa1 856 return me->ourgame->wants_statusbar();
fd1a1a2b 857}
c8230524 858
dafd6cf6 859void midend_supersede_game_desc(midend *me, char *desc, char *privdesc)
c380832d 860{
861 sfree(me->desc);
0a6892db 862 sfree(me->privdesc);
c380832d 863 me->desc = dupstr(desc);
0a6892db 864 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
c380832d 865}
866
dafd6cf6 867config_item *midend_get_config(midend *me, int which, char **wintitle)
c8230524 868{
ab53eb64 869 char *titlebuf, *parstr, *rest;
5928817c 870 config_item *ret;
ab53eb64 871 char sep;
5928817c 872
ab53eb64 873 assert(wintitle);
be8d5aa1 874 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
5928817c 875
876 switch (which) {
877 case CFG_SETTINGS:
be8d5aa1 878 sprintf(titlebuf, "%s configuration", me->ourgame->name);
ab53eb64 879 *wintitle = titlebuf;
be8d5aa1 880 return me->ourgame->configure(me->params);
5928817c 881 case CFG_SEED:
1185e3c5 882 case CFG_DESC:
ab53eb64 883 if (!me->curparams) {
884 sfree(titlebuf);
885 return NULL;
886 }
887 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1185e3c5 888 which == CFG_SEED ? "random" : "game");
ab53eb64 889 *wintitle = titlebuf;
5928817c 890
891 ret = snewn(2, config_item);
892
893 ret[0].type = C_STRING;
1185e3c5 894 if (which == CFG_SEED)
895 ret[0].name = "Game random seed";
896 else
897 ret[0].name = "Game ID";
5928817c 898 ret[0].ival = 0;
b0e26073 899 /*
1185e3c5 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
906 * changes).
b0e26073 907 */
f60f7e7c 908 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
ab53eb64 909 assert(parstr);
1185e3c5 910 if (which == CFG_DESC) {
ab53eb64 911 rest = me->desc ? me->desc : "";
912 sep = ':';
1185e3c5 913 } else {
ab53eb64 914 rest = me->seedstr ? me->seedstr : "";
915 sep = '#';
1185e3c5 916 }
ab53eb64 917 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
918 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
b0e26073 919 sfree(parstr);
5928817c 920
921 ret[1].type = C_END;
922 ret[1].name = ret[1].sval = NULL;
923 ret[1].ival = 0;
924
925 return ret;
926 }
927
928 assert(!"We shouldn't be here");
929 return NULL;
c8230524 930}
931
dafd6cf6 932static char *midend_game_id_int(midend *me, char *id, int defmode)
8b7938e7 933{
1185e3c5 934 char *error, *par, *desc, *seed;
5c9f61fd 935 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
936 int free_params;
8b7938e7 937
1185e3c5 938 seed = strchr(id, '#');
939 desc = strchr(id, ':');
8b7938e7 940
1185e3c5 941 if (desc && (!seed || desc < seed)) {
942 /*
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.
946 */
947 *desc++ = '\0';
948 par = id;
949 seed = NULL;
950 } else if (seed && (!desc || seed < desc)) {
8b7938e7 951 /*
50ff5730 952 * We have a hash separating parameters from random seed.
1185e3c5 953 * So `par' now points to the parameters string, and `seed'
954 * to the seed string.
8b7938e7 955 */
956 *seed++ = '\0';
957 par = id;
1185e3c5 958 desc = NULL;
8b7938e7 959 } else {
960 /*
1185e3c5 961 * We only have one string. Depending on `defmode', we take
962 * it to be either parameters, seed or description.
8b7938e7 963 */
1185e3c5 964 if (defmode == DEF_SEED) {
8b7938e7 965 seed = id;
1185e3c5 966 par = desc = NULL;
967 } else if (defmode == DEF_DESC) {
968 desc = id;
969 par = seed = NULL;
8b7938e7 970 } else {
8b7938e7 971 par = id;
1185e3c5 972 seed = desc = NULL;
8b7938e7 973 }
974 }
975
5c9f61fd 976 /*
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
981 * acceptable.
982 */
983 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
984
8b7938e7 985 if (par) {
5c9f61fd 986 newcurparams = me->ourgame->dup_params(me->params);
987 me->ourgame->decode_params(newcurparams, par);
3ff276f2 988 error = me->ourgame->validate_params(newcurparams, desc == NULL);
8b7938e7 989 if (error) {
5c9f61fd 990 me->ourgame->free_params(newcurparams);
8b7938e7 991 return error;
992 }
5c9f61fd 993 oldparams1 = me->curparams;
1185e3c5 994
995 /*
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
999 * persistent.
1000 */
5c9f61fd 1001 oldparams2 = me->params;
1185e3c5 1002 if (seed || desc) {
5c9f61fd 1003 char *tmpstr;
1004
1005 newparams = me->ourgame->dup_params(me->params);
1006
1007 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
1008 me->ourgame->decode_params(newparams, tmpstr);
1009
3af70dd4 1010 sfree(tmpstr);
1185e3c5 1011 } else {
5c9f61fd 1012 newparams = me->ourgame->dup_params(newcurparams);
1185e3c5 1013 }
5c9f61fd 1014 free_params = TRUE;
1015 } else {
1016 newcurparams = me->curparams;
1017 newparams = me->params;
1018 free_params = FALSE;
8b7938e7 1019 }
1020
5c9f61fd 1021 if (desc) {
1022 error = me->ourgame->validate_desc(newparams, desc);
1023 if (error) {
1024 if (free_params) {
1025 if (newcurparams)
1026 me->ourgame->free_params(newcurparams);
1027 if (newparams)
1028 me->ourgame->free_params(newparams);
1029 }
1030 return error;
1031 }
1032 }
1033
1034 /*
1035 * Now we've got past all possible error points. Update the
1036 * midend itself.
1037 */
1038 me->params = newparams;
1039 me->curparams = newcurparams;
1040 if (oldparams1)
1041 me->ourgame->free_params(oldparams1);
1042 if (oldparams2)
1043 me->ourgame->free_params(oldparams2);
1044
3af70dd4 1045 sfree(me->desc);
0a6892db 1046 sfree(me->privdesc);
1047 me->desc = me->privdesc = NULL;
3af70dd4 1048 sfree(me->seedstr);
1049 me->seedstr = NULL;
1050
1185e3c5 1051 if (desc) {
1185e3c5 1052 me->desc = dupstr(desc);
1053 me->genmode = GOT_DESC;
c566778e 1054 sfree(me->aux_info);
6f2d8d7c 1055 me->aux_info = NULL;
8b7938e7 1056 }
1057
1185e3c5 1058 if (seed) {
1185e3c5 1059 me->seedstr = dupstr(seed);
1060 me->genmode = GOT_SEED;
1061 }
1062
8b7938e7 1063 return NULL;
1064}
1065
dafd6cf6 1066char *midend_game_id(midend *me, char *id)
1185e3c5 1067{
1068 return midend_game_id_int(me, id, DEF_PARAMS);
1069}
1070
dafd6cf6 1071char *midend_get_game_id(midend *me)
1072{
1073 char *parstr, *ret;
1074
1075 parstr = me->ourgame->encode_params(me->curparams, FALSE);
1076 assert(parstr);
1077 assert(me->desc);
1078 ret = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
1079 sprintf(ret, "%s:%s", parstr, me->desc);
1080 sfree(parstr);
1081 return ret;
1082}
1083
1084char *midend_set_config(midend *me, int which, config_item *cfg)
c8230524 1085{
8b7938e7 1086 char *error;
c8230524 1087 game_params *params;
1088
5928817c 1089 switch (which) {
1090 case CFG_SETTINGS:
be8d5aa1 1091 params = me->ourgame->custom_params(cfg);
3ff276f2 1092 error = me->ourgame->validate_params(params, TRUE);
c8230524 1093
5928817c 1094 if (error) {
be8d5aa1 1095 me->ourgame->free_params(params);
5928817c 1096 return error;
1097 }
c8230524 1098
be8d5aa1 1099 me->ourgame->free_params(me->params);
5928817c 1100 me->params = params;
1101 break;
1102
1103 case CFG_SEED:
1185e3c5 1104 case CFG_DESC:
1105 error = midend_game_id_int(me, cfg[0].sval,
1106 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
5928817c 1107 if (error)
1108 return error;
5928817c 1109 break;
1110 }
c8230524 1111
1112 return NULL;
1113}
9b4b03d3 1114
dafd6cf6 1115char *midend_text_format(midend *me)
9b4b03d3 1116{
1117 if (me->ourgame->can_format_as_text && me->statepos > 0)
28d0118c 1118 return me->ourgame->text_format(me->states[me->statepos-1].state);
9b4b03d3 1119 else
1120 return NULL;
1121}
2ac6d24e 1122
dafd6cf6 1123char *midend_solve(midend *me)
2ac6d24e 1124{
1125 game_state *s;
df11cd4e 1126 char *msg, *movestr;
2ac6d24e 1127
1128 if (!me->ourgame->can_solve)
1129 return "This game does not support the Solve operation";
1130
1131 if (me->statepos < 1)
1132 return "No game set up to solve"; /* _shouldn't_ happen! */
1133
1134 msg = "Solve operation failed"; /* game _should_ overwrite on error */
df11cd4e 1135 movestr = me->ourgame->solve(me->states[0].state,
1136 me->states[me->statepos-1].state,
1137 me->aux_info, &msg);
1138 if (!movestr)
2ac6d24e 1139 return msg;
df11cd4e 1140 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1141 assert(s);
2ac6d24e 1142
1143 /*
28d0118c 1144 * Now enter the solved state as the next move.
2ac6d24e 1145 */
1146 midend_stop_anim(me);
1147 while (me->nstates > me->statepos)
28d0118c 1148 me->ourgame->free_game(me->states[--me->nstates].state);
2ac6d24e 1149 ensure(me);
28d0118c 1150 me->states[me->nstates].state = s;
a4393230 1151 me->states[me->nstates].movestr = movestr;
1152 me->states[me->nstates].movetype = SOLVE;
2ac6d24e 1153 me->statepos = ++me->nstates;
07dfb697 1154 if (me->ui)
1155 me->ourgame->changed_state(me->ui,
1156 me->states[me->statepos-2].state,
1157 me->states[me->statepos-1].state);
9d6c3859 1158 me->dir = +1;
1159 if (me->ourgame->mouse_priorities & SOLVE_ANIMATES) {
1160 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1161 me->anim_time =
1162 me->ourgame->anim_length(me->states[me->statepos-2].state,
1163 me->states[me->statepos-1].state,
1164 +1, me->ui);
e80e7b71 1165 me->anim_pos = 0.0;
9d6c3859 1166 } else {
1167 me->anim_time = 0.0;
1168 midend_finish_move(me);
1169 }
2ac6d24e 1170 midend_redraw(me);
48dcdd62 1171 midend_set_timer(me);
2ac6d24e 1172 return NULL;
1173}
48dcdd62 1174
dafd6cf6 1175char *midend_rewrite_statusbar(midend *me, char *text)
48dcdd62 1176{
1177 /*
1178 * An important special case is that we are occasionally called
1179 * with our own laststatus, to update the timer.
1180 */
1181 if (me->laststatus != text) {
1182 sfree(me->laststatus);
1183 me->laststatus = dupstr(text);
1184 }
1185
1186 if (me->ourgame->is_timed) {
1187 char timebuf[100], *ret;
1188 int min, sec;
1189
1190 sec = me->elapsed;
1191 min = sec / 60;
1192 sec %= 60;
1193 sprintf(timebuf, "[%d:%02d] ", min, sec);
1194
1195 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1196 strcpy(ret, timebuf);
1197 strcat(ret, text);
1198 return ret;
1199
1200 } else {
1201 return dupstr(text);
1202 }
1203}
a4393230 1204
1205#define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1206#define SERIALISE_VERSION "1"
1207
dafd6cf6 1208void midend_serialise(midend *me,
a4393230 1209 void (*write)(void *ctx, void *buf, int len),
1210 void *wctx)
1211{
1212 int i;
1213
1214 /*
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).
1222 */
1223#define wr(h,s) do { \
1224 char hbuf[80]; \
1225 char *str = (s); \
48d4740c 1226 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
a4393230 1227 write(wctx, hbuf, strlen(hbuf)); \
1228 write(wctx, str, strlen(str)); \
1229 write(wctx, "\n", 1); \
1230} while (0)
1231
1232 /*
1233 * Magic string identifying the file, and version number of the
1234 * file format.
1235 */
1236 wr("SAVEFILE", SERIALISE_MAGIC);
1237 wr("VERSION", SERIALISE_VERSION);
1238
1239 /*
1240 * The game name. (Copied locally to avoid const annoyance.)
1241 */
1242 {
1243 char *s = dupstr(me->ourgame->name);
1244 wr("GAME", s);
1245 sfree(s);
1246 }
1247
1248 /*
1249 * The current long-term parameters structure, in full.
1250 */
1251 if (me->params) {
1252 char *s = me->ourgame->encode_params(me->params, TRUE);
1253 wr("PARAMS", s);
1254 sfree(s);
1255 }
1256
1257 /*
1258 * The current short-term parameters structure, in full.
1259 */
1260 if (me->curparams) {
1261 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1262 wr("CPARAMS", s);
1263 sfree(s);
1264 }
1265
1266 /*
1267 * The current game description, the privdesc, and the random seed.
1268 */
1269 if (me->seedstr)
1270 wr("SEED", me->seedstr);
1271 if (me->desc)
1272 wr("DESC", me->desc);
1273 if (me->privdesc)
1274 wr("PRIVDESC", me->privdesc);
1275
1276 /*
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!)
1281 */
1282 if (me->aux_info) {
1283 unsigned char *s1;
1284 char *s2;
1285 int len;
1286
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);
1292
1293 wr("AUXINFO", s2);
1294
1295 sfree(s2);
1296 sfree(s1);
1297 }
1298
1299 /*
1300 * Any required serialisation of the game_ui.
1301 */
1302 if (me->ui) {
1303 char *s = me->ourgame->encode_ui(me->ui);
1304 if (s) {
1305 wr("UI", s);
1306 sfree(s);
1307 }
1308 }
1309
1310 /*
1311 * The game time, if it's a timed game.
1312 */
1313 if (me->ourgame->is_timed) {
1314 char buf[80];
1315 sprintf(buf, "%g", me->elapsed);
1316 wr("TIME", buf);
1317 }
1318
1319 /*
1320 * The length of, and position in, the states list.
1321 */
1322 {
1323 char buf[80];
1324 sprintf(buf, "%d", me->nstates);
1325 wr("NSTATES", buf);
1326 sprintf(buf, "%d", me->statepos);
1327 wr("STATEPOS", buf);
1328 }
1329
1330 /*
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
1334 * previous one.
1335 */
1336 for (i = 1; i < me->nstates; i++) {
1337 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1338 switch (me->states[i].movetype) {
1339 case MOVE:
1340 wr("MOVE", me->states[i].movestr);
1341 break;
1342 case SOLVE:
1343 wr("SOLVE", me->states[i].movestr);
1344 break;
1345 case RESTART:
1346 wr("RESTART", me->states[i].movestr);
1347 break;
1348 }
1349 }
1350
1351#undef wr
1352}
1353
1354/*
1355 * This function returns NULL on success, or an error message.
1356 */
dafd6cf6 1357char *midend_deserialise(midend *me,
a4393230 1358 int (*read)(void *ctx, void *buf, int len),
1359 void *rctx)
1360{
1361 int nstates = 0, statepos = -1, gotstates = 0;
1362 int started = FALSE;
1363 int i;
1364
1365 char *val = NULL;
1366 /* Initially all errors give the same report */
1367 char *ret = "Data does not appear to be a saved game file";
1368
1369 /*
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
dafd6cf6 1373 * modifying stuff in the midend passed in.
a4393230 1374 */
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;
1379 game_ui *ui = NULL;
1380 struct midend_state_entry *states = NULL;
1381
1382 /*
1383 * Loop round and round reading one key/value pair at a time
1384 * from the serialised stream, until we have enough game states
1385 * to finish.
1386 */
1387 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1388 char key[9], c;
1389 int len;
1390
1391 do {
1392 if (!read(rctx, key, 1)) {
1393 /* unexpected EOF */
1394 goto cleanup;
1395 }
1396 } while (key[0] == '\r' || key[0] == '\n');
1397
1398 if (!read(rctx, key+1, 8)) {
1399 /* unexpected EOF */
1400 goto cleanup;
1401 }
1402
1403 if (key[8] != ':') {
1404 if (started)
1405 ret = "Data was incorrectly formatted for a saved game file";
44f0599f 1406 goto cleanup;
a4393230 1407 }
1408 len = strcspn(key, ": ");
1409 assert(len <= 8);
1410 key[len] = '\0';
1411
1412 len = 0;
1413 while (1) {
1414 if (!read(rctx, &c, 1)) {
1415 /* unexpected EOF */
1416 goto cleanup;
1417 }
1418
1419 if (c == ':') {
1420 break;
1421 } else if (c >= '0' && c <= '9') {
1422 len = (len * 10) + (c - '0');
1423 } else {
1424 if (started)
1425 ret = "Data was incorrectly formatted for a"
1426 " saved game file";
1427 goto cleanup;
1428 }
1429 }
1430
1431 val = snewn(len+1, char);
1432 if (!read(rctx, val, len)) {
1433 if (started)
1434 goto cleanup;
1435 }
1436 val[len] = '\0';
1437
1438 if (!started) {
1439 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1440 /* ret already has the right message in it */
1441 goto cleanup;
1442 }
1443 /* Now most errors are this one, unless otherwise specified */
1444 ret = "Saved data ended unexpectedly";
1445 started = TRUE;
1446 } else {
1447 if (!strcmp(key, "VERSION")) {
1448 if (strcmp(val, SERIALISE_VERSION)) {
1449 ret = "Cannot handle this version of the saved game"
1450 " file format";
1451 goto cleanup;
1452 }
1453 } else if (!strcmp(key, "GAME")) {
1454 if (strcmp(val, me->ourgame->name)) {
1455 ret = "Save file is from a different game";
1456 goto cleanup;
1457 }
1458 } else if (!strcmp(key, "PARAMS")) {
1459 sfree(parstr);
1460 parstr = val;
1461 val = NULL;
1462 } else if (!strcmp(key, "CPARAMS")) {
1463 sfree(cparstr);
1464 cparstr = val;
1465 val = NULL;
1466 } else if (!strcmp(key, "SEED")) {
1467 sfree(seed);
1468 seed = val;
1469 val = NULL;
1470 } else if (!strcmp(key, "DESC")) {
1471 sfree(desc);
1472 desc = val;
1473 val = NULL;
1474 } else if (!strcmp(key, "PRIVDESC")) {
1475 sfree(privdesc);
1476 privdesc = val;
1477 val = NULL;
1478 } else if (!strcmp(key, "AUXINFO")) {
1479 unsigned char *tmp;
1480 int len = strlen(val) / 2; /* length in bytes */
1481 tmp = hex2bin(val, len);
1482 obfuscate_bitmap(tmp, len*8, TRUE);
1483
1484 sfree(auxinfo);
1485 auxinfo = snewn(len + 1, char);
1486 memcpy(auxinfo, tmp, len);
1487 auxinfo[len] = '\0';
1488 sfree(tmp);
1489 } else if (!strcmp(key, "UI")) {
1490 sfree(uistr);
1491 uistr = val;
1492 val = NULL;
1493 } else if (!strcmp(key, "TIME")) {
871bf294 1494 elapsed = atof(val);
a4393230 1495 } else if (!strcmp(key, "NSTATES")) {
1496 nstates = atoi(val);
1497 if (nstates <= 0) {
1498 ret = "Number of states in save file was negative";
1499 goto cleanup;
1500 }
1501 if (states) {
1502 ret = "Two state counts provided in save file";
1503 goto cleanup;
1504 }
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;
1510 }
1511 } else if (!strcmp(key, "STATEPOS")) {
1512 statepos = atoi(val);
1513 } else if (!strcmp(key, "MOVE")) {
1514 gotstates++;
1515 states[gotstates].movetype = MOVE;
1516 states[gotstates].movestr = val;
1517 val = NULL;
1518 } else if (!strcmp(key, "SOLVE")) {
1519 gotstates++;
1520 states[gotstates].movetype = SOLVE;
1521 states[gotstates].movestr = val;
1522 val = NULL;
1523 } else if (!strcmp(key, "RESTART")) {
1524 gotstates++;
1525 states[gotstates].movetype = RESTART;
1526 states[gotstates].movestr = val;
1527 val = NULL;
1528 }
1529 }
1530
1531 sfree(val);
1532 val = NULL;
1533 }
1534
1535 params = me->ourgame->default_params();
1536 me->ourgame->decode_params(params, parstr);
3ff276f2 1537 if (me->ourgame->validate_params(params, TRUE)) {
a4393230 1538 ret = "Long-term parameters in save file are invalid";
1539 goto cleanup;
1540 }
1541 cparams = me->ourgame->default_params();
1542 me->ourgame->decode_params(cparams, cparstr);
3ff276f2 1543 if (me->ourgame->validate_params(cparams, FALSE)) {
a4393230 1544 ret = "Short-term parameters in save file are invalid";
1545 goto cleanup;
1546 }
3ff276f2 1547 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1548 /*
1549 * The seed's no use with this version, but we can perfectly
1550 * well use the rest of the data.
1551 */
1552 sfree(seed);
1553 seed = NULL;
1554 }
a4393230 1555 if (!desc) {
1556 ret = "Game description in save file is missing";
1557 goto cleanup;
1558 } else if (me->ourgame->validate_desc(params, desc)) {
1559 ret = "Game description in save file is invalid";
1560 goto cleanup;
1561 }
1562 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1563 ret = "Game private description in save file is invalid";
1564 goto cleanup;
1565 }
1566 if (statepos < 0 || statepos >= nstates) {
1567 ret = "Game position in save file is out of range";
1568 }
1569
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) {
1575 case MOVE:
1576 case SOLVE:
1577 states[i].state = me->ourgame->execute_move(states[i-1].state,
1578 states[i].movestr);
1579 if (states[i].state == NULL) {
1580 ret = "Save file contained an invalid move";
1581 goto cleanup;
1582 }
1583 break;
1584 case RESTART:
1585 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1586 ret = "Save file contained an invalid restart move";
1587 goto cleanup;
1588 }
1589 states[i].state = me->ourgame->new_game(me, params,
1590 states[i].movestr);
1591 break;
1592 }
1593 }
1594
1595 ui = me->ourgame->new_ui(states[0].state);
1596 me->ourgame->decode_ui(ui, uistr);
1597
1598 /*
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
1603 * stuff.
1604 */
1605 {
1606 char *tmp;
1607
1608 tmp = me->desc;
1609 me->desc = desc;
1610 desc = tmp;
1611
1612 tmp = me->privdesc;
1613 me->privdesc = privdesc;
1614 privdesc = tmp;
1615
1616 tmp = me->seedstr;
1617 me->seedstr = seed;
1618 seed = tmp;
1619
1620 tmp = me->aux_info;
1621 me->aux_info = auxinfo;
1622 auxinfo = tmp;
1623 }
1624
1625 me->genmode = GOT_NOTHING;
1626
1627 me->statesize = nstates;
1628 nstates = me->nstates;
1629 me->nstates = me->statesize;
1630 {
1631 struct midend_state_entry *tmp;
1632 tmp = me->states;
1633 me->states = states;
1634 states = tmp;
1635 }
1636 me->statepos = statepos;
1637
1638 {
1639 game_params *tmp;
1640
1641 tmp = me->params;
1642 me->params = params;
1643 params = tmp;
1644
1645 tmp = me->curparams;
1646 me->curparams = cparams;
1647 cparams = tmp;
1648 }
1649
1650 me->oldstate = NULL;
1651 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1652 me->dir = 0;
1653
1654 {
1655 game_ui *tmp;
1656
1657 tmp = me->ui;
1658 me->ui = ui;
1659 ui = tmp;
1660 }
1661
1662 me->elapsed = elapsed;
1663 me->pressed_mouse_button = 0;
1664
1665 midend_set_timer(me);
1666
871bf294 1667 if (me->drawstate)
dafd6cf6 1668 me->ourgame->free_drawstate(me->drawing, me->drawstate);
871bf294 1669 me->drawstate =
dafd6cf6 1670 me->ourgame->new_drawstate(me->drawing,
1671 me->states[me->statepos-1].state);
871bf294 1672 midend_size_new_drawstate(me);
1673
a4393230 1674 ret = NULL; /* success! */
1675
1676 cleanup:
1677 sfree(val);
1678 sfree(seed);
1679 sfree(parstr);
1680 sfree(cparstr);
1681 sfree(desc);
1682 sfree(privdesc);
1683 sfree(auxinfo);
1684 sfree(uistr);
1685 if (params)
1686 me->ourgame->free_params(params);
1687 if (cparams)
1688 me->ourgame->free_params(cparams);
1689 if (ui)
1690 me->ourgame->free_ui(ui);
1691 if (states) {
1692 int i;
1693
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);
1698 }
1699 sfree(states);
1700 }
1701
1702 return ret;
1703}
dafd6cf6 1704
1705char *midend_print_puzzle(midend *me, document *doc, int with_soln)
1706{
1707 game_state *soln = NULL;
1708
1709 if (me->statepos < 1)
1710 return "No game set up to print";/* _shouldn't_ happen! */
1711
1712 if (with_soln) {
1713 char *msg, *movestr;
1714
1715 if (!me->ourgame->can_solve)
1716 return "This game does not support the Solve operation";
1717
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);
1722 if (!movestr)
1723 return msg;
1724 soln = me->ourgame->execute_move(me->states[me->statepos-1].state,
1725 movestr);
1726 assert(soln);
1727
1728 sfree(movestr);
1729 } else
1730 soln = NULL;
1731
1732 /*
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
1736 * non-NULL.
1737 */
1738 document_add_puzzle(doc, me->ourgame,
1739 me->ourgame->dup_params(me->curparams),
1740 me->ourgame->dup_game(me->states[0].state), soln);
1741
1742 return NULL;
1743}