abstracttui 0.2.19

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
Documentation
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Unix terminal backend: /dev/tty, termios raw mode, poll(2) reads,
//! SIGWINCH self-pipe resize wakeups with ioctl ground truth.
//!
//! OWNER: KERNEL. Rationale: `docs/design/term-input.md` §1.
//!
//! `unsafe` policy: every block is a single FFI call (or reads FFI-owned
//! memory) with a SAFETY note. No unsafe outside this boundary.

use super::options::EnterOptions;
use super::verbs::{self, CursorStyle};
use super::waker::TerminalWaker;
use super::{TermRead, Terminal};
use crate::base::{Error, PixelSize, Result, Size};
use std::os::unix::io::RawFd;
use std::time::{Duration, Instant};

// Process-global machinery (SIGWINCH claim, emergency restore, errno,
// fd helpers) lives in a sibling file; the path attribute keeps it a
// child module so the split is invisible to consumers.
#[path = "unix_sys.rs"]
mod sys;
pub use sys::emergency_restore;
use sys::{
    claim_winch, io_err, last_errno, release_winch, write_all_fd, EmergencySlot, WinchClaim,
    EMERGENCY,
};
// Re-exported for term-level test harnesses (the live tmux rig does its
// own ioctls); the alias itself lives in unix_sys.
pub(crate) use sys::IoctlReq;
// (sys::append_emergency_leave is called by the verb overrides below.)

const READ_BUF_LEN: usize = 4096;
/// Poll slice when we could not claim the SIGWINCH handler: resize is then
/// detected by comparing TIOCGWINSZ on each wake, so the wake cadence bounds
/// resize latency. Only this degraded path spends idle wakeups.
const NO_SIGNAL_SLICE: Duration = Duration::from_millis(250);

// ---------------------------------------------------------------------------
// The terminal.
// ---------------------------------------------------------------------------

struct EnteredState {
    saved_termios: libc::termios,
    opts: EnterOptions,
    winch: Option<WinchClaim>,
}

/// Write end of the per-instance wake pipe. Held inside the waker's `Arc`
/// closure: the fd stays open as long as ANY waker clone lives, so a waker
/// outliving its terminal writes into a reader-less pipe (harmless, at
/// worst EAGAIN when full) instead of racing fd-number reuse.
struct WakeFd(RawFd);

impl Drop for WakeFd {
    fn drop(&mut self) {
        // SAFETY: closing the write fd this wrapper exclusively owns.
        unsafe { libc::close(self.0) };
    }
}

/// Open the REAL terminal device behind a tty fd (`ttyname_r` -> fresh
/// O_RDWR open). `None` when the name cannot be resolved/opened, or when
/// it resolves to the un-pollable "/dev/tty" alias string (Darwin answers
/// that for alias fds — a real fd resolves to `/dev/ttysNNN`).
fn open_named_tty(tty_fd: RawFd) -> Option<RawFd> {
    let mut buf = [0 as libc::c_char; 1024];
    // SAFETY: ttyname_r writes a NUL-terminated path into our buffer on
    // success (returns 0); the fd is live.
    if unsafe { libc::ttyname_r(tty_fd, buf.as_mut_ptr(), buf.len()) } != 0 {
        return None;
    }
    // SAFETY: reading the NUL-terminated string ttyname_r produced.
    let name = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) };
    if name.to_bytes() == b"/dev/tty" {
        return None; // the alias again: not a resolution
    }
    // SAFETY: opening the path ttyname_r just produced.
    let real = unsafe { libc::open(buf.as_ptr(), libc::O_RDWR | libc::O_CLOEXEC) };
    if real < 0 {
        return None;
    }
    // The resolved fd must still be a terminal.
    // SAFETY: isatty on the fd we just opened.
    if unsafe { libc::isatty(real) } != 1 {
        // SAFETY: closing the fd we just opened.
        unsafe { libc::close(real) };
        return None;
    }
    Some(real)
}

