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:
Linus Björnstam 2026-11-30 20:31:29 +01:00
commit fe42387a4c
12 changed files with 1830 additions and 0 deletions

95
tests/keys.bjo Normal file
View file

@ -0,0 +1,95 @@
;; 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/.
;; The key decoder: bytes of terminal input in, events out.
;;
;; bjo test tests/keys.bjo
(import (std prelude))
(import (std simpletest))
(import (bjoterm terminal))
(: (-> (Vec int) (Array byte)))
(defun (bytes-of xs)
(def (: out (Array byte)) (make-array (vec-length xs)))
(loop (:for i (range 0 (vec-length xs)))
(:do (array-set! out i (cast byte (vec-ref xs i)))))
out)
(: (-> string (Array byte)))
(defun (utf8 s)
(bytestring->bytes (string->bytestring s)))
(: (-> (Array byte) string))
(defun (decoded bytes)
(string-join (vec-map event->string (decode-input bytes)) ", "))
(: (-> string string string void))
(defun (expect-keys name input expected)
(expect name (decoded (utf8 input)) expected))
(: string)
(def esc "\u{1B}")
(defun (main args)
;; Plain keys and control bytes.
(expect-keys "a letter" "a" "key a")
(expect-keys "Ctrl and a letter" "\u{1}" "key C-a")
(expect-keys "CR is Enter" "\r" "key <enter>")
(expect-keys "LF is Ctrl-J" "\n" "key C-j")
(expect-keys "Tab" "\t" "key <tab>")
(expect-keys "DEL is Backspace" "\u{7F}" "key <backspace>")
(expect-keys "BS is Ctrl-Backspace" "\u{8}" "key C-<backspace>")
(expect "NUL is Ctrl-Space" (decoded (bytes-of [0])) "key C-<space>")
(expect-keys "Ctrl-\\" "\u{1C}" "key C-\\")
(expect-keys "several keys" "ab" "key a, key b")
;; Escape and Alt.
(expect-keys "a lone ESC is Escape" esc "key <escape>")
(expect-keys "ESC and a key is Alt" (str esc "x") "key M-x")
(expect-keys "ESC and Ctrl-A" (str esc "\u{1}") "key C-M-a")
(expect-keys "ESC ESC is Alt-Escape" (str esc esc) "key M-<escape>")
(expect-keys "ESC [ alone is Alt-[" (str esc "[") "key M-[")
;; CSI keys.
(expect-keys "arrows" (str esc "[A" esc "[B" esc "[C" esc "[D")
"key <up>, key <down>, key <right>, key <left>")
(expect-keys "Home and End" (str esc "[H" esc "[F") "key <home>, key <end>")
(expect-keys "Ctrl-Up" (str esc "[1;5A") "key C-<up>")
(expect-keys "Alt-Left" (str esc "[1;3D") "key M-<left>")
(expect-keys "Shift-Right" (str esc "[1;2C") "key S-<right>")
(expect-keys "Ctrl-Shift-Alt-Up" (str esc "[1;8A") "key C-M-S-<up>")
(expect-keys "the ~ keys" (str esc "[2~" esc "[3~" esc "[5~" esc "[6~" esc "[1~" esc "[4~")
"key <insert>, key <delete>, key <pageup>, key <pagedown>, key <home>, key <end>")
(expect-keys "Ctrl-PageUp" (str esc "[5;5~") "key C-<pageup>")
(expect-keys "F5 to F12" (str esc "[15~" esc "[17~" esc "[21~" esc "[23~" esc "[24~")
"key <f5>, key <f6>, key <f10>, key <f11>, key <f12>")
(expect-keys "Shift-Tab" (str esc "[Z") "key S-<tab>")
(expect-keys "Alt-Up as ESC ESC [ A" (str esc esc "[A") "key M-<up>")
(expect-keys "Shift-F1 as CSI" (str esc "[1;2P") "key S-<f1>")
(expect-keys "an unknown sequence" (str esc "[99x") "key <unknown ^[[99x>")
(expect-keys "a cut sequence at the end" (str esc "[1;5") "key <unknown ^[[1;5>")
;; SS3 keys.
(expect-keys "F1 to F4" (str esc "OP" esc "OQ" esc "OR" esc "OS")
"key <f1>, key <f2>, key <f3>, key <f4>")
(expect-keys "application cursor keys" (str esc "OA" esc "OD") "key <up>, key <left>")
(expect-keys "ESC O alone is Alt-O" (str esc "O") "key M-O")
;; UTF-8.
(expect-keys "two bytes" "é" "key é")
(expect-keys "four bytes" "😀" "key 😀")
(expect-keys "letters between keys" (str "å" esc "[A" "ö") "key å, key <up>, key ö")
(expect "a cut character at the end" (decoded (bytes-of [195])) "key \u{FFFD}")
(expect "a byte that starts nothing" (decoded (bytes-of [255 97])) "key \u{FFFD}, key a")
(expect "a cut character before ASCII" (decoded (bytes-of [226 130 97])) "key \u{FFFD}, key a")
;; Bracketed paste.
(expect-keys "a paste" (str esc "[200~hello" esc "[201~") "paste \"hello\"")
(expect-keys "a paste makes line ends LF" (str esc "[200~a\r\nb\rc\nd" esc "[201~")
"paste \"a\\nb\\nc\\nd\"")
(expect-keys "keys in a paste are text" (str esc "[200~" esc "[A\u{3}" esc "[201~x")
(str "paste " (written (str esc "[A\u{3}")) ", key x"))
(expect-keys "a paste that does not end" (str esc "[200~abc") "")
(println "keys ok"))

