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