Debian Codegraph @

libsrc/text/console.scm

raw
1 ;;;
2 ;;; text.console - basic console control
3 ;;;
4 ;;; Copyright (c) 2014-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (define-module text.console
35 (use gauche.generator)
36 (use gauche.sequence)
37 (use gauche.termios)
38 (use data.trie)
39 (use data.queue)
40 (use util.match)
41 (export <vt100> <windows-console>
42
43 call-with-console
44 putch putstr getch get-raw-chars chready? canonical-mode? beep
45 query-screen-size query-cursor-position move-cursor-to
46 hide-cursor show-cursor cursor-down/scroll-up cursor-up/scroll-down
47 reset-terminal clear-screen clear-to-eol clear-to-eos
48 set-character-attribute reset-character-attribute
49 with-character-attribute
50 ensure-bottom-room
51
52 make-default-console vt100-compatible?))
53 (select-module text.console)
54
55 (autoload text.console.windows <windows-console>)
56
57 ;;;
58 ;;; Select appropriate console
59 ;;;
60
61 ;; Regexp that matches $TERM that behaves as if it's vt100.
62 ;; Strict compatibility isn't necessary; we're using just a common
63 ;; denominator. We expand this list as we discover other terminal types
64 ;; that works.
65 ;; See https://github.com/shirok/Gauche/issues/179 about 'screen'.
66 (define-constant *vt100-compatible-terminals*
67 #/^(vt10[02]|vt220|xterm.*|rxvt.*|screen.*|tmux.*|linux.*)$/)
68
69 ;; Convenience API
70 (define (vt100-compatible? term)
71 (boolean (*vt100-compatible-terminals* term)))
72
73 ;; Convenience API
74 ;; Inspect the runtime environment and returns a console object with
75 ;; appropriate setting.
76 ;; If it cannot find supported console type, an error is signalled,
77 ;; with a message describing why.
78 ;; We use some heuristics to recognize vt100 compatible terminals.
79 (define (make-default-console :key (if-not-available :error))
80 (define (e s) (and (eq? if-not-available :error) (error s)))
81 (cond [(not (memv if-not-available '(#f :error)))
82 (error "if-not-available argument must be either #f or :error, \
83 but got:" if-not-available)]
84 [(has-windows-console?) (make <windows-console>)]
85 [(and-let1 t (sys-getenv "TERM")
86 (vt100-compatible? t))
87 (if (or (sys-isatty 0)
88 ((with-module gauche.internal %sys-mintty?) 0))
89 (make <vt100>)
90 (e "Stdin isn't a console"))]
91 [(sys-getenv "TERM")
92 => (^t (e #"Unsupported terminal type: ~t"))]
93 [else
94 (e "TERM isn't set and we don't know how to control the terminal.")]))
95
96 ;;;
97 ;;; Generic character attributes
98 ;;;
99
100 ;; Portable character attributes - can be supported both on
101 ;; vt100 color terminal and on Windows console.
102 ;;
103 ;; (<fgcolor> [<bgcolor> . <option> ...])
104 ;; <fgcolor> : <color> | #f ; #f means default
105 ;; <bgcolor> : <color> | #f
106 ;; <color> : black | red | green | yellow | blue | magenta | cyan | white
107 ;; <option> : bright | reverse | underscore
108
109 ;; Internal character attributes
110 (define-class <char-attrs> ()
111 ((fgcolor :init-keyword :fgcolor :init-value #f)
112 (bgcolor :init-keyword :bgcolor :init-value #f)
113 (bright :init-keyword :bright :init-value #f)
114 (reverse :init-keyword :reverse :init-value #f)
115 (underscore :init-keyword :underscore :init-value #f)))
116
117 (define (parse-char-attrs spec :optional (storage #f))
118 (define (check-color color)
119 (or (memq color '(#f black red green yellow blue magenta cyan white))
120 (error "Invalid color name:" color)))
121 (define (check-option opt)
122 (or (memq opt '(bright underscore reverse))
123 (error "Invalid attribute option name:" opt)))
124 (match spec
125 [(fgcolor bgcolor . opts)
126 (check-color fgcolor)
127 (check-color bgcolor)
128 (for-each check-option opts)
129 (let ([bright (boolean (memq 'bright opts))]
130 [reverse (boolean (memq 'reverse opts))]
131 [underscore (boolean (memq 'underscore opts))])
132 (if storage
133 (begin
134 (set! (~ storage'fgcolor) fgcolor)
135 (set! (~ storage'bgcolor) bgcolor)
136 (set! (~ storage'bright) bright)
137 (set! (~ storage'reverse) reverse)
138 (set! (~ storage'underscore) underscore)
139 storage)
140 (make <char-attrs> :fgcolor fgcolor :bgcolor bgcolor
141 :bright bright :reverse reverse :underscore underscore)))]))
142
143 (define (copy-char-attrs attrs)
144 (make <char-attrs> :fgcolor (~ attrs'fgcolor) :bgcolor (~ attrs'bgcolor)
145 :bright (~ attrs'bright) :reverse (~ attrs'reverse)
146 :underscore (~ attrs'underscore)))
147
148 ;;;
149 ;;; Console class implementation - vt100
150 ;;;
151
152 (define-class <vt100> ()
153 ((iport :init-keyword :iport :initform (standard-input-port))
154 (oport :init-keyword :oport :initform (standard-output-port))
155 (input-delay :init-keyword :input-delay :init-value 1000); us, can be #f
156 ;; private
157 (current-attrs :init-form (make <char-attrs>))
158 (input-buffer :init-form (make-queue))
159 (screen-size :init-value #f) ; (width . height)
160 ))
161
162 (define-method call-with-console ((con <vt100>) proc :key (mode 'rare))
163 (with-terminal-mode (~ con'iport) mode
164 (^_ (proc con))
165 (^[]
166 (reset-character-attribute con)
167 (show-cursor con))))
168
169 (define-method putch ((con <vt100>) c)
170 (display c (~ con'oport)) (flush (~ con'oport)))
171 (define-method putstr ((con <vt100>) s)
172 (display s (~ con'oport)) (flush (~ con'oport)))
173 (define-method chready? ((con <vt100>))
174 (or (not (queue-empty? (~ con'input-buffer)))
175 (char-ready? (~ con'iport))))
176
177 ;; Returns #t if the console is 'canonical' mode, that is, line editing
178 ;; is done in the console driver. Usually you don't need to query such a
179 ;; thing because you set up the console mode by yourself, but when the process
180 ;; is stopped by job control and the resumed by SIGCONT, the console mode
181 ;; may have been changed.
182 (define-method canonical-mode? ((con <vt100>))
183 (not (zero? (logand (~ (sys-tcgetattr (~ con'iport)) 'lflag)
184 ICANON))))
185
186 (define-method beep ((con <vt100>)) (putch con #\alarm))
187
188 ;; We try to interpret input escape sequences as much as possible.
189 ;; To distinguish from real ESC key and the escape sequence, we time
190 ;; the input---if they comes immediately one after, we take it as a chunk.
191 ;; <vt100>'input-delay sets the timeout.
192
193 ;; Read a char; returns a char, or #f on timeout. May return EOF.
194 ;; The timeout argument is in us.
195 ;; MSYS needs special treatment, but we can't use cond-expand here since
196 ;; this file is precompiled. It is switched initialization time.
197 (define %read-char/timeout
198 (if (#/-mingw..$/ (gauche-architecture))
199 (^[con :optional (timeout (~ con'input-delay))]
200 ;; select seems unreliable
201 (define resolution-us 10000)
202 (if (or (char-ready? (~ con'iport)) (not timeout))
203 (read-char (~ con'iport))
204 (let loop ([t 0])
205 (if (>= t timeout)
206 #f ; timeout
207 (begin (sys-nanosleep (* resolution-us 1000))
208 (if (char-ready? (~ con'iport))
209 (read-char (~ con'iport))
210 (loop (+ t resolution-us))))))))
211 (^[con :optional (timeout (~ con'input-delay))]
212 (receive (nfds rfds wfds xfds)
213 (sys-select! (sys-fdset (~ con'iport)) #f #f timeout)
214 (if (= nfds 0)
215 #f ; timeout
216 (read-char (~ con'iport)))))))
217
218 (define *input-escape-sequence*
219 '([(#\[ #\A) . KEY_UP]
220 [(#\[ #\B) . KEY_DOWN]
221 [(#\[ #\C) . KEY_RIGHT]
222 [(#\[ #\D) . KEY_LEFT]
223 [(#\O #\A) . KEY_UP] ; variation
224 [(#\O #\B) . KEY_DOWN]
225 [(#\O #\C) . KEY_RIGHT]
226 [(#\O #\D) . KEY_LEFT]
227 [(#\[ #\F) . KEY_END]
228 [(#\[ #\H) . KEY_HOME]
229 [(#\[ #\2 #\~) . KEY_INS]
230 [(#\[ #\3 #\~) . KEY_DEL]
231 [(#\[ #\6 #\~) . KEY_PGDN]
232 [(#\[ #\5 #\~) . KEY_PGUP]
233 [(#\O #\P) . KEY_F1] ; original vt100
234 [(#\O #\Q) . KEY_F2]
235 [(#\O #\R) . KEY_F3]
236 [(#\O #\S) . KEY_F4]
237 [(#\[ #\1 #\1 #\~) . KEY_F1] ; some version of xterm
238 [(#\[ #\1 #\2 #\~) . KEY_F2]
239 [(#\[ #\1 #\3 #\~) . KEY_F3]
240 [(#\[ #\1 #\4 #\~) . KEY_F4]
241 [(#\[ #\1 #\5 #\~) . KEY_F5]
242 [(#\[ #\1 #\7 #\~) . KEY_F6] ; vt220
243 [(#\[ #\1 #\8 #\~) . KEY_F7]
244 [(#\[ #\1 #\9 #\~) . KEY_F8]
245 [(#\[ #\2 #\0 #\~) . KEY_F9]
246 [(#\[ #\2 #\1 #\~) . KEY_F10]
247 [(#\[ #\2 #\3 #\~) . KEY_F11]
248 [(#\[ #\2 #\4 #\~) . KEY_F12]
249 ))
250
251 (define *input-escape-sequence-trie*
252 (delay (rlet1 t (apply trie '() *input-escape-sequence*)
253 (dotimes [n 128]
254 (trie-put! t `(,(integer->char n))
255 `(ALT ,(integer->char n)))))))
256
257 ;; Get a char; returns a char, or #f on timeout.
258 ;; The timeout argument is in us.
259 (define-method getch ((con <vt100>) :optional (timeout #f))
260 (define tab (force *input-escape-sequence-trie*))
261 (define (fetch q)
262 (let1 ch (%read-char/timeout con)
263 (if (char? ch)
264 (begin (enqueue! q ch)
265 (if (trie-partial-key? tab (queue-internal-list q))
266 (fetch q)
267 (finish q)))
268 (finish q))))
269 (define (finish q)
270 (if (trie-exists? tab (queue-internal-list q))
271 (trie-get tab (dequeue-all! q))
272 (begin (dequeue-all! q) #\escape)))
273 (let1 q (~ con'input-buffer)
274 (if (queue-empty? q)
275 (let1 ch (if timeout
276 (%read-char/timeout con timeout)
277 (read-char (~ con'iport)))
278 (cond [(eqv? ch #\escape) (fetch q)]
279 [(not ch) #f] ;timeout
280 [else ch]))
281 (dequeue! q))))
282
283 (define-method get-raw-chars ((con <vt100>)) ; no translation
284 (let1 q (~ con'input-buffer)
285 (when (queue-empty? q) (enqueue! q (read-char (~ con'iport))))
286 (let loop ()
287 (let1 ch (%read-char/timeout con)
288 (if (char? ch)
289 (begin (enqueue! q ch) (loop))
290 (dequeue-all! q))))))
291
292 (define-method query-cursor-position ((con <vt100>))
293 (define (r) (read-char (~ con'iport))) ; we bypass getch buffering
294 ;; Read an esc seq terminted by #\R and return it as a char list
295 ;; (excluding leading ESC). Buffer any other seq in the console's
296 ;; input buffer.
297 (define (get-ESC-R)
298 (let loop ([ch (r)] [chars '()])
299 (cond [(eqv? ch #\escape)
300 ;; buffer previous escape sequence
301 (apply enqueue! (~ con'input-buffer) #\escape (reverse chars))
302 (loop (r) '())]
303 [(eqv? ch #\R) ; we got it
304 (reverse (cons ch chars))]
305 [(char? ch) (loop (r) (cons ch chars))]
306 [else
307 (apply enqueue! (~ con'input-buffer) #\escape (reverse chars))
308 (e)])))
309 (define (e) (error "terminal error when receiving cursor position"))
310
311 (putstr con "\x1b;[6n")
312 (do-generator [ch (gtake-while (^c (not (eqv? c #\x1b))) r)]
313 (enqueue! (~ con'input-buffer) ch))
314 (rxmatch-case (list->string (get-ESC-R))
315 [#/^\[(\d+)\;(\d+)R$/ (_ row col)
316 (values (- (x->integer row) 1) (- (x->integer col) 1))]
317 [else (e)]))
318
319 ;; we're zero-origin as curses; vt100 takes 1-origin.
320 (define-method move-cursor-to ((con <vt100>) y x)
321 (putstr con (format "\x1b;[~d;~dH" (+ y 1) (+ x 1))))
322
323 (define-method reset-terminal ((con <vt100>))
324 (set! (~ con'screen-size) #f)
325 (putstr con "\x1b;c"))
326 (define-method clear-screen ((con <vt100>)) (putstr con "\x1b;[2J"))
327 (define-method clear-to-eol ((con <vt100>)) (putstr con "\x1b;[K"))
328 (define-method clear-to-eos ((con <vt100>)) (putstr con "\x1b;[J"))
329
330 (define-method hide-cursor ((con <vt100>)) (putstr con "\x1b;[?25l"))
331 (define-method show-cursor ((con <vt100>)) (putstr con "\x1b;[?25h"))
332
333 ;; Move cursor; if cursor is already top or bottom, scroll.
334 ;; If optional arguments are specified, these methods return
335 ;; the difference of the cursor position y.
336 ;; NB: full-column-flag is a dummy argument for compatibility with
337 ;; <windows-console>.
338 (define-method cursor-down/scroll-up ((con <vt100>)
339 :optional (y #f) (height #f)
340 (full-column-flag #f))
341 (putstr con "\x1b;D")
342 (if (and y height (>= y (- height 1))) 0 1))
343 (define-method cursor-up/scroll-down ((con <vt100>)
344 :optional (y #f))
345 (putstr con "\x1b;M")
346 (if (and y (<= y 0)) 0 -1))
347
348 ;; No portable way to directly query it, so we take a kind of heuristic approach.
349 (define-method query-screen-size ((con <vt100>) :optional (clear-cache #f))
350 (if-let1 p (and (not clear-cache) (~ con'screen-size))
351 (values (car p) (cdr p))
352 (let ((max-dim 2000))
353 (putstr con "\x1b;7") ; save cursor pos
354 (move-cursor-to con max-dim max-dim)
355 (unwind-protect (receive (h w) (query-cursor-position con)
356 (set! (~ con'screen-size) (cons (+ h 1) (+ w 1)))
357 (values (+ h 1) (+ w 1)))
358 (putstr con "\x1b;8"))))) ;restore cursor pos
359
360 (define-method set-character-attribute ((con <vt100>) spec)
361 (define (color->n color)
362 (or (find-index (cut eq? <> color)
363 '(black red green yellow blue magenta cyan white))
364 9)) ; default
365 (let* ([chattr (parse-char-attrs spec (~ con'current-attrs))]
366 [opts (cond-list [(~ chattr'bright) 1]
367 [(~ chattr'underscore) 4]
368 [(~ chattr'reverse) 7])]
369 [fgcolor (+ (color->n (~ chattr'fgcolor)) 30)]
370 [bgcolor (+ (color->n (~ chattr'bgcolor)) 40)]
371 [nlist `(0 ,fgcolor ,bgcolor ,@opts)])
372 ($ putstr con
373 $ format "\x1b;[~am"
374 $ string-join (map number->string nlist) ";")))
375
376 (define-method reset-character-attribute ((con <vt100>))
377 (putstr con "\x1b;[0m"))
378
379 ;; NB: This should actually save the attr and restores it, so that
380 ;; we can nest this. However, somehow I can't make "Save/restore cursor&attrs"
381 ;; sequences (ESC 7 and ESC 8) on xterm. For the time being, don't nest this.
382 (define-method with-character-attribute ((con <vt100>) attrs thunk)
383 (unwind-protect
384 (begin
385 (set-character-attribute con attrs)
386 (thunk))
387 (reset-character-attribute con)))
388
389 ;; This method is for workaround of windows IME bug. For vt100,
390 ;; we don't need to do anything. See console/windows.scm for the details.
391 (define-method ensure-bottom-room ((con <vt100>) :optional full-column-flag)
392 #f)