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

            
17
use std::io;
18
use std::time::Duration;
19

            
20
pub 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.
24
pub const MOUSE_ENABLE: &[u8] = b"\x1b[?1000h\x1b[?1002h\x1b[?1006h";
25
pub 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]
30
26
pub fn failed_steps<const N: usize>(
31
26
    steps: [(&'static str, io::Result<()>); N],
32
26
) -> Vec<(&'static str, io::Error)> {
33
26
    steps
34
26
        .into_iter()
35
114
        .filter_map(|(step, result)| result.err().map(|err| (step, err)))
36
        .collect()
37
26
}
38

            
39
/// Logs what a restore in `Drop` could not do, since it cannot return an error.
40
30
pub fn warn_failed(failed: Vec<(&'static str, io::Error)>) {
41
30
    for (step, err) in failed {
42
20
        tracing::warn!("terminal restore: {step} failed: {err}");
43
    }
44
30
}
45

            
46
/// Pixel size of one terminal cell when the client does not report it.
47
pub const DEFAULT_CELL_PIXELS: (u16, u16) = (10, 20);
48

            
49
pub 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)]
55
pub 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.
75
pub 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
153
    fn client_term(&self) -> Option<&str> {
115
153
        None
116
153
    }
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
155
    fn cell_pixels(&self) -> (u16, u16) {
123
155
        DEFAULT_CELL_PIXELS
124
155
    }
125
}
126

            
127
#[cfg(test)]
128
pub 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
12
    pub fn quit_keys() -> [RawEvent; 2] {
144
12
        [
145
12
            RawEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)),
146
12
            RawEvent::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)),
147
12
        ]
148
12
    }
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
17
        pub fn new(width: u16, height: u16, events: Vec<RawEvent>) -> Self {
175
17
            Self {
176
17
                terminal: Terminal::new(TestBackend::new(width, height))
177
17
                    .expect("TestBackend never errors"),
178
17
                queue: events.into(),
179
17
                idle: 0,
180
17
                passed: Vec::new(),
181
17
            }
182
17
        }
183
    }
184

            
185
    impl Transport for ScriptedTransport {
186
        type Backend = TestBackend;
187

            
188
304
        fn terminal_mut(&mut self) -> &mut Terminal<TestBackend> {
189
304
            &mut self.terminal
190
304
        }
191

            
192
653
        fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>> {
193
653
            if let Some(event) = self.queue.pop_front() {
194
44
                return Ok(Some(event));
195
609
            }
196
609
            self.idle += 1;
197
609
            if self.idle > IDLE_POLLS {
198
1
                return Err(io::ErrorKind::UnexpectedEof.into());
199
608
            }
200
608
            std::thread::sleep(timeout.min(Duration::from_millis(10)));
201
608
            Ok(None)
202
653
        }
203

            
204
1
        fn write_passthrough(&mut self, bytes: &[u8]) -> io::Result<()> {
205
1
            self.passed.extend_from_slice(bytes);
206
1
            Ok(())
207
1
        }
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
3
        pub fn new(width: u16, height: u16) -> Self {
224
3
            Self {
225
3
                terminal: Terminal::new(TestBackend::new(width, height))
226
3
                    .expect("TestBackend never errors"),
227
3
            }
228
3
        }
229
    }
230

            
231
    impl Transport for DisconnectedTransport {
232
        type Backend = TestBackend;
233

            
234
2
        fn terminal_mut(&mut self) -> &mut Terminal<TestBackend> {
235
2
            &mut self.terminal
236
2
        }
237

            
238
2
        fn poll(&mut self, _timeout: Duration) -> io::Result<Option<RawEvent>> {
239
2
            Err(io::Error::new(io::ErrorKind::UnexpectedEof, "peer hung up"))
240
2
        }
241
    }
242
}
243

            
244
#[cfg(test)]
245
mod tests {
246
    use super::*;
247
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
248
    use tests_support::{DisconnectedTransport, IDLE_POLLS, ScriptedTransport};
249

            
250
    #[test]
251
1
    fn default_cell_pixels_is_ten_by_twenty() {
252
1
        let t = ScriptedTransport::new(40, 10, Vec::new());
253
1
        assert_eq!(t.cell_pixels(), DEFAULT_CELL_PIXELS);
254
1
        assert_eq!(t.cell_pixels(), (10, 20));
255
1
    }
256

            
257
    #[test]
258
1
    fn scripted_transport_drains_events_in_order() {
259
1
        let events = vec![
260
1
            RawEvent::Key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)),
261
1
            RawEvent::Resize(80, 24),
262
        ];
263
1
        let mut t = ScriptedTransport::new(40, 10, events);
264
1
        let first = t.poll(Duration::from_millis(0)).unwrap();
265
1
        assert!(matches!(first, Some(RawEvent::Key(_))));
266
1
        let second = t.poll(Duration::from_millis(0)).unwrap();
267
1
        assert!(matches!(second, Some(RawEvent::Resize(80, 24))));
268
1
        let third = t.poll(Duration::from_millis(0)).unwrap();
269
1
        assert!(third.is_none());
270
500
        let spent = (0..=IDLE_POLLS).find_map(|_| t.poll(Duration::ZERO).err());
271
1
        assert_eq!(spent.map(|e| e.kind()), Some(io::ErrorKind::UnexpectedEof));
272
1
    }
273

            
274
    #[test]
275
1
    fn disconnected_transport_reports_eof() {
276
1
        let mut t = DisconnectedTransport::new(40, 10);
277
1
        let err = t.poll(Duration::from_millis(0)).unwrap_err();
278
1
        assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
279
1
    }
280
}