• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* interestingtimes.c - cursor control
2  *
3  * Copyright 2015 Rob Landley <rob@landley.net>
4  */
5 
6 #include "toys.h"
7 
xgettty(void)8 int 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 
terminal_size(unsigned * xx,unsigned * yy)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 (!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 
terminal_probesize(unsigned * xx,unsigned * yy)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("\e[s\e[999C\e[999B\e[6n\e[u");
60 
61   return 0;
62 }
63 
64 // Wrapper that parses results from ANSI probe to update screensize.
65 // Otherwise acts like scan_key()
scan_key_getsize(char * scratch,int miliwait,unsigned * xx,unsigned * yy)66 int scan_key_getsize(char *scratch, int miliwait, unsigned *xx, unsigned *yy)
67 {
68   int key;
69 
70   if (512&(key = scan_key(scratch, miliwait))) {
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.
set_terminal(int fd,int raw,struct termios * old)83 int set_terminal(int fd, int raw, struct termios *old)
84 {
85   struct termios termio;
86 
87   // Fetch local copy of old terminfo, and copy struct contents to *old if set
88   if (!tcgetattr(fd, &termio) && old) *old = termio;
89 
90   // the following are the bits set for an xterm. Linux text mode TTYs by
91   // default add two additional bits that only matter for serial processing
92   // (turn serial line break into an interrupt, and XON/XOFF flow control)
93 
94   // Any key unblocks output, swap CR and NL on input
95   termio.c_iflag = IXANY|ICRNL|INLCR;
96   if (toys.which->flags & TOYFLAG_LOCALE) termio.c_iflag |= IUTF8;
97 
98   // Output appends CR to NL, does magic undocumented postprocessing
99   termio.c_oflag = ONLCR|OPOST;
100 
101   // Leave serial port speed alone
102   // termio.c_cflag = C_READ|CS8|EXTB;
103 
104   // Generate signals, input entire line at once, echo output
105   // erase, line kill, escape control characters with ^
106   // erase line char at a time
107   // "extended" behavior: ctrl-V quotes next char, ctrl-R reprints unread chars,
108   // ctrl-W erases word
109   termio.c_lflag = ISIG|ICANON|ECHO|ECHOE|ECHOK|ECHOCTL|ECHOKE|IEXTEN;
110 
111   if (raw) cfmakeraw(&termio);
112 
113   return tcsetattr(fd, TCSANOW, &termio);
114 }
115 
xset_terminal(int fd,int raw,struct termios * old)116 void xset_terminal(int fd, int raw, struct termios *old)
117 {
118   if (-1 == set_terminal(fd, raw, old)) perror_exit("bad tty fd#%d", fd);
119 }
120 
121 struct scan_key_list {
122   char *name, *seq;
123 } static const scan_key_list[] = TAGGED_ARRAY(KEY,
124   // up down right left pgup pgdn home end ins
125   {"UP", "\033[A"}, {"DOWN", "\033[B"}, {"RIGHT", "\033[C"}, {"LEFT", "\033[D"},
126   {"PGUP", "\033[5~"}, {"PGDN", "\033[6~"}, {"HOME", "\033OH"},
127   {"END", "\033OF"}, {"INSERT", "\033[2~"},
128 
129   {"F1", "\033OP"}, {"F2", "\033OQ"}, {"F3", "\033OR"}, {"F4", "\033OS"},
130   {"F5", "\033[15~"}, {"F6", "\033[17~"}, {"F7", "\033[18~"},
131   {"F8", "\033[19~"}, {"F9", "\033[20~"},
132 
133   {"SUP", "\033[1;2A"}, {"AUP", "\033[1;3A"}, {"CUP", "\033[1;5A"},
134   {"SDOWN", "\033[1;2B"}, {"ADOWN", "\033[1;3B"}, {"CDOWN", "\033[1;5B"},
135   {"SRIGHT", "\033[1;2C"}, {"ARIGHT", "\033[1;3C"}, {"CRIGHT", "\033[1;5C"},
136   {"SLEFT", "\033[1;2D"}, {"ALEFT", "\033[1;3D"}, {"CLEFT", "\033[1;5D"},
137 
138   {"SF1", "\033O1;2P"}, {"AF1", "\033O1;3P"}, {"CF1", "\033[1;5P"}
139 );
140 
141 // Scan stdin for a keypress, parsing known escape sequences
142 // Blocks for miliwait miliseconds, none 0, forever if -1
143 // Returns: 0-255=literal, -1=EOF, -2=TIMEOUT, 256-...=index into scan_key_list
144 // >512 is x<<9+y<<21
145 // scratch space is necessary because last char of !seq could start new seq
146 // Zero out first byte of scratch before first call to scan_key
147 // block=0 allows fetching multiple characters before updating display
scan_key(char * scratch,int miliwait)148 int scan_key(char *scratch, int miliwait)
149 {
150   struct pollfd pfd;
151   int maybe, i, j;
152   char *test;
153 
154   for (;;) {
155     pfd.fd = 0;
156     pfd.events = POLLIN;
157     pfd.revents = 0;
158 
159     maybe = 0;
160     if (*scratch) {
161       int pos[6];
162       unsigned x, y;
163 
164       // Check for return from terminal size probe
165       memset(pos, 0, 6*sizeof(int));
166       scratch[(1+*scratch)&15] = 0;
167       sscanf(scratch+1, "\033%n[%n%3u%n;%n%3u%nR%n", pos, pos+1, &y,
168              pos+2, pos+3, &x, pos+4, pos+5);
169       if (pos[5]) {
170         // Recognized X/Y position, consume and return
171         *scratch = 0;
172         return 512+(x<<10)+(y<<20);
173       } else for (i=0; i<6; i++) if (pos[i]==*scratch) maybe = 1;
174 
175       // Check sequences
176       for (i = 0; i<ARRAY_LEN(scan_key_list); i++) {
177         test = scan_key_list[i].seq;
178         for (j = 0; j<*scratch; j++) if (scratch[j+1] != test[j]) break;
179         if (j == *scratch) {
180           maybe = 1;
181           if (!test[j]) {
182             // We recognized current sequence: consume and return
183             *scratch = 0;
184             return 256+i;
185           }
186         }
187       }
188 
189       // If current data can't be a known sequence, return next raw char
190       if (!maybe) break;
191     }
192 
193     // Need more data to decide
194 
195     // 30 miliseconds is about the gap between characters at 300 baud
196     if (maybe || miliwait != -1)
197       if (!xpoll(&pfd, 1, maybe ? 30 : miliwait)) break;
198 
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 || 1 != read(0, scratch+1+*scratch, 1))
202       return toys.signal ? -3 : -1;
203     ++*scratch;
204   }
205 
206   // Was not a sequence
207   if (!*scratch) return -2;
208   i = scratch[1];
209   if (--*scratch) memmove(scratch+1, scratch+2, *scratch);
210 
211   return i;
212 }
213 
tty_esc(char * s)214 void tty_esc(char *s)
215 {
216   printf("\033[%s", s);
217 }
218 
tty_jump(int x,int y)219 void tty_jump(int x, int y)
220 {
221   char s[32];
222 
223   sprintf(s, "%d;%dH", y+1, x+1);
224   tty_esc(s);
225 }
226 
tty_reset(void)227 void tty_reset(void)
228 {
229   set_terminal(0, 0, 0);
230   tty_esc("?25h");
231   tty_esc("0m");
232   tty_jump(0, 999);
233   tty_esc("K");
234   fflush(0);
235 }
236 
237 // If you call set_terminal(), use sigatexit(tty_sigreset);
tty_sigreset(int i)238 void tty_sigreset(int i)
239 {
240   tty_reset();
241   _exit(i ? 128+i : 0);
242 }
243