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