bjoterm: raw mode, key events and escape sequences
- (bjoterm terminal): terminal-open, with-raw-mode, terminal-size, terminal-suspend, read-event and read-event/timeout, and escape sequences for the cursor, clearing, the alternate screen, bracketed paste and styles. Linux only. - glue/Tty.cs: termios, poll on fd 0, SIGWINCH, SIGCONT, SIGTSTP, and restoring the modes at SIGTERM, SIGHUP, SIGQUIT and process exit. - glue/Keys.cs: the decoder of CSI and SS3 keys with modifiers, Alt, UTF-8 and bracketed paste. - Tests: the decoder from bytes, and raw mode on a pseudo-terminal under script. plan.org has the decisions and the phases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fe42387a4c
12 changed files with 1830 additions and 0 deletions
405
src/terminal.bjo
Normal file
405
src/terminal.bjo
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
;; This Source Code Form is subject to the terms of the Mozilla Public
|
||||
;; License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
;; (bjoterm terminal): raw mode, key events and escape sequences.
|
||||
;;
|
||||
;; (def (Ok term) (terminal-open) :leave-with 1)
|
||||
;; (with-raw-mode term
|
||||
;; (fun ()
|
||||
;; (let go ()
|
||||
;; (match (read-event term)
|
||||
;; ((TermKey (KeyChar #\q) _) unit)
|
||||
;; (ev (println (event->string ev)) (go))))))
|
||||
;;
|
||||
;; - Linux only. Standard input and standard output must be terminals.
|
||||
;; - Keys are read from fd 0 directly, not through `current-input-port`.
|
||||
;; Input that the port has buffered already is not seen.
|
||||
;; - Do not read keys through .NET's `Console` in a program that uses this
|
||||
;; module: .NET then sets its own terminal modes.
|
||||
;; - Output is strings: write them to standard output. `read-event` flushes
|
||||
;; `current-output-port` before it waits.
|
||||
;; - See glue/Tty.cs and glue/Keys.cs for the C# side.
|
||||
|
||||
(import (std prelude))
|
||||
|
||||
(export
|
||||
Terminal TerminalError Key Mods TermEvent Color Style
|
||||
terminal-open terminal-error-message with-raw-mode terminal-raw?
|
||||
terminal-size terminal-suspend
|
||||
read-event read-event/timeout
|
||||
no-mods key->string event->string decode-input
|
||||
;; Escape sequences.
|
||||
cursor-to cursor-up cursor-down cursor-forward cursor-back cursor-column
|
||||
cursor-save cursor-restore cursor-hide cursor-show
|
||||
clear-screen clear-below clear-line clear-to-line-end
|
||||
alt-screen-on alt-screen-off bracketed-paste-on bracketed-paste-off
|
||||
styled style-start style-reset)
|
||||
|
||||
(import/class
|
||||
(Tty (: Bjoterm.Tty))
|
||||
(NEvent (: Bjoterm.TermEvent)))
|
||||
|
||||
(import/extern
|
||||
(tty-open (: Bjoterm.Tty.Open (-> Tty)
|
||||
#:exceptions (System.PlatformNotSupportedException System.IO.IOException
|
||||
System.ComponentModel.Win32Exception) #:no-raise))
|
||||
(tty-size (: Bjoterm.Tty.Size (-> Tty (Array int)) #:no-raise))
|
||||
(tty-raw? (: Bjoterm.Tty.IsRaw (-> Tty bool) #:get #:no-raise))
|
||||
(enter-raw (: Bjoterm.Tty.EnterRaw (-> Tty bool void)
|
||||
#:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
|
||||
(leave-raw (: Bjoterm.Tty.LeaveRaw (-> Tty void) #:no-raise))
|
||||
(tty-suspend (: Bjoterm.Tty.Suspend (-> Tty void) #:no-raise))
|
||||
(tty-read (: Bjoterm.Tty.ReadAsync (-> Tty int NEvent) #:async
|
||||
#:raises (System.InvalidOperationException System.ComponentModel.Win32Exception)))
|
||||
(decode-all (: Bjoterm.Decoder.DecodeAll (-> (Array byte) (Array NEvent)) #:no-raise))
|
||||
(ev-kind (: Bjoterm.TermEvent.Kind (-> NEvent int) #:get #:no-raise))
|
||||
(ev-key (: Bjoterm.TermEvent.Key (-> NEvent int) #:get #:no-raise))
|
||||
(ev-value (: Bjoterm.TermEvent.Value (-> NEvent int) #:get #:no-raise))
|
||||
(ev-value2 (: Bjoterm.TermEvent.Value2 (-> NEvent int) #:get #:no-raise))
|
||||
(ev-mods (: Bjoterm.TermEvent.Mods (-> NEvent int) #:get #:no-raise))
|
||||
(ev-text (: Bjoterm.TermEvent.Text (-> NEvent string) #:get #:no-raise)))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Types
|
||||
;; ===========================================================================
|
||||
|
||||
;; The terminal of this process.
|
||||
(type (: Terminal #:opaque (Record (: tty Tty))))
|
||||
|
||||
;; Why `terminal-open` failed.
|
||||
;; - `TerminalUnsupported`: the system is not Linux.
|
||||
;; - `NotATerminal`: standard input or standard output is not a terminal.
|
||||
(type (: TerminalError (Union TerminalUnsupported (: NotATerminal string))))
|
||||
|
||||
;; The modifier keys held with a key.
|
||||
(type (: Mods (Record (: shift? bool) (: alt? bool) (: ctrl? bool))))
|
||||
|
||||
;; A key.
|
||||
;; - `KeyChar`: a character. Ctrl and a letter is the letter with `ctrl?`:
|
||||
;; Ctrl-A is `(KeyChar #\a)`. Ctrl-J (a line feed) is `(KeyChar #\j)`, not
|
||||
;; `KeyEnter`.
|
||||
;; - `KeyBackspace` with `ctrl?` is byte 8, which is Ctrl-H and, on some
|
||||
;; terminals, Ctrl-Backspace.
|
||||
;; - `KeyF`: F1 to F12.
|
||||
;; - `KeyUnknown`: a sequence the decoder does not know, with ESC shown as
|
||||
;; "^[".
|
||||
(type (: Key (Union (: KeyChar char) KeyEnter KeyTab KeyBackspace KeyEscape
|
||||
KeyUp KeyDown KeyLeft KeyRight KeyHome KeyEnd
|
||||
KeyPageUp KeyPageDown KeyInsert KeyDelete
|
||||
(: KeyF int) (: KeyUnknown string))))
|
||||
|
||||
;; An event read from the terminal.
|
||||
;; - `TermKey`: a key and its modifiers.
|
||||
;; - `TermPaste`: text pasted while bracketed paste is on, with line ends
|
||||
;; made "\n".
|
||||
;; - `TermResized`: the new size, columns then rows. Also after the program
|
||||
;; was stopped and continued: draw the screen again.
|
||||
;; - `TermEnd`: end of input; the terminal hung up.
|
||||
(type (: TermEvent (Union (: TermKey Key Mods) (: TermPaste string)
|
||||
(: TermResized int int) TermEnd)))
|
||||
|
||||
;; A color.
|
||||
;; - `Ansi`: 0 to 7 are black, red, green, yellow, blue, magenta, cyan and
|
||||
;; white; 8 to 15 are their bright forms.
|
||||
;; - `Palette`: 0 to 255, of the 256-color palette.
|
||||
;; - `Rgb`: red, green and blue, 0 to 255 each.
|
||||
(type (: Color (Union (: Ansi int) (: Palette int) (: Rgb int int int))))
|
||||
|
||||
;; A text style.
|
||||
(type (: Style (Union StyleBold StyleFaint StyleItalic StyleUnderline StyleReverse
|
||||
(: StyleFg Color) (: StyleBg Color))))
|
||||
|
||||
;; ===========================================================================
|
||||
;; The terminal
|
||||
;; ===========================================================================
|
||||
|
||||
;; Opens the terminal of this process. Returns the same terminal each time.
|
||||
(: (-> (Result TerminalError Terminal)))
|
||||
(defun (terminal-open)
|
||||
(match (tty-open)
|
||||
((Ok tty) (Ok (Terminal (tty tty))))
|
||||
((Err e)
|
||||
(match e
|
||||
((:is System.PlatformNotSupportedException) (Err TerminalUnsupported))
|
||||
(_ (Err (NotATerminal (.-Message e))))))))
|
||||
|
||||
(: (-> TerminalError string))
|
||||
(defun (terminal-error-message e)
|
||||
(match e
|
||||
(TerminalUnsupported "bjoterm supports only Linux")
|
||||
((NotATerminal why) why)))
|
||||
|
||||
;; Runs `body` in raw mode, and restores the terminal's modes after it.
|
||||
;; - Raw mode: no echo, no line editing, each byte is read as it comes.
|
||||
;; Output is unchanged: "\n" still starts a line at column 0.
|
||||
;; - `#:signals? #t` keeps Ctrl-C, Ctrl-Z and Ctrl-\ as signals. By default
|
||||
;; they are keys.
|
||||
;; - The modes are restored when `body` returns or raises, when main is
|
||||
;; cancelled (Ctrl-C with `#:signals? #t`), at process exit, and at
|
||||
;; SIGTERM, SIGHUP and SIGQUIT, which end the process.
|
||||
;; - When the process is stopped and continued, raw mode is set again.
|
||||
;; - Raises InvalidOperationException when the terminal is in raw mode
|
||||
;; already.
|
||||
(: (-> Terminal (-> %a) (#:signals? bool) %a))
|
||||
(defun (with-raw-mode term body #:signals? #f)
|
||||
(def tty (record-ref term tty))
|
||||
(enter-raw tty signals?)
|
||||
(try (body)
|
||||
#:finally (leave-raw tty)))
|
||||
|
||||
;; Whether the terminal is in raw mode.
|
||||
(: (-> Terminal bool))
|
||||
(defun (terminal-raw? term)
|
||||
(tty-raw? (record-ref term tty)))
|
||||
|
||||
;; The size: columns, then rows. 80 by 24 when the terminal does not say.
|
||||
(: (-> Terminal (Tuple int int)))
|
||||
(defun (terminal-size term)
|
||||
(def size (tty-size (record-ref term tty)))
|
||||
(Tuple (array-ref size 0) (array-ref size 1)))
|
||||
|
||||
;; Stops the program as Ctrl-Z does in a shell. For a program in raw mode
|
||||
;; that reads Ctrl-Z as a key.
|
||||
;; - The modes from before raw mode are restored while it is stopped, and
|
||||
;; raw mode is set again when it continues. The next event is then
|
||||
;; `TermResized`.
|
||||
;; - Under a shell without job control, nothing stops.
|
||||
(: (-> Terminal void))
|
||||
(defun (terminal-suspend term)
|
||||
(flush-port (parameter-ref current-output-port))
|
||||
(tty-suspend (record-ref term tty)))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Events
|
||||
;; ===========================================================================
|
||||
|
||||
;; Waits for the next event. Flushes `current-output-port` first.
|
||||
(: (-> Terminal TermEvent) #:sync)
|
||||
(defun (read-event term)
|
||||
(let go ()
|
||||
(match (read-event/timeout term -1)
|
||||
((Some ev) ev)
|
||||
(None (go)))))
|
||||
|
||||
;; Waits at most `ms` milliseconds for the next event; below 0, for ever.
|
||||
;; Returns None at the timeout. Flushes `current-output-port` first.
|
||||
(: (-> Terminal int (Option TermEvent)) #:sync)
|
||||
(defun (read-event/timeout term ms)
|
||||
(flush-port (parameter-ref current-output-port))
|
||||
(match (sync/blocking (promise-join (bjo (reading (record-ref term tty) ms))))
|
||||
((Err e) (raise e))
|
||||
((Ok ev) (event-of ev))))
|
||||
|
||||
(: (-> Tty int NEvent))
|
||||
(defbjo (reading tty ms)
|
||||
(tty-read tty ms))
|
||||
|
||||
(: (-> NEvent (Option TermEvent)))
|
||||
(defun (event-of ev)
|
||||
(match (ev-kind ev)
|
||||
(0 None)
|
||||
(1 (Some (TermKey (key-of ev) (mods-of (ev-mods ev)))))
|
||||
(2 (Some (TermPaste (ev-text ev))))
|
||||
(3 (Some (TermResized (ev-value ev) (ev-value2 ev))))
|
||||
(_ (Some TermEnd))))
|
||||
|
||||
(: (-> NEvent Key))
|
||||
(defun (key-of ev)
|
||||
(match (ev-key ev)
|
||||
(0 (KeyChar (int->char (ev-value ev))))
|
||||
(1 KeyEnter)
|
||||
(2 KeyTab)
|
||||
(3 KeyBackspace)
|
||||
(4 KeyEscape)
|
||||
(5 KeyUp)
|
||||
(6 KeyDown)
|
||||
(7 KeyLeft)
|
||||
(8 KeyRight)
|
||||
(9 KeyHome)
|
||||
(10 KeyEnd)
|
||||
(11 KeyPageUp)
|
||||
(12 KeyPageDown)
|
||||
(13 KeyInsert)
|
||||
(14 KeyDelete)
|
||||
(15 (KeyF (ev-value ev)))
|
||||
(_ (KeyUnknown (ev-text ev)))))
|
||||
|
||||
(: (-> int Mods))
|
||||
(defun (mods-of bits)
|
||||
(Mods (shift? (not (= 0 (bitwise-and bits 1))))
|
||||
(alt? (not (= 0 (bitwise-and bits 2))))
|
||||
(ctrl? (not (= 0 (bitwise-and bits 4))))))
|
||||
|
||||
;; Decodes bytes of terminal input into events, as `read-event` would
|
||||
;; return them. A partial event at the end is decoded as it is: a lone ESC
|
||||
;; is `KeyEscape`. For tests, and for input recorded earlier.
|
||||
(: (-> (Array byte) (Vec TermEvent)))
|
||||
(defun (decode-input bytes)
|
||||
(loop (:for ev (decode-all bytes))
|
||||
(:acc v (vecing (match (event-of ev)
|
||||
((Some e) e)
|
||||
(None TermEnd))))))
|
||||
|
||||
;; No modifier keys.
|
||||
(: Mods)
|
||||
(def no-mods (Mods (shift? #f) (alt? #f) (ctrl? #f)))
|
||||
|
||||
;; A key as text, such as "C-a", "M-<up>" or "S-<tab>": modifiers as
|
||||
;; Emacs writes them (C- Ctrl, M- Alt, S- Shift), and names in brackets.
|
||||
(: (-> Key Mods string))
|
||||
(defun (key->string key mods)
|
||||
(def name
|
||||
(match key
|
||||
((KeyChar #\space) "<space>")
|
||||
((KeyChar c) (char->string c))
|
||||
(KeyEnter "<enter>")
|
||||
(KeyTab "<tab>")
|
||||
(KeyBackspace "<backspace>")
|
||||
(KeyEscape "<escape>")
|
||||
(KeyUp "<up>")
|
||||
(KeyDown "<down>")
|
||||
(KeyLeft "<left>")
|
||||
(KeyRight "<right>")
|
||||
(KeyHome "<home>")
|
||||
(KeyEnd "<end>")
|
||||
(KeyPageUp "<pageup>")
|
||||
(KeyPageDown "<pagedown>")
|
||||
(KeyInsert "<insert>")
|
||||
(KeyDelete "<delete>")
|
||||
((KeyF n) (str "<f" (int->string n) ">"))
|
||||
((KeyUnknown text) (str "<unknown " text ">"))))
|
||||
(str (if (record-ref mods ctrl?) "C-" "")
|
||||
(if (record-ref mods alt?) "M-" "")
|
||||
(if (record-ref mods shift?) "S-" "")
|
||||
name))
|
||||
|
||||
;; An event as text, for logs and tests.
|
||||
(: (-> TermEvent string))
|
||||
(defun (event->string ev)
|
||||
(match ev
|
||||
((TermKey key mods) (str "key " (key->string key mods)))
|
||||
((TermPaste text) (str "paste " (written text)))
|
||||
((TermResized cols rows) (str "resized " (int->string cols) "x" (int->string rows)))
|
||||
(TermEnd "end")))
|
||||
|
||||
;; ===========================================================================
|
||||
;; Escape sequences
|
||||
;; ===========================================================================
|
||||
;; Each returns a string to write to standard output. Columns and rows
|
||||
;; count from 0.
|
||||
|
||||
(: string)
|
||||
(def esc "\u{1B}")
|
||||
|
||||
(: (-> string string))
|
||||
(defun (csi body) (str esc "[" body))
|
||||
|
||||
;; Moves the cursor to a column and a row, from 0.
|
||||
(: (-> int int string))
|
||||
(defun (cursor-to col row)
|
||||
(csi (str (int->string (+ row 1)) ";" (int->string (+ col 1)) "H")))
|
||||
|
||||
;; Moves the cursor to a column of its row, from 0.
|
||||
(: (-> int string))
|
||||
(defun (cursor-column col)
|
||||
(csi (str (int->string (+ col 1)) "G")))
|
||||
|
||||
(: (-> int string string))
|
||||
(defun (cursor-move n code)
|
||||
(if (<= n 0) "" (csi (str (int->string n) code))))
|
||||
|
||||
;; Moves the cursor `n` rows up. Nothing for 0.
|
||||
(: (-> int string))
|
||||
(defun (cursor-up n) (cursor-move n "A"))
|
||||
|
||||
(: (-> int string))
|
||||
(defun (cursor-down n) (cursor-move n "B"))
|
||||
|
||||
(: (-> int string))
|
||||
(defun (cursor-forward n) (cursor-move n "C"))
|
||||
|
||||
(: (-> int string))
|
||||
(defun (cursor-back n) (cursor-move n "D"))
|
||||
|
||||
(: string)
|
||||
(def cursor-save (str esc "7"))
|
||||
|
||||
(: string)
|
||||
(def cursor-restore (str esc "8"))
|
||||
|
||||
(: string)
|
||||
(def cursor-hide (csi "?25l"))
|
||||
|
||||
(: string)
|
||||
(def cursor-show (csi "?25h"))
|
||||
|
||||
;; Clears the screen. The cursor does not move.
|
||||
(: string)
|
||||
(def clear-screen (csi "2J"))
|
||||
|
||||
;; Clears from the cursor to the end of the screen.
|
||||
(: string)
|
||||
(def clear-below (csi "J"))
|
||||
|
||||
;; Clears the cursor's row.
|
||||
(: string)
|
||||
(def clear-line (csi "2K"))
|
||||
|
||||
;; Clears from the cursor to the end of its row.
|
||||
(: string)
|
||||
(def clear-to-line-end (csi "K"))
|
||||
|
||||
;; The alternate screen, which full-screen programs use. Leaving it shows
|
||||
;; the screen as it was.
|
||||
(: string)
|
||||
(def alt-screen-on (csi "?1049h"))
|
||||
|
||||
(: string)
|
||||
(def alt-screen-off (csi "?1049l"))
|
||||
|
||||
;; Bracketed paste: the terminal marks pasted text, and `read-event`
|
||||
;; returns it as one `TermPaste`. Turn it off before the program ends.
|
||||
(: string)
|
||||
(def bracketed-paste-on (csi "?2004h"))
|
||||
|
||||
(: string)
|
||||
(def bracketed-paste-off (csi "?2004l"))
|
||||
|
||||
(: (-> int Color string))
|
||||
(defun (color-code base c)
|
||||
(match c
|
||||
((Ansi n) (if (< n 8)
|
||||
(int->string (+ base n))
|
||||
(int->string (+ base 60 (- n 8)))))
|
||||
((Palette n) (str (int->string (+ base 8)) ";5;" (int->string n)))
|
||||
((Rgb r g b) (str (int->string (+ base 8)) ";2;" (int->string r) ";" (int->string g) ";" (int->string b)))))
|
||||
|
||||
(: (-> Style string))
|
||||
(defun (style-code s)
|
||||
(match s
|
||||
(StyleBold "1")
|
||||
(StyleFaint "2")
|
||||
(StyleItalic "3")
|
||||
(StyleUnderline "4")
|
||||
(StyleReverse "7")
|
||||
((StyleFg c) (color-code 30 c))
|
||||
((StyleBg c) (color-code 40 c))))
|
||||
|
||||
;; Starts the styles. Nothing for no styles.
|
||||
(: (-> (Vec Style) string))
|
||||
(defun (style-start styles)
|
||||
(if (= (vec-length styles) 0)
|
||||
""
|
||||
(csi (str (string-join (vec-map style-code styles) ";") "m"))))
|
||||
|
||||
;; Ends every style.
|
||||
(: string)
|
||||
(def style-reset (csi "0m"))
|
||||
|
||||
;; `text` in the styles, and the styles ended after it.
|
||||
(: (-> string (Vec Style) string))
|
||||
(defun (styled text styles)
|
||||
(if (= (vec-length styles) 0)
|
||||
text
|
||||
(str (style-start styles) text style-reset)))
|
||||
Loading…
Add table
Add a link
Reference in a new issue