Skip to main content

mira/
term.rs

1//! A terminal, hand-rolled on `libc`.
2//!
3//! The syscall half only. ratatui draws every row (see `tui::rata`),
4//! but none of its backends are linked: `CrosstermBackend` would add crossterm,
5//! mio, signal-hook and parking_lot to do what is already here, on a tree whose
6//! size (149 crates, 6.20 MiB) is a stated property of the product. So
7//! `termios` for raw mode, `TIOCGWINSZ` for the size, `poll(2)` for input,
8//! three `sigaction`s to survive a resize and a `kill`, and `Term::draw` to put
9//! the rows on the screen. `libc` is already in the tree for `statfs`.
10//!
11//! Unix only, which is the same bet `mmap`, `SIGTERM` and the filesystem guard
12//! already make.
13
14use std::io::{self, IsTerminal, Read, Write};
15use std::sync::OnceLock;
16
17/// The terminal settings as they were before [`Term::enter`].
18///
19/// A static rather than a field because the panic hook has to reach them, and
20/// the hook outlives any borrow we could hand it. `panic = "abort"` in the
21/// release profile does not skip hooks — it skips *unwinding* — so this is
22/// still the last thing that runs before a crash, and without it a panic leaves
23/// the shell in raw mode with no echo and no cursor.
24static ORIG: OnceLock<libc::termios> = OnceLock::new();
25
26pub struct Term {
27    /// Bytes read from stdin but not yet consumed as a key.
28    ///
29    /// One `read` can return a whole escape sequence, several keystrokes from a
30    /// fast typist, or half of either. Without this, the tail of a burst is
31    /// silently dropped.
32    pending: Vec<u8>,
33    out: io::BufWriter<io::Stdout>,
34}
35
36impl Term {
37    pub fn enter() -> io::Result<Term> {
38        // Checked before `tcgetattr`, which would otherwise report a redirected
39        // stdin as `ENOTTY` — "Inappropriate ioctl for device" — and says nothing
40        // at all about a redirected stdout, which instead fills the file with
41        // escape sequences.
42        if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
43            return Err(io::Error::new(
44                io::ErrorKind::Unsupported,
45                "not a terminal; the TUI needs stdin and stdout on a tty",
46            ));
47        }
48        // SAFETY: `termios` is integers and the `c_cc` byte array — no pointer,
49        // no niche, no field for which zero is not a value — so all-zero is a
50        // valid `termios` to hold until `tcgetattr` overwrites it.
51        let mut t: libc::termios = unsafe { std::mem::zeroed() };
52        // SAFETY: `&mut t` is a live, correctly typed, initialised `termios`, and
53        // `tcgetattr` writes nothing past its end.
54        ok_or_errno(unsafe { libc::tcgetattr(0, &mut t) })?;
55        let _ = ORIG.set(t);
56
57        let mut raw = t;
58        // SAFETY: `raw` is a copy of the struct `tcgetattr` just filled, so
59        // `cfmakeraw` reads and writes only initialised fields of a live struct.
60        unsafe { libc::cfmakeraw(&mut raw) };
61        // VMIN 0 / VTIME 0: `read` returns immediately with whatever is there.
62        // Blocking is `poll`'s job, and doing it in both places is how a
63        // keystroke ends up waiting for the next one.
64        raw.c_cc[libc::VMIN] = 0;
65        raw.c_cc[libc::VTIME] = 0;
66        // SAFETY: `raw` is fully initialised — copied out of `tcgetattr`, edited
67        // field by field — and `tcsetattr` only reads it, for the duration of
68        // the call.
69        ok_or_errno(unsafe { libc::tcsetattr(0, libc::TCSANOW, &raw) })?;
70
71        let prev = std::panic::take_hook();
72        std::panic::set_hook(Box::new(move |info| {
73            restore();
74            prev(info);
75        }));
76
77        // SIGWINCH so a resize breaks the `poll` in `key` and the loop repaints
78        // at the new size; SIGTERM and SIGHUP so a `kill` or a closed ssh
79        // session gives the terminal back the way the panic hook does. Their
80        // default dispositions — discard, and die on the spot — are both wrong
81        // for a process that owns the screen.
82        on_signal(libc::SIGWINCH, winch);
83        on_signal(libc::SIGTERM, bail);
84        on_signal(libc::SIGHUP, bail);
85
86        let mut out = io::BufWriter::new(io::stdout());
87        // Alternate screen, then hide the cursor. Leaving on the alternate
88        // screen is what puts the user's scrollback back the way they left it.
89        out.write_all(b"\x1b[?1049h\x1b[?25l\x1b[2J")?;
90        out.flush()?;
91        Ok(Term {
92            pending: Vec::with_capacity(64),
93            out,
94        })
95    }
96
97    /// Visible size, re-read every frame.
98    ///
99    /// The `SIGWINCH` handler [`enter`](Term::enter) installs records nothing;
100    /// it exists only to interrupt the `poll` the draw loop is parked in. This
101    /// call is what learns the new size, on the frame that interruption paints.
102    pub fn size(&self) -> (usize, usize) {
103        // SAFETY: `winsize` is four `u16`s, so zero is a valid value — and it
104        // has to be, because a failing `ioctl` leaves the struct untouched and
105        // the `ws_col == 0` arm below is what reads it back.
106        let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
107        // SAFETY: TIOCGWINSZ is the request whose argument is `*mut winsize`,
108        // which is exactly what `&mut ws` is. `ioctl` is variadic, so nothing
109        // checks that pairing but this comment — a different request constant
110        // with this argument is the way the call goes wrong.
111        if unsafe { libc::ioctl(1, libc::TIOCGWINSZ as _, &mut ws) } != 0 || ws.ws_col == 0 {
112            return (80, 24);
113        }
114        (ws.ws_col as usize, ws.ws_row as usize)
115    }
116
117    /// Paint one frame: home the cursor, write every row, erase whatever the
118    /// last frame left below.
119    ///
120    /// A full repaint rather than a diff. At 200×60 that is 12 000 cells, and
121    /// one `write` of 30 KB costs less than tracking which of them changed.
122    pub fn draw(&mut self, rows: &[String]) -> io::Result<()> {
123        self.out.write_all(b"\x1b[H")?;
124        for row in rows {
125            self.out.write_all(row.as_bytes())?;
126            self.out.write_all(b"\x1b[K\r\n")?;
127        }
128        self.out.write_all(b"\x1b[J")?;
129        self.out.flush()
130    }
131
132    /// Next key, or `None` if `timeout_ms` passed with nothing to read.
133    pub fn key(&mut self, timeout_ms: i32) -> io::Result<Option<Key>> {
134        loop {
135            match parse(&mut self.pending) {
136                Parsed::Key(k) => return Ok(Some(k)),
137                Parsed::Need => {}
138            }
139            // A lone ESC and the start of an arrow key are the same first byte.
140            // The only way to tell them apart is that the rest of the sequence
141            // is already in flight, so wait a beat before calling it ESC.
142            let wait = if self.pending.is_empty() {
143                timeout_ms
144            } else {
145                20
146            };
147            if !poll_in(wait)? {
148                return Ok(match self.pending.is_empty() {
149                    true => None,
150                    // Incomplete after the grace period: emit the first byte for
151                    // what it is and resynchronise rather than wedging.
152                    false => Some(take_one(&mut self.pending)),
153                });
154            }
155            let mut buf = [0u8; 256];
156            let n = io::stdin().read(&mut buf)?;
157            if n == 0 {
158                return Ok(Some(Key::Ctrl('c')));
159            }
160            self.pending.extend_from_slice(&buf[..n]);
161        }
162    }
163}
164
165enum Parsed {
166    Key(Key),
167    Need,
168}
169
170/// One key off the front of `b`, or [`Parsed::Need`] if what is there could
171/// still grow into a longer sequence.
172///
173/// Free rather than a method so the tests can drive it with a plain `Vec`: a
174/// `Term` restores the terminal when it drops, and constructing one in a test
175/// sprays escape codes across the test runner's output.
176fn parse(b: &mut Vec<u8>) -> Parsed {
177    let Some(&first) = b.first() else {
178        return Parsed::Need;
179    };
180    let one = |b: &mut Vec<u8>, k| {
181        b.remove(0);
182        Parsed::Key(k)
183    };
184    match first {
185        0x1b => {
186            match b.get(1) {
187                None => Parsed::Need,
188                // CSI: parameters, then one byte in 0x40..=0x7e ends it.
189                Some(b'[') => {
190                    let Some(end) = b[2..].iter().position(|c| (0x40..=0x7e).contains(c)) else {
191                        return Parsed::Need;
192                    };
193                    let seq: Vec<u8> = b[2..2 + end + 1].to_vec();
194                    b.drain(..3 + end);
195                    Parsed::Key(csi(&seq))
196                }
197                // SS3, which is what some terminals send for the arrows in
198                // application cursor mode.
199                Some(b'O') => match b.get(2) {
200                    None => Parsed::Need,
201                    Some(&c) => {
202                        b.drain(..3);
203                        Parsed::Key(csi(&[c]))
204                    }
205                },
206                // Alt+key. Nothing here binds one, so drop the modifier and keep
207                // the key rather than swallowing both.
208                Some(_) => {
209                    b.remove(0);
210                    Parsed::Need
211                }
212            }
213        }
214        b'\r' | b'\n' => one(b, Key::Enter),
215        b'\t' => one(b, Key::Tab),
216        0x7f | 0x08 => one(b, Key::Backspace),
217        c if c < 0x20 => one(b, Key::Ctrl((c + b'a' - 1) as char)),
218        c if c < 0x80 => one(b, Key::Char(c as char)),
219        c => {
220            // UTF-8 continuation bytes may not have arrived yet.
221            let len = match c {
222                0xc0..=0xdf => 2,
223                0xe0..=0xef => 3,
224                _ => 4,
225            };
226            if b.len() < len {
227                return Parsed::Need;
228            }
229            let s = String::from_utf8_lossy(&b[..len]).into_owned();
230            b.drain(..len);
231            Parsed::Key(s.chars().next().map_or(Key::Esc, Key::Char))
232        }
233    }
234}
235
236fn take_one(b: &mut Vec<u8>) -> Key {
237    match b.remove(0) {
238        0x1b => Key::Esc,
239        c if c < 0x20 => Key::Ctrl((c + b'a' - 1) as char),
240        c => Key::Char(c as char),
241    }
242}
243
244impl Drop for Term {
245    fn drop(&mut self) {
246        restore();
247    }
248}
249
250fn csi(seq: &[u8]) -> Key {
251    match seq {
252        b"A" => Key::Up,
253        b"B" => Key::Down,
254        b"C" => Key::Right,
255        b"D" => Key::Left,
256        b"H" | b"1~" | b"7~" => Key::Home,
257        b"F" | b"4~" | b"8~" => Key::End,
258        b"5~" => Key::PageUp,
259        b"6~" => Key::PageDown,
260        b"Z" => Key::BackTab,
261        _ => Key::Esc,
262    }
263}
264
265/// Put the terminal back. Idempotent, because `Drop`, the panic hook and a
266/// fatal signal can all reach it and a double panic would otherwise run it
267/// twice.
268///
269/// Every call in here is async-signal-safe — `tcsetattr` and `write` are on
270/// POSIX's list, and `OnceLock::get` is one atomic load — because [`bail`] runs
271/// it from a signal handler. `io::stdout()` is the thing that would not do:
272/// taking its lock in a handler that interrupted the thread already holding it
273/// is a deadlock at exactly the moment the user wants their terminal back.
274fn restore() {
275    if let Some(t) = ORIG.get() {
276        // SAFETY: `t` borrows the `termios` `enter` filled with `tcgetattr` and
277        // nothing has written it since — `OnceLock` hands out no `&mut` after
278        // `set`. Reached from the `bail` handler, and `tcsetattr` is on POSIX's
279        // async-signal-safe list, so interrupting a `tcsetattr` with this one is
280        // defined.
281        unsafe { libc::tcsetattr(0, libc::TCSANOW, t) };
282    }
283    const OFF: &[u8] = b"\x1b[?25h\x1b[?1049l";
284    // SAFETY: `OFF` is a `'static` slice, so its pointer is valid for the
285    // `OFF.len()` bytes claimed for as long as the program runs, and `write`
286    // only reads them. Async-signal-safe, which is why this is not `stdout`.
287    unsafe { libc::write(1, OFF.as_ptr().cast(), OFF.len()) };
288}
289
290/// Install `h` for `sig`, without `SA_RESTART`.
291///
292/// The flag is omitted because it buys nothing here, not because [`poll_in`]
293/// needs it: `poll(2)` is on signal(7)'s list of calls the kernel never
294/// restarts whatever the flag says, and the `read(2)` in the same loop runs
295/// under VMIN 0 / VTIME 0, so it returns immediately and is never sitting in a
296/// restartable wait either. What makes a resize wake `poll_in` is installing a
297/// handler at all — SIGWINCH's default disposition is to discard the signal,
298/// and a discarded signal interrupts nothing.
299fn on_signal(sig: libc::c_int, h: unsafe extern "C" fn(libc::c_int)) {
300    // SAFETY: `sigaction` is POD, and all-zero is its "no flags, SIG_DFL"
301    // value — the one the two writes below then replace.
302    let mut sa: libc::sigaction = unsafe { std::mem::zeroed() };
303    sa.sa_sigaction = h as usize;
304    // SAFETY: `sa` is initialised and outlives the call, which copies it;
305    // `sigemptyset` writes only `sa_mask`. The load-bearing part is `sa_flags`,
306    // left at zero by the `zeroed` above: with SA_SIGINFO clear the kernel calls
307    // `sa_sigaction` with the single `c_int` that `h`'s type declares, so
308    // setting that flag without widening `h`'s signature is what would break
309    // this. A null `oldact` means "do not report the previous disposition",
310    // which `sigaction(2)` permits. Both handlers this is ever called with —
311    // [`winch`] and [`bail`] — are async-signal-safe.
312    unsafe {
313        libc::sigemptyset(&mut sa.sa_mask);
314        libc::sigaction(sig, &sa, std::ptr::null_mut());
315    }
316}
317
318/// A resize. Nothing to do in the handler — the delivery itself is the message,
319/// and it arrives as an `EINTR` in [`poll_in`].
320unsafe extern "C" fn winch(_: libc::c_int) {}
321
322/// Give the terminal back, then die.
323///
324/// Installing a handler removed the default disposition, so returning would
325/// resume a process the user asked to end; `_exit` rather than `exit` because
326/// the latter runs atexit handlers that are not async-signal-safe, and 128+n is
327/// the status a shell reports for a signal death.
328unsafe extern "C" fn bail(sig: libc::c_int) {
329    restore();
330    // SAFETY: `_exit` dereferences nothing and never returns. It is
331    // async-signal-safe, which is the entire reason it is here rather than
332    // `exit` — see the doc above.
333    unsafe { libc::_exit(128 + sig) };
334}
335
336/// The `termios` calls' contract: `0`, or `-1` and the reason is in `errno`.
337///
338/// Read here rather than at the call site because nothing runs in between —
339/// `rc` is already a value by the time this is entered, and Rust code cannot
340/// touch `errno` — so the read is as prompt as an inline one, and the two call
341/// sites in [`enter`](Term::enter) stop being four lines each.
342fn ok_or_errno(rc: libc::c_int) -> io::Result<()> {
343    match rc {
344        0 => Ok(()),
345        _ => Err(io::Error::last_os_error()),
346    }
347}
348
349fn poll_in(timeout_ms: i32) -> io::Result<bool> {
350    let mut p = libc::pollfd {
351        fd: 0,
352        events: libc::POLLIN,
353        revents: 0,
354    };
355    // SAFETY: `&mut p` points at exactly the one initialised `pollfd` the count
356    // of `1` claims, it lives across the call, and `poll` writes only `revents`.
357    let n = unsafe { libc::poll(&mut p, 1, timeout_ms) };
358    if n >= 0 {
359        return Ok(n > 0);
360    }
361    let e = io::Error::last_os_error();
362    // A resize interrupts the poll, which is the only reason `enter` installs a
363    // SIGWINCH handler at all — the default disposition discards it and this
364    // arm would be unreachable. Reporting "nothing to read" sends the caller
365    // back around the draw loop, which re-reads the size — which is exactly the
366    // handling a resize wants, so it is not retried here.
367    match e.kind() {
368        io::ErrorKind::Interrupted => Ok(false),
369        _ => Err(e),
370    }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum Key {
375    Char(char),
376    Ctrl(char),
377    Up,
378    Down,
379    Left,
380    Right,
381    Enter,
382    Esc,
383    Tab,
384    BackTab,
385    Backspace,
386    Home,
387    End,
388    PageUp,
389    PageDown,
390}
391
392pub const RESET: &str = "\x1b[0m";
393pub const BOLD: &str = "\x1b[1m";
394pub const DIM: &str = "\x1b[2m";
395pub const REV: &str = "\x1b[7m";
396pub const RED: &str = "\x1b[31m";
397pub const GREEN: &str = "\x1b[32m";
398pub const YELLOW: &str = "\x1b[33m";
399pub const BLUE: &str = "\x1b[34m";
400pub const MAGENTA: &str = "\x1b[35m";
401pub const CYAN: &str = "\x1b[36m";
402
403#[cfg(test)]
404pub(crate) mod tests {
405    use super::*;
406
407    /// The sequences the app actually binds, including the ones that arrive
408    /// split across two reads.
409    #[test]
410    fn escape_sequences_decode_to_keys() {
411        let mut pending: Vec<u8> = Vec::new();
412        let mut keys = |bytes: &[u8]| {
413            pending.extend_from_slice(bytes);
414            let mut out = Vec::new();
415            while let Parsed::Key(k) = parse(&mut pending) {
416                out.push(k);
417            }
418            out
419        };
420        assert_eq!(keys(b"\x1b[A\x1b[B"), vec![Key::Up, Key::Down]);
421        assert_eq!(keys(b"\x1b[5~\x1b[6~"), vec![Key::PageUp, Key::PageDown]);
422        assert_eq!(keys(b"\x1bOD"), vec![Key::Left]);
423        assert_eq!(
424            keys(b"jk\r\x7f"),
425            vec![Key::Char('j'), Key::Char('k'), Key::Enter, Key::Backspace]
426        );
427        assert_eq!(keys(b"\x03"), vec![Key::Ctrl('c')]);
428        // Split mid-sequence: nothing until the rest lands. Both prefixes, since
429        // CSI and SS3 have separate "could still grow" arms.
430        assert_eq!(keys(b"\x1b["), vec![]);
431        assert_eq!(keys(b"C"), vec![Key::Right]);
432        assert_eq!(keys(b"\x1bO"), vec![]);
433        assert_eq!(keys(b"A"), vec![Key::Up]);
434        // Multi-byte UTF-8, likewise, at every lead-byte width — the width is
435        // read off the lead byte, so a wrong row in that table eats the next key.
436        assert_eq!(keys(&[0xc3]), vec![]);
437        assert_eq!(keys(&[0xa9]), vec![Key::Char('é')]);
438        assert_eq!(keys(&[0xe2, 0x82]), vec![]);
439        assert_eq!(keys(&[0xac]), vec![Key::Char('€')]);
440        assert_eq!(keys(&[0xf0, 0x9f, 0x98]), vec![]);
441        assert_eq!(keys(&[0x80]), vec![Key::Char('😀')]);
442    }
443
444    /// Every sequence in the `csi` table, because terminals disagree about which
445    /// one they send for the same physical key and the table exists to absorb
446    /// that. An unrecognised one is `Esc`, not a dropped byte: the app treats
447    /// `Esc` as "cancel", which is the safe reading of a key we do not know.
448    #[test]
449    fn one_key_arrives_in_as_many_spellings_as_there_are_terminals() {
450        // `None` is [`Parsed::Need`]: what is there could still grow into a
451        // longer sequence, so no key comes out of it yet.
452        fn key(bytes: &[u8]) -> Option<Key> {
453            match parse(&mut bytes.to_vec()) {
454                Parsed::Key(k) => Some(k),
455                Parsed::Need => None,
456            }
457        }
458        // A CSI with no final byte yet is the "could still grow" answer, not a
459        // key: the table below would otherwise be reading half a sequence.
460        assert_eq!(key(b"\x1b[1"), None);
461        for (bytes, want) in [
462            (&b"\x1b[H"[..], Some(Key::Home)),
463            (b"\x1b[1~", Some(Key::Home)),
464            (b"\x1b[7~", Some(Key::Home)),
465            (b"\x1b[F", Some(Key::End)),
466            (b"\x1b[4~", Some(Key::End)),
467            (b"\x1b[8~", Some(Key::End)),
468            (b"\x1b[Z", Some(Key::BackTab)),
469            (b"\x1b[C", Some(Key::Right)),
470            (b"\x1bOA", Some(Key::Up)),
471            // Not in the table, and not worth guessing at.
472            (b"\x1b[200~", Some(Key::Esc)),
473            (b"\t", Some(Key::Tab)),
474            (b"\x08", Some(Key::Backspace)),
475            (b"\n", Some(Key::Enter)),
476            // Nothing at all is not a key either: `key` is called in a loop that
477            // polls again, and a `Parsed::Key` here would be one nobody pressed.
478            (b"", None),
479            // Half of a CSI and half of an SS3, which is how they arrive when
480            // the read lands mid-sequence.
481            (b"\x1b[", None),
482            (b"\x1bO", None),
483        ] {
484            assert_eq!(key(bytes), want, "{bytes:?}");
485        }
486
487        // Alt+x: the modifier is dropped and the key kept, so the next call sees
488        // a bare `x` rather than both bytes being swallowed.
489        let mut b = b"\x1bx".to_vec();
490        assert!(matches!(parse(&mut b), Parsed::Need));
491        assert_eq!(key(&b), Some(Key::Char('x')));
492
493        // What `key` falls back to when a sequence never completes: the first
494        // byte for what it is, then resynchronise. A lone ESC is the case that
495        // matters — it is how the filter box gets cancelled.
496        for (byte, want) in [
497            (0x1b, Key::Esc),
498            (0x03, Key::Ctrl('c')),
499            (b'q', Key::Char('q')),
500        ] {
501            let mut b = vec![byte, b'!'];
502            assert_eq!(take_one(&mut b), want);
503            assert_eq!(b, b"!");
504        }
505    }
506
507    /// The branch that fires in anger: `mira mira` in a pipeline, in CI, or
508    /// under a process supervisor. The rest of the syscall half runs on a real
509    /// pty in [`the_terminal_half_runs_against_a_real_pty`].
510    #[test]
511    fn the_tui_refuses_a_stdin_that_is_not_a_terminal() {
512        let e = Term::enter()
513            .err()
514            .expect("cargo test does not run on a tty");
515        assert_eq!(e.kind(), io::ErrorKind::Unsupported);
516        assert!(e.to_string().contains("needs stdin and stdout on a tty"));
517    }
518
519    /// The other half of the same refusal: if a `termios` call fails anyway,
520    /// `enter` reports why instead of pressing on with a terminal it has half
521    /// configured. Provoked on a pipe, since `enter` turns away everything that
522    /// is not a tty before it reaches either call.
523    #[test]
524    fn a_failed_termios_call_carries_the_os_error() {
525        let mut fds = [-1; 2];
526        // SAFETY: `pipe` writes exactly the two `c_int`s this array holds.
527        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
528        // SAFETY: all-zero is a valid `termios`, as in `enter` — and here both
529        // calls fail without writing it at all.
530        let mut t: libc::termios = unsafe { std::mem::zeroed() };
531        // SAFETY: `fds[0]` is open until the `close` below, and both calls get
532        // a live, correctly typed `termios`.
533        let get = ok_or_errno(unsafe { libc::tcgetattr(fds[0], &mut t) });
534        // SAFETY: as above; `tcsetattr` only reads it.
535        let set = ok_or_errno(unsafe { libc::tcsetattr(fds[0], libc::TCSANOW, &t) });
536        // SAFETY: both fds were opened by the `pipe` above and are owned by
537        // nothing else, so this is the only close of either.
538        unsafe {
539            libc::close(fds[0]);
540            libc::close(fds[1]);
541        }
542        for r in [get, set] {
543            // ENOTTY, not a generic "it did not work": the message the user
544            // sees is the difference between a redirect and a broken terminal.
545            assert_eq!(r.unwrap_err().raw_os_error(), Some(libc::ENOTTY));
546        }
547    }
548
549    /// The name of the test below, as `--exact` wants it.
550    const ON_POLL: &str = "term::tests::a_poll_that_fails_for_anything_but_a_signal_is_an_error";
551
552    /// EINTR is a resize and means "nothing to read"; every other `poll` error
553    /// has to come back as one, or the draw loop spins on a syscall that is
554    /// failing every time and never says so.
555    ///
556    /// `poll_in` polls fd 0 with nfds 1, which nothing outside the process can
557    /// make fail — except that both Linux and macOS reject an nfds above
558    /// RLIMIT_NOFILE with EINVAL, and the soft limit can be dropped to zero.
559    /// That is process-wide and a process that can open nothing is no use to
560    /// the rest of the suite, so it happens in a re-exec of this one test.
561    #[test]
562    fn a_poll_that_fails_for_anything_but_a_signal_is_an_error() {
563        if std::env::var_os("MIRA_POLL_CHILD").is_none() {
564            let out = std::process::Command::new(std::env::current_exe().unwrap())
565                .args(["--exact", ON_POLL, "--nocapture"])
566                .env("MIRA_POLL_CHILD", "1")
567                .output()
568                .unwrap();
569            let err = String::from_utf8_lossy(&out.stderr);
570            assert!(out.status.success(), "{err}");
571            return;
572        }
573        // SAFETY: `rlimit` is two integers, and `getrlimit` writes exactly the
574        // one live struct it is handed.
575        let mut orig: libc::rlimit = unsafe { std::mem::zeroed() };
576        // SAFETY: as above.
577        let read = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut orig) };
578        assert_eq!(read, 0, "getrlimit: {}", io::Error::last_os_error());
579        let none = libc::rlimit {
580            rlim_cur: 0,
581            rlim_max: orig.rlim_max,
582        };
583        // SAFETY: `setrlimit` only reads the struct, for the call's duration.
584        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &none) }, 0);
585        let got = poll_in(0);
586        // Put it back before anything — the assertion's own panic machinery
587        // included — needs a descriptor. Lowering the soft limit is reversible
588        // precisely because the hard limit above was left alone.
589        // SAFETY: as above.
590        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &orig) }, 0);
591        assert_eq!(got.unwrap_err().raw_os_error(), Some(libc::EINVAL));
592    }
593
594    /// The name of the test below, as `--exact` wants it.
595    const SELF: &str = "term::tests::the_terminal_half_runs_against_a_real_pty";
596
597    /// Everything in this file that talks to a terminal, against a terminal.
598    ///
599    /// `enter`, `size`, `draw`, `key`, `poll_in` and `restore` all address fd 0
600    /// and fd 1 directly, so the only honest way to run them is on a process
601    /// whose fd 0 and fd 1 are a tty — and it must not be *this* process, whose
602    /// stdin belongs to the test runner and whose termios the runner needs back.
603    #[test]
604    fn the_terminal_half_runs_against_a_real_pty() {
605        if std::env::var_os("MIRA_PTY_CHILD").is_some() {
606            return on_the_pty();
607        }
608        // Destructured rather than held as a `Pty`: the assertions below want
609        // the names in their format strings, and a format argument on its own
610        // line is a region that only a failing run ever executes.
611        let Pty {
612            screen,
613            err,
614            stalled,
615            trailing,
616        } = drive(
617            SELF,
618            &[],
619            &[
620                ("mira-pty-ready", b"\x1b[B"),
621                ("mira-pty-down", b"x"),
622                ("mira-pty-x", b"\x1b"),
623            ],
624            // The restore sequence, asserted after the drain thread is joined
625            // rather than from inside the script: the child writes it from its
626            // panic hook on the way out, with no marker left to answer after it.
627            "\x1b[?25h\x1b[?1049l",
628        );
629        // The child signs off by panicking on purpose, so any *other* panic is a
630        // failed assertion and this is where it gets read out.
631        assert!(
632            stalled.is_none() && err.contains("mira-pty-done"),
633            "child stalled at {stalled:?}: {err}\nscreen:\n{screen:?}"
634        );
635        // The frame reached the terminal, cursor-homed and erased behind itself.
636        assert!(screen.contains("\x1b[H"), "{screen:?}");
637        assert!(screen.contains("mira-pty-ready\x1b[K\r\n"), "{screen:?}");
638        // ...and the panic hook handed the terminal back: cursor on, alternate
639        // screen off. Without it the user's shell is left in raw mode.
640        assert!(trailing, "{screen:?}");
641    }
642
643    /// What [`drive`] saw: everything the child wrote to the pty, everything it
644    /// wrote to stderr, the marker it stopped answering at if it stopped at one,
645    /// and whether the trailing marker ever arrived.
646    pub(crate) struct Pty {
647        pub screen: String,
648        pub err: String,
649        pub stalled: Option<&'static str>,
650        pub trailing: bool,
651    }
652
653    /// Run one test of this binary on the far side of a real pty.
654    ///
655    /// Open a pty, re-exec this same test binary against the slave side, and
656    /// drive it from the master. The child is the same instrumented binary, so
657    /// its coverage counts; `cargo llvm-cov` merges the profraw it writes.
658    ///
659    /// This is CLAUDE.md's `script -q /dev/null` recipe with the pty opened in
660    /// process, which is what makes it a test rather than a thing to run by hand.
661    /// [`crate::tui`] drives its own event loop through here for the same reason
662    /// this module does: a loop that calls `Term::enter` needs somewhere to enter.
663    pub(crate) fn drive(
664        test: &str,
665        env: &[(&str, &std::ffi::OsStr)],
666        script: &[(&'static str, &'static [u8])],
667        trailing: &str,
668    ) -> Pty {
669        use std::os::fd::FromRawFd;
670        use std::process::{Command, Stdio};
671        use std::sync::{Arc, Mutex};
672
673        // SAFETY: flags by value, no pointer argument.
674        let master = unsafe { libc::posix_openpt(libc::O_RDWR | libc::O_NOCTTY) };
675        assert!(master >= 0, "{}", io::Error::last_os_error());
676        // SAFETY: `master` is the fd `posix_openpt` just returned, proved not
677        // -1 by the assert above and closed by nothing until `from_raw_fd`
678        // below; both calls take it by value.
679        assert_eq!(unsafe { libc::grantpt(master) }, 0);
680        // SAFETY: as above.
681        assert_eq!(unsafe { libc::unlockpt(master) }, 0);
682        // SAFETY: `ptsname` returns a NUL-terminated string in a static buffer,
683        // non-null because `master` is a pty master — `grantpt` returned 0 on
684        // it one line up, which it does not for anything else. The buffer is
685        // clobbered by the next `ptsname` on any thread, so the `CStr` is copied
686        // into an owned `String` in this same expression and never held.
687        let slave_path = unsafe { std::ffi::CStr::from_ptr(libc::ptsname(master)) }
688            .to_str()
689            .unwrap()
690            .to_owned();
691
692        let slave = std::fs::OpenOptions::new()
693            .read(true)
694            .write(true)
695            .open(&slave_path)
696            .unwrap();
697        // A size the child can assert on, so `size` is checked against something
698        // it cannot have made up. Set on the slave: macOS refuses TIOCSWINSZ on
699        // a master with no slave open yet.
700        let ws = libc::winsize {
701            ws_row: 40,
702            ws_col: 120,
703            ws_xpixel: 0,
704            ws_ypixel: 0,
705        };
706        let fd = std::os::fd::AsRawFd::as_raw_fd(&slave);
707        // SAFETY: TIOCSWINSZ is the request whose variadic argument is
708        // `*const winsize`, which is what `&ws` is, and `fd` is borrowed from
709        // `slave`, still open here — it is dropped after the spawn.
710        let sized = unsafe { libc::ioctl(fd, libc::TIOCSWINSZ as _, &ws) };
711        assert_eq!(sized, 0, "TIOCSWINSZ: {}", io::Error::last_os_error());
712        let child = Command::new(std::env::current_exe().unwrap())
713            .args(["--exact", test, "--nocapture"])
714            .env("MIRA_PTY_CHILD", "1")
715            .envs(env.iter().copied())
716            .stdin(Stdio::from(slave.try_clone().unwrap()))
717            .stdout(Stdio::from(slave.try_clone().unwrap()))
718            // Not the pty: the child's failures have to come back over a channel
719            // the child cannot also be scribbling frames onto.
720            .stderr(Stdio::piped())
721            .spawn()
722            .unwrap();
723        drop(slave);
724
725        // SAFETY: `from_raw_fd` takes ownership, and this is the only owner
726        // `master` ever gets — it is still open (nothing has closed it since
727        // `posix_openpt`), and the child holds dups of the *slave*, not this fd.
728        // `rd` and its `try_clone` are now what will close it.
729        let mut rd = unsafe { std::fs::File::from_raw_fd(master) };
730        let mut wr = rd.try_clone().unwrap();
731        let screen = Arc::new(Mutex::new(String::new()));
732        let sink = screen.clone();
733        // Drained on a thread: a child that fills the pty buffer while this side
734        // is blocked writing to it is a deadlock, not a slow test.
735        let reader = std::thread::spawn(move || {
736            let mut buf = [0u8; 4096];
737            while let Ok(n) = rd.read(&mut buf) {
738                if n == 0 {
739                    break;
740                }
741                sink.lock()
742                    .unwrap()
743                    .push_str(&String::from_utf8_lossy(&buf[..n]));
744            }
745        });
746
747        let arrived = |marker: &str| {
748            (0..600).any(|_| {
749                if screen.lock().unwrap().contains(marker) {
750                    return true;
751                }
752                std::thread::sleep(std::time::Duration::from_millis(10));
753                false
754            })
755        };
756
757        // Every keystroke waits for the marker the child draws once it has
758        // consumed the previous one. Not politeness: a lone Esc only resolves as
759        // Esc because the 20ms grace period finds no byte behind it, so an Esc
760        // written while `x` is still in the buffer arrives as Alt+x.
761        let mut child = child;
762        let stalled = script
763            .iter()
764            .find(|(marker, keys)| !arrived(marker) || wr.write_all(keys).is_err())
765            .map(|(marker, _)| *marker);
766        // Otherwise it sits in `poll_in(-1)` for the rest of the afternoon. One
767        // expression rather than an `if`, so the healthy run — the only one CI
768        // ever takes — still executes the cleanup line.
769        let _ = stalled.map(|_| child.kill());
770
771        let out = child.wait_with_output().unwrap();
772        // The child being gone does not mean its last frame has been read: the
773        // draining thread is still holding bytes the kernel buffered. Joining it
774        // — the read side ends when the slave's last fd closes, which the exit
775        // above did — is what makes `screen` the whole session rather than
776        // however much had arrived by the time `wait` returned.
777        reader.join().unwrap();
778        let trailing = arrived(trailing);
779        Pty {
780            screen: screen.lock().unwrap().clone(),
781            err: String::from_utf8_lossy(&out.stderr).into_owned(),
782            stalled,
783            trailing,
784        }
785    }
786
787    /// The child of the test above. Panics are the failure channel: they land on
788    /// the piped stderr and the exit status carries them back.
789    fn on_the_pty() {
790        let mut t = Term::enter().expect("stdin and stdout are the pty slave");
791        assert_eq!(t.size(), (120, 40), "the size the parent set");
792
793        // A tty nobody sized — a bare `posix_openpt`, `script -q /dev/null` on
794        // some runners — answers TIOCGWINSZ with zeros rather than failing, and
795        // a frame laid out for zero columns is a blank screen. 80x24 instead.
796        let sizes = [(0, 0), (40, 120)].map(|(ws_row, ws_col)| libc::winsize {
797            ws_row,
798            ws_col,
799            ws_xpixel: 0,
800            ws_ypixel: 0,
801        });
802        for (ws, want) in sizes.iter().zip([(80, 24), (120, 40)]) {
803            // SAFETY: TIOCSWINSZ's variadic argument is `*const winsize`, which
804            // is what `ws` is, and fd 1 is the pty slave — the same fd `size`
805            // reads back through. Setting it back afterwards is what leaves the
806            // rest of this function at the size the parent asked for.
807            let rc = unsafe { libc::ioctl(1, libc::TIOCSWINSZ as _, ws) };
808            assert_eq!(rc, 0, "TIOCSWINSZ: {}", io::Error::last_os_error());
809            assert_eq!(t.size(), want, "{} columns", ws.ws_col);
810        }
811
812        // Before the first marker, so the parent provably has not typed yet: the
813        // timeout expires and says so, rather than returning a key nobody
814        // pressed. After a marker it would be a race the parent usually wins.
815        assert_eq!(t.key(30).unwrap(), None, "empty poll");
816
817        // A resize has to break an *infinite* poll, or the frame is never
818        // repainted at the new size. Aimed at this exact thread: plain `kill`
819        // is free to hand the signal to the test harness's thread, which is not
820        // the one parked in `poll`.
821        struct Tid(libc::pthread_t);
822        // Handing a thread handle to the thread that will signal with it is the
823        // only reason this type exists.
824        // SAFETY: `pthread_t` is a pointer on macOS, which is the only reason
825        // `Tid` is not `Send` already. The receiving thread does one thing with
826        // it — `pthread_kill`, which POSIX requires to be callable from any
827        // thread — and the handle cannot dangle, because this thread is parked
828        // in the `t.key(-1)` below until the signal it sends arrives. Delete
829        // that call and the id can outlive its thread.
830        unsafe impl Send for Tid {}
831        // SAFETY: `pthread_self` reads no memory and cannot fail.
832        let me = Tid(unsafe { libc::pthread_self() });
833        std::thread::spawn(move || {
834            std::thread::sleep(std::time::Duration::from_millis(30));
835            // SAFETY: `me.0` names the thread that is blocked in `poll` waiting
836            // for this — see the `unsafe impl` above for why it is still alive.
837            // SIGWINCH has a handler by now (`Term::enter` installed it), so
838            // delivery interrupts that poll instead of killing the process.
839            unsafe { libc::pthread_kill(me.0, libc::SIGWINCH) };
840        });
841        assert_eq!(t.key(-1).unwrap(), None, "a resize interrupts the poll");
842
843        // SIGTERM and SIGHUP are inspected rather than raised: they end the
844        // process, and a child that dies of a signal writes no coverage profile
845        // and reports nothing back. The failure that actually happened — no
846        // handler at all, so a `kill` left the shell in raw mode — is visible
847        // from the disposition. `SA_RESTART` is not asserted on: see
848        // [`on_signal`] for why the flag has no bearing on either syscall in
849        // this loop, and the wake-up above for the behaviour that does matter.
850        for sig in [libc::SIGWINCH, libc::SIGTERM, libc::SIGHUP] {
851            // SAFETY: POD and all-zero is a valid `sigaction`, as in
852            // [`on_signal`]; here it is only a destination.
853            let mut sa: libc::sigaction = unsafe { std::mem::zeroed() };
854            // SAFETY: a null `act` means "report the disposition without
855            // changing it", so the only pointer that has to be good is `&mut
856            // sa`, a live and correctly typed `sigaction`.
857            let got = unsafe { libc::sigaction(sig, std::ptr::null(), &mut sa) };
858            assert_eq!(got, 0, "reading the disposition of {sig}");
859            assert!(
860                sa.sa_sigaction != libc::SIG_DFL && sa.sa_sigaction != libc::SIG_IGN,
861                "signal {sig} has no handler"
862            );
863        }
864
865        // Each marker is both a frame to assert on and the parent's cue to send
866        // the next key. See the write loop above for why they interleave.
867        t.draw(&["mira-pty-ready".into(), "second row".into()])
868            .unwrap();
869        assert_eq!(t.key(-1).unwrap(), Some(Key::Down));
870        t.draw(&["mira-pty-down".into()]).unwrap();
871        assert_eq!(t.key(-1).unwrap(), Some(Key::Char('x')));
872        t.draw(&["mira-pty-x".into()]).unwrap();
873        // The lone Esc, which only resolves because the grace period ran out.
874        assert_eq!(t.key(-1).unwrap(), Some(Key::Esc));
875
876        // Two shapes a real terminal will not produce on demand, injected last
877        // because both of them break the pty this test is standing on.
878        //
879        // A window with no size: `size` reads it back off a *successful* ioctl,
880        // and zero columns is what a detached or not-yet-sized tty answers.
881        // Every column computation in `tui.rs` divides by that number.
882        let zero = libc::winsize {
883            ws_row: 0,
884            ws_col: 0,
885            ws_xpixel: 0,
886            ws_ypixel: 0,
887        };
888        // SAFETY: as the parent's TIOCSWINSZ above — `*const winsize` is the
889        // argument this request takes, and fd 1 is this process's pty slave.
890        let sized = unsafe { libc::ioctl(1, libc::TIOCSWINSZ as _, &zero) };
891        assert_eq!(sized, 0, "TIOCSWINSZ 0x0: {}", io::Error::last_os_error());
892        assert_eq!(t.size(), (80, 24), "no size is 80x24, not 0x0");
893
894        // EOF on stdin, which `read` reports as zero bytes on a `poll` that says
895        // there is something there. Reported as ^C because that is the only
896        // answer that ends the draw loop — anything else spins on a descriptor
897        // that is ready forever.
898        let devnull = std::fs::File::open("/dev/null").unwrap();
899        let null_fd = std::os::fd::AsRawFd::as_raw_fd(&devnull);
900        // SAFETY: both arguments are open descriptors this process owns. `dup2`
901        // closes fd 0 and duplicates `null_fd` onto it; nothing reads fd 0
902        // after this but the `key` below.
903        assert_eq!(unsafe { libc::dup2(null_fd, 0) }, 0);
904        assert_eq!(t.key(0).unwrap(), Some(Key::Ctrl('c')), "EOF is a quit");
905
906        // A panic, on purpose, as the last act: the promise `enter` makes by
907        // installing a hook is that a crash still gives you your terminal back,
908        // and the only way to check it is to crash. The parent looks for this
909        // exact message, so a real assertion failure above still reads as one.
910        panic!("mira-pty-done");
911    }
912}