145
tests/terminal.bjo Normal file
View file

@ -0,0 +1,145 @@
;; 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/.
;; Raw mode, reading events and restoring the modes, on a real terminal.
;;
;; bjo test tests/terminal.bjo
;;
;; The test runs itself again under `script`, which gives the child a
;; pseudo-terminal, and writes keys to it with pauses between them. The
;; parent checks what the child printed.
(import (std prelude))
(import (std simpletest))
(import (std run))
(import (bjoterm terminal))
(import/extern
(command-line (: System.Environment.GetCommandLineArgs (-> (Array string)) #:no-raise)))
;; ---- the child -------------------------------------------------------------
;; The terminal's local modes, from `stty -a`: "icanon" or "-icanon", and
;; the same for echo.
(: (-> string))
(defun (modes)
(match (run/output '(sh "-c" "stty -a </dev/tty"))
((Ok (Tuple _ text))
(str (if (string-contains? text "-icanon") "-icanon" "icanon") " "
(if (string-contains? text "-echo ") "-echo" "echo")))
((Err e) (run-error-message e))))
(: (-> Terminal void))
(defun (print-events-until-q term)
(let go ()
(match (read-event term)
((TermKey (KeyChar #\q) _) unit)
(ev (println (str "event: " (event->string ev)))
(go)))))
(: (-> void))
(defun (child)
(match (terminal-open)
((Err e) (println (str "open: " (terminal-error-message e))))
((Ok term)
(println (str "before: " (modes)))
(with-raw-mode term
(fun ()
(println (str "raw: " (modes)))
(println (str "timeout: " (match (read-event/timeout term 100)
(None "none")
((Some ev) (event->string ev)))))
;; The size changes, and the kernel sends SIGWINCH.
(ignore (run/status '(sh "-c" "stty cols 100 rows 30 </dev/tty")))
(println (str "event: " (event->string (read-event term))))
;; Stopped and continued: cooked while stopped, raw after, and
;; the next event asks for a redraw. A child stops this process,
;; records the modes, and continues it. `script` stops itself when
;; its child stops, so the child continues `script` too.
(ignore (run/status '(sh "-c" "kill -TSTP $PPID; sleep 0.3; stty -a </dev/tty | grep -o -- '-\\?icanon' > /tmp/bjoterm-stopped.txt; kill -CONT $PPID $(ps -o ppid= -p $PPID)")))
(println (str "stopped: " (match (file-read-text "/tmp/bjoterm-stopped.txt")
((Ok text) (string-trim text))
((Err _) "not recorded"))))
(ignore (file-delete "/tmp/bjoterm-stopped.txt"))
(println (str "continued: " (modes)))
(println (str "event: " (event->string (read-event term))))
(println "ready")
(print-events-until-q term)))
(println (str "after: " (modes)))
(println (str "nested: " (match (try (with-raw-mode term
(fun () (with-raw-mode term (fun () unit))))
#:catch (System.InvalidOperationException))
((Ok _) "no error")
((Err _) "raises"))))
(println (str "after-nested: " (modes) " " (if (terminal-raw? term) "raw" "not raw"))))))
;; Raw mode, then `signal` from a child. The parent checks the modes after
;; this process has ended.
(: (-> string bool void))
(defun (ending-child signal signals?)
(match (terminal-open)
((Err e) (println (str "open: " (terminal-error-message e))))
((Ok term)
(with-raw-mode term
(fun ()
(ignore (run/status '(sh "-c" ,(str "kill -" signal " $PPID"))))
(ignore (read-event term))
(println "not ended"))
#:signals? signals?))))
;; ---- the parent ------------------------------------------------------------
(: (-> void))
(defun (parent)
;; The test is an assembly that `dotnet` runs.
(def self (str "dotnet " (array-ref (command-line) 0)))
;; The keys come after "ready": `a`, Up, a lone ESC (the reader decides
;; after its timeout), Ctrl-Up split over two writes, then `q`.
(def keys (str "sleep 2; printf 'a\\033[A'; sleep 0.3; printf '\\033'; sleep 0.3; "
"printf '\\033[1;'; sleep 0.01; printf '5A'; sleep 0.3; printf q; sleep 1"))
(def command (str "(" keys ") | script -qec '" self " child' /dev/null"))
(def out (match (run/output '(sh "-c" ,command))
((Ok (Tuple _ text)) (string-replace text "\r" ""))
((Err e) (run-error-message e))))
(expect-true "the terminal opens" (not (string-contains? out "open:")))
(expect-true "cooked before" (string-contains? out "before: icanon echo"))
(expect-true "raw mode turns off line editing and echo" (string-contains? out "raw: -icanon -echo"))
(expect-true "read-event/timeout returns None" (string-contains? out "timeout: none"))
(expect-true "a resize is an event" (string-contains? out "event: resized 100x30"))
(expect-true "stopped in raw mode: cooked while stopped" (string-contains? out "stopped: icanon"))
(expect-true "raw again after SIGCONT" (string-contains? out "continued: -icanon -echo"))
(expect-true "and a redraw event" (string-contains? out "event: resized 100x30\nready"))
(expect-true "a letter" (string-contains? out "event: key a\n"))
(expect-true "an arrow in the same write" (string-contains? out "event: key <up>\n"))
(expect-true "a lone ESC after the timeout" (string-contains? out "event: key <escape>\n"))
(expect-true "a sequence split over two writes" (string-contains? out "event: key C-<up>\n"))
(expect-true "the modes come back" (string-contains? out "after: icanon echo"))
(expect-true "nested raw mode raises" (string-contains? out "nested: raises"))
(expect-true "and the modes come back after it" (string-contains? out "after-nested: icanon echo not raw"))
(unless (string-contains? out "after-nested: icanon echo not raw")
(println out))
(expect-true "SIGTERM in raw mode restores the modes"
(string-contains? (modes-after self "term") "exit=143 icanon"))
(expect-true "SIGINT in raw mode with #:signals? cancels main, which restores the modes"
(string-contains? (modes-after self "int") "exit=130 icanon")))
;; The exit code of the child that ends with `which`, and the terminal's
;; mode after it.
(: (-> string string string))
(defun (modes-after self which)
(def command (str "sleep 3 | script -qec '" self " " which "; "
"echo exit=$? $(stty -a </dev/tty | grep -o -- \"-\\?icanon\")' /dev/null"))
(match (run/output '(sh "-c" ,command))
((Ok (Tuple _ text)) (string-replace text "\r" ""))
((Err e) (run-error-message e))))
(defun (main args)
(cond
((= args ["child"]) (child))
((= args ["term"]) (ending-child "TERM" #f))
((= args ["int"]) (ending-child "INT" #t))
((file-exists? "/usr/bin/script") (parent))
(else (println "skipped: no script command")))
0)