chiark / gitweb /
comment c'n'p error
[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/restart/quit.
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #include "puzzles.h"
13
14 enum { DEF_PARAMS, DEF_SEED, DEF_DESC };   /* for midend_game_id_int */
15
16 struct midend_data {
17     frontend *frontend;
18     random_state *random;
19     const game *ourgame;
20
21     char *desc, *seedstr;
22     game_aux_info *aux_info;
23     enum { GOT_SEED, GOT_DESC, GOT_NOTHING } genmode;
24     int nstates, statesize, statepos;
25
26     game_params **presets;
27     char **preset_names;
28     int npresets, presetsize;
29
30     game_params *params, *tmpparams;
31     game_state **states;
32     game_drawstate *drawstate;
33     game_state *oldstate;
34     game_ui *ui;
35     float anim_time, anim_pos;
36     float flash_time, flash_pos;
37     int dir;
38
39     int pressed_mouse_button;
40 };
41
42 #define ensure(me) do { \
43     if ((me)->nstates >= (me)->statesize) { \
44         (me)->statesize = (me)->nstates + 128; \
45         (me)->states = sresize((me)->states, (me)->statesize, game_state *); \
46     } \
47 } while (0)
48
49 midend_data *midend_new(frontend *fe, const game *ourgame)
50 {
51     midend_data *me = snew(midend_data);
52     void *randseed;
53     int randseedsize;
54
55     get_random_seed(&randseed, &randseedsize);
56
57     me->frontend = fe;
58     me->ourgame = ourgame;
59     me->random = random_init(randseed, randseedsize);
60     me->nstates = me->statesize = me->statepos = 0;
61     me->states = NULL;
62     me->params = ourgame->default_params();
63     me->tmpparams = NULL;
64     me->desc = NULL;
65     me->seedstr = NULL;
66     me->aux_info = NULL;
67     me->genmode = GOT_NOTHING;
68     me->drawstate = NULL;
69     me->oldstate = NULL;
70     me->presets = NULL;
71     me->preset_names = NULL;
72     me->npresets = me->presetsize = 0;
73     me->anim_time = me->anim_pos = 0.0F;
74     me->flash_time = me->flash_pos = 0.0F;
75     me->dir = 0;
76     me->ui = NULL;
77     me->pressed_mouse_button = 0;
78
79     sfree(randseed);
80
81     return me;
82 }
83
84 void midend_free(midend_data *me)
85 {
86     sfree(me->states);
87     sfree(me->desc);
88     sfree(me->seedstr);
89     random_free(me->random);
90     if (me->aux_info)
91         me->ourgame->free_aux_info(me->aux_info);
92     me->ourgame->free_params(me->params);
93     if (me->tmpparams)
94         me->ourgame->free_params(me->tmpparams);
95     sfree(me);
96 }
97
98 void midend_size(midend_data *me, int *x, int *y)
99 {
100     me->ourgame->size(me->params, x, y);
101 }
102
103 void midend_set_params(midend_data *me, game_params *params)
104 {
105     me->ourgame->free_params(me->params);
106     me->params = me->ourgame->dup_params(params);
107 }
108
109 void midend_new_game(midend_data *me)
110 {
111     while (me->nstates > 0)
112         me->ourgame->free_game(me->states[--me->nstates]);
113
114     if (me->drawstate)
115         me->ourgame->free_drawstate(me->drawstate);
116
117     assert(me->nstates == 0);
118
119     if (me->genmode == GOT_DESC) {
120         me->genmode = GOT_NOTHING;
121     } else {
122         random_state *rs;
123
124         if (me->genmode == GOT_SEED) {
125             me->genmode = GOT_NOTHING;
126         } else {
127             /*
128              * Generate a new random seed. 15 digits comes to about
129              * 48 bits, which should be more than enough.
130              */
131             char newseed[16];
132             int i;
133             newseed[15] = '\0';
134             for (i = 0; i < 15; i++)
135                 newseed[i] = '0' + random_upto(me->random, 10);
136             sfree(me->seedstr);
137             me->seedstr = dupstr(newseed);
138         }
139
140         sfree(me->desc);
141         if (me->aux_info)
142             me->ourgame->free_aux_info(me->aux_info);
143         me->aux_info = NULL;
144
145         rs = random_init(me->seedstr, strlen(me->seedstr));
146         me->desc = me->ourgame->new_desc
147             (me->tmpparams ? me->tmpparams : me->params, rs, &me->aux_info);
148         random_free(rs);
149
150         if (me->tmpparams) {
151             me->ourgame->free_params(me->tmpparams);
152             me->tmpparams = NULL;
153         }
154     }
155
156     ensure(me);
157     me->states[me->nstates++] = me->ourgame->new_game(me->params, me->desc);
158     me->statepos = 1;
159     me->drawstate = me->ourgame->new_drawstate(me->states[0]);
160     if (me->ui)
161         me->ourgame->free_ui(me->ui);
162     me->ui = me->ourgame->new_ui(me->states[0]);
163     me->pressed_mouse_button = 0;
164 }
165
166 void midend_restart_game(midend_data *me)
167 {
168     while (me->nstates > 1)
169         me->ourgame->free_game(me->states[--me->nstates]);
170     me->statepos = me->nstates;
171     me->ourgame->free_ui(me->ui);
172     me->ui = me->ourgame->new_ui(me->states[0]);
173 }
174
175 static int midend_undo(midend_data *me)
176 {
177     if (me->statepos > 1) {
178         me->statepos--;
179         me->dir = -1;
180         return 1;
181     } else
182         return 0;
183 }
184
185 static int midend_redo(midend_data *me)
186 {
187     if (me->statepos < me->nstates) {
188         me->statepos++;
189         me->dir = +1;
190         return 1;
191     } else
192         return 0;
193 }
194
195 static void midend_finish_move(midend_data *me)
196 {
197     float flashtime;
198
199     if (me->oldstate || me->statepos > 1) {
200         flashtime = me->ourgame->flash_length(me->oldstate ? me->oldstate :
201                                               me->states[me->statepos-2],
202                                               me->states[me->statepos-1],
203                                               me->oldstate ? me->dir : +1);
204         if (flashtime > 0) {
205             me->flash_pos = 0.0F;
206             me->flash_time = flashtime;
207         }
208     }
209
210     if (me->oldstate)
211         me->ourgame->free_game(me->oldstate);
212     me->oldstate = NULL;
213     me->anim_pos = me->anim_time = 0;
214     me->dir = 0;
215
216     if (me->flash_time == 0 && me->anim_time == 0)
217         deactivate_timer(me->frontend);
218     else
219         activate_timer(me->frontend);
220 }
221
222 static void midend_stop_anim(midend_data *me)
223 {
224     if (me->oldstate || me->anim_time) {
225         midend_finish_move(me);
226         midend_redraw(me);
227     }
228 }
229
230 static int midend_really_process_key(midend_data *me, int x, int y, int button)
231 {
232     game_state *oldstate = me->ourgame->dup_game(me->states[me->statepos - 1]);
233     float anim_time;
234
235     if (button == 'n' || button == 'N' || button == '\x0E') {
236         midend_stop_anim(me);
237         midend_new_game(me);
238         midend_redraw(me);
239         return 1;                      /* never animate */
240     } else if (button == 'r' || button == 'R') {
241         midend_stop_anim(me);
242         midend_restart_game(me);
243         midend_redraw(me);
244         return 1;                      /* never animate */
245     } else if (button == 'u' || button == 'u' ||
246                button == '\x1A' || button == '\x1F') {
247         midend_stop_anim(me);
248         if (!midend_undo(me))
249             return 1;
250     } else if (button == '\x12') {
251         midend_stop_anim(me);
252         if (!midend_redo(me))
253             return 1;
254     } else if (button == 'q' || button == 'Q' || button == '\x11') {
255         me->ourgame->free_game(oldstate);
256         return 0;
257     } else {
258         game_state *s = me->ourgame->make_move(me->states[me->statepos-1],
259                                                me->ui, x, y, button);
260
261         if (s == me->states[me->statepos-1]) {
262             /*
263              * make_move() is allowed to return its input state to
264              * indicate that although no move has been made, the UI
265              * state has been updated and a redraw is called for.
266              */
267             midend_redraw(me);
268             return 1;
269         } else if (s) {
270             midend_stop_anim(me);
271             while (me->nstates > me->statepos)
272                 me->ourgame->free_game(me->states[--me->nstates]);
273             ensure(me);
274             me->states[me->nstates] = s;
275             me->statepos = ++me->nstates;
276             me->dir = +1;
277         } else {
278             me->ourgame->free_game(oldstate);
279             return 1;
280         }
281     }
282
283     /*
284      * See if this move requires an animation.
285      */
286     anim_time = me->ourgame->anim_length(oldstate, me->states[me->statepos-1],
287                                          me->dir);
288
289     me->oldstate = oldstate;
290     if (anim_time > 0) {
291         me->anim_time = anim_time;
292     } else {
293         me->anim_time = 0.0;
294         midend_finish_move(me);
295     }
296     me->anim_pos = 0.0;
297
298     midend_redraw(me);
299
300     activate_timer(me->frontend);
301
302     return 1;
303 }
304
305 int midend_process_key(midend_data *me, int x, int y, int button)
306 {
307     int ret = 1;
308
309     /*
310      * Harmonise mouse drag and release messages.
311      * 
312      * Some front ends might accidentally switch from sending, say,
313      * RIGHT_DRAG messages to sending LEFT_DRAG, half way through a
314      * drag. (This can happen on the Mac, for example, since
315      * RIGHT_DRAG is usually done using Command+drag, and if the
316      * user accidentally releases Command half way through the drag
317      * then there will be trouble.)
318      * 
319      * It would be an O(number of front ends) annoyance to fix this
320      * in the front ends, but an O(number of back ends) annoyance
321      * to have each game capable of dealing with it. Therefore, we
322      * fix it _here_ in the common midend code so that it only has
323      * to be done once.
324      * 
325      * The possible ways in which things can go screwy in the front
326      * end are:
327      * 
328      *  - in a system containing multiple physical buttons button
329      *    presses can inadvertently overlap. We can see ABab (caps
330      *    meaning button-down and lowercase meaning button-up) when
331      *    the user had semantically intended AaBb.
332      * 
333      *  - in a system where one button is simulated by means of a
334      *    modifier key and another button, buttons can mutate
335      *    between press and release (possibly during drag). So we
336      *    can see Ab instead of Aa.
337      * 
338      * Definite requirements are:
339      * 
340      *  - button _presses_ must never be invented or destroyed. If
341      *    the user presses two buttons in succession, the button
342      *    presses must be transferred to the backend unchanged. So
343      *    if we see AaBb , that's fine; if we see ABab (the button
344      *    presses inadvertently overlapped) we must somehow
345      *    `correct' it to AaBb.
346      * 
347      *  - every mouse action must end up looking like a press, zero
348      *    or more drags, then a release. This allows back ends to
349      *    make the _assumption_ that incoming mouse data will be
350      *    sane in this regard, and not worry about the details.
351      * 
352      * So my policy will be:
353      * 
354      *  - treat any button-up as a button-up for the currently
355      *    pressed button, or ignore it if there is no currently
356      *    pressed button.
357      * 
358      *  - treat any drag as a drag for the currently pressed
359      *    button, or ignore it if there is no currently pressed
360      *    button.
361      * 
362      *  - if we see a button-down while another button is currently
363      *    pressed, invent a button-up for the first one and then
364      *    pass the button-down through as before.
365      * 
366      */
367     if (IS_MOUSE_DRAG(button) || IS_MOUSE_RELEASE(button)) {
368         if (me->pressed_mouse_button) {
369             if (IS_MOUSE_DRAG(button)) {
370                 button = me->pressed_mouse_button +
371                     (LEFT_DRAG - LEFT_BUTTON);
372             } else {
373                 button = me->pressed_mouse_button +
374                     (LEFT_RELEASE - LEFT_BUTTON);
375             }
376         } else
377             return ret;                /* ignore it */
378     } else if (IS_MOUSE_DOWN(button) && me->pressed_mouse_button) {
379         /*
380          * Fabricate a button-up for the previously pressed button.
381          */
382         ret = ret && midend_really_process_key
383             (me, x, y, (me->pressed_mouse_button +
384                         (LEFT_RELEASE - LEFT_BUTTON)));
385     }
386
387     /*
388      * Now send on the event we originally received.
389      */
390     ret = ret && midend_really_process_key(me, x, y, button);
391
392     /*
393      * And update the currently pressed button.
394      */
395     if (IS_MOUSE_RELEASE(button))
396         me->pressed_mouse_button = 0;
397     else if (IS_MOUSE_DOWN(button))
398         me->pressed_mouse_button = button;
399
400     return ret;
401 }
402
403 void midend_redraw(midend_data *me)
404 {
405     if (me->statepos > 0 && me->drawstate) {
406         start_draw(me->frontend);
407         if (me->oldstate && me->anim_time > 0 &&
408             me->anim_pos < me->anim_time) {
409             assert(me->dir != 0);
410             me->ourgame->redraw(me->frontend, me->drawstate, me->oldstate,
411                                 me->states[me->statepos-1], me->dir,
412                                 me->ui, me->anim_pos, me->flash_pos);
413         } else {
414             me->ourgame->redraw(me->frontend, me->drawstate, NULL,
415                                 me->states[me->statepos-1], +1 /*shrug*/,
416                                 me->ui, 0.0, me->flash_pos);
417         }
418         end_draw(me->frontend);
419     }
420 }
421
422 void midend_timer(midend_data *me, float tplus)
423 {
424     me->anim_pos += tplus;
425     if (me->anim_pos >= me->anim_time ||
426         me->anim_time == 0 || !me->oldstate) {
427         if (me->anim_time > 0)
428             midend_finish_move(me);
429     }
430     me->flash_pos += tplus;
431     if (me->flash_pos >= me->flash_time || me->flash_time == 0) {
432         me->flash_pos = me->flash_time = 0;
433     }
434     if (me->flash_time == 0 && me->anim_time == 0)
435         deactivate_timer(me->frontend);
436     midend_redraw(me);
437 }
438
439 float *midend_colours(midend_data *me, int *ncolours)
440 {
441     game_state *state = NULL;
442     float *ret;
443
444     if (me->nstates == 0) {
445         game_aux_info *aux = NULL;
446         char *desc = me->ourgame->new_desc(me->params, me->random, &aux);
447         state = me->ourgame->new_game(me->params, desc);
448         sfree(desc);
449         if (aux)
450             me->ourgame->free_aux_info(aux);
451     } else
452         state = me->states[0];
453
454     ret = me->ourgame->colours(me->frontend, state, ncolours);
455
456     if (me->nstates == 0)
457         me->ourgame->free_game(state);
458
459     return ret;
460 }
461
462 int midend_num_presets(midend_data *me)
463 {
464     if (!me->npresets) {
465         char *name;
466         game_params *preset;
467
468         while (me->ourgame->fetch_preset(me->npresets, &name, &preset)) {
469             if (me->presetsize <= me->npresets) {
470                 me->presetsize = me->npresets + 10;
471                 me->presets = sresize(me->presets, me->presetsize,
472                                       game_params *);
473                 me->preset_names = sresize(me->preset_names, me->presetsize,
474                                            char *);
475             }
476
477             me->presets[me->npresets] = preset;
478             me->preset_names[me->npresets] = name;
479             me->npresets++;
480         }
481     }
482
483     return me->npresets;
484 }
485
486 void midend_fetch_preset(midend_data *me, int n,
487                          char **name, game_params **params)
488 {
489     assert(n >= 0 && n < me->npresets);
490     *name = me->preset_names[n];
491     *params = me->presets[n];
492 }
493
494 int midend_wants_statusbar(midend_data *me)
495 {
496     return me->ourgame->wants_statusbar();
497 }
498
499 config_item *midend_get_config(midend_data *me, int which, char **wintitle)
500 {
501     char *titlebuf, *parstr;
502     config_item *ret;
503
504     titlebuf = snewn(40 + strlen(me->ourgame->name), char);
505
506     switch (which) {
507       case CFG_SETTINGS:
508         sprintf(titlebuf, "%s configuration", me->ourgame->name);
509         *wintitle = dupstr(titlebuf);
510         return me->ourgame->configure(me->params);
511       case CFG_SEED:
512       case CFG_DESC:
513         sprintf(titlebuf, "%s %s selection", me->ourgame->name,
514                 which == CFG_SEED ? "random" : "game");
515         *wintitle = dupstr(titlebuf);
516
517         ret = snewn(2, config_item);
518
519         ret[0].type = C_STRING;
520         if (which == CFG_SEED)
521             ret[0].name = "Game random seed";
522         else
523             ret[0].name = "Game ID";
524         ret[0].ival = 0;
525         /*
526          * For CFG_DESC the text going in here will be a string
527          * encoding of the restricted parameters, plus a colon,
528          * plus the game description. For CFG_SEED it will be the
529          * full parameters, plus a hash, plus the random seed data.
530          * Either of these is a valid full game ID (although only
531          * the former is likely to persist across many code
532          * changes).
533          */
534         parstr = me->ourgame->encode_params(me->params, which == CFG_SEED);
535         if (which == CFG_DESC) {
536             ret[0].sval = snewn(strlen(parstr) + strlen(me->desc) + 2, char);
537             sprintf(ret[0].sval, "%s:%s", parstr, me->desc);
538         } else if (me->seedstr) {
539             ret[0].sval = snewn(strlen(parstr) + strlen(me->seedstr) + 2, char);
540             sprintf(ret[0].sval, "%s#%s", parstr, me->seedstr);
541         } else {
542             /*
543              * If the current game was not randomly generated, the
544              * best we can do is to give a template for typing a
545              * new seed in.
546              */
547             ret[0].sval = snewn(strlen(parstr) + 2, char);
548             sprintf(ret[0].sval, "%s#", parstr);
549         }
550         sfree(parstr);
551
552         ret[1].type = C_END;
553         ret[1].name = ret[1].sval = NULL;
554         ret[1].ival = 0;
555
556         return ret;
557     }
558
559     assert(!"We shouldn't be here");
560     return NULL;
561 }
562
563 static char *midend_game_id_int(midend_data *me, char *id, int defmode)
564 {
565     char *error, *par, *desc, *seed;
566
567     seed = strchr(id, '#');
568     desc = strchr(id, ':');
569
570     if (desc && (!seed || desc < seed)) {
571         /*
572          * We have a colon separating parameters from game
573          * description. So `par' now points to the parameters
574          * string, and `desc' to the description string.
575          */
576         *desc++ = '\0';
577         par = id;
578         seed = NULL;
579     } else if (seed && (!desc || seed < desc)) {
580         /*
581          * We have a hash separating parameters from random seed.
582          * So `par' now points to the parameters string, and `seed'
583          * to the seed string.
584          */
585         *seed++ = '\0';
586         par = id;
587         desc = NULL;
588     } else {
589         /*
590          * We only have one string. Depending on `defmode', we take
591          * it to be either parameters, seed or description.
592          */
593         if (defmode == DEF_SEED) {
594             seed = id;
595             par = desc = NULL;
596         } else if (defmode == DEF_DESC) {
597             desc = id;
598             par = seed = NULL;
599         } else {
600             par = id;
601             seed = desc = NULL;
602         }
603     }
604
605     if (par) {
606         game_params *tmpparams;
607         tmpparams = me->ourgame->dup_params(me->params);
608         me->ourgame->decode_params(tmpparams, par);
609         error = me->ourgame->validate_params(tmpparams);
610         if (error) {
611             me->ourgame->free_params(tmpparams);
612             return error;
613         }
614         if (me->tmpparams)
615             me->ourgame->free_params(me->tmpparams);
616         me->tmpparams = tmpparams;
617
618         /*
619          * Now filter only the persistent parts of this state into
620          * the long-term params structure, unless we've _only_
621          * received a params string in which case the whole lot is
622          * persistent.
623          */
624         if (seed || desc) {
625             char *tmpstr = me->ourgame->encode_params(tmpparams, FALSE);
626             me->ourgame->decode_params(me->params, tmpstr);
627         } else {
628             me->ourgame->free_params(me->params);
629             me->params = me->ourgame->dup_params(tmpparams);
630         }
631     }
632
633     if (desc) {
634         error = me->ourgame->validate_desc(me->params, desc);
635         if (error)
636             return error;
637
638         sfree(me->desc);
639         me->desc = dupstr(desc);
640         me->genmode = GOT_DESC;
641         if (me->aux_info)
642             me->ourgame->free_aux_info(me->aux_info);
643         me->aux_info = NULL;
644     }
645
646     if (seed) {
647         sfree(me->seedstr);
648         me->seedstr = dupstr(seed);
649         me->genmode = GOT_SEED;
650     }
651
652     return NULL;
653 }
654
655 char *midend_game_id(midend_data *me, char *id)
656 {
657     return midend_game_id_int(me, id, DEF_PARAMS);
658 }
659
660 char *midend_set_config(midend_data *me, int which, config_item *cfg)
661 {
662     char *error;
663     game_params *params;
664
665     switch (which) {
666       case CFG_SETTINGS:
667         params = me->ourgame->custom_params(cfg);
668         error = me->ourgame->validate_params(params);
669
670         if (error) {
671             me->ourgame->free_params(params);
672             return error;
673         }
674
675         me->ourgame->free_params(me->params);
676         me->params = params;
677         break;
678
679       case CFG_SEED:
680       case CFG_DESC:
681         error = midend_game_id_int(me, cfg[0].sval,
682                                    (which == CFG_SEED ? DEF_SEED : DEF_DESC));
683         if (error)
684             return error;
685         break;
686     }
687
688     return NULL;
689 }
690
691 char *midend_text_format(midend_data *me)
692 {
693     if (me->ourgame->can_format_as_text && me->statepos > 0)
694         return me->ourgame->text_format(me->states[me->statepos-1]);
695     else
696         return NULL;
697 }
698
699 char *midend_solve(midend_data *me)
700 {
701     game_state *s;
702     char *msg;
703
704     if (!me->ourgame->can_solve)
705         return "This game does not support the Solve operation";
706
707     if (me->statepos < 1)
708         return "No game set up to solve";   /* _shouldn't_ happen! */
709
710     msg = "Solve operation failed";    /* game _should_ overwrite on error */
711     s = me->ourgame->solve(me->states[0], me->aux_info, &msg);
712     if (!s)
713         return msg;
714
715     /*
716      * Now enter the solved state as the next move.~|~
717      */
718     midend_stop_anim(me);
719     while (me->nstates > me->statepos)
720         me->ourgame->free_game(me->states[--me->nstates]);
721     ensure(me);
722     me->states[me->nstates] = s;
723     me->statepos = ++me->nstates;
724     me->anim_time = 0.0;
725     midend_finish_move(me);
726     midend_redraw(me);
727     activate_timer(me->frontend);
728     return NULL;
729 }