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