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