bots-garden/razorbillpublic Fork
⑂ b971e1f
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#54 step 1: RazorbillTUI terminal layer restored from v0.1-agent

Terminal / PosixTerminal, Key / KeyDecoder (now with F1-F12 in the
ESC O and ESC [n~ forms), TextLayout, Screen (with hidesCursor), and a
FakeTerminal for tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-26T22:59:50+01:00 Browse files
b971e1f parent: cb55574
modified Package.swift +7 -0
@@ -73,6 +73,12 @@ let package = Package(
7373 .product(name: "NIOCore", package: "swift-nio"),
7474 ]
7575 ),
76+ // Full-screen terminal front-end (`rzb tui`) on a small ANSI layer of our own. Talks to a
77+ // running server over HTTP only: no MLX, no RazorbillServer.
78+ .target(
79+ name: "RazorbillTUI",
80+ dependencies: ["RazorbillCore"]
81+ ),
7682 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
7783 .target(
7884 name: "RazorbillCLI",
@@ -90,6 +96,7 @@ let package = Package(
9096 ),
9197 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),
9298 .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]),
99+ .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]),
93100 .testTarget(
94101 name: "RazorbillServerTests",
95102 dependencies: [
@@ -73,6 +73,12 @@ let package = Package(
73 .product(name: "NIOCore", package: "swift-nio"),73 .product(name: "NIOCore", package: "swift-nio"),
74 ]74 ]
75 ),75 ),
76+ // Full-screen terminal front-end (`rzb tui`) on a small ANSI layer of our own. Talks to a
77+ // running server over HTTP only: no MLX, no RazorbillServer.
78+ .target(
79+ name: "RazorbillTUI",
80+ dependencies: ["RazorbillCore"]
81+ ),
76 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.82 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
77 .target(83 .target(
78 name: "RazorbillCLI",84 name: "RazorbillCLI",
@@ -90,6 +96,7 @@ let package = Package(
90 ),96 ),
91 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),97 .testTarget(name: "RazorbillCoreTests", dependencies: ["RazorbillCore"]),
92 .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]),98 .testTarget(name: "RazorbillCLITests", dependencies: ["RazorbillCLI", "RazorbillServer"]),
99+ .testTarget(name: "RazorbillTUITests", dependencies: ["RazorbillTUI"]),
93 .testTarget(100 .testTarget(
94 name: "RazorbillServerTests",101 name: "RazorbillServerTests",
95 dependencies: [102 dependencies: [
added Sources/RazorbillTUI/Key.swift +114 -0
new file mode 100644
@@ -0,0 +1,114 @@
1+import Foundation
2+
3+/// A key press, or a terminal event, as the TUI understands it.
4+public enum Key: Sendable, Equatable {
5+ case character(Character)
6+ case enter, backspace, delete, tab, escape
7+ case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown
8+ /// A function key, `F1` = `.function(1)` … `F12` = `.function(12)`.
9+ case function(Int)
10+ /// Ctrl + a letter, e.g. `.control("c")`.
11+ case control(Character)
12+ /// The terminal changed size.
13+ case resize
14+}
15+
16+/// Turns the bytes read from a terminal in raw mode into ``Key``s.
17+///
18+/// Bytes arrive in arbitrary pieces: an escape sequence or a multi-byte UTF-8 character can be
19+/// cut in two, so incomplete input is kept until the next call.
20+///
21+/// ```swift
22+/// var decoder = KeyDecoder()
23+/// decoder.decode(Array("hi\r".utf8)) // [.character("h"), .character("i"), .enter]
24+/// decoder.decode([27, 91, 65]) // [.arrowUp]
25+/// decoder.decode([27, 79, 80]) // [.function(1)], F1 as xterm and Terminal.app send it
26+/// ```
27+public struct KeyDecoder: Sendable {
28+ private var pending: [UInt8] = []
29+
30+ public init() {}
31+
32+ public mutating func decode(_ bytes: [UInt8]) -> [Key] {
33+ pending += bytes
34+ var keys: [Key] = []
35+ while !pending.isEmpty {
36+ guard let (key, length) = Self.next(in: pending) else { break }
37+ keys.append(key)
38+ pending.removeFirst(length)
39+ }
40+ return keys
41+ }
42+
43+ /// A lone escape stays pending (it may start a sequence); call this when no more bytes come.
44+ public mutating func flush() -> [Key] {
45+ defer { pending = [] }
46+ return pending == [27] ? [.escape] : []
47+ }
48+
49+ /// The first key of `bytes` and how many bytes it used; `nil` when more bytes are needed.
50+ static func next(in bytes: [UInt8]) -> (Key, Int)? {
51+ let first = bytes[0]
52+ switch first {
53+ case 27:
54+ return escapeSequence(bytes)
55+ case 13, 10:
56+ return (.enter, 1)
57+ case 127, 8:
58+ return (.backspace, 1)
59+ case 9:
60+ return (.tab, 1)
61+ case 1 ... 26:
62+ return (.control(Character(Unicode.Scalar(first + 96))), 1)
63+ case 0 ..< 32:
64+ return (.escape, 1) // other control bytes are ignored as a harmless key
65+ default:
66+ return utf8Character(bytes)
67+ }
68+ }
69+
70+ private static func escapeSequence(_ bytes: [UInt8]) -> (Key, Int)? {
71+ guard bytes.count >= 2 else { return nil }
72+ guard bytes[1] == 91 || bytes[1] == 79 else { return (.escape, 1) } // ESC [ or ESC O
73+ guard bytes.count >= 3 else { return nil }
74+ let simple: [UInt8: Key] = [
75+ 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end,
76+ ]
77+ if let key = simple[bytes[2]] {
78+ return (key, 3)
79+ }
80+ // ESC O P … ESC O S: F1–F4 (xterm, Terminal.app, iTerm2).
81+ if bytes[1] == 79, (80 ... 83).contains(bytes[2]) {
82+ return (.function(Int(bytes[2]) - 79), 3)
83+ }
84+ // ESC [ <number> ~
85+ guard let tilde = bytes.dropFirst(2).firstIndex(of: 126) else {
86+ return bytes.count < 8 ? nil : (.escape, 1)
87+ }
88+ let number = String(bytes: bytes[2 ..< tilde], encoding: .ascii) ?? ""
89+ return (tilded[number] ?? .escape, tilde + 1)
90+ }
91+
92+ /// `ESC [ <number> ~` keys. F1–F4 as `11`–`14` come from rxvt and some Linux consoles.
93+ private static let tilded: [String: Key] = [
94+ "1": .home, "7": .home, "4": .end, "8": .end, "3": .delete, "5": .pageUp, "6": .pageDown,
95+ "11": .function(1), "12": .function(2), "13": .function(3), "14": .function(4),
96+ "15": .function(5), "17": .function(6), "18": .function(7), "19": .function(8),
97+ "20": .function(9), "21": .function(10), "23": .function(11), "24": .function(12),
98+ ]
99+
100+ private static func utf8Character(_ bytes: [UInt8]) -> (Key, Int)? {
101+ let first = bytes[0]
102+ let length =
103+ switch first {
104+ case 0xF0...: 4
105+ case 0xE0...: 3
106+ case 0xC0...: 2
107+ default: 1
108+ }
109+ guard bytes.count >= length else { return nil }
110+ // Invalid UTF-8 becomes a harmless, ignored key.
111+ let character = String(bytes: bytes[0 ..< length], encoding: .utf8)?.first
112+ return (character.map(Key.character) ?? .escape, length)
113+ }
114+}
new file mode 100644
@@ -0,0 +1,114 @@
1+import Foundation
2+
3+/// A key press, or a terminal event, as the TUI understands it.
4+public enum Key: Sendable, Equatable {
5+ case character(Character)
6+ case enter, backspace, delete, tab, escape
7+ case arrowLeft, arrowRight, arrowUp, arrowDown, home, end, pageUp, pageDown
8+ /// A function key, `F1` = `.function(1)` … `F12` = `.function(12)`.
9+ case function(Int)
10+ /// Ctrl + a letter, e.g. `.control("c")`.
11+ case control(Character)
12+ /// The terminal changed size.
13+ case resize
14+}
15+
16+/// Turns the bytes read from a terminal in raw mode into ``Key``s.
17+///
18+/// Bytes arrive in arbitrary pieces: an escape sequence or a multi-byte UTF-8 character can be
19+/// cut in two, so incomplete input is kept until the next call.
20+///
21+/// ```swift
22+/// var decoder = KeyDecoder()
23+/// decoder.decode(Array("hi\r".utf8)) // [.character("h"), .character("i"), .enter]
24+/// decoder.decode([27, 91, 65]) // [.arrowUp]
25+/// decoder.decode([27, 79, 80]) // [.function(1)], F1 as xterm and Terminal.app send it
26+/// ```
27+public struct KeyDecoder: Sendable {
28+ private var pending: [UInt8] = []
29+
30+ public init() {}
31+
32+ public mutating func decode(_ bytes: [UInt8]) -> [Key] {
33+ pending += bytes
34+ var keys: [Key] = []
35+ while !pending.isEmpty {
36+ guard let (key, length) = Self.next(in: pending) else { break }
37+ keys.append(key)
38+ pending.removeFirst(length)
39+ }
40+ return keys
41+ }
42+
43+ /// A lone escape stays pending (it may start a sequence); call this when no more bytes come.
44+ public mutating func flush() -> [Key] {
45+ defer { pending = [] }
46+ return pending == [27] ? [.escape] : []
47+ }
48+
49+ /// The first key of `bytes` and how many bytes it used; `nil` when more bytes are needed.
50+ static func next(in bytes: [UInt8]) -> (Key, Int)? {
51+ let first = bytes[0]
52+ switch first {
53+ case 27:
54+ return escapeSequence(bytes)
55+ case 13, 10:
56+ return (.enter, 1)
57+ case 127, 8:
58+ return (.backspace, 1)
59+ case 9:
60+ return (.tab, 1)
61+ case 1 ... 26:
62+ return (.control(Character(Unicode.Scalar(first + 96))), 1)
63+ case 0 ..< 32:
64+ return (.escape, 1) // other control bytes are ignored as a harmless key
65+ default:
66+ return utf8Character(bytes)
67+ }
68+ }
69+
70+ private static func escapeSequence(_ bytes: [UInt8]) -> (Key, Int)? {
71+ guard bytes.count >= 2 else { return nil }
72+ guard bytes[1] == 91 || bytes[1] == 79 else { return (.escape, 1) } // ESC [ or ESC O
73+ guard bytes.count >= 3 else { return nil }
74+ let simple: [UInt8: Key] = [
75+ 65: .arrowUp, 66: .arrowDown, 67: .arrowRight, 68: .arrowLeft, 72: .home, 70: .end,
76+ ]
77+ if let key = simple[bytes[2]] {
78+ return (key, 3)
79+ }
80+ // ESC O P … ESC O S: F1–F4 (xterm, Terminal.app, iTerm2).
81+ if bytes[1] == 79, (80 ... 83).contains(bytes[2]) {
82+ return (.function(Int(bytes[2]) - 79), 3)
83+ }
84+ // ESC [ <number> ~
85+ guard let tilde = bytes.dropFirst(2).firstIndex(of: 126) else {
86+ return bytes.count < 8 ? nil : (.escape, 1)
87+ }
88+ let number = String(bytes: bytes[2 ..< tilde], encoding: .ascii) ?? ""
89+ return (tilded[number] ?? .escape, tilde + 1)
90+ }
91+
92+ /// `ESC [ <number> ~` keys. F1–F4 as `11`–`14` come from rxvt and some Linux consoles.
93+ private static let tilded: [String: Key] = [
94+ "1": .home, "7": .home, "4": .end, "8": .end, "3": .delete, "5": .pageUp, "6": .pageDown,
95+ "11": .function(1), "12": .function(2), "13": .function(3), "14": .function(4),
96+ "15": .function(5), "17": .function(6), "18": .function(7), "19": .function(8),
97+ "20": .function(9), "21": .function(10), "23": .function(11), "24": .function(12),
98+ ]
99+
100+ private static func utf8Character(_ bytes: [UInt8]) -> (Key, Int)? {
101+ let first = bytes[0]
102+ let length =
103+ switch first {
104+ case 0xF0...: 4
105+ case 0xE0...: 3
106+ case 0xC0...: 2
107+ default: 1
108+ }
109+ guard bytes.count >= length else { return nil }
110+ // Invalid UTF-8 becomes a harmless, ignored key.
111+ let character = String(bytes: bytes[0 ..< length], encoding: .utf8)?.first
112+ return (character.map(Key.character) ?? .escape, length)
113+ }
114+}
added Sources/RazorbillTUI/Screen.swift +23 -0
new file mode 100644
@@ -0,0 +1,23 @@
1+/// A drawn screen: one string per row (ANSI styles allowed), and where the cursor goes (0-based).
2+/// Renderers produce it from a state; a ``Terminal`` puts it on screen.
3+///
4+/// ```swift
5+/// let screen = Screen(lines: ["razorbill", "", "› "], cursorRow: 2, cursorColumn: 2)
6+/// terminal.draw(screen)
7+/// ```
8+public struct Screen: Sendable, Equatable {
9+ public var lines: [String]
10+ public var cursorRow: Int
11+ public var cursorColumn: Int
12+ /// Hide the cursor (screens without a text field).
13+ public var hidesCursor: Bool
14+
15+ public init(
16+ lines: [String], cursorRow: Int = 0, cursorColumn: Int = 0, hidesCursor: Bool = false
17+ ) {
18+ self.lines = lines
19+ self.cursorRow = cursorRow
20+ self.cursorColumn = cursorColumn
21+ self.hidesCursor = hidesCursor
22+ }
23+}
new file mode 100644
@@ -0,0 +1,23 @@
1+/// A drawn screen: one string per row (ANSI styles allowed), and where the cursor goes (0-based).
2+/// Renderers produce it from a state; a ``Terminal`` puts it on screen.
3+///
4+/// ```swift
5+/// let screen = Screen(lines: ["razorbill", "", "› "], cursorRow: 2, cursorColumn: 2)
6+/// terminal.draw(screen)
7+/// ```
8+public struct Screen: Sendable, Equatable {
9+ public var lines: [String]
10+ public var cursorRow: Int
11+ public var cursorColumn: Int
12+ /// Hide the cursor (screens without a text field).
13+ public var hidesCursor: Bool
14+
15+ public init(
16+ lines: [String], cursorRow: Int = 0, cursorColumn: Int = 0, hidesCursor: Bool = false
17+ ) {
18+ self.lines = lines
19+ self.cursorRow = cursorRow
20+ self.cursorColumn = cursorColumn
21+ self.hidesCursor = hidesCursor
22+ }
23+}
added Sources/RazorbillTUI/Terminal.swift +126 -0
new file mode 100644
@@ -0,0 +1,126 @@
1+import Foundation
2+
3+#if canImport(Darwin)
4+import Darwin
5+#else
6+import Glibc
7+#endif
8+
9+/// The terminal the TUI draws on. ``PosixTerminal`` is the real one; tests use a fake.
10+public protocol Terminal: Sendable {
11+ /// Rows and columns.
12+ var size: (rows: Int, columns: Int) { get }
13+ /// Switches to raw mode and the alternate screen.
14+ func enter()
15+ /// Restores the terminal as it was. Safe to call twice.
16+ func leave()
17+ /// Keys typed, and `.resize` when the window changes size. Ends when input closes.
18+ func keys() -> AsyncStream<Key>
19+ /// Replaces the whole screen with `screen`.
20+ func draw(_ screen: Screen)
21+}
22+
23+/// The process's terminal (standard input and output), driven with termios and ANSI codes.
24+public final class PosixTerminal: Terminal, @unchecked Sendable {
25+ /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable.
26+ private var resizeSource: (any DispatchSourceSignal)?
27+
28+ public init() {}
29+
30+ /// Both standard input and standard output are terminals.
31+ public static var isAvailable: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDOUT_FILENO) == 1 }
32+
33+ public var size: (rows: Int, columns: Int) {
34+ var window = winsize()
35+ guard ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &window) == 0 else { return (24, 80) }
36+ let rows = Int(window.ws_row)
37+ let columns = Int(window.ws_col)
38+ return rows > 0 && columns > 0 ? (rows, columns) : (24, 80)
39+ }
40+
41+ public func enter() {
42+ TerminalRestorer.save()
43+ var raw = TerminalRestorer.original ?? termios()
44+ cfmakeraw(&raw)
45+ tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)
46+ // Alternate screen, cleared.
47+ write("\u{1B}[?1049h\u{1B}[2J")
48+ TerminalRestorer.installSignalHandlers()
49+ }
50+
51+ public func leave() {
52+ TerminalRestorer.restore()
53+ }
54+
55+ public func keys() -> AsyncStream<Key> {
56+ AsyncStream { continuation in
57+ let resize = DispatchSource.makeSignalSource(signal: SIGWINCH)
58+ signal(SIGWINCH, SIG_IGN)
59+ resize.setEventHandler { continuation.yield(.resize) }
60+ resize.resume()
61+ resizeSource = resize
62+ let reader = Thread {
63+ var decoder = KeyDecoder()
64+ var buffer = [UInt8](repeating: 0, count: 256)
65+ while true {
66+ let count = read(STDIN_FILENO, &buffer, buffer.count)
67+ if count < 0, errno == EINTR { continue }
68+ if count <= 0 { break }
69+ var keys = decoder.decode(Array(buffer[0 ..< count]))
70+ keys += decoder.flush() // a lone ESC read alone is the Escape key
71+ for key in keys { continuation.yield(key) }
72+ }
73+ self.resizeSource?.cancel()
74+ continuation.finish()
75+ }
76+ reader.start()
77+ }
78+ }
79+
80+ public func draw(_ screen: Screen) {
81+ var output = "\u{1B}[?25l" // hide the cursor while drawing
82+ for (row, line) in screen.lines.enumerated() {
83+ output += "\u{1B}[\(row + 1);1H\u{1B}[2K\(line)"
84+ }
85+ if !screen.hidesCursor {
86+ output += "\u{1B}[\(screen.cursorRow + 1);\(screen.cursorColumn + 1)H\u{1B}[?25h"
87+ }
88+ write(output)
89+ }
90+
91+ private func write(_ text: String) {
92+ FileHandle.standardOutput.write(Data(text.utf8))
93+ }
94+}
95+
96+/// Puts the terminal back when the TUI ends, including on SIGTERM / SIGHUP, so the user never
97+/// gets stuck in raw mode. (Signal handlers cannot capture context, hence the global state.)
98+enum TerminalRestorer {
99+ nonisolated(unsafe) static var original: termios?
100+
101+ static func save() {
102+ var current = termios()
103+ if tcgetattr(STDIN_FILENO, &current) == 0 {
104+ original = current
105+ }
106+ }
107+
108+ static func restore() {
109+ guard var saved = original else { return }
110+ tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved)
111+ let reset = "\u{1B}[?25h\u{1B}[?1049l"
112+ _ = reset.withCString { Foundation.write(STDOUT_FILENO, $0, strlen($0)) }
113+ original = nil
114+ }
115+
116+ static func installSignalHandlers() {
117+ atexit { TerminalRestorer.restore() }
118+ for signalNumber in [SIGTERM, SIGHUP, SIGQUIT] {
119+ signal(signalNumber) { received in
120+ TerminalRestorer.restore()
121+ signal(received, SIG_DFL)
122+ raise(received)
123+ }
124+ }
125+ }
126+}
new file mode 100644
@@ -0,0 +1,126 @@
1+import Foundation
2+
3+#if canImport(Darwin)
4+import Darwin
5+#else
6+import Glibc
7+#endif
8+
9+/// The terminal the TUI draws on. ``PosixTerminal`` is the real one; tests use a fake.
10+public protocol Terminal: Sendable {
11+ /// Rows and columns.
12+ var size: (rows: Int, columns: Int) { get }
13+ /// Switches to raw mode and the alternate screen.
14+ func enter()
15+ /// Restores the terminal as it was. Safe to call twice.
16+ func leave()
17+ /// Keys typed, and `.resize` when the window changes size. Ends when input closes.
18+ func keys() -> AsyncStream<Key>
19+ /// Replaces the whole screen with `screen`.
20+ func draw(_ screen: Screen)
21+}
22+
23+/// The process's terminal (standard input and output), driven with termios and ANSI codes.
24+public final class PosixTerminal: Terminal, @unchecked Sendable {
25+ /// Watches SIGWINCH while keys are read; kept here because Dispatch sources are not Sendable.
26+ private var resizeSource: (any DispatchSourceSignal)?
27+
28+ public init() {}
29+
30+ /// Both standard input and standard output are terminals.
31+ public static var isAvailable: Bool { isatty(STDIN_FILENO) == 1 && isatty(STDOUT_FILENO) == 1 }
32+
33+ public var size: (rows: Int, columns: Int) {
34+ var window = winsize()
35+ guard ioctl(STDOUT_FILENO, UInt(TIOCGWINSZ), &window) == 0 else { return (24, 80) }
36+ let rows = Int(window.ws_row)
37+ let columns = Int(window.ws_col)
38+ return rows > 0 && columns > 0 ? (rows, columns) : (24, 80)
39+ }
40+
41+ public func enter() {
42+ TerminalRestorer.save()
43+ var raw = TerminalRestorer.original ?? termios()
44+ cfmakeraw(&raw)
45+ tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw)
46+ // Alternate screen, cleared.
47+ write("\u{1B}[?1049h\u{1B}[2J")
48+ TerminalRestorer.installSignalHandlers()
49+ }
50+
51+ public func leave() {
52+ TerminalRestorer.restore()
53+ }
54+
55+ public func keys() -> AsyncStream<Key> {
56+ AsyncStream { continuation in
57+ let resize = DispatchSource.makeSignalSource(signal: SIGWINCH)
58+ signal(SIGWINCH, SIG_IGN)
59+ resize.setEventHandler { continuation.yield(.resize) }
60+ resize.resume()
61+ resizeSource = resize
62+ let reader = Thread {
63+ var decoder = KeyDecoder()
64+ var buffer = [UInt8](repeating: 0, count: 256)
65+ while true {
66+ let count = read(STDIN_FILENO, &buffer, buffer.count)
67+ if count < 0, errno == EINTR { continue }
68+ if count <= 0 { break }
69+ var keys = decoder.decode(Array(buffer[0 ..< count]))
70+ keys += decoder.flush() // a lone ESC read alone is the Escape key
71+ for key in keys { continuation.yield(key) }
72+ }
73+ self.resizeSource?.cancel()
74+ continuation.finish()
75+ }
76+ reader.start()
77+ }
78+ }
79+
80+ public func draw(_ screen: Screen) {
81+ var output = "\u{1B}[?25l" // hide the cursor while drawing
82+ for (row, line) in screen.lines.enumerated() {
83+ output += "\u{1B}[\(row + 1);1H\u{1B}[2K\(line)"
84+ }
85+ if !screen.hidesCursor {
86+ output += "\u{1B}[\(screen.cursorRow + 1);\(screen.cursorColumn + 1)H\u{1B}[?25h"
87+ }
88+ write(output)
89+ }
90+
91+ private func write(_ text: String) {
92+ FileHandle.standardOutput.write(Data(text.utf8))
93+ }
94+}
95+
96+/// Puts the terminal back when the TUI ends, including on SIGTERM / SIGHUP, so the user never
97+/// gets stuck in raw mode. (Signal handlers cannot capture context, hence the global state.)
98+enum TerminalRestorer {
99+ nonisolated(unsafe) static var original: termios?
100+
101+ static func save() {
102+ var current = termios()
103+ if tcgetattr(STDIN_FILENO, &current) == 0 {
104+ original = current
105+ }
106+ }
107+
108+ static func restore() {
109+ guard var saved = original else { return }
110+ tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved)
111+ let reset = "\u{1B}[?25h\u{1B}[?1049l"
112+ _ = reset.withCString { Foundation.write(STDOUT_FILENO, $0, strlen($0)) }
113+ original = nil
114+ }
115+
116+ static func installSignalHandlers() {
117+ atexit { TerminalRestorer.restore() }
118+ for signalNumber in [SIGTERM, SIGHUP, SIGQUIT] {
119+ signal(signalNumber) { received in
120+ TerminalRestorer.restore()
121+ signal(received, SIG_DFL)
122+ raise(received)
123+ }
124+ }
125+ }
126+}
added Sources/RazorbillTUI/TextLayout.swift +37 -0
new file mode 100644
@@ -0,0 +1,37 @@
1+/// Breaks text into lines that fit a width, at spaces when possible.
2+///
3+/// ```swift
4+/// TextLayout.wrap("hello wide world", width: 10) // ["hello wide", "world"]
5+/// ```
6+public enum TextLayout {
7+ public static func wrap(_ text: String, width: Int) -> [String] {
8+ guard width > 0 else { return [] }
9+ return text.split(separator: "\n", omittingEmptySubsequences: false).flatMap {
10+ wrapLine(String($0), width: width)
11+ }
12+ }
13+
14+ private static func wrapLine(_ line: String, width: Int) -> [String] {
15+ var rest = Substring(line)
16+ var lines: [String] = []
17+ while rest.count > width {
18+ let window = rest.prefix(width + 1)
19+ if let space = window.lastIndex(of: " "), space > rest.startIndex {
20+ lines.append(String(rest[..<space]))
21+ rest = rest[rest.index(after: space)...]
22+ } else {
23+ lines.append(String(rest.prefix(width)))
24+ rest = rest.dropFirst(width)
25+ }
26+ }
27+ lines.append(String(rest))
28+ return lines
29+ }
30+
31+ /// `text` cut to `width` characters, with `…` when cut.
32+ public static func truncate(_ text: String, width: Int) -> String {
33+ guard text.count > width else { return text }
34+ guard width > 1 else { return String(text.prefix(width)) }
35+ return String(text.prefix(width - 1)) + "…"
36+ }
37+}
new file mode 100644
@@ -0,0 +1,37 @@
1+/// Breaks text into lines that fit a width, at spaces when possible.
2+///
3+/// ```swift
4+/// TextLayout.wrap("hello wide world", width: 10) // ["hello wide", "world"]
5+/// ```
6+public enum TextLayout {
7+ public static func wrap(_ text: String, width: Int) -> [String] {
8+ guard width > 0 else { return [] }
9+ return text.split(separator: "\n", omittingEmptySubsequences: false).flatMap {
10+ wrapLine(String($0), width: width)
11+ }
12+ }
13+
14+ private static func wrapLine(_ line: String, width: Int) -> [String] {
15+ var rest = Substring(line)
16+ var lines: [String] = []
17+ while rest.count > width {
18+ let window = rest.prefix(width + 1)
19+ if let space = window.lastIndex(of: " "), space > rest.startIndex {
20+ lines.append(String(rest[..<space]))
21+ rest = rest[rest.index(after: space)...]
22+ } else {
23+ lines.append(String(rest.prefix(width)))
24+ rest = rest.dropFirst(width)
25+ }
26+ }
27+ lines.append(String(rest))
28+ return lines
29+ }
30+
31+ /// `text` cut to `width` characters, with `…` when cut.
32+ public static func truncate(_ text: String, width: Int) -> String {
33+ guard text.count > width else { return text }
34+ guard width > 1 else { return String(text.prefix(width)) }
35+ return String(text.prefix(width - 1)) + "…"
36+ }
37+}
added Tests/RazorbillTUITests/FakeTerminal.swift +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+import Foundation
2+import RazorbillTUI
3+import Testing
4+
5+/// A terminal for tests: keys are sent by the test, drawn screens are recorded.
6+///
7+/// ```swift
8+/// let terminal = FakeTerminal(rows: 24, columns: 80)
9+/// terminal.press(.function(2))
10+/// terminal.close() // ends the key stream, so the app returns
11+/// #expect(terminal.screens.last?.lines.first == "…")
12+/// ```
13+final class FakeTerminal: Terminal, @unchecked Sendable {
14+ private let lock = NSLock()
15+ private var drawn: [Screen] = []
16+ private var entered = 0
17+ private var left = 0
18+ private let stream: AsyncStream<Key>
19+ private let sender: AsyncStream<Key>.Continuation
20+ let size: (rows: Int, columns: Int)
21+
22+ init(rows: Int = 24, columns: Int = 80) {
23+ size = (rows, columns)
24+ (stream, sender) = AsyncStream<Key>.makeStream()
25+ }
26+
27+ func enter() { lock.withLock { entered += 1 } }
28+ func leave() { lock.withLock { left += 1 } }
29+ func keys() -> AsyncStream<Key> { stream }
30+ func draw(_ screen: Screen) { lock.withLock { drawn.append(screen) } }
31+
32+ func press(_ keys: Key...) { for key in keys { sender.yield(key) } }
33+ func type(_ text: String) { for character in text { sender.yield(.character(character)) } }
34+ func close() { sender.finish() }
35+
36+ var screens: [Screen] { lock.withLock { drawn } }
37+ /// The last screen as plain text (ANSI styles removed), one string per row.
38+ var lastText: [String] { (screens.last?.lines ?? []).map(Self.plain) }
39+ var enterCount: Int { lock.withLock { entered } }
40+ var leaveCount: Int { lock.withLock { left } }
41+
42+ /// `text` without ANSI escape sequences.
43+ static func plain(_ text: String) -> String {
44+ text.replacingOccurrences(
45+ of: "\u{1B}\\[[0-9;?]*[A-Za-z]", with: "", options: .regularExpression)
46+ }
47+}
48+
49+@Suite struct FakeTerminalTests {
50+ @Test func recordsScreensAndSendsKeys() async {
51+ let terminal = FakeTerminal(rows: 3, columns: 10)
52+ terminal.draw(Screen(lines: ["\u{1B}[1mhi\u{1B}[0m"]))
53+ #expect(terminal.lastText == ["hi"])
54+ terminal.press(.function(1))
55+ terminal.close()
56+ var received: [Key] = []
57+ for await key in terminal.keys() { received.append(key) }
58+ #expect(received == [.function(1)])
59+ }
60+}
new file mode 100644
@@ -0,0 +1,60 @@
1+import Foundation
2+import RazorbillTUI
3+import Testing
4+
5+/// A terminal for tests: keys are sent by the test, drawn screens are recorded.
6+///
7+/// ```swift
8+/// let terminal = FakeTerminal(rows: 24, columns: 80)
9+/// terminal.press(.function(2))
10+/// terminal.close() // ends the key stream, so the app returns
11+/// #expect(terminal.screens.last?.lines.first == "…")
12+/// ```
13+final class FakeTerminal: Terminal, @unchecked Sendable {
14+ private let lock = NSLock()
15+ private var drawn: [Screen] = []
16+ private var entered = 0
17+ private var left = 0
18+ private let stream: AsyncStream<Key>
19+ private let sender: AsyncStream<Key>.Continuation
20+ let size: (rows: Int, columns: Int)
21+
22+ init(rows: Int = 24, columns: Int = 80) {
23+ size = (rows, columns)
24+ (stream, sender) = AsyncStream<Key>.makeStream()
25+ }
26+
27+ func enter() { lock.withLock { entered += 1 } }
28+ func leave() { lock.withLock { left += 1 } }
29+ func keys() -> AsyncStream<Key> { stream }
30+ func draw(_ screen: Screen) { lock.withLock { drawn.append(screen) } }
31+
32+ func press(_ keys: Key...) { for key in keys { sender.yield(key) } }
33+ func type(_ text: String) { for character in text { sender.yield(.character(character)) } }
34+ func close() { sender.finish() }
35+
36+ var screens: [Screen] { lock.withLock { drawn } }
37+ /// The last screen as plain text (ANSI styles removed), one string per row.
38+ var lastText: [String] { (screens.last?.lines ?? []).map(Self.plain) }
39+ var enterCount: Int { lock.withLock { entered } }
40+ var leaveCount: Int { lock.withLock { left } }
41+
42+ /// `text` without ANSI escape sequences.
43+ static func plain(_ text: String) -> String {
44+ text.replacingOccurrences(
45+ of: "\u{1B}\\[[0-9;?]*[A-Za-z]", with: "", options: .regularExpression)
46+ }
47+}
48+
49+@Suite struct FakeTerminalTests {
50+ @Test func recordsScreensAndSendsKeys() async {
51+ let terminal = FakeTerminal(rows: 3, columns: 10)
52+ terminal.draw(Screen(lines: ["\u{1B}[1mhi\u{1B}[0m"]))
53+ #expect(terminal.lastText == ["hi"])
54+ terminal.press(.function(1))
55+ terminal.close()
56+ var received: [Key] = []
57+ for await key in terminal.keys() { received.append(key) }
58+ #expect(received == [.function(1)])
59+ }
60+}
added Tests/RazorbillTUITests/KeyAndLayoutTests.swift +78 -0
new file mode 100644
@@ -0,0 +1,78 @@
1+import RazorbillTUI
2+import Testing
3+
4+@Suite struct KeyDecoding {
5+ func decode(_ bytes: [UInt8]) -> [Key] {
6+ var decoder = KeyDecoder()
7+ return decoder.decode(bytes)
8+ }
9+
10+ @Test func printableAndUnicodeCharacters() {
11+ #expect(decode(Array("hé🙂".utf8)) == [.character("h"), .character("é"), .character("🙂")])
12+ }
13+
14+ @Test func controlKeys() {
15+ #expect(
16+ decode([13, 127, 9, 3, 4, 20]) == [
17+ .enter, .backspace, .tab, .control("c"), .control("d"), .control("t"),
18+ ])
19+ }
20+
21+ @Test func escapeSequences() {
22+ #expect(
23+ decode([27, 91, 65, 27, 91, 66, 27, 91, 67, 27, 91, 68]) == [
24+ .arrowUp, .arrowDown, .arrowRight, .arrowLeft,
25+ ])
26+ #expect(
27+ decode(Array("\u{1B}[5~\u{1B}[6~\u{1B}[3~\u{1B}[H\u{1B}[F".utf8)) == [
28+ .pageUp, .pageDown, .delete, .home, .end,
29+ ])
30+ #expect(decode([27, 79, 72]) == [.home])
31+ }
32+
33+ @Test func functionKeysInBothEncodings() {
34+ #expect(
35+ decode(Array("\u{1B}OP\u{1B}OQ\u{1B}OR\u{1B}OS".utf8)) == [
36+ .function(1), .function(2), .function(3), .function(4),
37+ ])
38+ #expect(
39+ decode(Array("\u{1B}[11~\u{1B}[14~\u{1B}[15~\u{1B}[24~".utf8)) == [
40+ .function(1), .function(4), .function(5), .function(12),
41+ ])
42+ }
43+
44+ @Test func functionKeyCutBetweenReadsIsJoined() {
45+ var decoder = KeyDecoder()
46+ #expect(decoder.decode([27, 79]).isEmpty)
47+ #expect(decoder.decode([80]) == [.function(1)])
48+ }
49+
50+ @Test func sequencesCutBetweenReadsAreJoined() {
51+ var decoder = KeyDecoder()
52+ #expect(decoder.decode([27]).isEmpty)
53+ #expect(decoder.decode([91]).isEmpty)
54+ #expect(decoder.decode([65]) == [.arrowUp])
55+ let euro = Array("€".utf8)
56+ #expect(decoder.decode(Array(euro.prefix(2))).isEmpty)
57+ #expect(decoder.decode(Array(euro.suffix(1))) == [.character("€")])
58+ }
59+
60+ @Test func aLoneEscapeIsTheEscapeKeyOnceInputPauses() {
61+ var decoder = KeyDecoder()
62+ #expect(decoder.decode([27]).isEmpty)
63+ #expect(decoder.flush() == [.escape])
64+ }
65+}
66+
67+@Suite struct Layout {
68+ @Test func wrapsAtSpacesAndCutsLongWords() {
69+ #expect(TextLayout.wrap("hello wide world", width: 10) == ["hello wide", "world"])
70+ #expect(TextLayout.wrap("abcdefghij", width: 4) == ["abcd", "efgh", "ij"])
71+ #expect(TextLayout.wrap("a\n\nb", width: 5) == ["a", "", "b"])
72+ }
73+
74+ @Test func truncatesWithAnEllipsis() {
75+ #expect(TextLayout.truncate("abcdef", width: 4) == "abc…")
76+ #expect(TextLayout.truncate("abc", width: 4) == "abc")
77+ }
78+}
new file mode 100644
@@ -0,0 +1,78 @@
1+import RazorbillTUI
2+import Testing
3+
4+@Suite struct KeyDecoding {
5+ func decode(_ bytes: [UInt8]) -> [Key] {
6+ var decoder = KeyDecoder()
7+ return decoder.decode(bytes)
8+ }
9+
10+ @Test func printableAndUnicodeCharacters() {
11+ #expect(decode(Array("hé🙂".utf8)) == [.character("h"), .character("é"), .character("🙂")])
12+ }
13+
14+ @Test func controlKeys() {
15+ #expect(
16+ decode([13, 127, 9, 3, 4, 20]) == [
17+ .enter, .backspace, .tab, .control("c"), .control("d"), .control("t"),
18+ ])
19+ }
20+
21+ @Test func escapeSequences() {
22+ #expect(
23+ decode([27, 91, 65, 27, 91, 66, 27, 91, 67, 27, 91, 68]) == [
24+ .arrowUp, .arrowDown, .arrowRight, .arrowLeft,
25+ ])
26+ #expect(
27+ decode(Array("\u{1B}[5~\u{1B}[6~\u{1B}[3~\u{1B}[H\u{1B}[F".utf8)) == [
28+ .pageUp, .pageDown, .delete, .home, .end,
29+ ])
30+ #expect(decode([27, 79, 72]) == [.home])
31+ }
32+
33+ @Test func functionKeysInBothEncodings() {
34+ #expect(
35+ decode(Array("\u{1B}OP\u{1B}OQ\u{1B}OR\u{1B}OS".utf8)) == [
36+ .function(1), .function(2), .function(3), .function(4),
37+ ])
38+ #expect(
39+ decode(Array("\u{1B}[11~\u{1B}[14~\u{1B}[15~\u{1B}[24~".utf8)) == [
40+ .function(1), .function(4), .function(5), .function(12),
41+ ])
42+ }
43+
44+ @Test func functionKeyCutBetweenReadsIsJoined() {
45+ var decoder = KeyDecoder()
46+ #expect(decoder.decode([27, 79]).isEmpty)
47+ #expect(decoder.decode([80]) == [.function(1)])
48+ }
49+
50+ @Test func sequencesCutBetweenReadsAreJoined() {
51+ var decoder = KeyDecoder()
52+ #expect(decoder.decode([27]).isEmpty)
53+ #expect(decoder.decode([91]).isEmpty)
54+ #expect(decoder.decode([65]) == [.arrowUp])
55+ let euro = Array("€".utf8)
56+ #expect(decoder.decode(Array(euro.prefix(2))).isEmpty)
57+ #expect(decoder.decode(Array(euro.suffix(1))) == [.character("€")])
58+ }
59+
60+ @Test func aLoneEscapeIsTheEscapeKeyOnceInputPauses() {
61+ var decoder = KeyDecoder()
62+ #expect(decoder.decode([27]).isEmpty)
63+ #expect(decoder.flush() == [.escape])
64+ }
65+}
66+
67+@Suite struct Layout {
68+ @Test func wrapsAtSpacesAndCutsLongWords() {
69+ #expect(TextLayout.wrap("hello wide world", width: 10) == ["hello wide", "world"])
70+ #expect(TextLayout.wrap("abcdefghij", width: 4) == ["abcd", "efgh", "ij"])
71+ #expect(TextLayout.wrap("a\n\nb", width: 5) == ["a", "", "b"])
72+ }
73+
74+ @Test func truncatesWithAnEllipsis() {
75+ #expect(TextLayout.truncate("abcdef", width: 4) == "abc…")
76+ #expect(TextLayout.truncate("abc", width: 4) == "abc")
77+ }
78+}