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