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