Home | History | Annotate | Line # | Download | only in cgram
cgram.c revision 1.26
      1 /* $NetBSD: cgram.c,v 1.26 2021/10/29 11:45:39 nia 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 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.26 2021/10/29 11:45:39 nia 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 static bool
     51 ch_isspace(char ch)
     52 {
     53 	return isspace((unsigned char)ch) != 0;
     54 }
     55 
     56 static bool
     57 ch_islower(char ch)
     58 {
     59 	return ch >= 'a' && ch <= 'z';
     60 }
     61 
     62 static bool
     63 ch_isupper(char ch)
     64 {
     65 	return ch >= 'A' && ch <= 'Z';
     66 }
     67 
     68 static bool
     69 ch_isalpha(char ch)
     70 {
     71 	return ch_islower(ch) || ch_isupper(ch);
     72 }
     73 
     74 static char
     75 ch_toupper(char ch)
     76 {
     77 	return ch_islower(ch) ? (char)(ch - 'a' + 'A') : ch;
     78 }
     79 
     80 static char
     81 ch_tolower(char ch)
     82 {
     83 	return ch_isupper(ch) ? (char)(ch - 'A' + 'a') : ch;
     84 }
     85 
     86 static int
     87 imax(int a, int b)
     88 {
     89 	return a > b ? a : b;
     90 }
     91 
     92 static int
     93 imin(int a, int b)
     94 {
     95 	return a < b ? a : b;
     96 }
     97 
     98 ////////////////////////////////////////////////////////////
     99 
    100 struct string {
    101 	char *s;
    102 	size_t len;
    103 	size_t cap;
    104 };
    105 
    106 struct stringarray {
    107 	struct string *v;
    108 	size_t num;
    109 };
    110 
    111 static void
    112 string_init(struct string *s)
    113 {
    114 	s->s = NULL;
    115 	s->len = 0;
    116 	s->cap = 0;
    117 }
    118 
    119 static void
    120 string_add(struct string *s, char ch)
    121 {
    122 	if (s->len >= s->cap) {
    123 		s->cap = 2 * s->cap + 16;
    124 		s->s = realloc(s->s, s->cap);
    125 		if (s->s == NULL)
    126 			errx(1, "Out of memory");
    127 	}
    128 	s->s[s->len++] = ch;
    129 }
    130 
    131 static void
    132 string_finish(struct string *s)
    133 {
    134 	string_add(s, '\0');
    135 	s->len--;
    136 }
    137 
    138 static void
    139 stringarray_init(struct stringarray *a)
    140 {
    141 	a->v = NULL;
    142 	a->num = 0;
    143 }
    144 
    145 static void
    146 stringarray_done(struct stringarray *a)
    147 {
    148 	for (size_t i = 0; i < a->num; i++)
    149 		free(a->v[i].s);
    150 	free(a->v);
    151 }
    152 
    153 static void
    154 stringarray_add(struct stringarray *a, struct string *s)
    155 {
    156 	size_t num = a->num++;
    157 	if (reallocarr(&a->v, a->num, sizeof(a->v[0])) != 0)
    158 		errx(1, "Out of memory");
    159 	a->v[num] = *s;
    160 }
    161 
    162 static void
    163 stringarray_dup(struct stringarray *dst, const struct stringarray *src)
    164 {
    165 	assert(dst->num == 0);
    166 	for (size_t i = 0; i < src->num; i++) {
    167 		struct string str;
    168 		string_init(&str);
    169 		for (const char *p = src->v[i].s; *p != '\0'; p++)
    170 			string_add(&str, *p);
    171 		string_finish(&str);
    172 		stringarray_add(dst, &str);
    173 	}
    174 }
    175 
    176 ////////////////////////////////////////////////////////////
    177 
    178 static struct stringarray lines;
    179 static struct stringarray sollines;
    180 static bool hinting;
    181 static int extent_x;
    182 static int extent_y;
    183 static int offset_x;
    184 static int offset_y;
    185 static int cursor_x;
    186 static int cursor_y;
    187 
    188 static int
    189 cur_max_x(void)
    190 {
    191 	return (int)lines.v[cursor_y].len;
    192 }
    193 
    194 static int
    195 cur_max_y(void)
    196 {
    197 	return extent_y - 1;
    198 }
    199 
    200 static char
    201 char_left_of_cursor(void)
    202 {
    203 	if (cursor_x > 0)
    204 		return lines.v[cursor_y].s[cursor_x - 1];
    205 	assert(cursor_y > 0);
    206 	return '\n'; /* eol of previous line */
    207 }
    208 
    209 static char
    210 char_at_cursor(void)
    211 {
    212 	if (cursor_x == cur_max_x())
    213 		return '\n';
    214 	return lines.v[cursor_y].s[cursor_x];
    215 }
    216 
    217 static void
    218 getquote(FILE *f)
    219 {
    220 	struct string line;
    221 	string_init(&line);
    222 
    223 	int ch;
    224 	while ((ch = fgetc(f)) != EOF) {
    225 		if (ch == '\n') {
    226 			string_finish(&line);
    227 			stringarray_add(&lines, &line);
    228 			string_init(&line);
    229 		} else if (ch == '\t') {
    230 			string_add(&line, ' ');
    231 			while (line.len % 8 != 0)
    232 				string_add(&line, ' ');
    233 		} else if (ch == '\b') {
    234 			if (line.len > 0)
    235 				line.len--;
    236 		} else {
    237 			string_add(&line, (char)ch);
    238 		}
    239 	}
    240 
    241 	stringarray_dup(&sollines, &lines);
    242 
    243 	extent_y = (int)lines.num;
    244 	for (int i = 0; i < extent_y; i++)
    245 		extent_x = imax(extent_x, (int)lines.v[i].len);
    246 }
    247 
    248 static void
    249 readfile(const char *name)
    250 {
    251 	FILE *f = fopen(name, "r");
    252 	if (f == NULL)
    253 		err(1, "%s", name);
    254 
    255 	getquote(f);
    256 
    257 	if (fclose(f) != 0)
    258 		err(1, "%s", name);
    259 }
    260 
    261 
    262 static void
    263 readquote(void)
    264 {
    265 	FILE *f = popen(_PATH_FORTUNE, "r");
    266 	if (f == NULL)
    267 		err(1, "%s", _PATH_FORTUNE);
    268 
    269 	getquote(f);
    270 
    271 	if (pclose(f) != 0)
    272 		exit(1); /* error message must come from child process */
    273 }
    274 
    275 static void
    276 encode(void)
    277 {
    278 	int key[26];
    279 
    280 	for (int i = 0; i < 26; i++)
    281 		key[i] = i;
    282 
    283 	for (int i = 26; i > 1; i--) {
    284 		int c = (int)(random() % i);
    285 		int t = key[i - 1];
    286 		key[i - 1] = key[c];
    287 		key[c] = t;
    288 	}
    289 
    290 	for (int y = 0; y < extent_y; y++) {
    291 		for (char *p = lines.v[y].s; *p != '\0'; p++) {
    292 			if (ch_islower(*p))
    293 				*p = (char)('a' + key[*p - 'a']);
    294 			if (ch_isupper(*p))
    295 				*p = (char)('A' + key[*p - 'A']);
    296 		}
    297 	}
    298 }
    299 
    300 static void
    301 substitute(char a, char b)
    302 {
    303 	char la = ch_tolower(a);
    304 	char ua = ch_toupper(a);
    305 	char lb = ch_tolower(b);
    306 	char ub = ch_toupper(b);
    307 
    308 	for (int y = 0; y < (int)lines.num; y++) {
    309 		for (char *p = lines.v[y].s; *p != '\0'; p++) {
    310 			if (*p == la)
    311 				*p = lb;
    312 			else if (*p == ua)
    313 				*p = ub;
    314 			else if (*p == lb)
    315 				*p = la;
    316 			else if (*p == ub)
    317 				*p = ua;
    318 		}
    319 	}
    320 }
    321 
    322 static bool
    323 is_solved(void)
    324 {
    325 	for (size_t i = 0; i < lines.num; i++)
    326 		if (strcmp(lines.v[i].s, sollines.v[i].s) != 0)
    327 			return false;
    328 	return true;
    329 }
    330 
    331 ////////////////////////////////////////////////////////////
    332 
    333 static void
    334 redraw(void)
    335 {
    336 	erase();
    337 
    338 	int max_y = imin(LINES - 1, extent_y - offset_y);
    339 	for (int y = 0; y < max_y; y++) {
    340 		move(y, 0);
    341 
    342 		int len = (int)lines.v[offset_y + y].len;
    343 		int max_x = imin(COLS - 1, len - offset_x);
    344 		const char *line = lines.v[offset_y + y].s;
    345 		const char *solline = sollines.v[offset_y + y].s;
    346 
    347 		for (int x = 0; x < max_x; x++) {
    348 			char ch = line[offset_x + x];
    349 			bool bold = hinting &&
    350 			    (ch == solline[offset_x + x] || !ch_isalpha(ch));
    351 
    352 			if (bold)
    353 				attron(A_BOLD);
    354 			addch(ch);
    355 			if (bold)
    356 				attroff(A_BOLD);
    357 		}
    358 		clrtoeol();
    359 	}
    360 
    361 	move(LINES - 1, 0);
    362 	addstr("~ to quit, * to cheat, ^pnfb to move");
    363 
    364 	if (is_solved()) {
    365 		if (extent_y + 1 - offset_y < LINES - 2)
    366 			move(extent_y + 1 - offset_y, 0);
    367 		else
    368 			addch(' ');
    369 		attron(A_BOLD | A_STANDOUT);
    370 		addstr("*solved*");
    371 		attroff(A_BOLD | A_STANDOUT);
    372 	}
    373 
    374 	move(cursor_y - offset_y, cursor_x - offset_x);
    375 
    376 	refresh();
    377 }
    378 
    379 ////////////////////////////////////////////////////////////
    380 
    381 static void
    382 saturate_cursor(void)
    383 {
    384 	cursor_y = imax(cursor_y, 0);
    385 	cursor_y = imin(cursor_y, cur_max_y());
    386 
    387 	assert(cursor_x >= 0);
    388 	cursor_x = imin(cursor_x, cur_max_x());
    389 }
    390 
    391 static void
    392 scroll_into_view(void)
    393 {
    394 	if (cursor_x < offset_x)
    395 		offset_x = cursor_x;
    396 	if (cursor_x > offset_x + COLS - 1)
    397 		offset_x = cursor_x - (COLS - 1);
    398 
    399 	if (cursor_y < offset_y)
    400 		offset_y = cursor_y;
    401 	if (cursor_y > offset_y + LINES - 2)
    402 		offset_y = cursor_y - (LINES - 2);
    403 }
    404 
    405 static bool
    406 can_go_left(void)
    407 {
    408 	return cursor_y > 0 ||
    409 	    (cursor_y == 0 && cursor_x > 0);
    410 }
    411 
    412 static bool
    413 can_go_right(void)
    414 {
    415 	return cursor_y < cur_max_y() ||
    416 	    (cursor_y == cur_max_y() && cursor_x < cur_max_x());
    417 }
    418 
    419 static void
    420 go_to_prev_line(void)
    421 {
    422 	cursor_y--;
    423 	cursor_x = cur_max_x();
    424 }
    425 
    426 static void
    427 go_to_next_line(void)
    428 {
    429 	cursor_x = 0;
    430 	cursor_y++;
    431 }
    432 
    433 static void
    434 go_left(void)
    435 {
    436 	if (cursor_x > 0)
    437 		cursor_x--;
    438 	else if (cursor_y > 0)
    439 		go_to_prev_line();
    440 }
    441 
    442 static void
    443 go_right(void)
    444 {
    445 	if (cursor_x < cur_max_x())
    446 		cursor_x++;
    447 	else if (cursor_y < cur_max_y())
    448 		go_to_next_line();
    449 }
    450 
    451 static void
    452 go_to_prev_word(void)
    453 {
    454 	while (can_go_left() && ch_isspace(char_left_of_cursor()))
    455 		go_left();
    456 
    457 	while (can_go_left() && !ch_isspace(char_left_of_cursor()))
    458 		go_left();
    459 }
    460 
    461 static void
    462 go_to_next_word(void)
    463 {
    464 	while (can_go_right() && !ch_isspace(char_at_cursor()))
    465 		go_right();
    466 
    467 	while (can_go_right() && ch_isspace(char_at_cursor()))
    468 		go_right();
    469 }
    470 
    471 static bool
    472 can_substitute_here(int ch)
    473 {
    474 	return isascii(ch) &&
    475 	    ch_isalpha((char)ch) &&
    476 	    cursor_x < cur_max_x() &&
    477 	    ch_isalpha(char_at_cursor());
    478 }
    479 
    480 static void
    481 handle_char_input(int ch)
    482 {
    483 	if (ch == char_at_cursor())
    484 		go_right();
    485 	else if (can_substitute_here(ch)) {
    486 		substitute(char_at_cursor(), (char)ch);
    487 		go_right();
    488 	} else
    489 		beep();
    490 }
    491 
    492 static bool
    493 handle_key(void)
    494 {
    495 	int ch = getch();
    496 
    497 	switch (ch) {
    498 	case 1:			/* ^A */
    499 	case KEY_HOME:
    500 		cursor_x = 0;
    501 		break;
    502 	case 2:			/* ^B */
    503 	case KEY_LEFT:
    504 		go_left();
    505 		break;
    506 	case 5:			/* ^E */
    507 	case KEY_END:
    508 		cursor_x = cur_max_x();
    509 		break;
    510 	case 6:			/* ^F */
    511 	case KEY_RIGHT:
    512 		go_right();
    513 		break;
    514 	case '\t':
    515 		go_to_next_word();
    516 		break;
    517 	case KEY_BTAB:
    518 		go_to_prev_word();
    519 		break;
    520 	case '\n':
    521 		go_to_next_line();
    522 		break;
    523 	case 12:		/* ^L */
    524 		clear();
    525 		break;
    526 	case 14:		/* ^N */
    527 	case KEY_DOWN:
    528 		cursor_y++;
    529 		break;
    530 	case 16:		/* ^P */
    531 	case KEY_UP:
    532 		cursor_y--;
    533 		break;
    534 	case KEY_PPAGE:
    535 		cursor_y -= LINES - 2;
    536 		break;
    537 	case KEY_NPAGE:
    538 		cursor_y += LINES - 2;
    539 		break;
    540 	case '*':
    541 		hinting = !hinting;
    542 		break;
    543 	case '~':
    544 		return false;
    545 	case KEY_RESIZE:
    546 		break;
    547 	default:
    548 		handle_char_input(ch);
    549 		break;
    550 	}
    551 	return true;
    552 }
    553 
    554 static void
    555 init(const char *filename)
    556 {
    557 	stringarray_init(&lines);
    558 	stringarray_init(&sollines);
    559 	srandom((unsigned int)time(NULL));
    560 	if (filename != NULL) {
    561 	    readfile(filename);
    562 	} else {
    563 	    readquote();
    564 	}
    565 	encode();
    566 
    567 	initscr();
    568 	cbreak();
    569 	noecho();
    570 	keypad(stdscr, true);
    571 }
    572 
    573 static void
    574 loop(void)
    575 {
    576 	for (;;) {
    577 		redraw();
    578 		if (!handle_key())
    579 			break;
    580 		saturate_cursor();
    581 		scroll_into_view();
    582 	}
    583 }
    584 
    585 static void
    586 done(void)
    587 {
    588 	endwin();
    589 
    590 	stringarray_done(&sollines);
    591 	stringarray_done(&lines);
    592 }
    593 
    594 
    595 static void __dead
    596 usage(void)
    597 {
    598 
    599 	fprintf(stderr, "usage: %s [file]\n", getprogname());
    600 	exit(1);
    601 }
    602 
    603 int
    604 main(int argc, char *argv[])
    605 {
    606 
    607 	setprogname(argv[0]);
    608 	if (argc != 1 && argc != 2)
    609 		usage();
    610 
    611 	init(argc > 1 ? argv[1] : NULL);
    612 	loop();
    613 	done();
    614 	return 0;
    615 }
    616