bjoterm/tests/terminal.bjo
Linus Björnstam fe42387a4c 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>
2026-11-30 20:31:29 +01:00

145 lines
7 KiB
Text

;; 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)