1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
//! The platform seam: the **only** part of the crate allowed to contain
//! `unsafe`, and the only part that knows which operating system this is.
//!
//! This file itself contains no `unsafe` and no syscalls. It declares the
//! public surface, owns the three signal flags (which are portable atomics),
//! re-exports the pure [`abi`] core, and `cfg`-dispatches to exactly one
//! backend:
//!
//! ```text
//! main.rs / term.rs / key.rs safe, portable, no cfg(target_os) anywhere
//! ────────────────────────────────────────────────────────────────────────────
//! sys/mod.rs public surface + dispatch (no unsafe)
//! sys/abi.rs pure ABI arithmetic (no unsafe, no syscalls, tested)
//! sys/layout.rs pure C struct layouts (no unsafe, every OS, tested)
//! ────────────────────────────────────────────────────────────────────────────
//! sys/unix.rs termios + ioctl │ sys/stub.rs do-nothing fallback
//! unix_linux.rs / unix_darwin.rs │
//! ```
//!
//! The unix backend covers Linux (glibc and musl) and Darwin (macOS on x86_64
//! and aarch64). Those two share every syscall used here and differ only in
//! `struct termios`, the errno symbol, and a handful of constants — so the
//! constants live in [`abi`], the layouts in [`layout`], both host-tested for
//! *both* OSes, and the per-OS files hold two items each.
//!
//! Per SPEC.md §"Hard constraints" #1 every syscall is a hand-written
//! `extern "C"` declaration; there is no `libc` crate and never will be.
//!
//! # The contract a backend must satisfy
//!
//! A backend is one module that provides *exactly* the names below with these
//! signatures and these semantics. Nothing above `sys` changes when one is
//! added. Anything a backend can compute without touching the OS belongs in
//! [`abi`] instead, so it is unit-tested on whatever host CI happens to run.
//!
//! | Item | Signature | Contract |
//! | --- | --- | --- |
//! | `SavedTermios` | opaque `Copy` type | Whatever [`restore`] needs to put the terminal back byte-for-byte as found. May be a `struct termios`, a pair of console-mode `DWORD`s, anything. |
//! | `install_signal_handlers()` | `fn()` | Idempotent. Arrange for the three `*_pending` flags in this module to become true when the corresponding event happens. Whatever mechanism is used must be safe to run in that context (the unix backend's handlers touch nothing but a lock-free atomic). |
//! | `is_tty(Fd)` | `fn(Fd) -> bool` | Does this handle refer to a terminal? |
//! | `open_tty()` | `fn() -> Option<Fd>` | A fresh read+write handle to the controlling terminal, even when stdin is a pipe. `None` when there is none. |
//! | `tty_fd()` | `fn() -> Option<(Fd, bool)>` | Handle to read keys from. The `bool` is "the caller owns this and must [`close_fd`] it". Must prefer [`STDIN`] when it is a terminal. |
//! | `close_fd(Fd)` | `fn(Fd)` | Close a handle from [`open_tty`]. Must ignore the standard handles. |
//! | `winsize()` | `fn() -> Option<(u16, u16)>` | Terminal size as `(cols, rows)`, trying whatever handles are plausible. |
//! | `winsize_of(Fd)` | `fn(Fd) -> Option<(u16, u16)>` | Size of one handle. `None` on failure **and** on a zero dimension; `term.rs` substitutes 80x24. Must report the *visible window*, not any scrollback buffer. |
//! | `set_raw(Fd)` | `fn(Fd) -> Option<SavedTermios>` | Enter raw mode — no echo, no line buffering, no signal generation from keys, no output post-processing — and return the previous state. `None` if that is impossible; `main.rs` treats it as "no tty" and dumps instead. |
//! | `restore(Fd, &SavedTermios)` | `fn(Fd, &SavedTermios) -> bool` | Undo `set_raw` exactly. Called from a panic hook, so it must not allocate or panic. |
//! | `read_input(Fd, &mut [u8])` | `fn(Fd, &mut [u8]) -> ReadOutcome` | Up to `buf.len()` bytes of **UTF-8 encoded terminal input**, retrying past interruptions. **Must return [`ReadOutcome::Timeout`] after roughly 100 ms of silence** — that tick is how the event loop notices a resize. Never split a UTF-8 sequence's meaning: `key.rs` will wait for continuation bytes forever. |
//! | `write_all(Fd, &[u8])` | `fn(Fd, &[u8]) -> Result<(), i32>` | Write the whole buffer, looping over short writes. `Err` carries the platform error code. |
//!
//! Two further obligations are behavioural rather than typed:
//!
//! * **The mouse is never captured.** A backend must not emit `?1000h`,
//! `?1002h`, `?1003h` or `?1006h`, and must not enable any OS-level mouse
//! reporting mode. Terminal-native click-drag selection has to keep working
//! (SPEC.md §"Hard constraints" #5). On Windows that additionally means
//! leaving `ENABLE_QUICK_EDIT_MODE` set and `ENABLE_MOUSE_INPUT` clear.
//! * **Input arrives as ANSI.** `key.rs` decodes an escape-sequence byte
//! stream and has no platform branch. A backend whose OS does not natively
//! speak VT must translate (on Windows: set
//! `ENABLE_VIRTUAL_TERMINAL_INPUT`), not push a branch upwards.
//!
//! Adding an OS is therefore: a new file next to `unix.rs`, its constants added
//! to [`abi`] and its C struct layouts to [`layout`] — both with host tests and
//! `const _: () = assert!(size_of::<T>() == N);` pins, because there is no
//! machine in this project's loop that can *run* a non-Linux backend — and one
//! arm added to the dispatch below.
use ;
// Handing a URL to the system opener (SPEC.md §"Opening a link outside the
// reader"). Declared on every target for the same reason `win_abi` is: the
// argument vector each OS wants is a table, and a table is host-testable for
// OSes this builder is not. It is the only part of `sys` that spawns a process,
// and the only place in the crate that names `xdg-open`, `open` or `rundll32`.
// The Windows console ABI gets the same treatment as the Darwin tables above:
// declared on *every* target, never behind `cfg(windows)`, so its constants,
// its console-mode arithmetic and its C struct sizes are compile-asserted and
// `cargo test`-ed on the Linux host. `windows.rs` itself is only the FFI.
// ---------------------------------------------------------------------------
// Types shared by every backend
// ---------------------------------------------------------------------------
/// A raw file descriptor / handle. Opaque to callers above this module: they
/// only ever pass one back to a `sys` function, never inspect it.
pub type Fd = i32;
/// Standard output handle.
pub const STDOUT: Fd = 1;
/// Standard input handle.
pub const STDIN: Fd = 0;
/// Outcome of a single non-blocking-ish read from the terminal.
// ---------------------------------------------------------------------------
// Signal flags — portable, shared by every backend
// ---------------------------------------------------------------------------
static WINCH: AtomicBool = new;
static INTR: AtomicBool = new;
static TERM: AtomicBool = new;
/// True (and cleared) if a terminal-resize event arrived since the last call.
/// True (and cleared) if an interrupt (Ctrl-C at the OS level) arrived.
/// True (and cleared) if a termination signal (SIGTERM/SIGHUP/SIGQUIT, or the
/// platform equivalent) arrived. Their default disposition kills the process
/// outright, stranding the tty in raw mode on the alternate screen (release is
/// `panic = "abort"`, so no `Drop` and no panic hook); catching them makes
/// `kill <pid>` an ordinary quit.
// ---------------------------------------------------------------------------
// Backend dispatch
// ---------------------------------------------------------------------------
// No real backend for this target yet: a placeholder with the same surface and
// no `unsafe`, so the crate still compiles. See docs/windows.md.
pub use *;
/// Can the terminal interpret ANSI escape sequences?
///
/// Part of the contract, but portable rather than per-backend: on unix a
/// terminal that speaks no VT is not a case this reader has ever handled, so the
/// answer is a constant `true`. Windows is the one platform where a *real*
/// console can refuse `ENABLE_VIRTUAL_TERMINAL_PROCESSING` (conhost before
/// Windows 10 1703), and this is how that is signalled upward: the safe layer
/// can consult it and fall back to plain, uncoloured output instead of printing
/// escape codes at the user. The Windows backend additionally refuses raw mode
/// outright in that case, so the reader degrades to the non-interactive dump.