Lines
100 %
Functions
87.5 %
Branches
//! Transport-agnostic event loop.
//!
//! Receives a [`Transport`] and an [`App`], draws the UI, polls for
//! input, translates key events to [`Intent`](crate::event::Intent)s, and applies them.
//! Quits when `App::should_quit` is set. The loop is generic so both
//! the local binary and the SSH daemon share identical behaviour.
use crate::app::App;
use crate::draw::draw;
use crate::hits::Hits;
use crate::keymap;
use crate::tabs::reports::chart::TerminalEnv;
use crate::transport::{RawEvent, Transport};
use rpc::chart::chart_backend;
use std::io;
use std::time::{Duration, Instant};
/// Poll interval. Short enough to feel responsive to
/// `App::should_quit` flips, long enough to not burn CPU.
pub const POLL_INTERVAL: Duration = Duration::from_millis(200);
/// Run the TUI until the app requests shutdown or the transport
/// disconnects. Does **not** drop the transport; the caller
/// owns its lifecycle.
///
/// # Errors
/// Propagates `io::Error`s from:
/// - `Terminal::draw`, which fails if the backend's writer is broken
/// (stdout closed, SSH channel closed while writing).
/// - `Transport::poll`, which fails on disconnect.
pub fn run_loop<T>(transport: &mut T, app: &mut App) -> io::Result<()>
where
T: Transport,
<T::Backend as ratatui::backend::Backend>::Error: std::error::Error + Send + Sync + 'static,
{
let result = drive(transport, app);
app.flush_key_press();
result
}
fn drive<T>(transport: &mut T, app: &mut App) -> io::Result<()>
app.local_files = T::LOCAL_FILES;
while !app.should_quit {
let wait = if app.drain_eval() {
Duration::ZERO
} else {
POLL_INTERVAL
};
let wait = app
.next_deadline(Instant::now())
.map_or(wait, |left| wait.min(left));
let screen = transport.terminal_mut().size().map_err(io::Error::other)?;
app.sync_terminal(TerminalEnv {
screen,
cell_pixels: transport.cell_pixels(),
backend: chart_backend(transport.client_term(), app.terminal.backend_override()),
});
let mut hits = Hits::default();
transport
.terminal_mut()
.draw(|frame| draw(frame, app, &mut hits))
.map_err(io::Error::other)?;
app.hits = hits;
if let Some(event) = transport.poll(wait)? {
handle_event(app, event);
app.tick(Instant::now());
for bytes in app.take_outbound() {
transport.write_passthrough(&bytes)?;
Ok(())
fn handle_event(app: &mut App, event: RawEvent) {
match event {
RawEvent::Key(key) => {
keymap::handle_key(app, key);
RawEvent::Mouse(mouse, at) => crate::mouse::handle_mouse(app, mouse, at),
// The next pass re-reads the screen size, and `draw` resizes the buffers.
RawEvent::Resize(_, _) => {}
#[cfg(test)]
mod button_tests;
mod tests {
use super::*;
use crate::tabs::reports::chart::{ChartPane, pane_cells};
use crate::transport::RawEvent;
use crate::transport::tests_support::{DisconnectedTransport, ScriptedTransport, quit_keys};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
fn key(code: KeyCode) -> RawEvent {
RawEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
#[test]
fn run_loop_exits_on_quit_intent() {
let mut app = crate::test_support::app();
let mut transport = ScriptedTransport::new(40, 10, quit_keys().into());
run_loop(&mut transport, &mut app).unwrap();
assert!(app.should_quit);
fn run_loop_gives_the_chart_the_terminal_geometry() {
let mut transport = ScriptedTransport::new(40, 20, quit_keys().into());
let env = app.terminal.env().expect("geometry known");
let cells = pane_cells(crate::draw::body_area(ratatui::layout::Rect::new(
0, 0, 40, 20,
)));
let call = ChartPane::call(
&forms::REPORT_BALANCE,
&forms::FormValues::default(),
env,
cells,
&app.theme,
);
assert!(call.contains(":width 380 :height 320 :text-px"), "{call}");
fn run_loop_sends_queued_clipboard_bytes_through_the_transport() {
use crate::modal::{Csv, Modal};
app.overlays.push(Modal::Csv(Csv::new(
"a.csv".to_string(),
"a,b\n".to_string(),
let events = vec![key(KeyCode::Char('y')), key(KeyCode::Char('q'))];
let events = [events, quit_keys().into()].concat();
let mut transport = ScriptedTransport::new(40, 10, events);
assert_eq!(transport.passed, b"\x1b]52;c;YSxiCg==\x07");
assert!(!app.local_files);
fn run_loop_applies_tab_selection() {
let mut transport = ScriptedTransport::new(
40,
10,
[vec![key(KeyCode::Char('1'))], quit_keys().into()].concat(),
assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
fn run_loop_ignores_a_click_on_nothing() {
use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
let click = RawEvent::Mouse(
MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: 5,
row: 5,
modifiers: KeyModifiers::NONE,
},
std::time::Instant::now(),
let mut transport =
ScriptedTransport::new(40, 10, [vec![click], quit_keys().into()].concat());
fn run_loop_keeps_the_areas_of_the_last_frame_it_drew() {
use crate::hits::Target;
assert!(
app.hits
.entries()
.iter()
.any(|(_, target)| *target == Target::MenuTitle(0))
fn run_loop_routes_cmdline_submit() {
use crate::view::Tab;
let events = vec![
key(KeyCode::Char(':')),
key(KeyCode::Char('v')),
key(KeyCode::Char('e')),
key(KeyCode::Char('r')),
key(KeyCode::Char('s')),
key(KeyCode::Char('i')),
key(KeyCode::Char('o')),
key(KeyCode::Char('n')),
key(KeyCode::Enter),
];
let mut transport = ScriptedTransport::new(60, 10, events);
assert!(!app.cmdline.active);
// `version` is now an eval leaf: it submits the form and switches to Console.
assert_eq!(app.front_kind(), Some(Tab::Console));
app.console()
.scrollback
.any(|l| l.contains("(get-version)")),
"form should appear in scrollback"
fn handle_event_tolerates_resize() {
handle_event(&mut app, RawEvent::Resize(80, 24));
assert!(!app.should_quit);
fn run_loop_exits_without_polling_when_app_already_quitting() {
app.request_quit();
// An empty queue would normally let the loop continue past the
// first iteration; the should_quit guard must short-circuit
// before poll ever runs, even against an always-erroring poll.
let mut transport = DisconnectedTransport::new(40, 10);
run_loop(&mut transport, &mut app).expect("should return Ok");
fn run_loop_propagates_poll_errors() {
let err = run_loop(&mut transport, &mut app).expect_err("poll err bubbles");
assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
// The loop should not have flipped the quit flag; the caller
// decides whether an I/O error means "quit" or "retry".
fn run_loop_ignores_unbound_keys() {
// Keys with no binding must not panic or change state.
[vec![key(KeyCode::F(5))], quit_keys().into()].concat(),