/// True when an interactive terminal is reachable — the same acquisition
/// test `UnixTerminal::new()` performs, without keeping the fd. This is
/// the question boot's auto-skip must ask (DESIGN request 10 / RT1-10c:
/// `isatty(stdout)` is the wrong question, the engine renders to
/// `/dev/tty` even when stdout is a pipe).
pub fn have_tty() -> bool {
    // SAFETY: open(2) with a static NUL-terminated path; closed just below.
    let fd = unsafe { libc::open(c"/dev/tty".as_ptr(), libc::O_RDWR | libc::O_CLOEXEC) };
    if fd >= 0 {
        // SAFETY: closing the fd we just opened.
        unsafe { libc::close(fd) };
        return true;
    }
    // SAFETY: isatty on the standard descriptors.
    unsafe { libc::isatty(libc::STDIN_FILENO) == 1 && libc::isatty(libc::STDOUT_FILENO) == 1 }
}

/// The unix terminal backend (macOS/Linux): real device fds, manual
/// termios raw mode, poll(2)-gated reads, SIGWINCH self-pipe, per
/// instance wake pipe. Construct via [`UnixTerminal::new`] (acquisition
/// policy documented there) or [`UnixTerminal::from_fds`] (ptys, tests).
pub struct UnixTerminal {
    read_fd: RawFd,
    write_fd: RawFd,
    owns_fds: bool,
    entered: Option<EnteredState>,
    out: Vec<u8>,
    in_buf: Vec<u8>,
    /// Size cache for resize *detection* only. `size()` never reads it, so
    /// an app calling `size()` cannot swallow a pending Resize event.
    seen_size: Size,
    /// Read end of the wake pipe (`None` if pipe creation failed at
    /// construction — then `waker()` is honestly `None` too).
    wake_rd: Option<RawFd>,
    waker: Option<TerminalWaker>,
    /// A non-default DECSCUSR was emitted: leave restores `Ps 0`.
    cursor_styled: bool,
    /// The title stack was pushed before our first title: leave pops it.
    title_pushed: bool,
    /// SGR-Pixels (1016) is on: leave turns it off.
    pixel_moused: bool,
    /// Labeled degradation, set when the read path had to abandon a
    /// non-pollable fd (POLLNVAL) for a stdin fallback. `None` = healthy
    /// primary path. Apps may surface it; the engine never prints.
    degraded: Option<&'static str>,
}

impl UnixTerminal {
    // Construction + raw-mode/session plumbing lives in a `#[path]`
    // child (file-size split): see unix_setup.rs — same impl.
}

#[path = "unix_setup.rs"]
mod setup;

impl Terminal for UnixTerminal {
    fn enter(&mut self, opts: &EnterOptions) -> Result<()> {
        if self.entered.is_some() {
            return Ok(());
        }
        let saved = self.apply_raw_mode()?;
        let winch = claim_winch(); // None => degraded poll-slice detection
        self.seen_size = self.ioctl_size().unwrap_or(Size::ZERO);

        // Arm the emergency slot BEFORE emitting mode changes: if the write
        // below panics mid-way, the panic hook can still undo everything.
        if let Ok(mut g) = EMERGENCY.lock() {
            *g = Some(EmergencySlot {
                fd: self.write_fd,
                termios: saved,
                leave_bytes: opts.leave_bytes(),
            });
        }

        self.entered = Some(EnteredState {
            saved_termios: saved,
            opts: *opts,
            winch,
        });
        self.write(&opts.enter_bytes())?;
        self.flush()?;
        Ok(())
    }

