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