summaryrefslogtreecommitdiff
path: root/src/cmd/init/driver/termcook.c
blob: a0da8c36cb82b07366ab0bdccc57c06d03c7306a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "driver.h"
#include <camellia/compat.h>
#include <camellia/syscalls.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

enum tstate {
	Normal,
	Esc,
	CSI,
};

static void w_output(hid_t output, const char *buf, size_t len) {
	size_t pos = 0;
	while (pos < len) {
		int ret = _sys_write(output, buf + pos, len - pos, pos, 0);
		if (ret < 0) break;
		pos += ret;
	}
}

static void line_editor(hid_t input, hid_t output) {
	char readbuf[16], linebuf[256];
	size_t linepos = 0;
	enum tstate state = Normal;
	for (;;) {
		int readlen = _sys_read(input, readbuf, sizeof readbuf, -1);
		if (readlen < 0) {
			errno = -readlen;
			err(1, "read");
			return;
		}
		for (int i = 0; i < readlen; i++) {
			char c = readbuf[i];
			switch (state) {
			case Normal:
				switch (c) {
				case '\b':
				case 0x7f:
					if (linepos != 0) {
						printf("\b \b");
						linepos--;
					}
					break;
				case 3: /* C-c */
					_sys_exit(1);
				case 4: /* EOT, C-d */
					if (linepos > 0) {
						w_output(output, linebuf, linepos);
						linepos = 0;
					} else {
						_sys_write(output, NULL, 0, 0, 0); /* EOF */
					}
					break;
				case '\n':
				case '\r':
					printf("\n");
					if (linepos < sizeof linebuf)
						linebuf[linepos++] = '\n';
					w_output(output, linebuf, linepos);
					linepos = 0;
					break;
				case '\e':
					state = Esc;
					break;
				case '\t':
					break;
				default:
					if (linepos < sizeof linebuf) {
						linebuf[linepos++] = c;
						printf("%c", c);
					}
					break;
				}
				break;
			case Esc:
				if (c == '[') state = CSI;
				else state = Normal;
				break;
			case CSI:
				if (0x40 <= c && c <= 0x7E) state = Normal;
				break;
			}
		}
	}
}

void termcook(void) {
	hid_t stdin_pipe[2] = {-1, -1};
	if (_sys_pipe(stdin_pipe, 0) < 0)
		return;

	if (!fork()) {
		/* the caller continues in a child process,
		 * so it can be killed when the line editor quits */
		_sys_dup(stdin_pipe[0], 0, 0);
		close(stdin_pipe[0]);
		close(stdin_pipe[1]);
		return;
	}
	if (!fork()) {
		close(stdin_pipe[0]);
		line_editor(0, stdin_pipe[1]);
		exit(0);
	}
	exit(_sys_await());
}