Skip to main content

tui/
runtime.rs

1//! Transport-agnostic event loop.
2//!
3//! Receives a [`Transport`] and an [`App`], draws the UI, polls for
4//! input, translates key events to [`Intent`](crate::event::Intent)s, and applies them.
5//! Quits when `App::should_quit` is set. The loop is generic so both
6//! the local binary and the SSH daemon share identical behaviour.
7
8use crate::app::App;
9use crate::draw::draw;
10use crate::hits::Hits;
11use crate::keymap;
12use crate::tabs::reports::chart::TerminalEnv;
13use crate::transport::{RawEvent, Transport};
14use rpc::chart::chart_backend;
15use std::io;
16use std::time::{Duration, Instant};
17
18/// Poll interval. Short enough to feel responsive to
19/// `App::should_quit` flips, long enough to not burn CPU.
20pub const POLL_INTERVAL: Duration = Duration::from_millis(200);
21
22/// Run the TUI until the app requests shutdown or the transport
23/// disconnects. Does **not** drop the transport; the caller
24/// owns its lifecycle.
25///
26/// # Errors
27///
28/// Propagates `io::Error`s from:
29/// - `Terminal::draw`, which fails if the backend's writer is broken
30///   (stdout closed, SSH channel closed while writing).
31/// - `Transport::poll`, which fails on disconnect.
32pub fn run_loop<T>(transport: &mut T, app: &mut App) -> io::Result<()>
33where
34    T: Transport,
35    <T::Backend as ratatui::backend::Backend>::Error: std::error::Error + Send + Sync + 'static,
36{
37    let result = drive(transport, app);
38    app.flush_key_press();
39    result
40}
41
42fn drive<T>(transport: &mut T, app: &mut App) -> io::Result<()>
43where
44    T: Transport,
45    <T::Backend as ratatui::backend::Backend>::Error: std::error::Error + Send + Sync + 'static,
46{
47    app.local_files = T::LOCAL_FILES;
48    while !app.should_quit {
49        let wait = if app.drain_eval() {
50            Duration::ZERO
51        } else {
52            POLL_INTERVAL
53        };
54        let wait = app
55            .next_deadline(Instant::now())
56            .map_or(wait, |left| wait.min(left));
57        let screen = transport.terminal_mut().size().map_err(io::Error::other)?;
58        app.sync_terminal(TerminalEnv {
59            screen,
60            cell_pixels: transport.cell_pixels(),
61            backend: chart_backend(transport.client_term(), app.terminal.backend_override()),
62        });
63        let mut hits = Hits::default();
64        transport
65            .terminal_mut()
66            .draw(|frame| draw(frame, app, &mut hits))
67            .map_err(io::Error::other)?;
68        app.hits = hits;
69        if let Some(event) = transport.poll(wait)? {
70            handle_event(app, event);
71        }
72        app.tick(Instant::now());
73        for bytes in app.take_outbound() {
74            transport.write_passthrough(&bytes)?;
75        }
76    }
77    Ok(())
78}
79
80fn handle_event(app: &mut App, event: RawEvent) {
81    match event {
82        RawEvent::Key(key) => {
83            keymap::handle_key(app, key);
84        }
85        RawEvent::Mouse(mouse, at) => crate::mouse::handle_mouse(app, mouse, at),
86        // The next pass re-reads the screen size, and `draw` resizes the buffers.
87        RawEvent::Resize(_, _) => {}
88    }
89}
90
91#[cfg(test)]
92mod button_tests;
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::tabs::reports::chart::{ChartPane, pane_cells};
98    use crate::transport::RawEvent;
99    use crate::transport::tests_support::{DisconnectedTransport, ScriptedTransport, quit_keys};
100    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
101
102    fn key(code: KeyCode) -> RawEvent {
103        RawEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
104    }
105
106    #[test]
107    fn run_loop_exits_on_quit_intent() {
108        let mut app = crate::test_support::app();
109        let mut transport = ScriptedTransport::new(40, 10, quit_keys().into());
110        run_loop(&mut transport, &mut app).unwrap();
111        assert!(app.should_quit);
112    }
113
114    #[test]
115    fn run_loop_gives_the_chart_the_terminal_geometry() {
116        let mut app = crate::test_support::app();
117        let mut transport = ScriptedTransport::new(40, 20, quit_keys().into());
118        run_loop(&mut transport, &mut app).unwrap();
119        let env = app.terminal.env().expect("geometry known");
120        let cells = pane_cells(crate::draw::body_area(ratatui::layout::Rect::new(
121            0, 0, 40, 20,
122        )));
123        let call = ChartPane::call(
124            &forms::REPORT_BALANCE,
125            &forms::FormValues::default(),
126            env,
127            cells,
128            &app.theme,
129        );
130        assert!(call.contains(":width 380 :height 320 :text-px"), "{call}");
131    }
132
133    #[test]
134    fn run_loop_sends_queued_clipboard_bytes_through_the_transport() {
135        use crate::modal::{Csv, Modal};
136        let mut app = crate::test_support::app();
137        app.overlays.push(Modal::Csv(Csv::new(
138            "a.csv".to_string(),
139            "a,b\n".to_string(),
140        )));
141        let events = vec![key(KeyCode::Char('y')), key(KeyCode::Char('q'))];
142        let events = [events, quit_keys().into()].concat();
143        let mut transport = ScriptedTransport::new(40, 10, events);
144        run_loop(&mut transport, &mut app).unwrap();
145        assert_eq!(transport.passed, b"\x1b]52;c;YSxiCg==\x07");
146        assert!(!app.local_files);
147    }
148
149    #[test]
150    fn run_loop_applies_tab_selection() {
151        let mut app = crate::test_support::app();
152        let mut transport = ScriptedTransport::new(
153            40,
154            10,
155            [vec![key(KeyCode::Char('1'))], quit_keys().into()].concat(),
156        );
157        run_loop(&mut transport, &mut app).unwrap();
158        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
159    }
160
161    #[test]
162    fn run_loop_ignores_a_click_on_nothing() {
163        use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
164        let mut app = crate::test_support::app();
165        let click = RawEvent::Mouse(
166            MouseEvent {
167                kind: MouseEventKind::Down(MouseButton::Left),
168                column: 5,
169                row: 5,
170                modifiers: KeyModifiers::NONE,
171            },
172            std::time::Instant::now(),
173        );
174        let mut transport =
175            ScriptedTransport::new(40, 10, [vec![click], quit_keys().into()].concat());
176        run_loop(&mut transport, &mut app).unwrap();
177        assert!(app.should_quit);
178        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
179    }
180
181    #[test]
182    fn run_loop_keeps_the_areas_of_the_last_frame_it_drew() {
183        use crate::hits::Target;
184        let mut app = crate::test_support::app();
185        let mut transport = ScriptedTransport::new(40, 10, quit_keys().into());
186        run_loop(&mut transport, &mut app).unwrap();
187        assert!(
188            app.hits
189                .entries()
190                .iter()
191                .any(|(_, target)| *target == Target::MenuTitle(0))
192        );
193    }
194
195    #[test]
196    fn run_loop_routes_cmdline_submit() {
197        use crate::view::Tab;
198        let mut app = crate::test_support::app();
199        let events = vec![
200            key(KeyCode::Char(':')),
201            key(KeyCode::Char('v')),
202            key(KeyCode::Char('e')),
203            key(KeyCode::Char('r')),
204            key(KeyCode::Char('s')),
205            key(KeyCode::Char('i')),
206            key(KeyCode::Char('o')),
207            key(KeyCode::Char('n')),
208            key(KeyCode::Enter),
209        ];
210        let events = [events, quit_keys().into()].concat();
211        let mut transport = ScriptedTransport::new(60, 10, events);
212        run_loop(&mut transport, &mut app).unwrap();
213        assert!(!app.cmdline.active);
214        // `version` is now an eval leaf: it submits the form and switches to Console.
215        assert_eq!(app.front_kind(), Some(Tab::Console));
216        assert!(
217            app.console()
218                .scrollback
219                .iter()
220                .any(|l| l.contains("(get-version)")),
221            "form should appear in scrollback"
222        );
223    }
224
225    #[test]
226    fn handle_event_tolerates_resize() {
227        let mut app = crate::test_support::app();
228        handle_event(&mut app, RawEvent::Resize(80, 24));
229        assert!(!app.should_quit);
230        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
231    }
232
233    #[test]
234    fn run_loop_exits_without_polling_when_app_already_quitting() {
235        let mut app = crate::test_support::app();
236        app.request_quit();
237        // An empty queue would normally let the loop continue past the
238        // first iteration; the should_quit guard must short-circuit
239        // before poll ever runs, even against an always-erroring poll.
240        let mut transport = DisconnectedTransport::new(40, 10);
241        run_loop(&mut transport, &mut app).expect("should return Ok");
242    }
243
244    #[test]
245    fn run_loop_propagates_poll_errors() {
246        let mut app = crate::test_support::app();
247        let mut transport = DisconnectedTransport::new(40, 10);
248        let err = run_loop(&mut transport, &mut app).expect_err("poll err bubbles");
249        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
250        // The loop should not have flipped the quit flag; the caller
251        // decides whether an I/O error means "quit" or "retry".
252        assert!(!app.should_quit);
253    }
254
255    #[test]
256    fn run_loop_ignores_unbound_keys() {
257        // Keys with no binding must not panic or change state.
258        let mut app = crate::test_support::app();
259        let mut transport = ScriptedTransport::new(
260            40,
261            10,
262            [vec![key(KeyCode::F(5))], quit_keys().into()].concat(),
263        );
264        run_loop(&mut transport, &mut app).unwrap();
265        assert!(app.should_quit);
266    }
267}