chiark / gitweb /
Annoying special cases for Mines.
[sgt-puzzles.git] / 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 struct midend_state_entry {
19     game_state *state;
20     int special;                       /* created by solve or restart */
21 };
22
23 struct midend_data {
24     frontend *frontend;
25     random_state *random;
26     const game *ourgame;
27
28     /*
29      * `desc' and `privdesc' deserve a comment.
30      * 
31      * `desc' is the game description as presented to the user when
32      * they ask for Game -> Specific. `privdesc', if non-NULL, is a
33      * different game description used to reconstruct the initial
34      * game_state when de-serialising. If privdesc is NULL, `desc'
35      * is used for both.
36      * 
37      * For almost all games, `privdesc' is NULL and never used. The
38      * exception (as usual) is Mines: the initial game state has no
39      * squares open at all, but after the first click `desc' is
40      * rewritten to describe a game state with an initial click and
41      * thus a bunch of squares open. If we used that desc to
42      * serialise and deserialise, then the initial game state after
43      * deserialisation would look unlike the initial game state
44      * beforehand, and worse still execute_move() might fail on the
45      * attempted first click. So `privdesc' is also used in this
46      * case, to provide a game description describing the same
47      * fixed mine layout _but_ no initial click. (These game IDs
48      * may also be typed directly into Mines if you like.)
49      */
50     char *desc, *privdesc, *seedstr;
51     game_aux_info *aux_info;
52     enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
53     int nstates, statesize, statepos;
54
55     game_params **presets;
56     char **preset_names;
57     int npresets, presetsize;
58
59     game_params *params, *curparams;
60     struct midend_state_entry *states;
61     game_drawstate *drawstate;
62     game_state *oldstate;
63     game_ui *ui;
64     float anim_time, anim_pos;
65     float flash_time, flash_pos;
66     int dir;
67
68     int timing;
69     float elapsed;
70     char *laststatus;
71
72     int pressed_mouse_button;
73
74     int winwidth, winheight;
75 };
76
77 #define ensure(me) do { \
78     if ((me)->nstates >= (me)->statesize) { \
79         (me)->statesize = (me)->nstates + 128; \
80         (me)->states = sresize((me)->states, (me)->statesize, \
81                                struct midend_state_entry); \
82     } \
83 } while (0)
84
85 midend_data *midend_new(frontend *fe, const game *ourgame)
86 {
87     midend_data *me = snew(midend_data);
88     void *randseed;
89     int randseedsize;
90
91     get_random_seed(&randseed, &randseedsize);
92
93     me->frontend = fe;
94     me->ourgame = ourgame;
95     me->random = random_init(randseed, randseedsize);
96     me->nstates = me->statesize = me->statepos = 0;
97     me->states = NULL;
98     me->params = ourgame->default_params();
99     me->curparams = NULL;
100     me->desc = me->privdesc = NULL;
101     me->seedstr = NULL;
102     me->aux_info = NULL;
103     me->genmode = GOT_NOTHING;
104     me->drawstate = NULL;
105     me->oldstate = NULL;
106     me->presets = NULL;
107     me->preset_names = NULL;
108     me->npresets = me->presetsize = 0;
109     me->anim_time = me->anim_pos = 0.0F;
110     me->flash_time = me->flash_pos = 0.0F;
111     me->dir = 0;
112     me->ui = NULL;
113     me->pressed_mouse_button = 0;
114     me->laststatus = NULL;
115     me->timing = FALSE;
116     me->elapsed = 0.0F;
117     me->winwidth = me->winheight = 0;
118
119     sfree(randseed);
120
121     return me;
122 }
123
124 static void midend_free_game(midend_data *me)
125 {
126     while (me->nstates > 0)
127         me->ourgame->free_game(me->states[--me->nstates].state);
128
129     if (me->drawstate)
130         me->ourgame->free_drawstate(me->drawstate);
131 }
132
133 void midend_free(midend_data *me)
134 {
135     int i;
136
137     midend_free_game(me);
138
139     random_free(me->random);
140     sfree(me->states);
141     sfree(me->desc);
142     sfree(me->seedstr);
143     if (me->aux_info)
144         me->ourgame->free_aux_info(me->aux_info);
145     me->ourgame->free_params(me->params);
146     if (me->npresets) {
147         for (i = 0; i < me->npresets; i++) {
148             sfree(me->presets[i]);
149             sfree(me->preset_names[i]);
150         }
151         sfree(me->presets);
152         sfree(me->preset_names);
153     }
154     if (me->ui)
155         me->ourgame->free_ui(me->ui);
156     if (me->curparams)
157         me->ourgame->free_params(me->curparams);
158     sfree(me->laststatus);
159     sfree(me);
160 }
161
162 void midend_size(midend_data *me, int *x, int *y, int expand)
163 {
164     me->ourgame->size(me->params, me->drawstate, x, y, expand);
165     me->winwidth = *x;
166     me->winheight = *y;
167 }
168
169 void midend_set_params(midend_data *me, game_params *params)
170 {
171     me->ourgame->free_params(me->params);
172     me->params = me->ourgame->dup_params(params);
173 }
174
175 static void midend_set_timer(midend_data *me)
176 {
177     me->timing = (me->ourgame->is_timed &&
178                   me->ourgame->timing_state(me->states[me->statepos-1].state));
179     if (me->timing || me->flash_time || me->anim_time)
180         activate_timer(me->frontend);
181     else
182         deactivate_timer(me->frontend);
183 }
184
185 static void midend_size_new_drawstate(midend_data *me)
186 {
187     me->ourgame->size(me->params, me->drawstate, &me->winwidth, &me->winheight,
188                       TRUE);
189 }
190
191 void midend_force_redraw(midend_data *me)
192 {
193     if (me->drawstate)
194         me->ourgame->free_drawstate(me->drawstate);
195     me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
196     midend_size_new_drawstate(me);
197     midend_redraw(me);
198 }
199
200 void midend_new_game(midend_data *me)
201 {
202     midend_free_game(me);
203
204     assert(me->nstates == 0);
205
206     if (me->genmode == GOT_DESC) {
207         me->genmode = GOT_NOTHING;
208     } else {
209         random_state *rs;
210
211         if (me->genmode == GOT_SEED) {
212             me->genmode = GOT_NOTHING;
213         } else {
214             /*
215              * Generate a new random seed. 15 digits comes to about
216              * 48 bits, which should be more than enough.
217              * 
218              * I'll avoid putting a leading zero on the number,
219              * just in case it confuses anybody who thinks it's
220              * processed as an integer rather than a string.
221              */
222             char newseed[16];
223             int i;
224             newseed[15] = '\0';
225             newseed[0] = '1' + random_upto(me->random, 9);
226             for (i = 1; i < 15; i++)
227                 newseed[i] = '0' + random_upto(me->random, 10);
228             sfree(me->seedstr);
229             me->seedstr = dupstr(newseed);
230
231             if (me->curparams)
232                 me->ourgame->free_params(me->curparams);
233             me->curparams = me->ourgame->dup_params(me->params);
234         }
235
236         sfree(me->desc);
237         sfree(me->privdesc);
238         if (me->aux_info)
239             me->ourgame->free_aux_info(me->aux_info);
240         me->aux_info = NULL;
241
242         rs = random_init(me->seedstr, strlen(me->seedstr));
243         me->desc = me->ourgame->new_desc(me->curparams, rs,
244                                          &me->aux_info, TRUE);
245         me->privdesc = NULL;
246         random_free(rs);
247     }
248
249     ensure(me);
250     me->states[me->nstates].state =
251         me->ourgame->new_game(me, me->params, me->desc);
252     me->states[me->nstates].special = TRUE;
253     me->nstates++;
254     me->statepos = 1;
255     me->drawstate = me->ourgame->new_drawstate(me->states[0].state);
256     midend_size_new_drawstate(me);
257     me->elapsed = 0.0F;
258     midend_set_timer(me);
259     if (me->ui)
260         me->ourgame->free_ui(me->ui);
261     me->ui = me->ourgame->new_ui(me->states[0].state);
262     me->pressed_mouse_button = 0;
263 }
264
265 static int midend_undo(midend_data *me)
266 {
267     if (me->statepos > 1) {
268         if (me->ui)
269             me->ourgame->changed_state(me->ui,
270                                        me->states[me->statepos-1].state,
271                                        me->states[me->statepos-2].state);
272         me->statepos--;
273         me->dir = -1;
274         return 1;
275     } else
276         return 0;
277 }
278
279 static int midend_redo(midend_data *me)
280 {
281     if (me->statepos < me->nstates) {
282         if (me->ui)
283             me->ourgame->changed_state(me->ui,
284                                        me->states[me->statepos-1].state,
285                                        me->states[me->statepos].state);
286         me->statepos++;
287         me->dir = +1;
288         return 1;
289     } else
290         return 0;
291 }
292
293 static void midend_finish_move(midend_data *me)
294 {
295     float flashtime;
296
297     /*
298      * We do not flash if the later of the two states is special.
299      * This covers both forward Solve moves and backward (undone)
300      * Restart moves.
301      */
302     if ((me->oldstate || me->statepos > 1) &&
303         ((me->dir > 0 && !me->states[me->statepos-1].special) ||
304          (me->dir < 0 && me->statepos < me->nstates &&
305           !me->states[me->statepos].special))) {
306         flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
307                                               me->states[me->statepos-2].state,
308                                               me->states[me->statepos-1].state,
309                                               me->oldstate ? me->dir : +1,
310                                               me->ui);
311         if (flashtime > 0) {
312             me->flash_pos = 0.0F;
313             me->flash_time = flashtime;
314         }
315     }
316
317     if (me->oldstate)
318         me->ourgame->free_game(me->oldstate);
319     me->oldstate = NULL;
320     me->anim_pos = me->anim_time = 0;
321     me->dir = 0;
322
323     midend_set_timer(me);
324 }
325
326 void midend_stop_anim(midend_data *me)
327 {
328     if (me->oldstate || me->anim_time) {
329         midend_finish_move(me);
330         midend_redraw(me);
331     }
332 }
333
334 void midend_restart_game(midend_data *me)
335 {
336     game_state *s;
337
338     midend_stop_anim(me);
339
340     assert(me->statepos >= 1);
341     if (me->statepos == 1)
342         return;                        /* no point doing anything at all! */
343
344     /*
345      * During restart, we reconstruct the game from the (public)
346      * game description rather than from states[0], because that
347      * way Mines gets slightly more sensible behaviour (restart
348      * goes to _after_ the first click so you don't have to
349      * remember where you clicked).
350      */
351     s = me->ourgame->new_game(me, me->params, me->desc);
352
353     /*
354      * Now enter the restarted state as the next move.
355      */
356     midend_stop_anim(me);
357     while (me->nstates > me->statepos)
358         me->ourgame->free_game(me->states[--me->nstates].state);
359     ensure(me);
360     me->states[me->nstates].state = s;
361     me->states[me->nstates].special = TRUE;   /* we just restarted */
362     me->statepos = ++me->nstates;
363     if (me->ui)
364         me->ourgame->changed_state(me->ui,
365                                    me->states[me->statepos-2].state,
366                                    me->states[me->statepos-1].state);
367     me->anim_time = 0.0;
368     midend_finish_move(me);
369     midend_redraw(me);
370     midend_set_timer(me);
371 }
372
373 static int midend_really_process_key(midend_data *me, int x, int y, int button)
374 {
375     game_state *oldstate =
376         me->ourgame->dup_game(me->states[me->statepos - 1].state);
377     int special = FALSE, gotspecial = FALSE, ret = 1;
378     float anim_time;
379
380     if (button == 'n' || button == 'N' || button == '\x0E') {
381         midend_stop_anim(me);
382         midend_new_game(me);
383         midend_redraw(me);
384         goto done;                     /* never animate */
385     } else if (button == 'u' || button == 'u' ||
386                button == '\x1A' || button == '\x1F') {
387         midend_stop_anim(me);
388         special = me->states[me->statepos-1].special;
389         gotspecial = TRUE;
390         if (!midend_undo(me))
391             goto done;
392     } else if (button == 'r' || button == 'R' ||
393                button == '\x12' || button == '\x19') {
394         midend_stop_anim(me);
395         if (!midend_redo(me))
396             goto done;
397     } else if (button == 'q' || button == 'Q' || button == '\x11') {
398         ret = 0;
399         goto done;
400     } else {
401         game_state *s;
402         char *movestr;
403         
404         movestr =
405             me->ourgame->interpret_move(me->states[me->statepos-1].state,
406                                         me->ui, me->drawstate, x, y, button);
407         if (!movestr)
408             s = NULL;
409         else if (!*movestr)
410             s = me->states[me->statepos-1].state;
411         else {
412             s = me->ourgame->execute_move(me->states[me->statepos-1].state,
413                                           movestr);
414             assert(s != NULL);
415             sfree(movestr);
416         }
417
418         if (s == me->states[me->statepos-1].state) {
419             /*
420              * make_move() is allowed to return its input state to
421              * indicate that although no move has been made, the UI
422              * state has been updated and a redraw is called for.
423              */
424             midend_redraw(me);
425             goto done;
426         } else if (s) {
427             midend_stop_anim(me);
428             while (me->nstates > me->statepos)
429                 me->ourgame->free_game(me->states[--me->nstates].state);
430             ensure(me);
431             me->states[me->nstates].state = s;
432             me->states[me->nstates].special = FALSE;   /* normal move */
433             me->statepos = ++me->nstates;
434             me->dir = +1;
435         } else {
436           goto done;
437         }
438     }
439
440     if (!gotspecial)
441         special = me->states[me->statepos-1].special;
442
443     /*
444      * See if this move requires an animation.
445      */
446     if (special) {
447         anim_time = 0;
448     } else {
449         anim_time = me->ourgame->anim_length(oldstate,
450                                              me->states[me->statepos-1].state,
451                                              me->dir, me->ui);
452     }
453
454     me->oldstate = oldstate; oldstate = NULL;
455     if (anim_time > 0) {
456         me->anim_time = anim_time;
457     } else {
458         me->anim_time = 0.0;
459         midend_finish_move(me);
460     }
461     me->anim_pos = 0.0;
462
463     midend_redraw(me);
464
465     midend_set_timer(me);
466
467     done:
468     if (oldstate) me->ourgame->free_game(oldstate);
469     return ret;
470 }
471
472 int midend_process_key(midend_data *me, int x, int y, int button)
473 {
474     int ret = 1;
475
476     /*
477      * Harmonise mouse drag and release messages.
478      * 
479      * Some front ends might accidentally switch from sending, say,
480      * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
481      * drag. (This can happen on the Mac, for example, since
482      * RIGHT_DRAG is usually done using Command+drag, and if the
483      * user accidentally releases Command half way through the drag
484      * then there will be trouble.)
485      * 
486      * It would be an O(number of front ends) annoyance to fix this
487      * in the front ends, but an O(number of back ends) annoyance
488      * to have each game capable of dealing with it. Therefore, we
489      * fix it _here_ in the common midend code so that it only has
490      * to be done once.
491      * 
492      * The possible ways in which things can go screwy in the front
493      * end are:
494      * 
495      *  - in a system containing multiple physical buttons button
496      *    presses can inadvertently overlap. We can see ABab (caps
497      *    meaning button-down and lowercase meaning button-up) when
498      *    the user had semantically intended AaBb.
499      * 
500      *  - in a system where one button is simulated by means of a
501      *    modifier key and another button, buttons can mutate
502      *    between press and release (possibly during drag). So we
503      *    can see Ab instead of Aa.
504      * 
505      * Definite requirements are:
506      * 
507      *  - button _presses_ must never be invented or destroyed. If
508      *    the user presses two buttons in succession, the button
509      *    presses must be transferred to the backend unchanged. So
510      *    if we see AaBb , that's fine; if we see ABab (the button
511      *    presses inadvertently overlapped) we must somehow
512      *    `correct' it to AaBb.
513      * 
514      *  - every mouse action must end up looking like a press, zero
515      *    or more drags, then a release. This allows back ends to
516      *    make the _assumption_ that incoming mouse data will be
517      *    sane in this regard, and not worry about the details.
518      * 
519      * So my policy will be:
520      * 
521      *  - treat any button-up as a button-up for the currently
522      *    pressed button, or ignore it if there is no currently
523      *    pressed button.
524      * 
525      *  - treat any drag as a drag for the currently pressed
526      *    button, or ignore it if there is no currently pressed
527      *    button.
528      * 
529      *  - if we see a button-down while another button is currently
530      *    pressed, invent a button-up for the first one and then
531      *    pass the button-down through as before.
532      * 
533      * 2005-05-31: An addendum to the above. Some games might want
534      * a `priority order' among buttons, such that if one button is
535      * pressed while another is down then a fixed one of the
536      * buttons takes priority no matter what order they're pressed
537      * in. Mines, in particular, wants to treat a left+right click
538      * like a left click for the benefit of users of other
539      * implementations. So the last of the above points is modified
540      * in the presence of an (optional) button priority order.
541      */
542     if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
543         if (me->pressed_mouse_button) {
544             if (IS_MOUSE_DRAG(button)) {
545                 button = me->pressed_mouse_button +
546                     (LEFT_DRAG - LEFT_BUTTON);
547             } else {
548                 button = me->pressed_mouse_button +
549                     (LEFT_RELEASE - LEFT_BUTTON);
550             }
551         } else
552             return ret;                /* ignore it */
553     } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
554         /*
555          * If the new button has lower priority than the old one,
556          * don't bother doing this.
557          */
558         if (me->ourgame->mouse_priorities &
559             BUTTON_BEATS(me->pressed_mouse_button, button))
560             return ret;                /* just ignore it */
561
562         /*
563          * Fabricate a button-up for the previously pressed button.
564          */
565         ret = ret && midend_really_process_key
566             (me, x, y, (me->pressed_mouse_button +
567                         (LEFT_RELEASE - LEFT_BUTTON)));
568     }
569
570     /*
571      * Now send on the event we originally received.
572      */
573     ret = ret && midend_really_process_key(me, x, y, button);
574
575     /*
576      * And update the currently pressed button.
577      */
578     if (IS_MOUSE_RELEASE(button))
579         me->pressed_mouse_button = 0;
580     else if (IS_MOUSE_DOWN(button))
581         me->pressed_mouse_button = button;
582
583     return ret;
584 }
585
586 void midend_redraw(midend_data *me)
587 {
588     if (me->statepos > 0 && me->drawstate) {
589         start_draw(me->frontend);
590         if (me->oldstate && me->anim_time > 0 &&
591             me->anim_pos < me->anim_time) {
592             assert(me->dir != 0);
593             me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
594                                 me->states[me->statepos-1].state, me->dir,
595                                 me->ui, me->anim_pos, me->flash_pos);
596         } else {
597             me->ourgame->redraw(me->frontend, me->drawstate, NULL,
598                                 me->states[me->statepos-1].state, +1 /*shrug*/,
599                                 me->ui, 0.0, me->flash_pos);
600         }
601         end_draw(me->frontend);
602     }
603 }
604
605 void midend_timer(midend_data *me, float tplus)
606 {
607     me->anim_pos += tplus;
608     if (me->anim_pos >= me->anim_time ||
609         me->anim_time == 0 || !me->oldstate) {
610         if (me->anim_time > 0)
611             midend_finish_move(me);
612     }
613
614     me->flash_pos += tplus;
615     if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
616         me->flash_pos = me->flash_time = 0;
617     }
618
619     midend_redraw(me);
620
621     if (me->timing) {
622         float oldelapsed = me->elapsed;
623         me->elapsed += tplus;
624         if ((int)oldelapsed != (int)me->elapsed)
625             status_bar(me->frontend, me->laststatus ? me->laststatus : "");
626     }
627
628     midend_set_timer(me);
629 }
630
631 float *midend_colours(midend_data *me, int *ncolours)
632 {
633     game_state *state = NULL;
634     float *ret;
635
636     if (me->nstates == 0) {
637         game_aux_info *aux = NULL;
638         char *desc = me->ourgame->new_desc(me->params, me->random,
639                                            &aux, TRUE);
640         state = me->ourgame->new_game(me, me->params, desc);
641         sfree(desc);
642         if (aux)
643             me->ourgame->free_aux_info(aux);
644     } else
645         state = me->states[0].state;
646
647     ret = me->ourgame->colours(me->frontend, state, ncolours);
648
649     {
650         int i;
651
652         /*
653          * Allow environment-based overrides for the standard
654          * colours by defining variables along the lines of
655          * `NET_COLOUR_4=6000c0'.
656          */
657
658         for (i = 0; i < *ncolours; i++) {
659             char buf[80], *e;
660             unsigned int r, g, b;
661             int j;
662
663             sprintf(buf, "%s_COLOUR_%d", me->ourgame->name, i);
664             for (j = 0; buf[j]; j++)
665                 buf[j] = toupper((unsigned char)buf[j]);
666             if ((e = getenv(buf)) != NULL &&
667                 sscanf(e, "%2x%2x%2x", &r, &g, &b) == 3) {
668                 ret[i*3 + 0] = r / 255.0;
669                 ret[i*3 + 1] = g / 255.0;
670                 ret[i*3 + 2] = b / 255.0;
671             }
672         }
673     }
674
675     if (me->nstates == 0)
676         me->ourgame->free_game(state);
677
678     return ret;
679 }
680
681 int midend_num_presets(midend_data *me)
682 {
683     if (!me->npresets) {
684         char *name;
685         game_params *preset;
686
687         while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
688             if (me->presetsize <= me->npresets) {
689                 me->presetsize = me->npresets + 10;
690                 me->presets = sresize(me->presets, me->presetsize,
691                                       game_params *);
692                 me->preset_names = sresize(me->preset_names, me->presetsize,
693                                            char *);
694             }
695
696             me->presets[me->npresets] = preset;
697             me->preset_names[me->npresets] = name;
698             me->npresets++;
699         }
700     }
701
702     {
703         /*
704          * Allow environment-based extensions to the preset list by
705          * defining a variable along the lines of `SOLO_PRESETS=2x3
706          * Advanced:2x3da'. Colon-separated list of items,
707          * alternating between textual titles in the menu and
708          * encoded parameter strings.
709          */
710         char buf[80], *e, *p;
711         int j;
712
713         sprintf(buf, "%s_PRESETS", me->ourgame->name);
714         for (j = 0; buf[j]; j++)
715             buf[j] = toupper((unsigned char)buf[j]);
716
717         if ((e = getenv(buf)) != NULL) {
718             p = e = dupstr(e);
719
720             while (*p) {
721                 char *name, *val;
722                 game_params *preset;
723
724                 name = p;
725                 while (*p && *p != ':') p++;
726                 if (*p) *p++ = '\0';
727                 val = p;
728                 while (*p && *p != ':') p++;
729                 if (*p) *p++ = '\0';
730
731                 preset = me->ourgame->default_params();
732                 me->ourgame->decode_params(preset, val);
733
734                 if (me->ourgame->validate_params(preset)) {
735                     /* Drop this one from the list. */
736                     me->ourgame->free_params(preset);
737                     continue;
738                 }
739
740                 if (me->presetsize <= me->npresets) {
741                     me->presetsize = me->npresets + 10;
742                     me->presets = sresize(me->presets, me->presetsize,
743                                           game_params *);
744                     me->preset_names = sresize(me->preset_names,
745                                                me->presetsize, char *);
746                 }
747
748                 me->presets[me->npresets] = preset;
749                 me->preset_names[me->npresets] = name;
750                 me->npresets++;
751             }
752         }
753     }
754
755     return me->npresets;
756 }
757
758 void midend_fetch_preset(midend_data *me, int n,
759                          char **name, game_params **params)
760 {
761     assert(n >= 0 && n < me->npresets);
762     *name = me->preset_names[n];
763     *params = me->presets[n];
764 }
765
766 int midend_wants_statusbar(midend_data *me)
767 {
768     return me->ourgame->wants_statusbar();
769 }
770
771 void midend_supersede_game_desc(midend_data *me, char *desc, char *privdesc)
772 {
773     sfree(me->desc);
774     sfree(me->privdesc);
775 printf("%s\n%s\n", desc, privdesc);
776     me->desc = dupstr(desc);
777     me->privdesc = privdesc ? dupstr(privdesc) : NULL;
778 }
779
780 config_item *midend_get_config(midend_data *me, int which, char **wintitle)
781 {
782     char *titlebuf, *parstr, *rest;
783     config_item *ret;
784     char sep;
785
786     assert(wintitle);
787     titlebuf = snewn(40 + strlen(me->ourgame->name), char);
788
789     switch (which) {
790       case CFG_SETTINGS:
791         sprintf(titlebuf, "%s configuration", me->ourgame->name);
792         *wintitle = titlebuf;
793         return me->ourgame->configure(me->params);
794       case CFG_SEED:
795       case CFG_DESC:
796         if (!me->curparams) {
797           sfree(titlebuf);
798           return NULL;
799         }
800         sprintf(titlebuf, "%s %s selection", me->ourgame->name,
801                 which == CFG_SEED ? "random" : "game");
802         *wintitle = titlebuf;
803
804         ret = snewn(2, config_item);
805
806         ret[0].type = C_STRING;
807         if (which == CFG_SEED)
808             ret[0].name = "Game random seed";
809         else
810             ret[0].name = "Game ID";
811         ret[0].ival = 0;
812         /*
813          * For CFG_DESC the text going in here will be a string
814          * encoding of the restricted parameters, plus a colon,
815          * plus the game description. For CFG_SEED it will be the
816          * full parameters, plus a hash, plus the random seed data.
817          * Either of these is a valid full game ID (although only
818          * the former is likely to persist across many code
819          * changes).
820          */
821         parstr = me->ourgame->encode_params(me->curparams, which == CFG_SEED);
822         assert(parstr);
823         if (which == CFG_DESC) {
824             rest = me->desc ? me->desc : "";
825             sep = ':';
826         } else {
827             rest = me->seedstr ? me->seedstr : "";
828             sep = '#';
829         }
830         ret[0].sval = snewn(strlen(parstr) + strlen(rest) + 2, char);
831         sprintf(ret[0].sval, "%s%c%s", parstr, sep, rest);
832         sfree(parstr);
833
834         ret[1].type = C_END;
835         ret[1].name = ret[1].sval = NULL;
836         ret[1].ival = 0;
837
838         return ret;
839     }
840
841     assert(!"We shouldn't be here");
842     return NULL;
843 }
844
845 static char *midend_game_id_int(midend_data *me, char *id, int defmode)
846 {
847     char *error, *par, *desc, *seed;
848
849     seed = strchr(id, '#');
850     desc = strchr(id, ':');
851
852     if (desc && (!seed || desc < seed)) {
853         /*
854          * We have a colon separating parameters from game
855          * description. So `par' now points to the parameters
856          * string, and `desc' to the description string.
857          */
858         *desc++ = '\0';
859         par = id;
860         seed = NULL;
861     } else if (seed && (!desc || seed < desc)) {
862         /*
863          * We have a hash separating parameters from random seed.
864          * So `par' now points to the parameters string, and `seed'
865          * to the seed string.
866          */
867         *seed++ = '\0';
868         par = id;
869         desc = NULL;
870     } else {
871         /*
872          * We only have one string. Depending on `defmode', we take
873          * it to be either parameters, seed or description.
874          */
875         if (defmode == DEF_SEED) {
876             seed = id;
877             par = desc = NULL;
878         } else if (defmode == DEF_DESC) {
879             desc = id;
880             par = seed = NULL;
881         } else {
882             par = id;
883             seed = desc = NULL;
884         }
885     }
886
887     if (par) {
888         game_params *tmpparams;
889         tmpparams = me->ourgame->dup_params(me->params);
890         me->ourgame->decode_params(tmpparams, par);
891         error = me->ourgame->validate_params(tmpparams);
892         if (error) {
893             me->ourgame->free_params(tmpparams);
894             return error;
895         }
896         if (me->curparams)
897             me->ourgame->free_params(me->curparams);
898         me->curparams = tmpparams;
899
900         /*
901          * Now filter only the persistent parts of this state into
902          * the long-term params structure, unless we've _only_
903          * received a params string in which case the whole lot is
904          * persistent.
905          */
906         if (seed || desc) {
907             char *tmpstr = me->ourgame->encode_params(tmpparams, FALSE);
908             me->ourgame->decode_params(me->params, tmpstr);
909             sfree(tmpstr);
910         } else {
911             me->ourgame->free_params(me->params);
912             me->params = me->ourgame->dup_params(tmpparams);
913         }
914     }
915
916     sfree(me->desc);
917     sfree(me->privdesc);
918     me->desc = me->privdesc = NULL;
919     sfree(me->seedstr);
920     me->seedstr = NULL;
921
922     if (desc) {
923         error = me->ourgame->validate_desc(me->params, desc);
924         if (error)
925             return error;
926
927         me->desc = dupstr(desc);
928         me->genmode = GOT_DESC;
929         if (me->aux_info)
930             me->ourgame->free_aux_info(me->aux_info);
931         me->aux_info = NULL;
932     }
933
934     if (seed) {
935         me->seedstr = dupstr(seed);
936         me->genmode = GOT_SEED;
937     }
938
939     return NULL;
940 }
941
942 char *midend_game_id(midend_data *me, char *id)
943 {
944     return midend_game_id_int(me, id, DEF_PARAMS);
945 }
946
947 char *midend_set_config(midend_data *me, int which, config_item *cfg)
948 {
949     char *error;
950     game_params *params;
951
952     switch (which) {
953       case CFG_SETTINGS:
954         params = me->ourgame->custom_params(cfg);
955         error = me->ourgame->validate_params(params);
956
957         if (error) {
958             me->ourgame->free_params(params);
959             return error;
960         }
961
962         me->ourgame->free_params(me->params);
963         me->params = params;
964         break;
965
966       case CFG_SEED:
967       case CFG_DESC:
968         error = midend_game_id_int(me, cfg[0].sval,
969                                    (which == CFG_SEED ? DEF_SEED : DEF_DESC));
970         if (error)
971             return error;
972         break;
973     }
974
975     return NULL;
976 }
977
978 char *midend_text_format(midend_data *me)
979 {
980     if (me->ourgame->can_format_as_text && me->statepos > 0)
981         return me->ourgame->text_format(me->states[me->statepos-1].state);
982     else
983         return NULL;
984 }
985
986 char *midend_solve(midend_data *me)
987 {
988     game_state *s;
989     char *msg, *movestr;
990
991     if (!me->ourgame->can_solve)
992         return "This game does not support the Solve operation";
993
994     if (me->statepos < 1)
995         return "No game set up to solve";   /* _shouldn't_ happen! */
996
997     msg = "Solve operation failed";    /* game _should_ overwrite on error */
998     movestr = me->ourgame->solve(me->states[0].state,
999                                  me->states[me->statepos-1].state,
1000                                  me->aux_info, &msg);
1001     if (!movestr)
1002         return msg;
1003     s = me->ourgame->execute_move(me->states[me->statepos-1].state, movestr);
1004     assert(s);
1005     sfree(movestr);
1006
1007     /*
1008      * Now enter the solved state as the next move.
1009      */
1010     midend_stop_anim(me);
1011     while (me->nstates > me->statepos)
1012         me->ourgame->free_game(me->states[--me->nstates].state);
1013     ensure(me);
1014     me->states[me->nstates].state = s;
1015     me->states[me->nstates].special = TRUE;   /* created using solve */
1016     me->statepos = ++me->nstates;
1017     if (me->ui)
1018         me->ourgame->changed_state(me->ui,
1019                                    me->states[me->statepos-2].state,
1020                                    me->states[me->statepos-1].state);
1021     me->anim_time = 0.0;
1022     midend_finish_move(me);
1023     midend_redraw(me);
1024     midend_set_timer(me);
1025     return NULL;
1026 }
1027
1028 char *midend_rewrite_statusbar(midend_data *me, char *text)
1029 {
1030     /*
1031      * An important special case is that we are occasionally called
1032      * with our own laststatus, to update the timer.
1033      */
1034     if (me->laststatus != text) {
1035         sfree(me->laststatus);
1036         me->laststatus = dupstr(text);
1037     }
1038
1039     if (me->ourgame->is_timed) {
1040         char timebuf[100], *ret;
1041         int min, sec;
1042
1043         sec = me->elapsed;
1044         min = sec / 60;
1045         sec %= 60;
1046         sprintf(timebuf, "[%d:%02d] ", min, sec);
1047
1048         ret = snewn(strlen(timebuf) + strlen(text) + 1, char);
1049         strcpy(ret, timebuf);
1050         strcat(ret, text);
1051         return ret;
1052
1053     } else {
1054         return dupstr(text);
1055     }
1056 }