1 /* interestingtimes.c - cursor control 2 * 3 * Copyright 2015 Rob Landley <rob (at) landley.net> 4 */ 5 6 #include "toys.h" 7 8 int 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 21 int 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 53 int 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 64 // Wrapper that parses results from ANSI probe to update screensize. 65 // Otherwise acts like scan_key() 66 int scan_key_getsize(char *scratch, int timeout_ms, unsigned *xx, unsigned *yy) 67 { 68 int key; 69 70 if (512&(key = scan_key(scratch, timeout_ms))) { 71 if (key>0) { 72 if (xx) *xx = (key>>10)&1023; 73 if (yy) *yy = (key>>20)&1023; 74 75 return -3; 76 } 77 } 78 79 return key; 80 } 81 82 // Reset terminal to known state, saving copy of old state if old != NULL. 83 int set_terminal(int fd, int raw, int speed, struct termios *old) 84 { 85 struct termios termio; 86 int i = tcgetattr(fd, &termio); 87 88 // Fetch local copy of old terminfo, and copy struct contents to *old if set 89 if (i) return i; 90 if (old) *old = termio; 91 92 // the following are the bits set for an xterm. Linux text mode TTYs by 93 // default add two additional bits that only matter for serial processing 94 // (turn serial line break into an interrupt, and XON/XOFF flow control) 95 96 // Any key unblocks output, swap CR and NL on input 97 termio.c_iflag = IXANY|ICRNL|INLCR; 98 if (toys.which->flags & TOYFLAG_LOCALE) termio.c_iflag |= IUTF8; 99 100 // Output appends CR to NL, does magic undocumented postprocessing 101 termio.c_oflag = ONLCR|OPOST; 102 103 // Leave serial port speed alone 104 // termio.c_cflag = C_READ|CS8|EXTB; 105 106 // Generate signals, input entire line at once, echo output 107 // erase, line kill, escape control characters with ^ 108 // erase line char at a time 109 // "extended" behavior: ctrl-V quotes next char, ctrl-R reprints unread chars, 110 // ctrl-W erases word 111 termio.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN; 112 113 if (raw) cfmakeraw(&termio); 114 115 if (speed) { 116 int i, speeds[] = {50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 117 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 118 500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000, 119 2500000, 3000000, 3500000, 4000000}; 120 121 // Find speed in table, adjust to constant 122 for (i = 0; i < ARRAY_LEN(speeds); i++) if (speeds[i] == speed) break; 123 if (i == ARRAY_LEN(speeds)) error_exit("unknown speed: %d", speed); 124 cfsetspeed(&termio, i+1+4081*(i>15)); 125 } 126 127 return tcsetattr(fd, TCSAFLUSH, &termio); 128 } 129 130 void xset_terminal(int fd, int raw, int speed, struct termios *old) 131 { 132 if (-1 != set_terminal(fd, raw, speed, old)) return; 133 134 sprintf(libbuf, "/proc/self/fd/%d", fd); 135 libbuf[readlink0(libbuf, libbuf, sizeof(libbuf))] = 0; 136 perror_exit("tcsetattr %s", libbuf); 137 } 138 139 struct scan_key_list { 140 char *name, *seq; 141 } static const scan_key_list[] = TAGGED_ARRAY(KEY, 142 // up down right left pgup pgdn home end ins 143 {"UP", "\033[A"}, {"DOWN", "\033[B"}, {"RIGHT", "\033[C"}, {"LEFT", "\033[D"}, 144 {"PGUP", "\033[5~"}, {"PGDN", "\033[6~"}, {"HOME", "\033OH"}, 145 {"END", "\033OF"}, {"INSERT", "\033[2~"}, 146 147 {"F1", "\033OP"}, {"F2", "\033OQ"}, {"F3", "\033OR"}, {"F4", "\033OS"}, 148 {"F5", "\033[15~"}, {"F6", "\033[17~"}, {"F7", "\033[18~"}, 149 {"F8", "\033[19~"}, {"F9", "\033[20~"}, 150 151 {"SUP", "\033[1;2A"}, {"AUP", "\033[1;3A"}, {"CUP", "\033[1;5A"}, 152 {"SDOWN", "\033[1;2B"}, {"ADOWN", "\033[1;3B"}, {"CDOWN", "\033[1;5B"}, 153 {"SRIGHT", "\033[1;2C"}, {"ARIGHT", "\033[1;3C"}, {"CRIGHT", "\033[1;5C"}, 154 {"SLEFT", "\033[1;2D"}, {"ALEFT", "\033[1;3D"}, {"CLEFT", "\033[1;5D"}, 155 156 {"SF1", "\033O1;2P"}, {"AF1", "\033O1;3P"}, {"CF1", "\033[1;5P"} 157 ); 158 159 // Scan stdin for a keypress, parsing known escape sequences 160 // Blocks for timeout_ms milliseconds, none 0, forever if -1 161 // Returns: 0-255=literal, -1=EOF, -2=TIMEOUT, 256-...=index into scan_key_list 162 // >512 is x<<9+y<<21 163 // scratch space is necessary because last char of !seq could start new seq 164 // Zero out first byte of scratch before first call to scan_key 165 // block=0 allows fetching multiple characters before updating display 166 int scan_key(char *scratch, int timeout_ms) 167 { 168 struct pollfd pfd; 169 int maybe, i, j; 170 char *test; 171 172 for (;;) { 173 pfd.fd = 0; 174 pfd.events = POLLIN; 175 pfd.revents = 0; 176 177 maybe = 0; 178 if (*scratch) { 179 int pos[6]; 180 unsigned x, y; 181 182 // Check for return from terminal size probe 183 memset(pos, 0, 6*sizeof(int)); 184 scratch[(1+*scratch)&15] = 0; 185 sscanf(scratch+1, "\033%n[%n%3u%n;%n%3u%nR%n", pos, pos+1, &y, 186 pos+2, pos+3, &x, pos+4, pos+5); 187 if (pos[5]) { 188 // Recognized X/Y position, consume and return 189 *scratch = 0; 190 return 512+(x<<10)+(y<<20); 191 } else for (i=0; i<6; i++) if (pos[i]==*scratch) maybe = 1; 192 193 // Check sequences 194 for (i = 0; i<ARRAY_LEN(scan_key_list); i++) { 195 test = scan_key_list[i].seq; 196 for (j = 0; j<*scratch; j++) if (scratch[j+1] != test[j]) break; 197 if (j == *scratch) { 198 maybe = 1; 199 if (!test[j]) { 200 // We recognized current sequence: consume and return 201 *scratch = 0; 202 return 256+i; 203 } 204 } 205 } 206 207 // If current data can't be a known sequence, return next raw char 208 if (!maybe) break; 209 } 210 211 // Need more data to decide 212 213 // 30ms is about the gap between characters at 300 baud 214 if (maybe || timeout_ms != -1) 215 if (!xpoll(&pfd, 1, maybe ? 30 : timeout_ms)) break; 216 217 // Read 1 byte so we don't overshoot sequence match. (We can deviate 218 // and fail to match, but match consumes entire buffer.) 219 if (toys.signal>0 || 1 != read(0, scratch+1+*scratch, 1)) 220 return (toys.signal>0) ? -3 : -1; 221 ++*scratch; 222 } 223 224 // Was not a sequence 225 if (!*scratch) return -2; 226 i = scratch[1]; 227 if (--*scratch) memmove(scratch+1, scratch+2, *scratch); 228 229 return i; 230 } 231 232 void tty_esc(char *s) 233 { 234 printf("\033[%s", s); 235 } 236 237 void tty_jump(int x, int y) 238 { 239 char s[32]; 240 241 sprintf(s, "%d;%dH", y+1, x+1); 242 tty_esc(s); 243 } 244 245 void tty_reset(void) 246 { 247 set_terminal(0, 0, 0, 0); 248 tty_esc("?25h"); 249 tty_esc("0m"); 250 tty_jump(0, 999); 251 tty_esc("K"); 252 fflush(0); 253 } 254 255 // If you call set_terminal(), use sigatexit(tty_sigreset); 256 void tty_sigreset(int i) 257 { 258 tty_reset(); 259 _exit(i ? 128+i : 0); 260 } 261 262 void start_redraw(unsigned *width, unsigned *height) 263 { 264 // If never signaled, do raw mode setup. 265 if (!toys.signal) { 266 *width = 80; 267 *height = 25; 268 set_terminal(0, 1, 0, 0); 269 sigatexit(tty_sigreset); 270 xsignal(SIGWINCH, generic_signal); 271 } 272 if (toys.signal != -1) { 273 toys.signal = -1; 274 terminal_probesize(width, height); 275 } 276 xprintf("\033[H\033[J"); 277 } 278