Lines
96.63 %
Functions
76.32 %
Branches
100 %
//! Transport abstraction.
//!
//! The TUI event loop sits on top of two I/O concerns:
//! 1. A [`ratatui::backend::Backend`] that receives rendered frames.
//! 2. A source of user input events (keystrokes, terminal resizes).
//! Both are hidden behind [`Transport`]. A local invocation uses
//! [`LocalTransport`], which owns a `CrosstermBackend<Stdout>` and
//! polls crossterm for events. The SSH daemon will later provide a
//! different impl that writes to a russh channel and reads keystrokes
//! from that channel.
//! Keeping this layer tiny is deliberate. Anything richer (history,
//! paste handling) grows inside `App` / `Intent`, not here.
use std::io;
use std::time::Duration;
pub mod local;
/// Button events (`?1000`), motion while a button is held (`?1002`, ignored by a terminal
/// without it) and SGR coordinates (`?1006`): what both transports ask the terminal for.
pub const MOUSE_ENABLE: &[u8] = b"\x1b[?1000h\x1b[?1002h\x1b[?1006h";
pub const MOUSE_DISABLE: &[u8] = b"\x1b[?1006l\x1b[?1002l\x1b[?1000l";
/// The restore steps that failed, named. Every step has already run: a restore is not
/// short-circuited by an earlier failure.
#[must_use]
pub fn failed_steps<const N: usize>(
steps: [(&'static str, io::Result<()>); N],
) -> Vec<(&'static str, io::Error)> {
steps
.into_iter()
.filter_map(|(step, result)| result.err().map(|err| (step, err)))
.collect()
}
/// Logs what a restore in `Drop` could not do, since it cannot return an error.
pub fn warn_failed(failed: Vec<(&'static str, io::Error)>) {
for (step, err) in failed {
tracing::warn!("terminal restore: {step} failed: {err}");
/// Pixel size of one terminal cell when the client does not report it.
pub const DEFAULT_CELL_PIXELS: (u16, u16) = (10, 20);
pub use local::LocalTransport;
/// Input events the event loop cares about. Keystrokes, mouse reports and
/// resizes are explicit; disconnect is signalled via [`Transport::poll`]
/// returning an `io::Error`.
#[derive(Debug, Clone, Copy)]
pub enum RawEvent {
Key(ratatui::crossterm::event::KeyEvent),
/// A mouse report and the instant the transport read it.
Mouse(ratatui::crossterm::event::MouseEvent, std::time::Instant),
Resize(u16, u16),
/// Bridge between the event loop and whatever terminal it talks to.
///
/// Lifecycle: a `Transport` is constructed in whatever mode it needs
/// (raw mode, alternate screen, SSH channel attached), then passed by
/// mutable reference to [`crate::runtime::run_loop`]. When the loop
/// exits, the owner drops the transport, which restores its terminal on quit, error and
/// panic alike.
/// The transport owns the `Terminal` rather than just a raw backend
/// because ratatui's `Terminal<B>` requires `B: Backend`, which does
/// not hold for `&mut B`. Having the transport expose
/// `terminal_mut()` keeps the runtime generic without hitting that
/// trait-bound wall.
pub trait Transport {
type Backend: ratatui::backend::Backend;
/// Mutable access to the owned ratatui `Terminal` so the runtime
/// can drive `draw`.
fn terminal_mut(&mut self) -> &mut ratatui::Terminal<Self::Backend>;
/// Block up to `timeout` waiting for an input event. Returns
/// `Ok(None)` on timeout, `Ok(Some(event))` on activity.
/// # Errors
/// Returns `Err` on disconnect (local stdin closed, SSH channel
/// closed) or any unrecoverable read failure.
fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>>;
/// Forward a raw byte sequence to the same stream the backend
/// writes to, bypassing ratatui's cell grid. Used for terminal
/// escape sequences that ratatui can't model directly — kitty
/// graphics APC bytes, future sixel, etc. The default impl
/// silently drops the bytes so transports that don't speak that
/// dialect (or test doubles) don't need an override.
/// Returns `Err` only if the underlying stream write fails.
fn write_passthrough(&mut self, _bytes: &[u8]) -> io::Result<()> {
Ok(())
/// Terminal type the *client* claims to be, in OpenSSH-style
/// `xterm-256color` form. The local transport reads `$TERM`; the
/// SSH transport returns whatever the peer sent in `pty-req`.
/// Returns `None` when the transport cannot tell.
/// Capability detection (kitty graphics, true-colour, etc.)
/// should consult this rather than the daemon's own environment,
/// which is whatever the host running the daemon happened to
/// have.
fn client_term(&self) -> Option<&str> {
None
/// Whether the process runs on the user's own machine, so a path it writes is the user's.
const LOCAL_FILES: bool = false;
/// Pixel size of one terminal cell; [`DEFAULT_CELL_PIXELS`] when the client does not say.
fn cell_pixels(&self) -> (u16, u16) {
DEFAULT_CELL_PIXELS
#[cfg(test)]
pub mod tests_support {
//! Test doubles for [`Transport`]. The transports here back onto
//! [`ratatui::backend::TestBackend`] so tests can drive `run_loop`
//! without a real terminal.
use super::{RawEvent, Transport};
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::collections::VecDeque;
/// The events that confirm a quit of a cua-keyed app: M-x, then `y`.
pub fn quit_keys() -> [RawEvent; 2] {
[
RawEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)),
RawEvent::Key(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE)),
]
/// The empty polls a spent script allows, for the timed key presses still due.
pub const IDLE_POLLS: u32 = 500;
// The trait default keeps files off: a transport must opt in to local saves.
const _: () = assert!(!ScriptedTransport::LOCAL_FILES);
/// A [`Transport`] that yields a pre-scripted sequence of
/// [`RawEvent`]s; once they are spent, `poll` idles until [`IDLE_POLLS`] and then fails with
/// `UnexpectedEof`, so a script that never quits ends the loop instead of spinning it.
pub struct ScriptedTransport {
terminal: Terminal<TestBackend>,
queue: VecDeque<RawEvent>,
idle: u32,
/// Everything written through [`Transport::write_passthrough`].
pub passed: Vec<u8>,
impl ScriptedTransport {
/// # Panics
/// Panics only if `ratatui::Terminal::new` reports an error
/// for `TestBackend`, which is unreachable: `TestBackend`'s
/// associated `Error` type is `Infallible`.
pub fn new(width: u16, height: u16, events: Vec<RawEvent>) -> Self {
Self {
terminal: Terminal::new(TestBackend::new(width, height))
.expect("TestBackend never errors"),
queue: events.into(),
idle: 0,
passed: Vec::new(),
impl Transport for ScriptedTransport {
type Backend = TestBackend;
fn terminal_mut(&mut self) -> &mut Terminal<TestBackend> {
&mut self.terminal
fn poll(&mut self, timeout: Duration) -> io::Result<Option<RawEvent>> {
if let Some(event) = self.queue.pop_front() {
return Ok(Some(event));
self.idle += 1;
if self.idle > IDLE_POLLS {
return Err(io::ErrorKind::UnexpectedEof.into());
std::thread::sleep(timeout.min(Duration::from_millis(10)));
Ok(None)
fn write_passthrough(&mut self, bytes: &[u8]) -> io::Result<()> {
self.passed.extend_from_slice(bytes);
/// A [`Transport`] whose `poll` always returns `io::ErrorKind::
/// UnexpectedEof`, emulating an SSH channel closed by the remote.
pub struct DisconnectedTransport {
impl DisconnectedTransport {
pub fn new(width: u16, height: u16) -> Self {
impl Transport for DisconnectedTransport {
fn poll(&mut self, _timeout: Duration) -> io::Result<Option<RawEvent>> {
Err(io::Error::new(io::ErrorKind::UnexpectedEof, "peer hung up"))
mod tests {
use super::*;
use tests_support::{DisconnectedTransport, IDLE_POLLS, ScriptedTransport};
#[test]
fn default_cell_pixels_is_ten_by_twenty() {
let t = ScriptedTransport::new(40, 10, Vec::new());
assert_eq!(t.cell_pixels(), DEFAULT_CELL_PIXELS);
assert_eq!(t.cell_pixels(), (10, 20));
fn scripted_transport_drains_events_in_order() {
let events = vec![
RawEvent::Key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE)),
RawEvent::Resize(80, 24),
];
let mut t = ScriptedTransport::new(40, 10, events);
let first = t.poll(Duration::from_millis(0)).unwrap();
assert!(matches!(first, Some(RawEvent::Key(_))));
let second = t.poll(Duration::from_millis(0)).unwrap();
assert!(matches!(second, Some(RawEvent::Resize(80, 24))));
let third = t.poll(Duration::from_millis(0)).unwrap();
assert!(third.is_none());
let spent = (0..=IDLE_POLLS).find_map(|_| t.poll(Duration::ZERO).err());
assert_eq!(spent.map(|e| e.kind()), Some(io::ErrorKind::UnexpectedEof));
fn disconnected_transport_reports_eof() {
let mut t = DisconnectedTransport::new(40, 10);
let err = t.poll(Duration::from_millis(0)).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);