From 642b5fb0007b64c77d186fcb018d571152ee1d47 Mon Sep 17 00:00:00 2001 From: dzwdz Date: Mon, 14 Aug 2023 18:51:07 +0200 Subject: reorganization: first steps --- src/cmd/init/driver/termcook.c | 103 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/cmd/init/driver/termcook.c (limited to 'src/cmd/init/driver/termcook.c') diff --git a/src/cmd/init/driver/termcook.c b/src/cmd/init/driver/termcook.c new file mode 100644 index 0000000..a76f3a8 --- /dev/null +++ b/src/cmd/init/driver/termcook.c @@ -0,0 +1,103 @@ +#include "driver.h" +#include +#include +#include +#include + +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) 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()); +} -- cgit v1.2.3