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