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