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