1/* interestingtimes.c - cursor control
2 *
3 * Copyright 2015 Rob Landley <rob@landley.net>
4 */
5
6#include "toys.h"
7
8int xgettty(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 xopen("/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 (!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// Reset terminal to known state, saving copy of old state if old != NULL.
50int set_terminal(int fd, int raw, struct termios *old)
51{
52  struct termios termio;
53
54  // Fetch local copy of old terminfo, and copy struct contents to *old if set
55  if (!tcgetattr(fd, &termio) && old) *old = termio;
56
57  // the following are the bits set for an xterm. Linux text mode TTYs by
58  // default add two additional bits that only matter for serial processing
59  // (turn serial line break into an interrupt, and XON/XOFF flow control)
60
61  // Any key unblocks output, swap CR and NL on input
62  termio.c_iflag = IXANY|ICRNL|INLCR;
63  if (toys.which->flags & TOYFLAG_LOCALE) termio.c_iflag |= IUTF8;
64
65  // Output appends CR to NL, does magic undocumented postprocessing
66  termio.c_oflag = ONLCR|OPOST;
67
68  // Leave serial port speed alone
69  // termio.c_cflag = C_READ|CS8|EXTB;
70
71  // Generate signals, input entire line at once, echo output
72  // erase, line kill, escape control characters with ^
73  // erase line char at a time
74  // "extended" behavior: ctrl-V quotes next char, ctrl-R reprints unread chars,
75  // ctrl-W erases word
76  termio.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
77
78  if (raw) cfmakeraw(&termio);
79
80  return tcsetattr(fd, TCSANOW, &termio);
81}
82
83// Scan stdin for a keypress, parsing known escape sequences
84// seqs is array of char * strings, ends with NULL ptr
85// Returns: 0-255=literal, -1=EOF, -2=NONE, 256-...=index into seq
86// scratch space is necessary because last char of !seq could start new seq
87// Zero out first byte of scratch before first call to scan_key
88// block=0 allows fetching multiple characters before updating display
89int scan_key(char *scratch, char **seqs, int block)
90{
91  struct pollfd pfd;
92  int maybe, i, j;
93  char *test;
94
95  for (;;) {
96    pfd.fd = 0;
97    pfd.events = POLLIN;
98    pfd.revents = 0;
99
100    // check sequences
101    maybe = 0;
102    if (*scratch) {
103      for (i = maybe = 0; (test = seqs[i]); i++) {
104        for (j = 0; j<*scratch; j++) if (scratch[j+1] != test[j]) break;
105        if (j == *scratch) {
106          maybe = 1;
107          if (!test[j]) {
108            // We recognized current sequence: consume and return
109            *scratch = 0;
110            return 256+i;
111          }
112        }
113      }
114      // If current data can't be a known sequence, return next raw char
115      if (!maybe) break;
116    }
117
118    // Need more data to decide
119
120    // 30 miliseconds is about the gap between characters at 300 baud
121    if (maybe || !block) if (!xpoll(&pfd, 1, 30*maybe)) break;
122
123    if (1 != read(0, scratch+1+*scratch, 1)) return -1;
124    ++*scratch;
125  }
126
127  // Was not a sequence
128  if (!*scratch) return -2;
129  i = scratch[1];
130  if (--*scratch) memmove(scratch+1, scratch+2, *scratch);
131
132  return i;
133}
134