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