Just noticed another thing that could easily catch me out when
[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
7f77ea24 28struct midend_data {
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
6776a950 79 int pressed_mouse_button;
1e3e152d 80
1f3ee4ee 81 int tilesize, winwidth, winheight;
7f77ea24 82};
83
84#define ensure(me) do { \
85 if ((me)->nstates >= (me)->statesize) { \
86 (me)->statesize = (me)->nstates + 128; \
28d0118c 87 (me)->states = sresize((me)->states, (me)->statesize, \
88 struct midend_state_entry); \
7f77ea24 89 } \
90} while (0)
91
be8d5aa1 92midend_data *midend_new(frontend *fe, const game *ourgame)
7f77ea24 93{
94 midend_data *me = snew(midend_data);
cbb5549e 95 void *randseed;
96 int randseedsize;
97
98 get_random_seed(&randseed, &randseedsize);
7f77ea24 99
48d70ca9 100 me->frontend = fe;
be8d5aa1 101 me->ourgame = ourgame;
48d70ca9 102 me->random = random_init(randseed, randseedsize);
7f77ea24 103 me->nstates = me->statesize = me->statepos = 0;
104 me->states = NULL;
be8d5aa1 105 me->params = ourgame->default_params();
f60f7e7c 106 me->curparams = NULL;
0a6892db 107 me->desc = me->privdesc = NULL;
1185e3c5 108 me->seedstr = NULL;
6f2d8d7c 109 me->aux_info = NULL;
1185e3c5 110 me->genmode = GOT_NOTHING;
2ef96bd6 111 me->drawstate = NULL;
112 me->oldstate = NULL;
eb2ad6f1 113 me->presets = NULL;
114 me->preset_names = NULL;
115 me->npresets = me->presetsize = 0;
87ed82be 116 me->anim_time = me->anim_pos = 0.0F;
117 me->flash_time = me->flash_pos = 0.0F;
c822de4a 118 me->dir = 0;
74a4e547 119 me->ui = NULL;
6776a950 120 me->pressed_mouse_button = 0;
48dcdd62 121 me->laststatus = NULL;
122 me->timing = FALSE;
123 me->elapsed = 0.0F;
1f3ee4ee 124 me->tilesize = me->winwidth = me->winheight = 0;
7f77ea24 125
cbb5549e 126 sfree(randseed);
127
7f77ea24 128 return me;
129}
130
ab53eb64 131static void midend_free_game(midend_data *me)
132{
a4393230 133 while (me->nstates > 0) {
134 me->nstates--;
135 me->ourgame->free_game(me->states[me->nstates].state);
136 sfree(me->states[me->nstates].movestr);
137 }
ab53eb64 138
139 if (me->drawstate)
140 me->ourgame->free_drawstate(me->drawstate);
141}
142
7f77ea24 143void midend_free(midend_data *me)
144{
ab53eb64 145 int i;
146
147 midend_free_game(me);
148
149 random_free(me->random);
7f77ea24 150 sfree(me->states);
1185e3c5 151 sfree(me->desc);
871bf294 152 sfree(me->privdesc);
1185e3c5 153 sfree(me->seedstr);
c566778e 154 sfree(me->aux_info);
be8d5aa1 155 me->ourgame->free_params(me->params);
ab53eb64 156 if (me->npresets) {
157 for (i = 0; i < me->npresets; i++) {
158 sfree(me->presets[i]);
159 sfree(me->preset_names[i]);
160 }
161 sfree(me->presets);
162 sfree(me->preset_names);
163 }
164 if (me->ui)
165 me->ourgame->free_ui(me->ui);
f60f7e7c 166 if (me->curparams)
167 me->ourgame->free_params(me->curparams);
48dcdd62 168 sfree(me->laststatus);
7f77ea24 169 sfree(me);
170}
171
1f3ee4ee 172static void midend_size_new_drawstate(midend_data *me)
173{
174 /*
175 * Don't even bother, if we haven't worked out our tile size
176 * anyway yet.
177 */
178 if (me->tilesize > 0) {
179 me->ourgame->compute_size(me->params, me->tilesize,
180 &me->winwidth, &me->winheight);
181 me->ourgame->set_size(me->drawstate, me->params, me->tilesize);
182 }
183}
184
1e3e152d 185void midend_size(midend_data *me, int *x, int *y, int expand)
7f77ea24 186{
1f3ee4ee 187 int min, max;
188 int rx, ry;
189
190 /*
191 * Find the tile size that best fits within the given space. If
192 * `expand' is TRUE, we must actually find the _largest_ such
193 * tile size; otherwise, we bound above at the game's preferred
194 * tile size.
195 */
196 if (expand) {
197 max = 1;
198 do {
199 max *= 2;
200 me->ourgame->compute_size(me->params, max, &rx, &ry);
201 } while (rx <= *x && ry <= *y);
202 } else
203 max = me->ourgame->preferred_tilesize + 1;
204 min = 1;
205
206 /*
207 * Now binary-search between min and max. We're looking for a
208 * boundary rather than a value: the point at which tile sizes
209 * stop fitting within the given dimensions. Thus, we stop when
210 * max and min differ by exactly 1.
211 */
212 while (max - min > 1) {
213 int mid = (max + min) / 2;
214 me->ourgame->compute_size(me->params, mid, &rx, &ry);
215 if (rx <= *x && ry <= *y)
216 min = mid;
217 else
218 max = mid;
219 }
220
221 /*
222 * Now `min' is a valid size, and `max' isn't. So use `min'.
223 */
224
225 me->tilesize = min;
226 midend_size_new_drawstate(me);
227 *x = me->winwidth;
228 *y = me->winheight;
7f77ea24 229}
230
231void midend_set_params(midend_data *me, game_params *params)
232{
be8d5aa1 233 me->ourgame->free_params(me->params);
234 me->params = me->ourgame->dup_params(params);
7f77ea24 235}
236
48dcdd62 237static void midend_set_timer(midend_data *me)
238{
239 me->timing = (me->ourgame->is_timed &&
4d08de49 240 me->ourgame->timing_state(me->states[me->statepos-1].state,
241 me->ui));
48dcdd62 242 if (me->timing || me->flash_time || me->anim_time)
243 activate_timer(me->frontend);
244 else
245 deactivate_timer(me->frontend);
246}
247
008b4378 248void midend_force_redraw(midend_data *me)
249{
250 if (me->drawstate)
251 me->ourgame->free_drawstate(me->drawstate);
252 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
1e3e152d 253 midend_size_new_drawstate(me);
008b4378 254 midend_redraw(me);
255}
256
5928817c 257void midend_new_game(midend_data *me)
7f77ea24 258{
ab53eb64 259 midend_free_game(me);
2ef96bd6 260
7f77ea24 261 assert(me->nstates == 0);
262
1185e3c5 263 if (me->genmode == GOT_DESC) {
264 me->genmode = GOT_NOTHING;
265 } else {
266 random_state *rs;
267
268 if (me->genmode == GOT_SEED) {
269 me->genmode = GOT_NOTHING;
270 } else {
271 /*
272 * Generate a new random seed. 15 digits comes to about
273 * 48 bits, which should be more than enough.
97c44af3 274 *
275 * I'll avoid putting a leading zero on the number,
276 * just in case it confuses anybody who thinks it's
277 * processed as an integer rather than a string.
1185e3c5 278 */
279 char newseed[16];
280 int i;
281 newseed[15] = '\0';
97c44af3 282 newseed[0] = '1' + random_upto(me->random, 9);
283 for (i = 1; i < 15; i++)
1185e3c5 284 newseed[i] = '0' + random_upto(me->random, 10);
285 sfree(me->seedstr);
286 me->seedstr = dupstr(newseed);
f60f7e7c 287
288 if (me->curparams)
289 me->ourgame->free_params(me->curparams);
290 me->curparams = me->ourgame->dup_params(me->params);
1185e3c5 291 }
292
293 sfree(me->desc);
0a6892db 294 sfree(me->privdesc);
c566778e 295 sfree(me->aux_info);
6f2d8d7c 296 me->aux_info = NULL;
1185e3c5 297
298 rs = random_init(me->seedstr, strlen(me->seedstr));
6aa6af4c 299 me->desc = me->ourgame->new_desc(me->curparams, rs,
300 &me->aux_info, TRUE);
0a6892db 301 me->privdesc = NULL;
1185e3c5 302 random_free(rs);
1185e3c5 303 }
7f77ea24 304
305 ensure(me);
c380832d 306 me->states[me->nstates].state =
307 me->ourgame->new_game(me, me->params, me->desc);
a4393230 308 me->states[me->nstates].movestr = NULL;
309 me->states[me->nstates].movetype = NEWGAME;
28d0118c 310 me->nstates++;
7f77ea24 311 me->statepos = 1;
28d0118c 312 me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
1e3e152d 313 midend_size_new_drawstate(me);
48dcdd62 314 me->elapsed = 0.0F;
74a4e547 315 if (me->ui)
be8d5aa1 316 me->ourgame->free_ui(me->ui);
28d0118c 317 me->ui = me->ourgame->new_ui(me->states[0].state);
4d08de49 318 midend_set_timer(me);
6776a950 319 me->pressed_mouse_button = 0;
7f77ea24 320}
321
1482ee76 322static int midend_undo(midend_data *me)
7f77ea24 323{
1482ee76 324 if (me->statepos > 1) {
07dfb697 325 if (me->ui)
326 me->ourgame->changed_state(me->ui,
327 me->states[me->statepos-1].state,
328 me->states[me->statepos-2].state);
7f77ea24 329 me->statepos--;
c822de4a 330 me->dir = -1;
1482ee76 331 return 1;
332 } else
333 return 0;
7f77ea24 334}
335
1482ee76 336static int midend_redo(midend_data *me)
7f77ea24 337{
1482ee76 338 if (me->statepos < me->nstates) {
07dfb697 339 if (me->ui)
340 me->ourgame->changed_state(me->ui,
341 me->states[me->statepos-1].state,
342 me->states[me->statepos].state);
7f77ea24 343 me->statepos++;
c822de4a 344 me->dir = +1;
1482ee76 345 return 1;
346 } else
347 return 0;
7f77ea24 348}
349
87ed82be 350static void midend_finish_move(midend_data *me)
351{
352 float flashtime;
353
28d0118c 354 /*
355 * We do not flash if the later of the two states is special.
356 * This covers both forward Solve moves and backward (undone)
357 * Restart moves.
358 */
359 if ((me->oldstate || me->statepos > 1) &&
a4393230 360 ((me->dir > 0 && !special(me->states[me->statepos-1].movetype)) ||
28d0118c 361 (me->dir < 0 && me->statepos < me->nstates &&
a4393230 362 !special(me->states[me->statepos].movetype)))) {
be8d5aa1 363 flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
28d0118c 364 me->states[me->statepos-2].state,
365 me->states[me->statepos-1].state,
e3f21163 366 me->oldstate ? me->dir : +1,
367 me->ui);
87ed82be 368 if (flashtime > 0) {
369 me->flash_pos = 0.0F;
370 me->flash_time = flashtime;
371 }
372 }
373
374 if (me->oldstate)
be8d5aa1 375 me->ourgame->free_game(me->oldstate);
87ed82be 376 me->oldstate = NULL;
377 me->anim_pos = me->anim_time = 0;
c822de4a 378 me->dir = 0;
87ed82be 379
48dcdd62 380 midend_set_timer(me);
87ed82be 381}
382
ab53eb64 383void midend_stop_anim(midend_data *me)
7f77ea24 384{
8317499a 385 if (me->oldstate || me->anim_time != 0) {
87ed82be 386 midend_finish_move(me);
2ef96bd6 387 midend_redraw(me);
388 }
dd216087 389}
390
28d0118c 391void midend_restart_game(midend_data *me)
392{
393 game_state *s;
394
7f89707c 395 midend_stop_anim(me);
396
28d0118c 397 assert(me->statepos >= 1);
398 if (me->statepos == 1)
399 return; /* no point doing anything at all! */
400
0a6892db 401 /*
402 * During restart, we reconstruct the game from the (public)
403 * game description rather than from states[0], because that
404 * way Mines gets slightly more sensible behaviour (restart
405 * goes to _after_ the first click so you don't have to
406 * remember where you clicked).
407 */
408 s = me->ourgame->new_game(me, me->params, me->desc);
28d0118c 409
410 /*
411 * Now enter the restarted state as the next move.
412 */
413 midend_stop_anim(me);
414 while (me->nstates > me->statepos)
415 me->ourgame->free_game(me->states[--me->nstates].state);
416 ensure(me);
417 me->states[me->nstates].state = s;
a4393230 418 me->states[me->nstates].movestr = dupstr(me->desc);
419 me->states[me->nstates].movetype = RESTART;
28d0118c 420 me->statepos = ++me->nstates;
07dfb697 421 if (me->ui)
422 me->ourgame->changed_state(me->ui,
423 me->states[me->statepos-2].state,
424 me->states[me->statepos-1].state);
28d0118c 425 me->anim_time = 0.0;
426 midend_finish_move(me);
427 midend_redraw(me);
48dcdd62 428 midend_set_timer(me);
28d0118c 429}
430
6776a950 431static int midend_really_process_key(midend_data *me, int x, int y, int button)
dd216087 432{
28d0118c 433 game_state *oldstate =
434 me->ourgame->dup_game(me->states[me->statepos - 1].state);
9d6c3859 435 int type = MOVE, gottype = FALSE, ret = 1;
dd216087 436 float anim_time;
4c692867 437 game_state *s;
438 char *movestr;
439
440 movestr =
441 me->ourgame->interpret_move(me->states[me->statepos-1].state,
442 me->ui, me->drawstate, x, y, button);
7f77ea24 443
4c692867 444 if (!movestr) {
445 if (button == 'n' || button == 'N' || button == '\x0E') {
446 midend_stop_anim(me);
447 midend_new_game(me);
448 midend_redraw(me);
449 goto done; /* never animate */
450 } else if (button == 'u' || button == 'u' ||
451 button == '\x1A' || button == '\x1F') {
452 midend_stop_anim(me);
9d6c3859 453 type = me->states[me->statepos-1].movetype;
454 gottype = TRUE;
4c692867 455 if (!midend_undo(me))
456 goto done;
457 } else if (button == 'r' || button == 'R' ||
458 button == '\x12' || button == '\x19') {
459 midend_stop_anim(me);
460 if (!midend_redo(me))
461 goto done;
462 } else if (button == 'q' || button == 'Q' || button == '\x11') {
463 ret = 0;
464 goto done;
465 } else
ab53eb64 466 goto done;
2ef96bd6 467 } else {
4c692867 468 if (!*movestr)
df11cd4e 469 s = me->states[me->statepos-1].state;
470 else {
471 s = me->ourgame->execute_move(me->states[me->statepos-1].state,
472 movestr);
473 assert(s != NULL);
df11cd4e 474 }
74a4e547 475
28d0118c 476 if (s == me->states[me->statepos-1].state) {
74a4e547 477 /*
478 * make_move() is allowed to return its input state to
479 * indicate that although no move has been made, the UI
480 * state has been updated and a redraw is called for.
481 */
482 midend_redraw(me);
ab53eb64 483 goto done;
74a4e547 484 } else if (s) {
dd216087 485 midend_stop_anim(me);
2ef96bd6 486 while (me->nstates > me->statepos)
28d0118c 487 me->ourgame->free_game(me->states[--me->nstates].state);
2ef96bd6 488 ensure(me);
a4393230 489 assert(movestr != NULL);
28d0118c 490 me->states[me->nstates].state = s;
a4393230 491 me->states[me->nstates].movestr = movestr;
492 me->states[me->nstates].movetype = MOVE;
2ef96bd6 493 me->statepos = ++me->nstates;
c822de4a 494 me->dir = +1;
faff1e07 495 if (me->ui)
496 me->ourgame->changed_state(me->ui,
497 me->states[me->statepos-2].state,
498 me->states[me->statepos-1].state);
2ef96bd6 499 } else {
a4393230 500 goto done;
2ef96bd6 501 }
7f77ea24 502 }
503
9d6c3859 504 if (!gottype)
505 type = me->states[me->statepos-1].movetype;
28d0118c 506
2ef96bd6 507 /*
508 * See if this move requires an animation.
509 */
9d6c3859 510 if (special(type) && !(type == SOLVE &&
511 (me->ourgame->mouse_priorities & SOLVE_ANIMATES))) {
28d0118c 512 anim_time = 0;
513 } else {
514 anim_time = me->ourgame->anim_length(oldstate,
515 me->states[me->statepos-1].state,
e3f21163 516 me->dir, me->ui);
28d0118c 517 }
2ef96bd6 518
ab53eb64 519 me->oldstate = oldstate; oldstate = NULL;
2ef96bd6 520 if (anim_time > 0) {
2ef96bd6 521 me->anim_time = anim_time;
522 } else {
2ef96bd6 523 me->anim_time = 0.0;
87ed82be 524 midend_finish_move(me);
7f77ea24 525 }
2ef96bd6 526 me->anim_pos = 0.0;
527
528 midend_redraw(me);
529
48dcdd62 530 midend_set_timer(me);
7f77ea24 531
ab53eb64 532 done:
533 if (oldstate) me->ourgame->free_game(oldstate);
534 return ret;
7f77ea24 535}
2ef96bd6 536
6776a950 537int midend_process_key(midend_data *me, int x, int y, int button)
538{
539 int ret = 1;
540
541 /*
542 * Harmonise mouse drag and release messages.
543 *
544 * Some front ends might accidentally switch from sending, say,
545 * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
546 * drag. (This can happen on the Mac, for example, since
547 * RIGHT_DRAG is usually done using Command+drag, and if the
548 * user accidentally releases Command half way through the drag
549 * then there will be trouble.)
550 *
551 * It would be an O(number of front ends) annoyance to fix this
552 * in the front ends, but an O(number of back ends) annoyance
553 * to have each game capable of dealing with it. Therefore, we
554 * fix it _here_ in the common midend code so that it only has
555 * to be done once.
556 *
eeba2afe 557 * The possible ways in which things can go screwy in the front
558 * end are:
6776a950 559 *
eeba2afe 560 * - in a system containing multiple physical buttons button
561 * presses can inadvertently overlap. We can see ABab (caps
562 * meaning button-down and lowercase meaning button-up) when
563 * the user had semantically intended AaBb.
6776a950 564 *
eeba2afe 565 * - in a system where one button is simulated by means of a
566 * modifier key and another button, buttons can mutate
567 * between press and release (possibly during drag). So we
568 * can see Ab instead of Aa.
6776a950 569 *
eeba2afe 570 * Definite requirements are:
571 *
572 * - button _presses_ must never be invented or destroyed. If
573 * the user presses two buttons in succession, the button
574 * presses must be transferred to the backend unchanged. So
575 * if we see AaBb , that's fine; if we see ABab (the button
576 * presses inadvertently overlapped) we must somehow
577 * `correct' it to AaBb.
578 *
579 * - every mouse action must end up looking like a press, zero
580 * or more drags, then a release. This allows back ends to
581 * make the _assumption_ that incoming mouse data will be
582 * sane in this regard, and not worry about the details.
583 *
584 * So my policy will be:
585 *
586 * - treat any button-up as a button-up for the currently
587 * pressed button, or ignore it if there is no currently
588 * pressed button.
589 *
590 * - treat any drag as a drag for the currently pressed
591 * button, or ignore it if there is no currently pressed
592 * button.
593 *
594 * - if we see a button-down while another button is currently
595 * pressed, invent a button-up for the first one and then
596 * pass the button-down through as before.
6776a950 597 *
93b1da3d 598 * 2005-05-31: An addendum to the above. Some games might want
599 * a `priority order' among buttons, such that if one button is
600 * pressed while another is down then a fixed one of the
601 * buttons takes priority no matter what order they're pressed
602 * in. Mines, in particular, wants to treat a left+right click
603 * like a left click for the benefit of users of other
604 * implementations. So the last of the above points is modified
605 * in the presence of an (optional) button priority order.
6776a950 606 */
607 if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
eeba2afe 608 if (me->pressed_mouse_button) {
609 if (IS_MOUSE_DRAG(button)) {
610 button = me->pressed_mouse_button +
611 (LEFT_DRAG - LEFT_BUTTON);
612 } else {
613 button = me->pressed_mouse_button +
614 (LEFT_RELEASE - LEFT_BUTTON);
6776a950 615 }
eeba2afe 616 } else
617 return ret; /* ignore it */
6776a950 618 } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
93b1da3d 619 /*
620 * If the new button has lower priority than the old one,
621 * don't bother doing this.
622 */
623 if (me->ourgame->mouse_priorities &
624 BUTTON_BEATS(me->pressed_mouse_button, button))
625 return ret; /* just ignore it */
626
6776a950 627 /*
628 * Fabricate a button-up for the previously pressed button.
629 */
630 ret = ret && midend_really_process_key
631 (me, x, y, (me->pressed_mouse_button +
632 (LEFT_RELEASE - LEFT_BUTTON)));
633 }
634
635 /*
636 * Now send on the event we originally received.
637 */
638 ret = ret && midend_really_process_key(me, x, y, button);
639
640 /*
641 * And update the currently pressed button.
642 */
643 if (IS_MOUSE_RELEASE(button))
644 me->pressed_mouse_button = 0;
645 else if (IS_MOUSE_DOWN(button))
646 me->pressed_mouse_button = button;
647
648 return ret;
649}
650
2ef96bd6 651void midend_redraw(midend_data *me)
652{
653 if (me->statepos > 0 && me->drawstate) {
654 start_draw(me->frontend);
655 if (me->oldstate && me->anim_time > 0 &&
656 me->anim_pos < me->anim_time) {
c822de4a 657 assert(me->dir != 0);
be8d5aa1 658 me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
28d0118c 659 me->states[me->statepos-1].state, me->dir,
be8d5aa1 660 me->ui, me->anim_pos, me->flash_pos);
2ef96bd6 661 } else {
be8d5aa1 662 me->ourgame->redraw(me->frontend, me->drawstate, NULL,
28d0118c 663 me->states[me->statepos-1].state, +1 /*shrug*/,
be8d5aa1 664 me->ui, 0.0, me->flash_pos);
2ef96bd6 665 }
666 end_draw(me->frontend);
667 }
668}
669
670void midend_timer(midend_data *me, float tplus)
671{
672 me->anim_pos += tplus;
673 if (me->anim_pos >= me->anim_time ||
674 me->anim_time == 0 || !me->oldstate) {
87ed82be 675 if (me->anim_time > 0)
676 midend_finish_move(me);
677 }
48dcdd62 678
87ed82be 679 me->flash_pos += tplus;
680 if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
681 me->flash_pos = me->flash_time = 0;
2ef96bd6 682 }
48dcdd62 683
2ef96bd6 684 midend_redraw(me);
48dcdd62 685
686 if (me->timing) {
687 float oldelapsed = me->elapsed;
688 me->elapsed += tplus;
689 if ((int)oldelapsed != (int)me->elapsed)
690 status_bar(me->frontend, me->laststatus ? me->laststatus : "");
691 }
692
693 midend_set_timer(me);
2ef96bd6 694}
695
696float *midend_colours(midend_data *me, int *ncolours)
697{
698 game_state *state = NULL;
699 float *ret;
700
701 if (me->nstates == 0) {
c566778e 702 char *aux = NULL;
6aa6af4c 703 char *desc = me->ourgame->new_desc(me->params, me->random,
704 &aux, TRUE);
c380832d 705 state = me->ourgame->new_game(me, me->params, desc);
1185e3c5 706 sfree(desc);
c566778e 707 sfree(aux);
2ef96bd6 708 } else
28d0118c 709 state = me->states[0].state;
2ef96bd6 710
be8d5aa1 711 ret = me->ourgame->colours(me->frontend, state, ncolours);
2ef96bd6 712
813593cc 713 {
714 int i;
715
716 /*
717 * Allow environment-based overrides for the standard
718 * colours by defining variables along the lines of
719 * `NET_COLOUR_4=6000c0'.
720 */
721
722 for (i = 0; i < *ncolours; i++) {
723 char buf[80], *e;
724 unsigned int r, g, b;
056405ec 725 int j, k;
813593cc 726
727 sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
056405ec 728 for (j = k = 0; buf[j]; j++)
729 if (!isspace((unsigned char)buf[j]))
730 buf[k++] = toupper((unsigned char)buf[j]);
731 buf[k] = '\0';
813593cc 732 if ((e = getenv(buf)) != NULL &&
733 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
734 ret[i*3 + 0] = r / 255.0;
735 ret[i*3 + 1] = g / 255.0;
736 ret[i*3 + 2] = b / 255.0;
737 }
738 }
739 }
740
2ef96bd6 741 if (me->nstates == 0)
be8d5aa1 742 me->ourgame->free_game(state);
2ef96bd6 743
744 return ret;
745}
eb2ad6f1 746
747int midend_num_presets(midend_data *me)
748{
749 if (!me->npresets) {
750 char *name;
751 game_params *preset;
752
be8d5aa1 753 while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
eb2ad6f1 754 if (me->presetsize <= me->npresets) {
755 me->presetsize = me->npresets + 10;
756 me->presets = sresize(me->presets, me->presetsize,
757 game_params *);
758 me->preset_names = sresize(me->preset_names, me->presetsize,
759 char *);
760 }
761
762 me->presets[me->npresets] = preset;
763 me->preset_names[me->npresets] = name;
764 me->npresets++;
765 }
766 }
767
813593cc 768 {
769 /*
770 * Allow environment-based extensions to the preset list by
771 * defining a variable along the lines of `SOLO_PRESETS=2x3
772 * Advanced:2x3da'. Colon-separated list of items,
773 * alternating between textual titles in the menu and
774 * encoded parameter strings.
775 */
776 char buf[80], *e, *p;
056405ec 777 int j, k;
813593cc 778
779 sprintf(buf, "%s_PRESETS", me->ourgame->name);
056405ec 780 for (j = k = 0; buf[j]; j++)
781 if (!isspace((unsigned char)buf[j]))
782 buf[k++] = toupper((unsigned char)buf[j]);
783 buf[k] = '\0';
813593cc 784
785 if ((e = getenv(buf)) != NULL) {
786 p = e = dupstr(e);
787
788 while (*p) {
789 char *name, *val;
790 game_params *preset;
791
792 name = p;
793 while (*p && *p != ':') p++;
794 if (*p) *p++ = '\0';
795 val = p;
796 while (*p && *p != ':') p++;
797 if (*p) *p++ = '\0';
798
799 preset = me->ourgame->default_params();
800 me->ourgame->decode_params(preset, val);
801
3ff276f2 802 if (me->ourgame->validate_params(preset, TRUE)) {
239ba6e6 803 /* Drop this one from the list. */
804 me->ourgame->free_params(preset);
805 continue;
806 }
807
813593cc 808 if (me->presetsize <= me->npresets) {
809 me->presetsize = me->npresets + 10;
810 me->presets = sresize(me->presets, me->presetsize,
811 game_params *);
812 me->preset_names = sresize(me->preset_names,
813 me->presetsize, char *);
814 }
815
816 me->presets[me->npresets] = preset;
cb64d2dd 817 me->preset_names[me->npresets] = dupstr(name);
813593cc 818 me->npresets++;
819 }
820 }
821 }
822
eb2ad6f1 823 return me->npresets;
824}
825
826void midend_fetch_preset(midend_data *me, int n,
827 char **name, game_params **params)
828{
829 assert(n >= 0 && n < me->npresets);
830 *name = me->preset_names[n];
831 *params = me->presets[n];
832}
fd1a1a2b 833
834int midend_wants_statusbar(midend_data *me)
835{
be8d5aa1 836 return me->ourgame->wants_statusbar();
fd1a1a2b 837}
c8230524 838
0a6892db 839void midend_supersede_game_desc(midend_data *me, char *desc, char *privdesc)
c380832d 840{
841 sfree(me->desc);
0a6892db 842 sfree(me->privdesc);
c380832d 843 me->desc = dupstr(desc);
0a6892db 844 me->privdesc = privdesc ? dupstr(privdesc) : NULL;
c380832d 845}
846
5928817c 847config_item *midend_get_config(midend_data *me, int which, char **wintitle)
c8230524 848{
ab53eb64 849 char *titlebuf, *parstr, *rest;
5928817c 850 config_item *ret;
ab53eb64 851 char sep;
5928817c 852
ab53eb64 853 assert(wintitle);
be8d5aa1 854 titlebuf = snewn(40 + strlen(me->ourgame->name), char);
5928817c 855
856 switch (which) {
857 case CFG_SETTINGS:
be8d5aa1 858 sprintf(titlebuf, "%s configuration", me->ourgame->name);
ab53eb64 859 *wintitle = titlebuf;
be8d5aa1 860 return me->ourgame->configure(me->params);
5928817c 861 case CFG_SEED:
1185e3c5 862 case CFG_DESC:
ab53eb64 863 if (!me->curparams) {
864 sfree(titlebuf);
865 return NULL;
866 }
867 sprintf(titlebuf, "%s %s selection", me->ourgame->name,
1185e3c5 868 which == CFG_SEED ? "random" : "game");
ab53eb64 869 *wintitle = titlebuf;
5928817c 870
871 ret = snewn(2, config_item);
872
873 ret[0].type = C_STRING;
1185e3c5 874 if (which == CFG_SEED)
875 ret[0].name = "Game random seed";
876 else
877 ret[0].name = "Game ID";
5928817c 878 ret[0].ival = 0;
b0e26073 879 /*
1185e3c5 880 * For CFG_DESC the text going in here will be a string
881 * encoding of the restricted parameters, plus a colon,
882 * plus the game description. For CFG_SEED it will be the
883 * full parameters, plus a hash, plus the random seed data.
884 * Either of these is a valid full game ID (although only
885 * the former is likely to persist across many code
886 * changes).
b0e26073 887 */
f60f7e7c 888 parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
ab53eb64 889 assert(parstr);
1185e3c5 890 if (which == CFG_DESC) {
ab53eb64 891 rest = me->desc ? me->desc : "";
892 sep = ':';
1185e3c5 893 } else {
ab53eb64 894 rest = me->seedstr ? me->seedstr : "";
895 sep = '#';
1185e3c5 896 }
ab53eb64 897 ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
898 sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
b0e26073 899 sfree(parstr);
5928817c 900
901 ret[1].type = C_END;
902 ret[1].name = ret[1].sval = NULL;
903 ret[1].ival = 0;
904
905 return ret;
906 }
907
908 assert(!"We shouldn't be here");
909 return NULL;
c8230524 910}
911
1185e3c5 912static char *midend_game_id_int(midend_data *me, char *id, int defmode)
8b7938e7 913{
1185e3c5 914 char *error, *par, *desc, *seed;
5c9f61fd 915 game_params *newcurparams, *newparams, *oldparams1, *oldparams2;
916 int free_params;
8b7938e7 917
1185e3c5 918 seed = strchr(id, '#');
919 desc = strchr(id, ':');
8b7938e7 920
1185e3c5 921 if (desc && (!seed || desc < seed)) {
922 /*
923 * We have a colon separating parameters from game
924 * description. So `par' now points to the parameters
925 * string, and `desc' to the description string.
926 */
927 *desc++ = '\0';
928 par = id;
929 seed = NULL;
930 } else if (seed && (!desc || seed < desc)) {
8b7938e7 931 /*
50ff5730 932 * We have a hash separating parameters from random seed.
1185e3c5 933 * So `par' now points to the parameters string, and `seed'
934 * to the seed string.
8b7938e7 935 */
936 *seed++ = '\0';
937 par = id;
1185e3c5 938 desc = NULL;
8b7938e7 939 } else {
940 /*
1185e3c5 941 * We only have one string. Depending on `defmode', we take
942 * it to be either parameters, seed or description.
8b7938e7 943 */
1185e3c5 944 if (defmode == DEF_SEED) {
8b7938e7 945 seed = id;
1185e3c5 946 par = desc = NULL;
947 } else if (defmode == DEF_DESC) {
948 desc = id;
949 par = seed = NULL;
8b7938e7 950 } else {
8b7938e7 951 par = id;
1185e3c5 952 seed = desc = NULL;
8b7938e7 953 }
954 }
955
5c9f61fd 956 /*
957 * We must be reasonably careful here not to modify anything in
958 * `me' until we have finished validating things. This function
959 * must either return an error and do nothing to the midend, or
960 * return success and do everything; nothing in between is
961 * acceptable.
962 */
963 newcurparams = newparams = oldparams1 = oldparams2 = NULL;
964
8b7938e7 965 if (par) {
5c9f61fd 966 newcurparams = me->ourgame->dup_params(me->params);
967 me->ourgame->decode_params(newcurparams, par);
3ff276f2 968 error = me->ourgame->validate_params(newcurparams, desc == NULL);
8b7938e7 969 if (error) {
5c9f61fd 970 me->ourgame->free_params(newcurparams);
8b7938e7 971 return error;
972 }
5c9f61fd 973 oldparams1 = me->curparams;
1185e3c5 974
975 /*
976 * Now filter only the persistent parts of this state into
977 * the long-term params structure, unless we've _only_
978 * received a params string in which case the whole lot is
979 * persistent.
980 */
5c9f61fd 981 oldparams2 = me->params;
1185e3c5 982 if (seed || desc) {
5c9f61fd 983 char *tmpstr;
984
985 newparams = me->ourgame->dup_params(me->params);
986
987 tmpstr = me->ourgame->encode_params(newcurparams, FALSE);
988 me->ourgame->decode_params(newparams, tmpstr);
989
3af70dd4 990 sfree(tmpstr);
1185e3c5 991 } else {
5c9f61fd 992 newparams = me->ourgame->dup_params(newcurparams);
1185e3c5 993 }
5c9f61fd 994 free_params = TRUE;
995 } else {
996 newcurparams = me->curparams;
997 newparams = me->params;
998 free_params = FALSE;
8b7938e7 999 }
1000
5c9f61fd 1001 if (desc) {
1002 error = me->ourgame->validate_desc(newparams, desc);
1003 if (error) {
1004 if (free_params) {
1005 if (newcurparams)
1006 me->ourgame->free_params(newcurparams);
1007 if (newparams)
1008 me->ourgame->free_params(newparams);
1009 }
1010 return error;
1011 }
1012 }
1013
1014 /*
1015 * Now we've got past all possible error points. Update the
1016 * midend itself.
1017 */
1018 me->params = newparams;
1019 me->curparams = newcurparams;
1020 if (oldparams1)
1021 me->ourgame->free_params(oldparams1);
1022 if (oldparams2)
1023 me->ourgame->free_params(oldparams2);
1024
3af70dd4 1025 sfree(me->desc);
0a6892db 1026 sfree(me->privdesc);
1027 me->desc = me->privdesc = NULL;
3af70dd4 1028 sfree(me->seedstr);
1029 me->seedstr = NULL;
1030
1185e3c5 1031 if (desc) {
1185e3c5 1032 me->desc = dupstr(desc);
1033 me->genmode = GOT_DESC;
c566778e 1034 sfree(me->aux_info);
6f2d8d7c 1035 me->aux_info = NULL;
8b7938e7 1036 }
1037
1185e3c5 1038 if (seed) {
1185e3c5 1039 me->seedstr = dupstr(seed);
1040 me->genmode = GOT_SEED;
1041 }
1042
8b7938e7 1043 return NULL;
1044}
1045
1185e3c5 1046char *midend_game_id(midend_data *me, char *id)
1047{
1048 return midend_game_id_int(me, id, DEF_PARAMS);
1049}
1050
5928817c 1051char *midend_set_config(midend_data *me, int which, config_item *cfg)
c8230524 1052{
8b7938e7 1053 char *error;
c8230524 1054 game_params *params;
1055
5928817c 1056 switch (which) {
1057 case CFG_SETTINGS:
be8d5aa1 1058 params = me->ourgame->custom_params(cfg);
3ff276f2 1059 error = me->ourgame->validate_params(params, TRUE);
c8230524 1060
5928817c 1061 if (error) {
be8d5aa1 1062 me->ourgame->free_params(params);
5928817c 1063 return error;
1064 }
c8230524 1065
be8d5aa1 1066 me->ourgame->free_params(me->params);
5928817c 1067 me->params = params;
1068 break;
1069
1070 case CFG_SEED:
1185e3c5 1071 case CFG_DESC:
1072 error = midend_game_id_int(me, cfg[0].sval,
1073 (which == CFG_SEED ? DEF_SEED : DEF_DESC));
5928817c 1074 if (error)
1075 return error;
5928817c 1076 break;
1077 }
c8230524 1078
1079 return NULL;
1080}
9b4b03d3 1081
1082char *midend_text_format(midend_data *me)
1083{
1084 if (me->ourgame->can_format_as_text && me->statepos > 0)
28d0118c 1085 return me->ourgame->text_format(me->states[me->statepos-1].state);
9b4b03d3 1086 else
1087 return NULL;
1088}
2ac6d24e 1089
1090char *midend_solve(midend_data *me)
1091{
1092 game_state *s;
df11cd4e 1093 char *msg, *movestr;
2ac6d24e 1094
1095 if (!me->ourgame->can_solve)
1096 return "This game does not support the Solve operation";
1097
1098 if (me->statepos < 1)
1099 return "No game set up to solve"; /* _shouldn't_ happen! */
1100
1101 msg = "Solve operation failed"; /* game _should_ overwrite on error */
df11cd4e 1102 movestr = me->ourgame->solve(me->states[0].state,
1103 me->states[me->statepos-1].state,
1104 me->aux_info, &msg);
1105 if (!movestr)
2ac6d24e 1106 return msg;
df11cd4e 1107 s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1108 assert(s);
2ac6d24e 1109
1110 /*
28d0118c 1111 * Now enter the solved state as the next move.
2ac6d24e 1112 */
1113 midend_stop_anim(me);
1114 while (me->nstates > me->statepos)
28d0118c 1115 me->ourgame->free_game(me->states[--me->nstates].state);
2ac6d24e 1116 ensure(me);
28d0118c 1117 me->states[me->nstates].state = s;
a4393230 1118 me->states[me->nstates].movestr = movestr;
1119 me->states[me->nstates].movetype = SOLVE;
2ac6d24e 1120 me->statepos = ++me->nstates;
07dfb697 1121 if (me->ui)
1122 me->ourgame->changed_state(me->ui,
1123 me->states[me->statepos-2].state,
1124 me->states[me->statepos-1].state);
9d6c3859 1125 me->dir = +1;
1126 if (me->ourgame->mouse_priorities & SOLVE_ANIMATES) {
1127 me->oldstate = me->ourgame->dup_game(me->states[me->statepos-2].state);
1128 me->anim_time =
1129 me->ourgame->anim_length(me->states[me->statepos-2].state,
1130 me->states[me->statepos-1].state,
1131 +1, me->ui);
e80e7b71 1132 me->anim_pos = 0.0;
9d6c3859 1133 } else {
1134 me->anim_time = 0.0;
1135 midend_finish_move(me);
1136 }
2ac6d24e 1137 midend_redraw(me);
48dcdd62 1138 midend_set_timer(me);
2ac6d24e 1139 return NULL;
1140}
48dcdd62 1141
1142char *midend_rewrite_statusbar(midend_data *me, char *text)
1143{
1144 /*
1145 * An important special case is that we are occasionally called
1146 * with our own laststatus, to update the timer.
1147 */
1148 if (me->laststatus != text) {
1149 sfree(me->laststatus);
1150 me->laststatus = dupstr(text);
1151 }
1152
1153 if (me->ourgame->is_timed) {
1154 char timebuf[100], *ret;
1155 int min, sec;
1156
1157 sec = me->elapsed;
1158 min = sec / 60;
1159 sec %= 60;
1160 sprintf(timebuf, "[%d:%02d] ", min, sec);
1161
1162 ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1163 strcpy(ret, timebuf);
1164 strcat(ret, text);
1165 return ret;
1166
1167 } else {
1168 return dupstr(text);
1169 }
1170}
a4393230 1171
1172#define SERIALISE_MAGIC "Simon Tatham's Portable Puzzle Collection"
1173#define SERIALISE_VERSION "1"
1174
1175void midend_serialise(midend_data *me,
1176 void (*write)(void *ctx, void *buf, int len),
1177 void *wctx)
1178{
1179 int i;
1180
1181 /*
1182 * Each line of the save file contains three components. First
1183 * exactly 8 characters of header word indicating what type of
1184 * data is contained on the line; then a colon followed by a
1185 * decimal integer giving the length of the main string on the
1186 * line; then a colon followed by the string itself (exactly as
1187 * many bytes as previously specified, no matter what they
1188 * contain). Then a newline (of reasonably flexible form).
1189 */
1190#define wr(h,s) do { \
1191 char hbuf[80]; \
1192 char *str = (s); \
48d4740c 1193 sprintf(hbuf, "%-8.8s:%d:", (h), (int)strlen(str)); \
a4393230 1194 write(wctx, hbuf, strlen(hbuf)); \
1195 write(wctx, str, strlen(str)); \
1196 write(wctx, "\n", 1); \
1197} while (0)
1198
1199 /*
1200 * Magic string identifying the file, and version number of the
1201 * file format.
1202 */
1203 wr("SAVEFILE", SERIALISE_MAGIC);
1204 wr("VERSION", SERIALISE_VERSION);
1205
1206 /*
1207 * The game name. (Copied locally to avoid const annoyance.)
1208 */
1209 {
1210 char *s = dupstr(me->ourgame->name);
1211 wr("GAME", s);
1212 sfree(s);
1213 }
1214
1215 /*
1216 * The current long-term parameters structure, in full.
1217 */
1218 if (me->params) {
1219 char *s = me->ourgame->encode_params(me->params, TRUE);
1220 wr("PARAMS", s);
1221 sfree(s);
1222 }
1223
1224 /*
1225 * The current short-term parameters structure, in full.
1226 */
1227 if (me->curparams) {
1228 char *s = me->ourgame->encode_params(me->curparams, TRUE);
1229 wr("CPARAMS", s);
1230 sfree(s);
1231 }
1232
1233 /*
1234 * The current game description, the privdesc, and the random seed.
1235 */
1236 if (me->seedstr)
1237 wr("SEED", me->seedstr);
1238 if (me->desc)
1239 wr("DESC", me->desc);
1240 if (me->privdesc)
1241 wr("PRIVDESC", me->privdesc);
1242
1243 /*
1244 * The game's aux_info. We obfuscate this to prevent spoilers
1245 * (people are likely to run `head' or similar on a saved game
1246 * file simply to find out what it is, and don't necessarily
1247 * want to be told the answer to the puzzle!)
1248 */
1249 if (me->aux_info) {
1250 unsigned char *s1;
1251 char *s2;
1252 int len;
1253
1254 len = strlen(me->aux_info);
1255 s1 = snewn(len, unsigned char);
1256 memcpy(s1, me->aux_info, len);
1257 obfuscate_bitmap(s1, len*8, FALSE);
1258 s2 = bin2hex(s1, len);
1259
1260 wr("AUXINFO", s2);
1261
1262 sfree(s2);
1263 sfree(s1);
1264 }
1265
1266 /*
1267 * Any required serialisation of the game_ui.
1268 */
1269 if (me->ui) {
1270 char *s = me->ourgame->encode_ui(me->ui);
1271 if (s) {
1272 wr("UI", s);
1273 sfree(s);
1274 }
1275 }
1276
1277 /*
1278 * The game time, if it's a timed game.
1279 */
1280 if (me->ourgame->is_timed) {
1281 char buf[80];
1282 sprintf(buf, "%g", me->elapsed);
1283 wr("TIME", buf);
1284 }
1285
1286 /*
1287 * The length of, and position in, the states list.
1288 */
1289 {
1290 char buf[80];
1291 sprintf(buf, "%d", me->nstates);
1292 wr("NSTATES", buf);
1293 sprintf(buf, "%d", me->statepos);
1294 wr("STATEPOS", buf);
1295 }
1296
1297 /*
1298 * For each state after the initial one (which we know is
1299 * constructed from either privdesc or desc), enough
1300 * information for execute_move() to reconstruct it from the
1301 * previous one.
1302 */
1303 for (i = 1; i < me->nstates; i++) {
1304 assert(me->states[i].movetype != NEWGAME); /* only state 0 */
1305 switch (me->states[i].movetype) {
1306 case MOVE:
1307 wr("MOVE", me->states[i].movestr);
1308 break;
1309 case SOLVE:
1310 wr("SOLVE", me->states[i].movestr);
1311 break;
1312 case RESTART:
1313 wr("RESTART", me->states[i].movestr);
1314 break;
1315 }
1316 }
1317
1318#undef wr
1319}
1320
1321/*
1322 * This function returns NULL on success, or an error message.
1323 */
1324char *midend_deserialise(midend_data *me,
1325 int (*read)(void *ctx, void *buf, int len),
1326 void *rctx)
1327{
1328 int nstates = 0, statepos = -1, gotstates = 0;
1329 int started = FALSE;
1330 int i;
1331
1332 char *val = NULL;
1333 /* Initially all errors give the same report */
1334 char *ret = "Data does not appear to be a saved game file";
1335
1336 /*
1337 * We construct all the new state in local variables while we
1338 * check its sanity. Only once we have finished reading the
1339 * serialised data and detected no errors at all do we start
1340 * modifying stuff in the midend_data passed in.
1341 */
1342 char *seed = NULL, *parstr = NULL, *desc = NULL, *privdesc = NULL;
1343 char *auxinfo = NULL, *uistr = NULL, *cparstr = NULL;
1344 float elapsed = 0.0F;
1345 game_params *params = NULL, *cparams = NULL;
1346 game_ui *ui = NULL;
1347 struct midend_state_entry *states = NULL;
1348
1349 /*
1350 * Loop round and round reading one key/value pair at a time
1351 * from the serialised stream, until we have enough game states
1352 * to finish.
1353 */
1354 while (nstates <= 0 || statepos < 0 || gotstates < nstates-1) {
1355 char key[9], c;
1356 int len;
1357
1358 do {
1359 if (!read(rctx, key, 1)) {
1360 /* unexpected EOF */
1361 goto cleanup;
1362 }
1363 } while (key[0] == '\r' || key[0] == '\n');
1364
1365 if (!read(rctx, key+1, 8)) {
1366 /* unexpected EOF */
1367 goto cleanup;
1368 }
1369
1370 if (key[8] != ':') {
1371 if (started)
1372 ret = "Data was incorrectly formatted for a saved game file";
44f0599f 1373 goto cleanup;
a4393230 1374 }
1375 len = strcspn(key, ": ");
1376 assert(len <= 8);
1377 key[len] = '\0';
1378
1379 len = 0;
1380 while (1) {
1381 if (!read(rctx, &c, 1)) {
1382 /* unexpected EOF */
1383 goto cleanup;
1384 }
1385
1386 if (c == ':') {
1387 break;
1388 } else if (c >= '0' && c <= '9') {
1389 len = (len * 10) + (c - '0');
1390 } else {
1391 if (started)
1392 ret = "Data was incorrectly formatted for a"
1393 " saved game file";
1394 goto cleanup;
1395 }
1396 }
1397
1398 val = snewn(len+1, char);
1399 if (!read(rctx, val, len)) {
1400 if (started)
1401 goto cleanup;
1402 }
1403 val[len] = '\0';
1404
1405 if (!started) {
1406 if (strcmp(key, "SAVEFILE") || strcmp(val, SERIALISE_MAGIC)) {
1407 /* ret already has the right message in it */
1408 goto cleanup;
1409 }
1410 /* Now most errors are this one, unless otherwise specified */
1411 ret = "Saved data ended unexpectedly";
1412 started = TRUE;
1413 } else {
1414 if (!strcmp(key, "VERSION")) {
1415 if (strcmp(val, SERIALISE_VERSION)) {
1416 ret = "Cannot handle this version of the saved game"
1417 " file format";
1418 goto cleanup;
1419 }
1420 } else if (!strcmp(key, "GAME")) {
1421 if (strcmp(val, me->ourgame->name)) {
1422 ret = "Save file is from a different game";
1423 goto cleanup;
1424 }
1425 } else if (!strcmp(key, "PARAMS")) {
1426 sfree(parstr);
1427 parstr = val;
1428 val = NULL;
1429 } else if (!strcmp(key, "CPARAMS")) {
1430 sfree(cparstr);
1431 cparstr = val;
1432 val = NULL;
1433 } else if (!strcmp(key, "SEED")) {
1434 sfree(seed);
1435 seed = val;
1436 val = NULL;
1437 } else if (!strcmp(key, "DESC")) {
1438 sfree(desc);
1439 desc = val;
1440 val = NULL;
1441 } else if (!strcmp(key, "PRIVDESC")) {
1442 sfree(privdesc);
1443 privdesc = val;
1444 val = NULL;
1445 } else if (!strcmp(key, "AUXINFO")) {
1446 unsigned char *tmp;
1447 int len = strlen(val) / 2; /* length in bytes */
1448 tmp = hex2bin(val, len);
1449 obfuscate_bitmap(tmp, len*8, TRUE);
1450
1451 sfree(auxinfo);
1452 auxinfo = snewn(len + 1, char);
1453 memcpy(auxinfo, tmp, len);
1454 auxinfo[len] = '\0';
1455 sfree(tmp);
1456 } else if (!strcmp(key, "UI")) {
1457 sfree(uistr);
1458 uistr = val;
1459 val = NULL;
1460 } else if (!strcmp(key, "TIME")) {
871bf294 1461 elapsed = atof(val);
a4393230 1462 } else if (!strcmp(key, "NSTATES")) {
1463 nstates = atoi(val);
1464 if (nstates <= 0) {
1465 ret = "Number of states in save file was negative";
1466 goto cleanup;
1467 }
1468 if (states) {
1469 ret = "Two state counts provided in save file";
1470 goto cleanup;
1471 }
1472 states = snewn(nstates, struct midend_state_entry);
1473 for (i = 0; i < nstates; i++) {
1474 states[i].state = NULL;
1475 states[i].movestr = NULL;
1476 states[i].movetype = NEWGAME;
1477 }
1478 } else if (!strcmp(key, "STATEPOS")) {
1479 statepos = atoi(val);
1480 } else if (!strcmp(key, "MOVE")) {
1481 gotstates++;
1482 states[gotstates].movetype = MOVE;
1483 states[gotstates].movestr = val;
1484 val = NULL;
1485 } else if (!strcmp(key, "SOLVE")) {
1486 gotstates++;
1487 states[gotstates].movetype = SOLVE;
1488 states[gotstates].movestr = val;
1489 val = NULL;
1490 } else if (!strcmp(key, "RESTART")) {
1491 gotstates++;
1492 states[gotstates].movetype = RESTART;
1493 states[gotstates].movestr = val;
1494 val = NULL;
1495 }
1496 }
1497
1498 sfree(val);
1499 val = NULL;
1500 }
1501
1502 params = me->ourgame->default_params();
1503 me->ourgame->decode_params(params, parstr);
3ff276f2 1504 if (me->ourgame->validate_params(params, TRUE)) {
a4393230 1505 ret = "Long-term parameters in save file are invalid";
1506 goto cleanup;
1507 }
1508 cparams = me->ourgame->default_params();
1509 me->ourgame->decode_params(cparams, cparstr);
3ff276f2 1510 if (me->ourgame->validate_params(cparams, FALSE)) {
a4393230 1511 ret = "Short-term parameters in save file are invalid";
1512 goto cleanup;
1513 }
3ff276f2 1514 if (seed && me->ourgame->validate_params(cparams, TRUE)) {
1515 /*
1516 * The seed's no use with this version, but we can perfectly
1517 * well use the rest of the data.
1518 */
1519 sfree(seed);
1520 seed = NULL;
1521 }
a4393230 1522 if (!desc) {
1523 ret = "Game description in save file is missing";
1524 goto cleanup;
1525 } else if (me->ourgame->validate_desc(params, desc)) {
1526 ret = "Game description in save file is invalid";
1527 goto cleanup;
1528 }
1529 if (privdesc && me->ourgame->validate_desc(params, privdesc)) {
1530 ret = "Game private description in save file is invalid";
1531 goto cleanup;
1532 }
1533 if (statepos < 0 || statepos >= nstates) {
1534 ret = "Game position in save file is out of range";
1535 }
1536
1537 states[0].state = me->ourgame->new_game(me, params,
1538 privdesc ? privdesc : desc);
1539 for (i = 1; i < nstates; i++) {
1540 assert(states[i].movetype != NEWGAME);
1541 switch (states[i].movetype) {
1542 case MOVE:
1543 case SOLVE:
1544 states[i].state = me->ourgame->execute_move(states[i-1].state,
1545 states[i].movestr);
1546 if (states[i].state == NULL) {
1547 ret = "Save file contained an invalid move";
1548 goto cleanup;
1549 }
1550 break;
1551 case RESTART:
1552 if (me->ourgame->validate_desc(params, states[i].movestr)) {
1553 ret = "Save file contained an invalid restart move";
1554 goto cleanup;
1555 }
1556 states[i].state = me->ourgame->new_game(me, params,
1557 states[i].movestr);
1558 break;
1559 }
1560 }
1561
1562 ui = me->ourgame->new_ui(states[0].state);
1563 me->ourgame->decode_ui(ui, uistr);
1564
1565 /*
1566 * Now we've run out of possible error conditions, so we're
1567 * ready to start overwriting the real data in the current
1568 * midend. We'll do this by swapping things with the local
1569 * variables, so that the same cleanup code will free the old
1570 * stuff.
1571 */
1572 {
1573 char *tmp;
1574
1575 tmp = me->desc;
1576 me->desc = desc;
1577 desc = tmp;
1578
1579 tmp = me->privdesc;
1580 me->privdesc = privdesc;
1581 privdesc = tmp;
1582
1583 tmp = me->seedstr;
1584 me->seedstr = seed;
1585 seed = tmp;
1586
1587 tmp = me->aux_info;
1588 me->aux_info = auxinfo;
1589 auxinfo = tmp;
1590 }
1591
1592 me->genmode = GOT_NOTHING;
1593
1594 me->statesize = nstates;
1595 nstates = me->nstates;
1596 me->nstates = me->statesize;
1597 {
1598 struct midend_state_entry *tmp;
1599 tmp = me->states;
1600 me->states = states;
1601 states = tmp;
1602 }
1603 me->statepos = statepos;
1604
1605 {
1606 game_params *tmp;
1607
1608 tmp = me->params;
1609 me->params = params;
1610 params = tmp;
1611
1612 tmp = me->curparams;
1613 me->curparams = cparams;
1614 cparams = tmp;
1615 }
1616
1617 me->oldstate = NULL;
1618 me->anim_time = me->anim_pos = me->flash_time = me->flash_pos = 0.0F;
1619 me->dir = 0;
1620
1621 {
1622 game_ui *tmp;
1623
1624 tmp = me->ui;
1625 me->ui = ui;
1626 ui = tmp;
1627 }
1628
1629 me->elapsed = elapsed;
1630 me->pressed_mouse_button = 0;
1631
1632 midend_set_timer(me);
1633
871bf294 1634 if (me->drawstate)
1635 me->ourgame->free_drawstate(me->drawstate);
1636 me->drawstate =
1637 me->ourgame->new_drawstate(me->states[me->statepos-1].state);
1638 midend_size_new_drawstate(me);
1639
a4393230 1640 ret = NULL; /* success! */
1641
1642 cleanup:
1643 sfree(val);
1644 sfree(seed);
1645 sfree(parstr);
1646 sfree(cparstr);
1647 sfree(desc);
1648 sfree(privdesc);
1649 sfree(auxinfo);
1650 sfree(uistr);
1651 if (params)
1652 me->ourgame->free_params(params);
1653 if (cparams)
1654 me->ourgame->free_params(cparams);
1655 if (ui)
1656 me->ourgame->free_ui(ui);
1657 if (states) {
1658 int i;
1659
1660 for (i = 0; i < nstates; i++) {
1661 if (states[i].state)
1662 me->ourgame->free_game(states[i].state);
1663 sfree(states[i].movestr);
1664 }
1665 sfree(states);
1666 }
1667
1668 return ret;
1669}