tty.c 8.7 KB

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