    fn leave(&mut self) -> Result<()> {
        let state = self.entered.take();
        if state.is_none() && !self.cursor_styled && !self.title_pushed && !self.pixel_moused {
            return Ok(());
        }
        // Best-effort all the way down: a failed write must not prevent the
        // termios restore, which is the difference between "ugly screen" and
        // "unusable shell".
        let mut first_err: Option<Error> = None;
        if let Some(s) = &state {
            self.out.extend_from_slice(&s.opts.leave_bytes());
        }
        // Verb resets AFTER the mode teardown: the cursor style and title
        // restore must apply to the main screen the user returns to (some
        // terminals scope cursor shape per screen buffer).
        if self.pixel_moused {
            self.out.extend_from_slice(verbs::PIXEL_MOUSE_OFF);
            self.pixel_moused = false;
        }
        if self.cursor_styled {
            self.out.extend_from_slice(verbs::CURSOR_STYLE_RESET);
            self.cursor_styled = false;
        }
        if self.title_pushed {
            self.out.extend_from_slice(verbs::TITLE_POP);
            self.title_pushed = false;
        }
        if let Err(e) = self.flush() {
            first_err.get_or_insert(e);
        }
        let Some(state) = state else {
            // Verb-only cleanup (styled/titled without a session): no
            // termios/signal state to restore.
            return match first_err {
                Some(e) => Err(e),
                None => Ok(()),
            };
        };
        // SAFETY: restoring the termios captured by enter() on the same fd.
        if unsafe { libc::tcsetattr(self.read_fd, libc::TCSANOW, &state.saved_termios) } != 0 {
            first_err.get_or_insert(io_err("tcsetattr(restore)"));
        }
        if let Some(claim) = state.winch {
            release_winch(claim);
        }
        if let Ok(mut g) = EMERGENCY.lock() {
            *g = None;
        }
        match first_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    fn size(&mut self) -> Result<Size> {
        self.ioctl_size()
    }

    fn read(&mut self, deadline: Option<Instant>) -> Result<TermRead<'_>> {
        let winch_rd = self
            .entered
            .as_ref()
            .and_then(|s| s.winch.as_ref())
            .map(|w| w.pipe_rd);
        loop {
            // Remaining wait for this poll round. Without the signal claim,
            // cap slices so TIOCGWINSZ re-checks bound resize latency.
            // A deadline already in the past yields a zero-timeout poll:
            // one last drain of anything ready right now, then Idle below.
            let now = Instant::now();
            let remaining = deadline.map(|d| d.saturating_duration_since(now));
            let slice = match (remaining, winch_rd) {
                (Some(r), Some(_)) => Some(r),
                (Some(r), None) => Some(r.min(NO_SIGNAL_SLICE)),
                (None, Some(_)) => None,
                (None, None) => Some(NO_SIGNAL_SLICE),
            };
            let timeout_ms: libc::c_int = match slice {
                None => -1,
                Some(d) => d.as_millis().min(i32::MAX as u128) as libc::c_int,
            };

            // POSIX: a negative fd in a pollfd is skipped (revents = 0),
            // so absent channels are simply holes in a fixed 3-slot array:
            // [tty, sigwinch pipe, wake pipe].
            let mut fds = [
                libc::pollfd {
                    fd: self.read_fd,
                    events: libc::POLLIN,
                    revents: 0,
                },
                libc::pollfd {
                    fd: winch_rd.unwrap_or(-1),
                    events: libc::POLLIN,
                    revents: 0,
                },
                libc::pollfd {
                    fd: self.wake_rd.unwrap_or(-1),
                    events: libc::POLLIN,
                    revents: 0,
                },
            ];
            // SAFETY: poll over the 3 pollfds living on this stack frame.
            let rc = unsafe { libc::poll(fds.as_mut_ptr(), 3, timeout_ms) };
            if rc < 0 {
                if last_errno() == libc::EINTR {
                    // A signal (possibly SIGWINCH in degraded mode) landed:
                    // re-check geometry, then re-poll with a fresh timeout.
                    if let Some(sz) = self.check_resize() {
                        return Ok(TermRead::Resize(sz));
                    }
                    continue;
                }
                return Err(io_err("poll"));
            }

            // Keyboard-dead is the worst possible failure and must be
            // structurally impossible (RT5-1): a terminal fd the kernel
            // refuses to poll (POLLNVAL — Darwin's /dev/tty alias is the
            // live-proven case) falls back ONCE to stdin-as-tty with a
            // labeled degradation; with no candidate it fails LOUDLY.
            // Silence is the one outcome this branch forbids.
            if fds[0].revents & libc::POLLNVAL != 0 {
                // SAFETY: isatty on the standard input descriptor.
                let stdin_tty = unsafe { libc::isatty(libc::STDIN_FILENO) == 1 };
                if stdin_tty && self.read_fd != libc::STDIN_FILENO {
                    self.read_fd = libc::STDIN_FILENO;
                    self.degraded =
                        Some("terminal fd not pollable (POLLNVAL); reading stdin instead");
                    continue; // re-poll immediately on the fallback fd
                }
                return Err(Error::Term(
                    "terminal read fd is not pollable (POLLNVAL) and no stdin tty \
                     fallback exists — refusing to go keyboard-dead. This is a \
                     terminal-emulator/platform quirk worth reporting (include \
                     your emulator + OS); rerun with stdin attached to the \
                     terminal as a workaround"
                        .into(),
                ));
            }

            if fds[1].revents & libc::POLLIN != 0 {
                Self::drain_winch_pipe(fds[1].fd);
            }
            // Geometry check on EVERY wake (pipe, input, or timeout): the
            // ioctl is one cheap syscall and closes coalesced/lost-signal
            // races. Resize outranks everything: renderers want the new
            // geometry before processing whatever else queued up.
            if let Some(sz) = self.check_resize() {
                return Ok(TermRead::Resize(sz));
            }

            // Input outranks Wake (input latency budget); the wake pipe is
            // NOT drained on this path, so it stays readable and the very
            // next read returns Wake — nothing lost, nothing starved.
            if fds[0].revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 {
                // SAFETY: read into our owned buffer; len is the buffer len.
                let n = unsafe {
                    libc::read(
                        self.read_fd,
                        self.in_buf.as_mut_ptr() as *mut libc::c_void,
                        self.in_buf.len(),
                    )
                };
                if n < 0 {
                    let e = last_errno();
                    if e == libc::EINTR || e == libc::EAGAIN {
                        continue;
                    }
                    return Err(io_err("read(tty)"));
                }
                if n == 0 {
                    return Err(Error::Term(
                        "terminal closed (EOF on tty) — the emulator hung up; the app should exit"
                            .into(),
                    ));
                }
                return Ok(TermRead::Input(&self.in_buf[..n as usize]));
            }

            if fds[2].revents & libc::POLLIN != 0 {
                Self::drain_winch_pipe(fds[2].fd); // same drain shape
                return Ok(TermRead::Wake);
            }

            if let Some(d) = deadline {
                if Instant::now() >= d {
                    return Ok(TermRead::Idle);
                }
            }
        }
    }

