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