Skip to main content

tui/transport/
mod.rs

1//! Transport abstraction.
2//!
3//! The TUI event loop sits on top of two I/O concerns:
4//!
5//! 1. A [`ratatui::backend::Backend`] that receives rendered frames.
6//! 2. A source of user input events (keystrokes, terminal resizes).
7//!
8//! Both are hidden behind [`Transport`]. A local invocation uses
9//! [`LocalTransport`], which owns a `CrosstermBackend<Stdout>` and
10//! polls crossterm for events. The SSH daemon will later provide a
11//! different impl that writes to a russh channel and reads keystrokes
12//! from that channel.
13//!
14//! Keeping this layer tiny is deliberate. Anything richer (history,
15//! paste handling) grows inside `App` / `Intent`, not here.
16
17use std::io;
18use std::time::Duration;
19
20pub mod local;
21
22/// Button events (`?1000`), motion while a button is held (`?1002`, ignored by a terminal
23/// without it) and SGR coordinates (`?1006`): what both transports ask the terminal for.
24pub const MOUSE_ENABLE: &[u8] = b"\x1b[?1000h\x1b[?1002h\x1b[?1006h";
25pub const MOUSE_DISABLE: &[u8] = b"\x1b[?1006l\x1b[?1002l\x1b[?1000l";
26
27/// The restore steps that failed, named. Every step has already run: a restore is not
28/// short-circuited by an earlier failure.
29#[must_use]
30pub fn failed_steps<const N: usize>(
31    steps: [(&'static str, io::Result<()>); N],
32) -> Vec<(&'static str, io::Error)> {
33    steps
34        .into_iter()
35        .filter_map(|(step, result)| result.err().map(|err| (step, err)))
36        .collect()
37}
38
39/// Logs what a restore in `Drop` could not do, since it cannot return an error.
40pub fn warn_failed(failed: Vec<(&'static str, io::Error)>) {
41    for (step, err) in failed {
42        tracing::warn!("terminal restore: {step} failed: {err}");
43    }
44}
45
46/// Pixel size of one terminal cell when the client does not report it.
47pub const DEFAULT_CELL_PIXELS: (u16, u16) = (10, 20);
48
49pub use local::LocalTransport;
50
51/// Input events the event loop cares about. Keystrokes, mouse reports and
52/// resizes are explicit; disconnect is signalled via [`Transport::poll`]
53/// returning an `io::Error`.
54#[derive(Debug, Clone, Copy)]
55pub enum RawEvent {
56    Key(ratatui::crossterm::event::KeyEvent),
57    /// A mouse report and the instant the transport read it.
58    Mouse(ratatui::crossterm::event::MouseEvent, std::time::Instant),
59    Resize(u16, u16),
60}
61
62/// Bridge between the event loop and whatever terminal it talks to.
63///
64/// Lifecycle: a `Transport` is constructed in whatever mode it needs
65/// (raw mode, alternate screen, SSH channel attached), then passed by
66/// mutable reference to [`crate::runtime::run_loop`]. When the loop
67/// exits, the owner drops the transport, which restores its terminal on quit, error and
68/// panic alike.
69///
70/// The transport owns the `Terminal` rather than just a raw backend
71/// because ratatui's `Terminal<B>` requires `B: Backend`, which does
72/// not hold for `&mut B`. Having the transport expose
73/// `terminal_mut()` keeps the runtime generic without hitting that
74/// trait-bound wall.
75pub trait Transport {
76    type Backend: ratatui::backend::Backend;
77
78    /// Mutable access to the owned ratatui `Terminal` so the runtime
79    /// can drive `draw`.
80    fn terminal_mut(&mut self) -> &mut ratatui::Terminal<Self::Backend>;
81
82    /// Block up to `timeout` waiting for an input event. Returns
83    /// `Ok(None)` on timeout, `Ok(Some(event))` on activity.
84    ///
85    /// # Errors
86    ///
87    /// Returns `Err` on disconnect (local stdin closed, SSH channel
88    /// closed) or any unrecoverable read failure.
89    fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>>;
90
91    /// Forward a raw byte sequence to the same stream the backend
92    /// writes to, bypassing ratatui's cell grid. Used for terminal
93    /// escape sequences that ratatui can't model directly — kitty
94    /// graphics APC bytes, future sixel, etc. The default impl
95    /// silently drops the bytes so transports that don't speak that
96    /// dialect (or test doubles) don't need an override.
97    ///
98    /// # Errors
99    ///
100    /// Returns `Err` only if the underlying stream write fails.
101    fn write_passthrough(&mut self, _bytes: &[u8]) -> io::Result<()> {
102        Ok(())
103    }
104
105    /// Terminal type the *client* claims to be, in OpenSSH-style
106    /// `xterm-256color` form. The local transport reads `$TERM`; the
107    /// SSH transport returns whatever the peer sent in `pty-req`.
108    /// Returns `None` when the transport cannot tell.
109    ///
110    /// Capability detection (kitty graphics, true-colour, etc.)
111    /// should consult this rather than the daemon's own environment,
112    /// which is whatever the host running the daemon happened to
113    /// have.
114    fn client_term(&self) -> Option<&str> {
115        None
116    }
117
118    /// Whether the process runs on the user's own machine, so a path it writes is the user's.
119    const LOCAL_FILES: bool = false;
120
121    /// Pixel size of one terminal cell; [`DEFAULT_CELL_PIXELS`] when the client does not say.
122    fn cell_pixels(&self) -> (u16, u16) {
123        DEFAULT_CELL_PIXELS
124    }
125}
126
127#[cfg(test)]
128pub mod tests_support {
129    //! Test doubles for [`Transport`]. The transports here back onto
130    //! [`ratatui::backend::TestBackend`] so tests can drive `run_loop`
131    //! without a real terminal.
132
133    use super::{RawEvent, Transport};
134    use ratatui::Terminal;
135    use ratatui::backend::TestBackend;
136    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
137    use std::collections::VecDeque;
138    use std::io;
139    use std::time::Duration;
140
141    /// The events that confirm a quit of a cua-keyed app: M-x, then `y`.
142    #[must_use]
143    pub fn quit_keys() -> [RawEvent; 2] {
144        [
145            RawEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)),
146            RawEvent::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)),
147        ]
148    }
149
150    /// The empty polls a spent script allows, for the timed key presses still due.
151    pub const IDLE_POLLS: u32 = 500;
152
153    // The trait default keeps files off: a transport must opt in to local saves.
154    const _: () = assert!(!ScriptedTransport::LOCAL_FILES);
155
156    /// A [`Transport`] that yields a pre-scripted sequence of
157    /// [`RawEvent`]s; once they are spent, `poll` idles until [`IDLE_POLLS`] and then fails with
158    /// `UnexpectedEof`, so a script that never quits ends the loop instead of spinning it.
159    pub struct ScriptedTransport {
160        terminal: Terminal<TestBackend>,
161        queue: VecDeque<RawEvent>,
162        idle: u32,
163        /// Everything written through [`Transport::write_passthrough`].
164        pub passed: Vec<u8>,
165    }
166
167    impl ScriptedTransport {
168        /// # Panics
169        ///
170        /// Panics only if `ratatui::Terminal::new` reports an error
171        /// for `TestBackend`, which is unreachable: `TestBackend`'s
172        /// associated `Error` type is `Infallible`.
173        #[must_use]
174        pub fn new(width: u16, height: u16, events: Vec<RawEvent>) -> Self {
175            Self {
176                terminal: Terminal::new(TestBackend::new(width, height))
177                    .expect("TestBackend never errors"),
178                queue: events.into(),
179                idle: 0,
180                passed: Vec::new(),
181            }
182        }
183    }
184
185    impl Transport for ScriptedTransport {
186        type Backend = TestBackend;
187
188        fn terminal_mut(&mut self) -> &mut Terminal<TestBackend> {
189            &mut self.terminal
190        }
191
192        fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>> {
193            if let Some(event) = self.queue.pop_front() {
194                return Ok(Some(event));
195            }
196            self.idle += 1;
197            if self.idle > IDLE_POLLS {
198                return Err(io::ErrorKind::UnexpectedEof.into());
199            }
200            std::thread::sleep(timeout.min(Duration::from_millis(10)));
201            Ok(None)
202        }
203
204        fn write_passthrough(&mut self, bytes: &[u8]) -> io::Result<()> {
205            self.passed.extend_from_slice(bytes);
206            Ok(())
207        }
208    }
209
210    /// A [`Transport`] whose `poll` always returns `io::ErrorKind::
211    /// UnexpectedEof`, emulating an SSH channel closed by the remote.
212    pub struct DisconnectedTransport {
213        terminal: Terminal<TestBackend>,
214    }
215
216    impl DisconnectedTransport {
217        /// # Panics
218        ///
219        /// Panics only if `ratatui::Terminal::new` reports an error
220        /// for `TestBackend`, which is unreachable: `TestBackend`'s
221        /// associated `Error` type is `Infallible`.
222        #[must_use]
223        pub fn new(width: u16, height: u16) -> Self {
224            Self {
225                terminal: Terminal::new(TestBackend::new(width, height))
226                    .expect("TestBackend never errors"),
227            }
228        }
229    }
230
231    impl Transport for DisconnectedTransport {
232        type Backend = TestBackend;
233
234        fn terminal_mut(&mut self) -> &mut Terminal<TestBackend> {
235            &mut self.terminal
236        }
237
238        fn poll(&mut self, _timeout: Duration) -> io::Result<Option<RawEvent>> {
239            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "peer hung up"))
240        }
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
248    use tests_support::{DisconnectedTransport, IDLE_POLLS, ScriptedTransport};
249
250    #[test]
251    fn default_cell_pixels_is_ten_by_twenty() {
252        let t = ScriptedTransport::new(40, 10, Vec::new());
253        assert_eq!(t.cell_pixels(), DEFAULT_CELL_PIXELS);
254        assert_eq!(t.cell_pixels(), (10, 20));
255    }
256
257    #[test]
258    fn scripted_transport_drains_events_in_order() {
259        let events = vec![
260            RawEvent::Key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)),
261            RawEvent::Resize(80, 24),
262        ];
263        let mut t = ScriptedTransport::new(40, 10, events);
264        let first = t.poll(Duration::from_millis(0)).unwrap();
265        assert!(matches!(first, Some(RawEvent::Key(_))));
266        let second = t.poll(Duration::from_millis(0)).unwrap();
267        assert!(matches!(second, Some(RawEvent::Resize(80, 24))));
268        let third = t.poll(Duration::from_millis(0)).unwrap();
269        assert!(third.is_none());
270        let spent = (0..=IDLE_POLLS).find_map(|_| t.poll(Duration::ZERO).err());
271        assert_eq!(spent.map(|e| e.kind()), Some(io::ErrorKind::UnexpectedEof));
272    }
273
274    #[test]
275    fn disconnected_transport_reports_eof() {
276        let mut t = DisconnectedTransport::new(40, 10);
277        let err = t.poll(Duration::from_millis(0)).unwrap_err();
278        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
279    }
280}