    fn write(&mut self, bytes: &[u8]) -> Result<()> {
        self.out.extend_from_slice(bytes);
        // Backstop so a presenter bug cannot balloon memory; ordinary frames
        // flush explicitly long before this.
        if self.out.len() >= 1 << 16 {
            self.flush()?;
        }
        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        if self.out.is_empty() {
            return Ok(());
        }
        let res = write_all_fd(self.write_fd, &self.out);
        self.out.clear();
        res
    }

    fn waker(&self) -> Option<TerminalWaker> {
        self.waker.clone()
    }

    fn degraded(&self) -> Option<&'static str> {
        self.degraded
    }

    fn is_tty(&self) -> bool {
        // The RENDER handle's ttyness (RT1-10c): /dev/tty or the stdout
        // fallback — whichever this instance actually writes to.
        // SAFETY: isatty on our write fd.
        unsafe { libc::isatty(self.write_fd) == 1 }
    }

    fn suspend(&mut self) -> Result<()> {
        // Full restore -> group stop -> re-enter with the same options.
        // Execution resumes below when SIGCONT arrives. Preconditions the
        // caller owns: SIGTSTP has its default action (an app installing
        // its own handler bypasses this verb anyway), and the process
        // group is the tty's foreground group (true for any normally
        // launched app; an orphaned group ignores the stop and this
        // becomes a fast leave+enter — harmless).
        let opts = self.entered.as_ref().map(|s| s.opts);
        match opts {
            Some(opts) => {
                self.leave()?;
                Self::deliver_stop();
                // The window may have been resized while stopped; enter()
                // re-reads geometry, and the trait doc obliges callers to
                // damage-all + re-query size() after suspend() returns.
                self.enter(&opts)
            }
            None => {
                // Not in a session: still honor the stop request.
                Self::deliver_stop();
                Ok(())
            }
        }
    }

    fn set_cursor_style(&mut self, style: CursorStyle) -> Result<()> {
        self.write(&verbs::cursor_style_bytes(style))?;
        if style != CursorStyle::Default && !self.cursor_styled {
            self.cursor_styled = true;
            // Keep the panic-hook path honest: it must now also reset the
            // style it cannot know about.
            sys::append_emergency_leave(verbs::CURSOR_STYLE_RESET);
        }
        Ok(())
    }

    fn set_title(&mut self, title: &str) -> Result<()> {
        if !self.title_pushed {
            self.title_pushed = true;
            self.write(verbs::TITLE_PUSH)?;
            sys::append_emergency_leave(verbs::TITLE_POP);
        }
        self.write(&verbs::set_title_bytes(title))
    }

    fn set_pixel_mouse(&mut self, on: bool) -> Result<()> {
        self.write(if on {
            verbs::PIXEL_MOUSE_ON
        } else {
            verbs::PIXEL_MOUSE_OFF
        })?;
        if on && !self.pixel_moused {
            sys::append_emergency_leave(verbs::PIXEL_MOUSE_OFF);
        }
        self.pixel_moused = on;
        Ok(())
    }

    fn set_mouse_reporting(&mut self, on: bool) -> Result<()> {
        // The entered options know which tracking mode is armed; emitting
        // its exact disarm/arm pair keeps this verb drift-free with
        // enter/leave (options.rs owns both byte pairs). Leave stays
        // correct either way: it emits the disarm unconditionally, and a
        // DECRST of an already-reset mode is a no-op at the terminal.
        let Some(state) = &self.entered else {
            return Err(Error::Term(
                "set_mouse_reporting outside a session — enter() first".into(),
            ));
        };
        let mode = state.opts.mouse;
        self.write(if on {
            mode.arm_bytes()
        } else {
            mode.disarm_bytes()
        })
    }

    fn set_kitty_keyboard(&mut self, flags: super::options::KittyFlags) -> Result<()> {
        // The push/pop accounting lives in the entered options: leave
        // derives its pop from them, and suspend re-enters with them, so
        // updating `opts.kitty_keyboard` here makes leave pop exactly
        // once and suspend pop-then-re-push with zero extra state.
        let Some(state) = &mut self.entered else {
            return Err(Error::Term(
                "set_kitty_keyboard outside a session — enter() first".into(),
            ));
        };
        let prev = state.opts.kitty_keyboard;
        if prev == flags {
            return Ok(());
        }
        state.opts.kitty_keyboard = flags;
        let mut bytes = Vec::with_capacity(16);
        if !prev.is_empty() {
            bytes.extend_from_slice(super::options::KittyFlags::POP_BYTES);
        }
        if !flags.is_empty() {
            bytes.extend_from_slice(&flags.push_bytes());
        }
        if prev.is_empty() && !flags.is_empty() {
            // The panic hook must now pop the entry it cannot know about
            // — PREPENDED so the pop runs while the alternate screen is
            // still active (kitty stacks are per screen buffer). The
            // inverse transition leaves the captured pop in place: a pop
            // on an empty stack is defined harmless (flags reset to 0).
            sys::prepend_emergency_leave(super::options::KittyFlags::POP_BYTES);
        }
        self.write(&bytes)
    }

    fn cell_pixel_size(&mut self) -> Option<PixelSize> {
        // TIOCGWINSZ reports the WHOLE window in pixels; one cell is the
        // quotient. Many terminals report 0 pixels — that is "unknown",
        // and the wire probe (CSI 16 t) may still answer.
        let ws = self.raw_winsize().ok()?;
        if ws.ws_xpixel == 0 || ws.ws_ypixel == 0 || ws.ws_col == 0 || ws.ws_row == 0 {
            return None;
        }
        Some(PixelSize::new(
            ws.ws_xpixel / ws.ws_col,
            ws.ws_ypixel / ws.ws_row,
        ))
    }
}

impl Drop for UnixTerminal {
    fn drop(&mut self) {
        let _ = self.leave();
        if let Some(rd) = self.wake_rd {
            // SAFETY: closing the wake-pipe read end we created; the write
            // end closes when the last waker clone drops (see WakeFd).
            unsafe { libc::close(rd) };
        }
        if self.owns_fds {
            // SAFETY: closing fds we opened; a shared fd closes exactly once.
            unsafe {
                libc::close(self.read_fd);
                if self.write_fd != self.read_fd {
                    libc::close(self.write_fd);
                }
            }
        }
    }
}

// Pty-backed tests live beside this file to keep the backend readable;
// the path attribute keeps them a true child module (private items and
// imports of this module stay visible to them).
#[cfg(test)]
#[path = "unix_tests.rs"]
mod tests;