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