]> git.cameronkatri.com Git - bsdgames-darwin.git/blob - cgram/cgram.c
cgram: properly handle input errors
[bsdgames-darwin.git] / cgram / cgram.c
1 /* $NetBSD: cgram.c,v 1.12 2021/02/22 16:28:20 rillig Exp $ */
2
3 /*-
4 * Copyright (c) 2013, 2021 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by David A. Holland and Roland Illig.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #if defined(__RCSID) && !defined(lint)
34 __RCSID("$NetBSD: cgram.c,v 1.12 2021/02/22 16:28:20 rillig Exp $");
35 #endif
36
37 #include <assert.h>
38 #include <ctype.h>
39 #include <curses.h>
40 #include <err.h>
41 #include <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46
47 #include "pathnames.h"
48
49 ////////////////////////////////////////////////////////////
50
51 static char
52 ch_toupper(char ch)
53 {
54 return (char)toupper((unsigned char)ch);
55 }
56
57 static char
58 ch_tolower(char ch)
59 {
60 return (char)tolower((unsigned char)ch);
61 }
62
63 static bool
64 ch_isalpha(char ch)
65 {
66 return isalpha((unsigned char)ch) != 0;
67 }
68
69 static bool
70 ch_islower(char ch)
71 {
72 return islower((unsigned char)ch) != 0;
73 }
74
75 static bool
76 ch_isupper(char ch)
77 {
78 return isupper((unsigned char)ch) != 0;
79 }
80
81 static int
82 imax(int a, int b)
83 {
84 return a > b ? a : b;
85 }
86
87 static int
88 imin(int a, int b)
89 {
90 return a < b ? a : b;
91 }
92
93 ////////////////////////////////////////////////////////////
94
95 struct string {
96 char *s;
97 size_t len;
98 size_t cap;
99 };
100
101 struct stringarray {
102 struct string *v;
103 size_t num;
104 };
105
106 static void
107 string_init(struct string *s)
108 {
109 s->s = NULL;
110 s->len = 0;
111 s->cap = 0;
112 }
113
114 static void
115 string_add(struct string *s, char ch)
116 {
117 if (s->len >= s->cap) {
118 s->cap = 2 * s->cap + 16;
119 s->s = realloc(s->s, s->cap);
120 if (s->s == NULL)
121 errx(1, "Out of memory");
122 }
123 s->s[s->len++] = ch;
124 }
125
126 static void
127 string_finish(struct string *s)
128 {
129 string_add(s, '\0');
130 s->len--;
131 }
132
133 static void
134 stringarray_init(struct stringarray *a)
135 {
136 a->v = NULL;
137 a->num = 0;
138 }
139
140 static void
141 stringarray_cleanup(struct stringarray *a)
142 {
143 for (size_t i = 0; i < a->num; i++)
144 free(a->v[i].s);
145 free(a->v);
146 }
147
148 static void
149 stringarray_add(struct stringarray *a, struct string *s)
150 {
151 size_t num = a->num++;
152 a->v = realloc(a->v, a->num * sizeof a->v[0]);
153 if (a->v == NULL)
154 errx(1, "Out of memory");
155 a->v[num] = *s;
156 }
157
158 static void
159 stringarray_dup(struct stringarray *dst, const struct stringarray *src)
160 {
161 assert(dst->num == 0);
162 for (size_t i = 0; i < src->num; i++) {
163 struct string str;
164 string_init(&str);
165 for (const char *p = src->v[i].s; *p != '\0'; p++)
166 string_add(&str, *p);
167 string_finish(&str);
168 stringarray_add(dst, &str);
169 }
170 }
171
172 ////////////////////////////////////////////////////////////
173
174 static struct stringarray lines;
175 static struct stringarray sollines;
176 static bool hinting;
177 static int extent_x;
178 static int extent_y;
179 static int offset_x;
180 static int offset_y;
181 static int cursor_x;
182 static int cursor_y;
183
184 static int
185 cur_max_x(void)
186 {
187 return (int)lines.v[cursor_y].len;
188 }
189
190 static int
191 cur_max_y(void)
192 {
193 return extent_y - 1;
194 }
195
196 static void
197 readquote(void)
198 {
199 FILE *f = popen(_PATH_FORTUNE, "r");
200 if (f == NULL)
201 err(1, "%s", _PATH_FORTUNE);
202
203 struct string line;
204 string_init(&line);
205
206 int ch;
207 while ((ch = fgetc(f)) != EOF) {
208 if (ch == '\n') {
209 string_finish(&line);
210 stringarray_add(&lines, &line);
211 string_init(&line);
212 } else if (ch == '\t') {
213 string_add(&line, ' ');
214 while (line.len % 8 != 0)
215 string_add(&line, ' ');
216 } else if (ch == '\b') {
217 if (line.len > 0)
218 line.len--;
219 } else {
220 string_add(&line, (char)ch);
221 }
222 }
223
224 stringarray_dup(&sollines, &lines);
225
226 extent_y = (int)lines.num;
227 for (int i = 0; i < extent_y; i++)
228 extent_x = imax(extent_x, (int)lines.v[i].len);
229
230 if (pclose(f) != 0)
231 exit(1); /* error message must come from child process */
232 }
233
234 static void
235 encode(void)
236 {
237 int key[26];
238
239 for (int i = 0; i < 26; i++)
240 key[i] = i;
241
242 for (int i = 26; i > 1; i--) {
243 int c = (int)(random() % i);
244 int t = key[i - 1];
245 key[i - 1] = key[c];
246 key[c] = t;
247 }
248
249 for (int y = 0; y < extent_y; y++) {
250 for (char *p = lines.v[y].s; *p != '\0'; p++) {
251 if (ch_islower(*p))
252 *p = (char)('a' + key[*p - 'a']);
253 if (ch_isupper(*p))
254 *p = (char)('A' + key[*p - 'A']);
255 }
256 }
257 }
258
259 static bool
260 substitute(char ch)
261 {
262 assert(cursor_x >= 0 && cursor_x < extent_x);
263 assert(cursor_y >= 0 && cursor_y < extent_y);
264 if (cursor_x >= cur_max_x()) {
265 beep();
266 return false;
267 }
268
269 char och = lines.v[cursor_y].s[cursor_x];
270 if (!ch_isalpha(och)) {
271 beep();
272 return false;
273 }
274
275 char loch = ch_tolower(och);
276 char uoch = ch_toupper(och);
277 char lch = ch_tolower(ch);
278 char uch = ch_toupper(ch);
279
280 for (int y = 0; y < (int)lines.num; y++) {
281 for (char *p = lines.v[y].s; *p != '\0'; p++) {
282 if (*p == loch)
283 *p = lch;
284 else if (*p == uoch)
285 *p = uch;
286 else if (*p == lch)
287 *p = loch;
288 else if (*p == uch)
289 *p = uoch;
290 }
291 }
292 return true;
293 }
294
295 ////////////////////////////////////////////////////////////
296
297 static bool
298 is_solved(void)
299 {
300 for (size_t i = 0; i < lines.num; i++)
301 if (strcmp(lines.v[i].s, sollines.v[i].s) != 0)
302 return false;
303 return true;
304 }
305
306 static void
307 redraw(void)
308 {
309 erase();
310
311 int max_y = imin(LINES - 1, extent_y - offset_y);
312 for (int y = 0; y < max_y; y++) {
313 move(y, 0);
314
315 int len = (int)lines.v[offset_y + y].len;
316 int max_x = imin(COLS - 1, len - offset_x);
317 const char *line = lines.v[offset_y + y].s;
318 const char *solline = sollines.v[offset_y + y].s;
319
320 for (int x = 0; x < max_x; x++) {
321 char ch = line[offset_x + x];
322 bool bold = hinting &&
323 ch == solline[offset_x + x] &&
324 ch_isalpha(ch);
325
326 if (bold)
327 attron(A_BOLD);
328 addch(ch);
329 if (bold)
330 attroff(A_BOLD);
331 }
332 clrtoeol();
333 }
334
335 move(LINES - 1, 0);
336 if (is_solved())
337 addstr("*solved* ");
338 addstr("~ to quit, * to cheat, ^pnfb to move");
339
340 move(cursor_y - offset_y, cursor_x - offset_x);
341
342 refresh();
343 }
344
345 static void
346 opencurses(void)
347 {
348 initscr();
349 cbreak();
350 noecho();
351 keypad(stdscr, true);
352 }
353
354 static void
355 closecurses(void)
356 {
357 endwin();
358 }
359
360 ////////////////////////////////////////////////////////////
361
362 static void
363 saturate_cursor(void)
364 {
365 cursor_y = imax(cursor_y, 0);
366 cursor_y = imin(cursor_y, cur_max_y());
367
368 assert(cursor_x >= 0);
369 cursor_x = imin(cursor_x, cur_max_x());
370 }
371
372 static void
373 scroll_into_view(void)
374 {
375 if (cursor_x < offset_x)
376 offset_x = cursor_x;
377 if (cursor_x > offset_x + COLS - 1)
378 offset_x = cursor_x - (COLS - 1);
379
380 if (cursor_y < offset_y)
381 offset_y = cursor_y;
382 if (cursor_y > offset_y + LINES - 2)
383 offset_y = cursor_y - (LINES - 2);
384 }
385
386 static void
387 handle_char_input(int ch)
388 {
389 if (isascii(ch) && ch_isalpha((char)ch)) {
390 if (substitute((char)ch)) {
391 if (cursor_x < cur_max_x())
392 cursor_x++;
393 if (cursor_x == cur_max_x() &&
394 cursor_y < cur_max_y()) {
395 cursor_x = 0;
396 cursor_y++;
397 }
398 }
399 } else if (cursor_x < cur_max_x() &&
400 ch == lines.v[cursor_y].s[cursor_x]) {
401 cursor_x++;
402 if (cursor_x == cur_max_x() &&
403 cursor_y < cur_max_y()) {
404 cursor_x = 0;
405 cursor_y++;
406 }
407 } else {
408 beep();
409 }
410 }
411
412 static bool
413 handle_key(void)
414 {
415 int ch = getch();
416
417 switch (ch) {
418 case 1: /* ^A */
419 case KEY_HOME:
420 cursor_x = 0;
421 break;
422 case 2: /* ^B */
423 case KEY_LEFT:
424 if (cursor_x > 0) {
425 cursor_x--;
426 } else if (cursor_y > 0) {
427 cursor_y--;
428 cursor_x = cur_max_x();
429 }
430 break;
431 case 5: /* ^E */
432 case KEY_END:
433 cursor_x = cur_max_x();
434 break;
435 case 6: /* ^F */
436 case KEY_RIGHT:
437 if (cursor_x < cur_max_x()) {
438 cursor_x++;
439 } else if (cursor_y < cur_max_y()) {
440 cursor_y++;
441 cursor_x = 0;
442 }
443 break;
444 case 12: /* ^L */
445 clear();
446 break;
447 case 14: /* ^N */
448 case KEY_DOWN:
449 cursor_y++;
450 break;
451 case 16: /* ^P */
452 case KEY_UP:
453 cursor_y--;
454 break;
455 case KEY_PPAGE:
456 cursor_y -= LINES - 2;
457 break;
458 case KEY_NPAGE:
459 cursor_y += LINES - 2;
460 break;
461 case '*':
462 hinting = !hinting;
463 break;
464 case '~':
465 return false;
466 default:
467 handle_char_input(ch);
468 break;
469 }
470 return true;
471 }
472
473 static void
474 init(void)
475 {
476 stringarray_init(&lines);
477 stringarray_init(&sollines);
478 srandom((unsigned int)time(NULL));
479 readquote();
480 encode();
481 opencurses();
482 }
483
484 static void
485 loop(void)
486 {
487 for (;;) {
488 redraw();
489 if (!handle_key())
490 break;
491 saturate_cursor();
492 scroll_into_view();
493 }
494 }
495
496 static void
497 clean_up(void)
498 {
499 closecurses();
500 stringarray_cleanup(&sollines);
501 stringarray_cleanup(&lines);
502 }
503
504 ////////////////////////////////////////////////////////////
505
506 int
507 main(void)
508 {
509 init();
510 loop();
511 clean_up();
512 }