Skip to main content

tui/transport/
local.rs

1//! Local PTY transport.
2//!
3//! Owns `enable_raw_mode`/`EnterAlternateScreen` in its constructor and
4//! tears them down on drop, and in a panic hook. Polls crossterm for
5//! key and resize events.
6
7use super::{
8    DEFAULT_CELL_PIXELS, MOUSE_DISABLE, MOUSE_ENABLE, RawEvent, Transport, failed_steps,
9    warn_failed,
10};
11use ratatui::Terminal;
12use ratatui::backend::CrosstermBackend;
13use ratatui::crossterm::cursor::Show;
14use ratatui::crossterm::event::{
15    self as xevent, Event, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
16    PushKeyboardEnhancementFlags,
17};
18use ratatui::crossterm::execute;
19use ratatui::crossterm::terminal::{
20    EnterAlternateScreen, LeaveAlternateScreen, WindowSize, disable_raw_mode, enable_raw_mode,
21    supports_keyboard_enhancement, window_size,
22};
23use std::env;
24use std::io::{self, Stdout, Write};
25use std::panic;
26use std::sync::atomic::{AtomicBool, Ordering};
27use std::thread::{self, ThreadId};
28use std::time::{Duration, Instant};
29
30/// Whether the terminal was asked to disambiguate escape codes, so the exit paths that have no
31/// transport to ask (the panic hook, the drop) pop them.
32static KEYBOARD_ENHANCED: AtomicBool = AtomicBool::new(false);
33
34pub struct LocalTransport {
35    terminal: Terminal<CrosstermBackend<Stdout>>,
36    term: Option<String>,
37}
38
39impl LocalTransport {
40    /// Enter raw mode + alternate screen and return a transport bound
41    /// to stdout. A failure after any step restores what was done.
42    ///
43    /// # Errors
44    ///
45    /// Returns `Err` if stdout is not a terminal or the kernel rejects
46    /// the `TCSETATTR` / escape-sequence writes that raw-mode setup
47    /// needs.
48    pub fn new() -> io::Result<Self> {
49        enable_raw_mode()?;
50        let enhanced = supports_keyboard_enhancement().unwrap_or(false);
51        let terminal = enter_terminal(&mut io::stdout(), enhanced, disable_raw_mode, || {
52            Terminal::new(CrosstermBackend::new(io::stdout()))
53        })?;
54        KEYBOARD_ENHANCED.store(enhanced, Ordering::SeqCst);
55        Ok(Self {
56            terminal,
57            term: env::var("TERM").ok(),
58        })
59    }
60}
61
62/// Runs the setup steps and then `finish`; any failure leaves the terminal as it was found.
63fn enter_terminal<W: Write, T>(
64    out: &mut W,
65    enhanced: bool,
66    raw_mode_off: fn() -> io::Result<()>,
67    finish: impl FnOnce() -> io::Result<T>,
68) -> io::Result<T> {
69    let entered = setup_steps(out, enhanced).and_then(|()| finish());
70    if entered.is_err() {
71        warn_failed(leave_terminal(out, raw_mode_off(), enhanced));
72    }
73    entered
74}
75
76fn setup_steps<W: Write>(out: &mut W, enhanced: bool) -> io::Result<()> {
77    execute!(out, EnterAlternateScreen)?;
78    if enhanced {
79        push_keyboard_enhancement(out)?;
80    }
81    out.write_all(MOUSE_ENABLE)?;
82    out.flush()
83}
84
85/// Asks the terminal to send modified function keys unambiguously: Alt-F3 as `CSI 13;3~`, not
86/// `CSI 1;3R`, which reads as a cursor report.
87fn push_keyboard_enhancement<W: Write>(out: &mut W) -> io::Result<()> {
88    execute!(
89        out,
90        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
91    )
92}
93
94/// Pops what [`push_keyboard_enhancement`] pushed, on the screen it was pushed on.
95fn pop_keyboard_enhancement<W: Write>(out: &mut W, enhanced: bool) -> io::Result<()> {
96    match enhanced {
97        true => execute!(out, PopKeyboardEnhancementFlags),
98        false => Ok(()),
99    }
100}
101
102/// Every step of leaving the TUI, each tried whatever the ones before it did; the failures
103/// are named.
104fn leave_terminal<W: Write>(
105    out: &mut W,
106    raw_mode_off: io::Result<()>,
107    enhanced: bool,
108) -> Vec<(&'static str, io::Error)> {
109    failed_steps([
110        ("raw mode", raw_mode_off),
111        ("keyboard", pop_keyboard_enhancement(out, enhanced)),
112        ("alternate screen", execute!(out, LeaveAlternateScreen)),
113        (
114            "mouse",
115            out.write_all(MOUSE_DISABLE).and_then(|()| out.flush()),
116        ),
117        ("cursor", execute!(out, Show)),
118    ])
119}
120
121/// The keyboard flags still to pop, which the next restore must not pop again.
122fn take_keyboard_enhanced() -> bool {
123    KEYBOARD_ENHANCED.swap(false, Ordering::SeqCst)
124}
125
126/// A panic on the UI thread restores the terminal before the message prints, so it lands on the
127/// normal screen and is not erased with the alternate one; the drop that follows the unwind
128/// repeats the steps, which is harmless. A panic on another thread, such as the console worker,
129/// is caught by its task and the UI goes on: it is only logged, since the default hook's stderr
130/// would paint over the screen.
131pub fn install_panic_hook() {
132    let ui = thread::current().id();
133    let previous = panic::take_hook();
134    panic::set_hook(Box::new(move |info| {
135        let restore = || {
136            warn_failed(leave_terminal(
137                &mut io::stdout(),
138                disable_raw_mode(),
139                take_keyboard_enhanced(),
140            ))
141        };
142        handle_panic(
143            ui,
144            thread::current().id(),
145            &info.to_string(),
146            restore,
147            || previous(info),
148        );
149    }));
150}
151
152fn handle_panic(
153    ui: ThreadId,
154    here: ThreadId,
155    message: &str,
156    restore: impl FnOnce(),
157    previous: impl FnOnce(),
158) {
159    if ui == here {
160        restore();
161        previous();
162    } else {
163        tracing::error!("panic on a worker thread: {message}");
164    }
165}
166
167impl Drop for LocalTransport {
168    fn drop(&mut self) {
169        warn_failed(leave_terminal(
170            self.terminal.backend_mut(),
171            disable_raw_mode(),
172            take_keyboard_enhanced(),
173        ));
174    }
175}
176
177impl Transport for LocalTransport {
178    type Backend = CrosstermBackend<Stdout>;
179
180    fn terminal_mut(&mut self) -> &mut Terminal<Self::Backend> {
181        &mut self.terminal
182    }
183
184    fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>> {
185        if !xevent::poll(timeout)? {
186            return Ok(None);
187        }
188        Ok(raw_event(xevent::read()?))
189    }
190
191    fn write_passthrough(&mut self, bytes: &[u8]) -> io::Result<()> {
192        let mut stdout = io::stdout().lock();
193        stdout.write_all(bytes)?;
194        stdout.flush()
195    }
196
197    const LOCAL_FILES: bool = true;
198
199    fn client_term(&self) -> Option<&str> {
200        self.term.as_deref()
201    }
202
203    fn cell_pixels(&self) -> (u16, u16) {
204        window_size()
205            .ok()
206            .and_then(|size| pixels_per_cell(&size))
207            .unwrap_or(DEFAULT_CELL_PIXELS)
208    }
209}
210
211/// The events the loop handles; focus, paste and the rest are dropped.
212fn raw_event(event: Event) -> Option<RawEvent> {
213    match event {
214        Event::Key(key) => Some(RawEvent::Key(key)),
215        Event::Mouse(mouse) => Some(RawEvent::Mouse(mouse, Instant::now())),
216        Event::Resize(w, h) => Some(RawEvent::Resize(w, h)),
217        _ => None,
218    }
219}
220
221/// The pixel size of one cell; `None` when the terminal reports no pixel size.
222fn pixels_per_cell(size: &WindowSize) -> Option<(u16, u16)> {
223    let width = size.width.checked_div(size.columns)?;
224    let height = size.height.checked_div(size.rows)?;
225    (width > 0 && height > 0).then_some((width, height))
226}
227
228#[cfg(test)]
229mod tests;