]> git.draconx.ca Git - rrace.git/blob - src/curses.c
Use new packed option format from gen-options.awk.
[rrace.git] / src / curses.c
1 /*
2  * Curses UI for slide puzzle game
3  * Copyright © 2022-2023 Nick Bowler
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17  */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <locale.h>
22 #include <assert.h>
23 #include <getopt.h>
24 #include <curses.h>
25
26 #include "help.h"
27 #include "xtra.h"
28 #include "version.h"
29
30 #include "cursesui.h"
31 #include "cursesopt.h"
32
33 enum {
34         GAME_YPOS = 1 // top row of game and goal areas.
35 };
36
37 static const char *progname = "rrace";
38
39 static struct app_state state;
40
41 static void print_version(void)
42 {
43         version_print_head("rrace-curses", stdout);
44         puts("License GPLv3+: GNU GPL version 3 or any later version");
45         puts("This is free software: you are free to change and redistribute it.");
46         puts("There is NO WARRANTY, to the extent permitted by law.");
47 }
48
49 static void print_usage(FILE *f)
50 {
51         fprintf(f, "Usage: %s [options]\n", progname);
52         if (f != stdout)
53                 fprintf(f, "Try %s --help for more information.\n", progname);
54 }
55
56 static void print_help(const struct option *lopts)
57 {
58         struct lopt_help help = {0};
59         const struct option *opt;
60
61         print_usage(stdout);
62
63         putchar('\n');
64         puts("Options:");
65         for (opt = lopts; opt->name; opt++) {
66                 if (!lopt_get_help(opt, &help))
67                         continue;
68                 help_print_option(opt, help.arg, help.desc, 20);
69         }
70         putchar('\n');
71
72         printf("Report bugs to <%s>.\n", PACKAGE_BUGREPORT);
73 }
74
75 static void draw_tile(WINDOW **win, unsigned colour, unsigned selected,
76                       unsigned x, unsigned y, unsigned start_column)
77 {
78         WINDOW *border = win[PLAYWIN_TILEBORDER], *fill = win[PLAYWIN_TILEFILL];
79         int w, h, attr, ch, bc = selected ? '#' : 0;
80
81         assert(colour < TILE_MAX);
82         attr = COLOR_PAIR(colour);
83         switch (colour) {
84         case TILE_RED:    ch = 'X'; break;
85         case TILE_ORANGE: ch = '|'; break;
86         case TILE_GREEN:  ch = '+'; break;
87         case TILE_YELLOW: ch = '~'; attr |= A_BOLD; break;
88         case TILE_BLUE:   ch = 'o'; attr |= A_BOLD; break;
89         case TILE_WHITE:  ch = '.'; attr |= A_BOLD; break;
90
91         case TILE_EMPTY: attr = A_BOLD|COLOR_PAIR(RR_COLOUR_SHADOW);
92         }
93
94         getmaxyx(border, h, w);
95         w = 2*(w+1)/2;
96
97         if (mvwin(border, 1+GAME_YPOS+h*y, start_column+w*x) == ERR)
98                 return;
99
100         if (colour != TILE_EMPTY) {
101                 mvderwin(fill, 1, 1);
102                 wbkgdset(fill, A_REVERSE|attr|ch);
103                 werase(fill);
104         } else {
105                 werase(border);
106         }
107
108         if (bc || colour) {
109                 wattrset(border, attr);
110                 wborder(border, bc, bc, bc, bc, bc, bc, bc, bc);
111         }
112
113         wnoutrefresh(border);
114 }
115
116 static int
117 redraw_tile(WINDOW **win, unsigned x, unsigned y, unsigned start_column,
118             uint_least32_t *gp, unsigned selected)
119 {
120         unsigned tile = board_tile(gp, 5*y+x);
121
122         assert(tile < TILE_MAX);
123         draw_tile(win, tile, selected, x, y, start_column);
124         return tile;
125 }
126
127 static void redraw_area_border(WINDOW **win, unsigned x, unsigned sz)
128 {
129         int w, h, tr = 0, rs = 0, br = 0, bs = 0, bl = 0;
130         WINDOW *area = win[PLAYWIN_AREA];
131
132         getmaxyx(stdscr, h, w);
133
134         if (h <= GAME_YPOS+1) {
135                 bl = ACS_ULCORNER, br = ACS_URCORNER;
136         } else if (h <= 3*sz+GAME_YPOS+1) {
137                 bl = br = ACS_VLINE, bs = ' ';
138         }
139
140         if (w <= x+1) {
141                 tr = ACS_ULCORNER, br = ACS_LLCORNER;
142         } else if (w <= 6*sz+x+2) {
143                 tr = ACS_HLINE, rs = ' ';
144                 br = br ? ' ' : ACS_HLINE;
145         }
146
147         wborder(area, 0, rs, 0, bs, 0, tr, bl, br);
148         wnoutrefresh(area);
149 }
150
151 static void curs_redraw_game(struct app_state *state, uint_fast32_t mask)
152 {
153         uint_least32_t buf[3], *gp = state->board.game;
154         int i;
155
156         if (mask == -1)
157                 redraw_area_border(state->gamewin, 2, 5);
158
159         if (state->view_goal_on_game)
160                 gp = game_overlay_goal(&state->board, buf);
161
162         for (i = 0; i < 25; i++) {
163                 if (mask & 1) {
164                         redraw_tile(state->gamewin, i%5, i/5,
165                                     4, gp, i == state->cursor);
166                 }
167                 mask >>= 1;
168         }
169 }
170
171 static void curs_redraw_goal(struct app_state *state, uint_fast32_t mask)
172 {
173         uint_least32_t gp[3] = {
174                 state->board.goal[0],
175                 state->board.goal[1],
176                 state->board.goal[2]
177         };
178         int i, x, y;
179
180         if (!state->goalwin[PLAYWIN_AREA])
181                 return;
182
183         getbegyx(state->goalwin[PLAYWIN_AREA], y, x);
184         if (mask == -1)
185                 redraw_area_border(state->goalwin, x, 3);
186
187         for (i = 0; i < 9; i++) {
188                 if (mask & 1) {
189                         redraw_tile(state->goalwin, i%3, i/3, x+2, gp, 0);
190                 }
191                 mask >>= 1;
192         }
193 }
194
195 /* Thin wrapper around wresize which returns ERR if support is unavailable. */
196 static int do_wresize(WINDOW *window, int h, int w)
197 {
198 #if HAVE_CURSES_WRESIZE
199         return wresize(window, h, w);
200 #endif
201         return ERR;
202 }
203
204 static WINDOW *realloc_area(WINDOW **orig, int h, int w, int y, int x)
205 {
206         WINDOW *win = *orig;
207
208         if (win) {
209                 if (do_wresize(win, h, w) != ERR) {
210                         mvwin(win, y, x);
211                         return win;
212                 }
213
214                 delwin(win);
215         }
216
217         if (w > 0 && h > 0)
218                 return *orig = subwin(stdscr, h, w, y, x);
219         return *orig = NULL;
220 }
221
222 static void realloc_tiles(WINDOW **win, int h)
223 {
224         WINDOW *border = win[PLAYWIN_TILEBORDER], *fill = win[PLAYWIN_TILEFILL];
225         int w = 2*h - 1;
226
227         if (fill && border) {
228                 int old_w, old_h;
229
230                 if (do_wresize(fill, h-2, w-2) != ERR
231                     && do_wresize(border, h, w) != ERR)
232                         return;
233
234                 getmaxyx(border, old_h, old_w);
235                 if (old_h == h)
236                         return;
237         }
238
239         if (fill)
240                 delwin(fill);
241         if (border)
242                 delwin(border);
243
244         win[PLAYWIN_TILEBORDER] = border = newwin(h, w, 0, 0);
245         win[PLAYWIN_TILEFILL] = derwin(border, h-2, w-2, 1, 1);
246 }
247
248 static void setup_mainwin(struct app_state *state)
249 {
250         int w, h, gamesz, goalsz, scr_w, scr_h, split;
251
252         getmaxyx(stdscr, scr_h, scr_w);
253
254         /* First try to fit the game tiles based on window height. */
255         gamesz = MAX(3, (scr_h - 4) / 5);
256
257         /* Adjust downward until we can fit smallest possible goal area. */
258         for (; split = 5+10*gamesz, gamesz > 3; gamesz--) {
259                 if (split + 20 < scr_w)
260                         break;
261         }
262
263         /* Pick a goal size that will fit in the remaining area */
264         goalsz = MAX(3, (scr_w - split - 4) / 6);
265         if (goalsz >= gamesz)
266                 goalsz = MAX(3, gamesz - 1);
267
268         realloc_tiles(state->gamewin, gamesz);
269         realloc_tiles(state->goalwin, goalsz);
270
271         /* Frame for game area */
272         w = MIN(scr_w-2, 3+10*gamesz);
273         h = MIN(scr_h-GAME_YPOS, 2+5*gamesz);
274         realloc_area(&state->gamewin[PLAYWIN_AREA], h, w, GAME_YPOS, 2);
275
276         /* Frame for goal area */
277         w = MIN(scr_w-split, 3+6*goalsz);
278         h = MIN(scr_h-GAME_YPOS, 2+3*goalsz);
279         realloc_area(&state->goalwin[PLAYWIN_AREA], h, w, GAME_YPOS, split);
280
281         /* Status area */
282         w = MAX(0, scr_w-split-1);
283         realloc_area(&state->timer, 1, w, GAME_YPOS+h, split+1);
284
285         /* Toolbar */
286         realloc_area(&state->toolbar, 1, scr_w, scr_h-1, 0);
287         curs_draw_toolbar(state);
288 }
289
290 static void app_initialize(int argc, char **argv)
291 {
292         int enable_mouse = 1;
293         int opt;
294
295         XTRA_PACKED_LOPTS(lopts);
296
297         if (argc > 0)
298                 progname = argv[0];
299
300         while ((opt = getopt_long(argc, argv, SOPT_STRING, lopts, 0)) != -1) {
301                 switch (opt) {
302                 case LOPT_MOUSE:
303                         enable_mouse = 2;
304                         break;
305                 case LOPT_NO_MOUSE:
306                         enable_mouse = 0;
307                         break;
308                 case LOPT_VERSION:
309                         print_version();
310                         exit(EXIT_SUCCESS);
311                 case LOPT_HELP:
312                         print_help(lopts);
313                         exit(EXIT_SUCCESS);
314                 default:
315                         print_usage(stderr);
316                         exit(EXIT_FAILURE);
317                 }
318         }
319
320         game_reset(&state.board);
321         state.cursor = -1;
322
323         initscr();
324         start_color();
325         curs_set(0);
326
327         cbreak();
328         keypad(stdscr, TRUE);
329         if (enable_mouse) {
330                 /*
331                  * While we only care about a subset of these events, for
332                  * some reason with ncurses failing to enable all of them
333                  * causes timeout to stop working when disabled buttons are
334                  * pressed (or released).
335                  *
336                  * It is not known if other curses have this problem; at least
337                  * pdcurses does not, but the extra events should be harmless
338                  * in any case.
339                  */
340 #if HAVE_CURSES_MOUSE_SUPPORT
341                 unsigned long mask = BUTTON1_PRESSED | BUTTON1_RELEASED
342                                    | BUTTON2_PRESSED | BUTTON2_RELEASED
343                                    | BUTTON3_PRESSED | BUTTON3_RELEASED
344 #ifdef BUTTON4_PRESSED
345                                    | BUTTON4_PRESSED | BUTTON4_RELEASED
346 #endif
347 #ifdef BUTTON5_PRESSED
348                                    | BUTTON5_PRESSED | BUTTON5_RELEASED
349 #endif
350                                    ;
351 #if HAVE_CURSES_MOUSE_SET
352                 mouse_set(mask);
353 #elif HAVE_CURSES_MOUSEMASK
354                 mousemask(mask, NULL);
355 #endif
356 #if HAVE_CURSES_MOUSEINTERVAL
357                 mouseinterval(0);
358 #endif
359 #endif /* HAVE_CURSES_MOUSE_SUPPORT */
360         }
361
362         noecho();
363
364         init_pair(TILE_RED, COLOR_RED, COLOR_BLACK);
365         init_pair(TILE_ORANGE, COLOR_YELLOW, COLOR_BLACK);
366         init_pair(TILE_YELLOW, COLOR_YELLOW, COLOR_BLACK);
367         init_pair(TILE_GREEN, COLOR_GREEN, COLOR_BLACK);
368         init_pair(TILE_BLUE, COLOR_BLUE, COLOR_BLACK);
369         init_pair(TILE_WHITE, COLOR_WHITE, COLOR_BLACK);
370         init_pair(RR_COLOUR_SHADOW, COLOR_BLACK, COLOR_BLACK);
371         init_pair(RR_COLOUR_TOOLBAR, COLOR_CYAN, COLOR_BLACK);
372
373         setup_mainwin(&state);
374         refresh();
375 }
376
377 static void update_timer(struct app_state *state, uint_fast32_t ms)
378 {
379         unsigned sec, min;
380
381         state->timer_ms = ms;
382         sec = ms / 1000; ms %= 1000;
383         min = sec / 60; sec %= 60;
384         mvwprintw(state->timer, 0, 0, "Time: %u:%.2u.%.3u",
385                   min, sec, (unsigned)ms);
386         wclrtoeol(state->timer);
387         wnoutrefresh(state->timer);
388 }
389
390 static uint_fast32_t do_move(struct app_state *state, int x, int y)
391 {
392         uint_fast32_t mask;
393
394         if ((mask = game_do_move(&state->board, x, y)) != 0) {
395                 uint_fast32_t goal = game_check_goal(&state->board);
396
397                 if (state->view_goal_on_game) {
398                         state->view_goal_on_game = 0;
399                         mask |= goal;
400                 }
401
402                 if (goal == 0) {
403                         /* Solved! */
404                         update_timer(state, game_finish(&state->board));
405                         mask |= ~GOAL_MASK;
406                         state->cursor = -1;
407                         timeout(-1);
408                 }
409
410                 curs_redraw_game(state, mask);
411                 doupdate();
412         }
413
414         return mask;
415 }
416
417 static void do_reset_cursor(struct app_state *state)
418 {
419         state->cursor = 5*state->board.y + state->board.x;
420 }
421
422 void curs_new_game(struct app_state *state)
423 {
424         game_reset(&state->board);
425
426         do_reset_cursor(state);
427         state->view_goal_on_game = 0;
428         curs_redraw_game(state, -1);
429         curs_redraw_goal(state, -1);
430         update_timer(state, 0);
431         doupdate();
432
433         timeout(33);
434         game_begin(&state->board);
435 }
436
437 #if HAVE_CURSES_MOUSE_SUPPORT
438 /*
439  * Given x, y as screen coordinates, record which (if any) toolbar function
440  * label is at that position, to be performed later.
441  *
442  * If no function is indicated, returns zero.  Otherwise, returns non-zero.
443  */
444 static int press_toolbar(struct app_state *state, int x, int y)
445 {
446         return state->toolbar_click = curs_toolbar_mouse_func(state, x, y);
447 }
448
449 /*
450  * Given x, y as screen coordinates, perform the toolbar action.
451  *
452  * Perform the action previously recorded by press_toolbar, if and only if
453  * the x, y screen coordinates correspond to the same function.
454  */
455 static void release_toolbar(struct app_state *state, int x, int y)
456 {
457         int func = curs_toolbar_mouse_func(state, x, y);
458
459         if (func && state->toolbar_click == func) {
460                 curs_execute_function(state, func);
461         }
462
463         state->toolbar_click = 0;
464 }
465
466 /*
467  * Given x, y as screen coordinates, determine which (if any) game tile is
468  * at that position.
469  *
470  * If there is no such tile, performs no action and returns 0.
471  *
472  * Otherwise, attempts to move that tile and returns non-zero.
473  */
474 static int press_tile(struct app_state *state, int x, int y)
475 {
476         int game_x, game_y, tile_w, tile_h;
477         uint_fast32_t cursor_mask, move_mask;
478
479         getbegyx(state->gamewin[PLAYWIN_AREA], game_y, game_x);
480         getmaxyx(state->gamewin[PLAYWIN_TILEBORDER], tile_h, tile_w);
481         tile_w += tile_w & 1;
482
483         /* special case the left spacer column */
484         if (x == game_x+1)
485                 x++;
486
487         if (x < game_x+2 || (x -= game_x+2)/5 >= tile_w)
488                 return 0;
489         if (y < game_y+1 || (y -= game_y+1)/5 >= tile_h)
490                 return 0;
491
492         /* OK, selected a tile. */
493         x /= tile_w;
494         y /= tile_h;
495
496         /* Disable the keyboard cursor due to mouse action */
497         cursor_mask = state->cursor < 0 ? -1 : 1ul << state->cursor;
498         state->cursor = -1;
499
500         move_mask = do_move(state, x, y);
501         if ((cursor_mask & move_mask) == 0) {
502                 curs_redraw_game(state, cursor_mask);
503                 doupdate();
504         }
505
506         return 1;
507 }
508
509 static void do_mouse(struct app_state *state)
510 {
511         unsigned long bstate;
512         int x, y;
513
514 #if HAVE_CURSES_GETMOUSE_NCURSES
515         MEVENT mev;
516
517         if (getmouse(&mev) == ERR)
518                 return;
519
520         x = mev.x, y = mev.y;
521         bstate = mev.bstate;
522 #elif HAVE_CURSES_REQUEST_MOUSE_POS
523         request_mouse_pos();
524         x = MOUSE_X_POS;
525         y = MOUSE_Y_POS;
526
527         bstate = 0;
528
529 #define set_bstate_helper(button) do { if (BUTTON_CHANGED(button)) \
530         switch (BUTTON_STATUS(button)) { \
531         case BUTTON_RELEASED: bstate |= BUTTON ## button ##  _RELEASED; break; \
532         case BUTTON_PRESSED:  bstate |= BUTTON ## button ##  _PRESSED; break; \
533         } \
534 } while (0);
535
536         set_bstate_helper(1);
537         set_bstate_helper(3);
538 #endif
539         if (bstate & BUTTON3_PRESSED) {
540                 state->view_goal_on_game = 1;
541                 curs_redraw_game(state, game_check_goal(&state->board));
542                 doupdate();
543         }
544
545         if (bstate & BUTTON3_RELEASED) {
546                 state->view_goal_on_game = 0;
547                 curs_redraw_game(state, game_check_goal(&state->board));
548                 doupdate();
549         }
550
551         /* Ignore button1 if holding button3 to view goal */
552         if (state->view_goal_on_game & 1)
553                 return;
554
555         if (bstate & BUTTON1_PRESSED) {
556                 if (press_toolbar(state, x, y));
557                 else if (press_tile(state, x, y));
558         }
559
560         if (bstate & BUTTON1_RELEASED) {
561                 release_toolbar(state, x, y);
562         }
563 }
564 #endif /* HAVE_CURSES_MOUSE_SUPPORT */
565
566 static void do_move_cursor(struct app_state *state, int c)
567 {
568         uint_fast32_t mask = 0;
569
570         if (state->cursor < 0) {
571                 /* Cursor was hidden; reset it */
572                 do_reset_cursor(state);
573         } else {
574                 mask = 1ul << state->cursor;
575         }
576
577         if (state->view_goal_on_game) {
578                 state->view_goal_on_game = 0;
579                 mask |= game_check_goal(&state->board);
580         }
581
582         switch (c) {
583         case KEY_UP:
584                 if ((state->cursor -= 5) < 0)
585                         state->cursor += 25;
586                 break;
587         case KEY_DOWN:
588                 if ((state->cursor += 5) >= 25)
589                         state->cursor -= 25;
590                 break;
591         case KEY_LEFT:
592                 if ((state->cursor -= 1) % 5 == 4 || state->cursor < 0)
593                         state->cursor += 5;
594                 break;
595         case KEY_RIGHT:
596                 if ((state->cursor += 1) % 5 == 0)
597                         state->cursor -= 5;
598                 break;
599         }
600
601         curs_redraw_game(state, mask | 1ul << state->cursor);
602         doupdate();
603 }
604
605 static void do_keystroke(struct app_state *state, int c)
606 {
607         int last_input = state->last_input;
608         state->last_input = c;
609
610         switch (c) {
611         case KEY_DOWN: case KEY_UP: case KEY_LEFT: case KEY_RIGHT:
612                 do_move_cursor(state, c);
613                 break;
614         case '\t':
615                 state->view_goal_on_game ^= 2u;
616                 curs_redraw_game(state, game_check_goal(&state->board));
617                 doupdate();
618                 break;
619         case ' ':
620                 if (!(state->view_goal_on_game & 1) && state->cursor >= 0)
621                         do_move(state, state->cursor%5, state->cursor/5);
622                 break;
623         }
624
625         /* ESC+# keys */
626         if (last_input == '\33' && c >= '0' && c <= '9') {
627                 curs_execute_function(state, (c -= '0') == 0 ? 10 : c);
628         }
629
630         /* F# keys */
631         if (c >= KEY_F(1) && c <= KEY_F(10)) {
632                 curs_execute_function(state, c - KEY_F0);
633         }
634 }
635
636 /* One iteration of main input loop */
637 void do_mainloop(struct app_state *state)
638 {
639         int c = getch();
640
641         switch (c) {
642 #ifdef KEY_RESIZE
643         case KEY_RESIZE:
644                 setup_mainwin(state);
645                 clear();
646                 refresh();
647                 curs_redraw_game(state, -1);
648                 curs_redraw_goal(state, -1);
649                 curs_draw_toolbar(state);
650                 update_timer(state, state->timer_ms);
651                 doupdate();
652                 break;
653 #endif
654 #if HAVE_CURSES_MOUSE_SUPPORT
655         case KEY_MOUSE:
656                 do_mouse(state);
657                 break;
658 #endif
659         default:
660                 do_keystroke(state, c);
661         case ERR:;
662         }
663
664         if (state->board.x <= 4) {
665                 update_timer(state, game_elapsed(&state->board));
666                 doupdate();
667         }
668 }
669
670 int main(int argc, char **argv)
671 {
672         setlocale(LC_ALL, "");
673         app_initialize(argc, argv);
674
675         curs_new_game(&state);
676         while (1)
677                 do_mainloop(&state);
678         abort();
679 }