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