tty.c 8.9 KB

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