1 /* tty.c - cursor control
2 *
3 * Copyright 2015 Rob Landley <[email protected]>
4 *
5 * Common ANSI (See https://man7.org/linux/man-pages/man4/console_codes.4.html)
6 * \e[#m - color change \e[y;xH - jump to x/y pos (1;1 is top left)
7 * \e[K - delete to EOL \e[25l - disable cursor (h to enable)
8 * \e[1L - Insert 1 (blank) line \e[1M - Delete 1 line (scrolling rest up)
9 * \e[2J - clear screen
10 *
11 * colors: 0=black 1=red 2=green 3=brown 4=blue 5=purple 6=cyan 7=grey
12 * +30 foreground, +40 background.
13 * \e[1m = bright, \e[2m = dark, \e[0m = reset to defaults
14 * \e[1;32;2;42mhello\e[0m - dark green text on light green background
15 */
16
17 #include "toys.h"
18
19 // Check stdout, stderr, stdin (in that order) and if none open /dev/tty
tty_fd(void)20 int tty_fd(void)
21 {
22 int i, j;
23
24 for (i = 0; i<3; i++) if (isatty(j = (i+1)%3)) return j;
25
26 return xnotstdio(open("/dev/tty", O_RDWR));
27 }
28
29 // Query size of terminal (without ANSI probe fallback).
30 // set x=80 y=25 before calling to provide defaults. Returns 0 if couldn't
31 // determine size.
32
terminal_size(unsigned * xx,unsigned * yy)33 int terminal_size(unsigned *xx, unsigned *yy)
34 {
35 struct winsize ws;
36 unsigned i, x = 0, y = 0;
37 char *s;
38
39 // Check stdin, stdout, stderr
40 for (i = 0; i<3; i++) {
41 memset(&ws, 0, sizeof(ws));
42 if (isatty(i) && !ioctl(i, TIOCGWINSZ, &ws)) {
43 if (ws.ws_col) x = ws.ws_col;
44 if (ws.ws_row) y = ws.ws_row;
45
46 break;
47 }
48 }
49 s = getenv("COLUMNS");
50 if (s) sscanf(s, "%u", &x);
51 s = getenv("LINES");
52 if (s) sscanf(s, "%u", &y);
53
54 // Never return 0 for either value, leave it at default instead.
55 if (xx && x) *xx = x;
56 if (yy && y) *yy = y;
57
58 return x || y;
59 }
60
61 // Query terminal size, sending ANSI probe if necesary. (Probe queries xterm
62 // size through serial connection, when local TTY doesn't know but remote does.)
63 // Returns 0 if ANSI probe sent, 1 if size determined from tty or environment
64
terminal_probesize(unsigned * xx,unsigned * yy)65 int terminal_probesize(unsigned *xx, unsigned *yy)
66 {
67 if (terminal_size(xx, yy) && (!xx || *xx) && (!yy || *yy)) return 1;
68
69 // Send probe: bookmark cursor position, jump to bottom right,
70 // query position, return cursor to bookmarked position.
71 xprintf("\e[s\e[999C\e[999B\e[6n\e[u");
72
73 return 0;
74 }
75
76 // This table skips both B0 and BOTHER
77 static const int speeds[] = {50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800,
78 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 500000, 576000,
79 921600, 1000000, 1152000, 1500000, 2000000, 2500000, 3000000,3500000,4000000};
80
81 // Show bits per second for cfspeed value. Assumes we have a valid speed
cfspeed2bps(unsigned speed)82 unsigned cfspeed2bps(unsigned speed)
83 {
84 if (!(speed&15)) return 0;
85 if (speed>15) speed = (speed&15)+15;
86
87 return speeds[--speed];
88 }
89
90 // Convert bits per second to cfspeed value. Returns 0 for unknown bps
bps2cfspeed(unsigned baud)91 unsigned bps2cfspeed(unsigned baud)
92 {
93 int i = 0;
94
95 while (i<ARRAY_LEN(speeds))
96 if (speeds[i++]==baud) return i+(i>15)*(4096-16+1);
97
98 return 0;
99 }
100
xsetspeed(struct termios * tio,int bps)101 void xsetspeed(struct termios *tio, int bps)
102 {
103 int i = bps2cfspeed(bps);
104
105 if (!i) error_exit("unknown speed: %d", bps);
106 cfsetspeed(tio, i);
107 }
108
109 // Reset terminal to known state, saving copy of old state if old != NULL.
set_terminal(int fd,int raw,int speed,struct termios * old)110 int set_terminal(int fd, int raw, int speed, struct termios *old)
111 {
112 struct termios tio;
113 int i = tcgetattr(fd, &tio);
114
115 // Fetch local copy of old terminfo, and copy struct contents to *old if set
116 if (i) return i;
117 if (old) *old = tio;
118
119 cfmakeraw(&tio);
120 if (speed) xsetspeed(&tio, speed);
121 if (!raw) {
122 // Put the "cooked" bits back.
123
124 // Convert CR to NL on input, UTF8 aware backspace, Any key unblocks input.
125 tio.c_iflag |= ICRNL|IUTF8|IXANY;
126
127 // Output appends CR to NL and does magic undocumented postprocessing.
128 tio.c_oflag |= OPOST|ONLCR;
129
130 // 8 bit chars, enable receiver.
131 tio.c_cflag |= CS8|CREAD;
132
133 // Generate signals, input entire line at once, echo output erase,
134 // line kill, escape control characters with ^, erase line char at a time
135 // "extended" behavior: ctrl-V quotes next char, ctrl-R reprints unread line
136 // ctrl-W erases word
137 tio.c_lflag |= ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
138 }
139
140 return tcsetattr(fd, TCSAFLUSH, &tio);
141 }
142
xset_terminal(int fd,int raw,int speed,struct termios * old)143 void xset_terminal(int fd, int raw, int speed, struct termios *old)
144 {
145 if (-1 == set_terminal(fd, raw, speed, old)) perror_exit("tcsetattr");
146 }
147
148 struct scan_key_list {
149 int key;
150 char *seq;
151 } static const scan_key_list[] = {
152 {KEY_UP, "\e[A"}, {KEY_DOWN, "\e[B"},
153 {KEY_RIGHT, "\e[C"}, {KEY_LEFT, "\e[D"},
154
155 {KEY_UP|KEY_SHIFT, "\e[1;2A"}, {KEY_DOWN|KEY_SHIFT, "\e[1;2B"},
156 {KEY_RIGHT|KEY_SHIFT, "\e[1;2C"}, {KEY_LEFT|KEY_SHIFT, "\e[1;2D"},
157
158 {KEY_UP|KEY_ALT, "\e[1;3A"}, {KEY_DOWN|KEY_ALT, "\e[1;3B"},
159 {KEY_RIGHT|KEY_ALT, "\e[1;3C"}, {KEY_LEFT|KEY_ALT, "\e[1;3D"},
160
161 {KEY_UP|KEY_CTRL, "\e[1;5A"}, {KEY_DOWN|KEY_CTRL, "\e[1;5B"},
162 {KEY_RIGHT|KEY_CTRL, "\e[1;5C"}, {KEY_LEFT|KEY_CTRL, "\e[1;5D"},
163
164 // VT102/VT220 escapes.
165 {KEY_HOME, "\e[1~"},
166 {KEY_HOME|KEY_CTRL, "\e[1;5~"},
167 {KEY_INSERT, "\e[2~"},
168 {KEY_DELETE, "\e[3~"},
169 {KEY_END, "\e[4~"},
170 {KEY_END|KEY_CTRL, "\e[4;5~"},
171 {KEY_PGUP, "\e[5~"},
172 {KEY_PGDN, "\e[6~"},
173 // "Normal" "PC" escapes (xterm).
174 {KEY_HOME, "\eOH"},
175 {KEY_END, "\eOF"},
176 // "Application" "PC" escapes (gnome-terminal).
177 {KEY_HOME, "\e[H"},
178 {KEY_END, "\e[F"},
179 {KEY_HOME|KEY_CTRL, "\e[1;5H"},
180 {KEY_END|KEY_CTRL, "\e[1;5F"},
181
182 {KEY_FN+1, "\eOP"}, {KEY_FN+2, "\eOQ"}, {KEY_FN+3, "\eOR"},
183 {KEY_FN+4, "\eOS"}, {KEY_FN+5, "\e[15~"}, {KEY_FN+6, "\e[17~"},
184 {KEY_FN+7, "\e[18~"}, {KEY_FN+8, "\e[19~"}, {KEY_FN+9, "\e[20~"},
185 };
186
187 // Scan stdin for a keypress, parsing known escape sequences, including
188 // responses to screen size queries.
189 // Blocks for timeout_ms milliseconds, 0=return immediately, -1=wait forever.
190 // Returns 0-255=literal, -1=EOF, -2=TIMEOUT, -3=RESIZE, 256+= a KEY_ constant.
191 // Scratch space is necessary because last char of !seq could start new seq.
192 // Zero out first byte of scratch before first call to scan_key.
scan_key_getsize(char * scratch,int timeout_ms,unsigned * xx,unsigned * yy)193 int scan_key_getsize(char *scratch, int timeout_ms, unsigned *xx, unsigned *yy)
194 {
195 struct pollfd pfd;
196 int maybe, i, j;
197 char *test;
198
199 for (;;) {
200 pfd.fd = 0;
201 pfd.events = POLLIN;
202 pfd.revents = 0;
203
204 maybe = 0;
205 if (*scratch) {
206 int pos[6];
207 unsigned x, y;
208
209 // Check for return from terminal size probe
210 memset(pos, 0, 6*sizeof(int));
211 scratch[(1+*scratch)&15] = 0;
212 sscanf(scratch+1, "\e%n[%n%3u%n;%n%3u%nR%n", pos, pos+1, &y,
213 pos+2, pos+3, &x, pos+4, pos+5);
214 if (pos[5]) {
215 // Recognized X/Y position, consume and return
216 *scratch = 0;
217 if (xx) *xx = x;
218 if (yy) *yy = y;
219 return -3;
220 } else for (i=0; i<6; i++) if (pos[i]==*scratch) maybe = 1;
221
222 // Check sequences
223 for (i = 0; i<ARRAY_LEN(scan_key_list); i++) {
224 test = scan_key_list[i].seq;
225 for (j = 0; j<*scratch; j++) if (scratch[j+1] != test[j]) break;
226 if (j == *scratch) {
227 maybe = 1;
228 if (!test[j]) {
229 // We recognized current sequence: consume and return
230 *scratch = 0;
231 return 256+scan_key_list[i].key;
232 }
233 }
234 }
235
236 // If current data can't be a known sequence, return next raw char
237 if (!maybe) break;
238 }
239
240 // Need more data to decide
241
242 // 30ms is about the gap between characters at 300 baud
243 if (maybe || timeout_ms != -1)
244 if (!xpoll(&pfd, 1, maybe ? 30 : timeout_ms)) break;
245
246 // Read 1 byte so we don't overshoot sequence match. (We can deviate
247 // and fail to match, but match consumes entire buffer.)
248 if (toys.signal>0 || 1 != read(0, scratch+1+*scratch, 1))
249 return (toys.signal>0) ? -3 : -1;
250 ++*scratch;
251 }
252
253 // Was not a sequence
254 if (!*scratch) return -2;
255 i = scratch[1];
256 if (--*scratch) memmove(scratch+1, scratch+2, *scratch);
257
258 return i;
259 }
260
261 // Wrapper that ignores results from ANSI probe to update screensize.
262 // Otherwise acts like scan_key_getsize().
scan_key(char * scratch,int timeout_ms)263 int scan_key(char *scratch, int timeout_ms)
264 {
265 return scan_key_getsize(scratch, timeout_ms, NULL, NULL);
266 }
267
tty_reset(void)268 void tty_reset(void)
269 {
270 set_terminal(0, 0, 0, 0);
271 xputsn("\e[?25h\e[0m\e[999H\e[K");
272 }
273
274 // If you call set_terminal(), use sigatexit(tty_sigreset);
tty_sigreset(int i)275 void tty_sigreset(int i)
276 {
277 tty_reset();
278 _exit(i ? 128+i : 0);
279 }
280
start_redraw(unsigned * width,unsigned * height)281 void start_redraw(unsigned *width, unsigned *height)
282 {
283 // If never signaled, do raw mode setup.
284 if (!toys.signal) {
285 *width = 80;
286 *height = 25;
287 set_terminal(0, 1, 0, 0);
288 sigatexit(tty_sigreset);
289 xsignal(SIGWINCH, generic_signal);
290 }
291 if (toys.signal != -1) {
292 toys.signal = -1;
293 terminal_probesize(width, height);
294 }
295 xputsn("\e[H\e[J");
296 }
297