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