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

            
7
use super::{
8
    DEFAULT_CELL_PIXELS, MOUSE_DISABLE, MOUSE_ENABLE, RawEvent, Transport, failed_steps,
9
    warn_failed,
10
};
11
use ratatui::Terminal;
12
use ratatui::backend::CrosstermBackend;
13
use ratatui::crossterm::cursor::Show;
14
use ratatui::crossterm::event::{
15
    self as xevent, Event, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
16
    PushKeyboardEnhancementFlags,
17
};
18
use ratatui::crossterm::execute;
19
use ratatui::crossterm::terminal::{
20
    EnterAlternateScreen, LeaveAlternateScreen, WindowSize, disable_raw_mode, enable_raw_mode,
21
    supports_keyboard_enhancement, window_size,
22
};
23
use std::env;
24
use std::io::{self, Stdout, Write};
25
use std::panic;
26
use std::sync::atomic::{AtomicBool, Ordering};
27
use std::thread::{self, ThreadId};
28
use 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.
32
static KEYBOARD_ENHANCED: AtomicBool = AtomicBool::new(false);
33

            
34
pub struct LocalTransport {
35
    terminal: Terminal<CrosstermBackend<Stdout>>,
36
    term: Option<String>,
37
}
38

            
39
impl 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.
63
4
fn enter_terminal<W: Write, T>(
64
4
    out: &mut W,
65
4
    enhanced: bool,
66
4
    raw_mode_off: fn() -> io::Result<()>,
67
4
    finish: impl FnOnce() -> io::Result<T>,
68
4
) -> io::Result<T> {
69
4
    let entered = setup_steps(out, enhanced).and_then(|()| finish());
70
4
    if entered.is_err() {
71
2
        warn_failed(leave_terminal(out, raw_mode_off(), enhanced));
72
2
    }
73
4
    entered
74
4
}
75

            
76
4
fn setup_steps<W: Write>(out: &mut W, enhanced: bool) -> io::Result<()> {
77
4
    execute!(out, EnterAlternateScreen)?;
78
4
    if enhanced {
79
1
        push_keyboard_enhancement(out)?;
80
3
    }
81
4
    out.write_all(MOUSE_ENABLE)?;
82
3
    out.flush()
83
4
}
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.
87
1
fn push_keyboard_enhancement<W: Write>(out: &mut W) -> io::Result<()> {
88
1
    execute!(
89
1
        out,
90
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
91
    )
92
1
}
93

            
94
/// Pops what [`push_keyboard_enhancement`] pushed, on the screen it was pushed on.
95
10
fn pop_keyboard_enhancement<W: Write>(out: &mut W, enhanced: bool) -> io::Result<()> {
96
10
    match enhanced {
97
2
        true => execute!(out, PopKeyboardEnhancementFlags),
98
8
        false => Ok(()),
99
    }
100
10
}
101

            
102
/// Every step of leaving the TUI, each tried whatever the ones before it did; the failures
103
/// are named.
104
10
fn leave_terminal<W: Write>(
105
10
    out: &mut W,
106
10
    raw_mode_off: io::Result<()>,
107
10
    enhanced: bool,
108
10
) -> Vec<(&'static str, io::Error)> {
109
10
    failed_steps([
110
10
        ("raw mode", raw_mode_off),
111
10
        ("keyboard", pop_keyboard_enhancement(out, enhanced)),
112
10
        ("alternate screen", execute!(out, LeaveAlternateScreen)),
113
        (
114
10
            "mouse",
115
10
            out.write_all(MOUSE_DISABLE).and_then(|()| out.flush()),
116
        ),
117
10
        ("cursor", execute!(out, Show)),
118
    ])
119
10
}
120

            
121
/// The keyboard flags still to pop, which the next restore must not pop again.
122
2
fn take_keyboard_enhanced() -> bool {
123
2
    KEYBOARD_ENHANCED.swap(false, Ordering::SeqCst)
124
2
}
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.
131
pub 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

            
152
2
fn handle_panic(
153
2
    ui: ThreadId,
154
2
    here: ThreadId,
155
2
    message: &str,
156
2
    restore: impl FnOnce(),
157
2
    previous: impl FnOnce(),
158
2
) {
159
2
    if ui == here {
160
1
        restore();
161
1
        previous();
162
    } else {
163
1
        tracing::error!("panic on a worker thread: {message}");
164
    }
165
2
}
166

            
167
impl 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

            
177
impl 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.
212
4
fn raw_event(event: Event) -> Option<RawEvent> {
213
4
    match event {
214
1
        Event::Key(key) => Some(RawEvent::Key(key)),
215
1
        Event::Mouse(mouse) => Some(RawEvent::Mouse(mouse, Instant::now())),
216
1
        Event::Resize(w, h) => Some(RawEvent::Resize(w, h)),
217
1
        _ => None,
218
    }
219
4
}
220

            
221
/// The pixel size of one cell; `None` when the terminal reports no pixel size.
222
5
fn pixels_per_cell(size: &WindowSize) -> Option<(u16, u16)> {
223
5
    let width = size.width.checked_div(size.columns)?;
224
4
    let height = size.height.checked_div(size.rows)?;
225
4
    (width > 0 && height > 0).then_some((width, height))
226
5
}
227

            
228
#[cfg(test)]
229
mod tests;