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