koh_term.c

4.7 KB · raw

1#include "koh_term.h"23#include <errno.h>4#include <poll.h>5#include <signal.h>6#include <stdio.h>7#include <sys/ioctl.h>8#include <termios.h>9#include <unistd.h>1011static struct termios koh_saved;12static int koh_have_saved = 0;1314/* A kill cannot run the caller's cleanup, so raw mode installs its own exit:15 * restore the terminal, leave the alternate screen, and die with the signal16 * encoded in the status the shell expects. The previous handlers go back when17 * raw mode ends so the rest of the process sees the default disposition. */18static const int koh_fatal_signals[] = { SIGTERM, SIGHUP, SIGQUIT };19#define KOH_FATAL_COUNT 32021static struct sigaction koh_prev_handlers[KOH_FATAL_COUNT];22static int koh_handler_count = 0;2324static void koh_leave_on_signal(int sig) {25	if (koh_have_saved) {26		tcsetattr(STDIN_FILENO, TCSAFLUSH, &koh_saved);27	}28	static const char leave[] = "\x1b[?25h\x1b[?1049l";29	ssize_t ignored = write(STDOUT_FILENO, leave, sizeof(leave) - 1);30	(void)ignored;31	_exit(128 + sig);32}3334static void koh_install_handlers(void) {35	if (koh_handler_count > 0) {36		return;37	}38	struct sigaction action = { .sa_handler = koh_leave_on_signal };39	sigemptyset(&action.sa_mask);40	action.sa_flags = 0;41	for (int i = 0; i < KOH_FATAL_COUNT; i++) {42		if (sigaction(koh_fatal_signals[i], &action, &koh_prev_handlers[i]) != 0) {43			break;44		}45		koh_handler_count = i + 1;46	}47}4849static void koh_restore_handlers(void) {50	for (int i = 0; i < koh_handler_count; i++) {51		sigaction(koh_fatal_signals[i], &koh_prev_handlers[i], NULL);52	}53	koh_handler_count = 0;54}5556int koh_term_raw(int enable) {57	if (enable) {58		if (!isatty(STDIN_FILENO)) {59			return 0;60		}61		if (tcgetattr(STDIN_FILENO, &koh_saved) != 0) {62			return 0;63		}64		koh_have_saved = 1;65		struct termios raw = koh_saved;66		/* No line buffering, no echo, no flow control, no signal keys: the67		 * view wants the bytes and has to be able to clean up after itself. */68		raw.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ISIG | IEXTEN);69		raw.c_iflag &= (tcflag_t) ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP);70		raw.c_cc[VMIN] = 1;71		raw.c_cc[VTIME] = 0;72		if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) != 0) {73			koh_have_saved = 0;74			return 0;75		}76		koh_install_handlers();77		return 1;78	}79	if (koh_have_saved) {80		tcsetattr(STDIN_FILENO, TCSAFLUSH, &koh_saved);81		koh_have_saved = 0;82	}83	koh_restore_handlers();84	return 1;85}8687int koh_term_size(int *rows, int *cols) {88	struct winsize size;89	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0 && size.ws_row > 0 && size.ws_col > 0) {90		*rows = (int)size.ws_row;91		*cols = (int)size.ws_col;92		return 1;93	}94	*rows = 24;95	*cols = 80;96	return 0;97}9899static int koh_poll_input(int milliseconds) {100	struct pollfd p;101	p.fd = STDIN_FILENO;102	p.events = POLLIN;103	p.revents = 0;104	return poll(&p, 1, milliseconds) > 0;105}106107/* One keystroke, blocking if there is none yet. Both koh_read_key and108 * koh_wait_key go through here so a key means the same thing either way. */109static int koh_read_one(char *buf, int cap) {110	if (cap <= 0) {111		return 0;112	}113	ssize_t n = read(STDIN_FILENO, buf, 1);114	if (n <= 0) {115		return 0;116	}117	int total = 1;118	/* An arrow key arrives as ESC [ A, usually in one burst but not always,119	 * so give the rest of the sequence a moment to show up. */120	if (buf[0] == 0x1b) {121		if (koh_poll_input(25)) {122			ssize_t m = read(STDIN_FILENO, buf + 1, (size_t)(cap - 1));123			if (m > 0) {124				total += (int)m;125			}126		}127		return total;128	}129	/* Otherwise deliver exactly one character: the continuation bytes of a130	 * multi-byte character are gathered, but nothing else is. Two keys typed131	 * quickly, or pasted, therefore arrive as two keystrokes rather than one132	 * blob that no single key can be matched against. */133	int remaining = 0;134	unsigned char first = (unsigned char)buf[0];135	if ((first & 0xf8) == 0xf0) {136		remaining = 3;137	} else if ((first & 0xf0) == 0xe0) {138		remaining = 2;139	} else if ((first & 0xe0) == 0xc0) {140		remaining = 1;141	}142	while (remaining > 0 && total < cap) {143		if (!koh_poll_input(10)) {144			break;145		}146		ssize_t m = read(STDIN_FILENO, buf + total, 1);147		if (m <= 0) {148			break;149		}150		total += (int)m;151		remaining--;152	}153	return total;154}155156int koh_read_key(char *buf, int cap) {157	return koh_read_one(buf, cap);158}159160int koh_wait_key(char *buf, int cap, int milliseconds) {161	if (cap <= 0) {162		return 0;163	}164	struct pollfd p;165	p.fd = STDIN_FILENO;166	p.events = POLLIN;167	p.revents = 0;168	int ready;169	do {170		ready = poll(&p, 1, milliseconds);171	} while (ready < 0 && errno == EINTR);172	if (ready <= 0) {173		return 0;174	}175	int n = koh_read_one(buf, cap);176	/* A key reader that returns nothing after poll said readable means the177	 * input is gone, not quiet: report it apart so the caller quits instead178	 * of waiting forever on a dead stdin. */179	return n == 0 ? -1 : n;180}