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

            
8
use crate::app::App;
9
use crate::draw::draw;
10
use crate::hits::Hits;
11
use crate::keymap;
12
use crate::tabs::reports::chart::TerminalEnv;
13
use crate::transport::{RawEvent, Transport};
14
use rpc::chart::chart_backend;
15
use std::io;
16
use 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.
20
pub 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.
32
29
pub fn run_loop<T>(transport: &mut T, app: &mut App) -> io::Result<()>
33
29
where
34
29
    T: Transport,
35
29
    <T::Backend as ratatui::backend::Backend>::Error: std::error::Error + Send + Sync + 'static,
36
{
37
29
    let result = drive(transport, app);
38
29
    app.flush_key_press();
39
29
    result
40
29
}
41

            
42
29
fn drive<T>(transport: &mut T, app: &mut App) -> io::Result<()>
43
29
where
44
29
    T: Transport,
45
29
    <T::Backend as ratatui::backend::Backend>::Error: std::error::Error + Send + Sync + 'static,
46
{
47
29
    app.local_files = T::LOCAL_FILES;
48
405
    while !app.should_quit {
49
390
        let wait = if app.drain_eval() {
50
27
            Duration::ZERO
51
        } else {
52
363
            POLL_INTERVAL
53
        };
54
390
        let wait = app
55
390
            .next_deadline(Instant::now())
56
390
            .map_or(wait, |left| wait.min(left));
57
390
        let screen = transport.terminal_mut().size().map_err(io::Error::other)?;
58
390
        app.sync_terminal(TerminalEnv {
59
390
            screen,
60
390
            cell_pixels: transport.cell_pixels(),
61
390
            backend: chart_backend(transport.client_term(), app.terminal.backend_override()),
62
390
        });
63
390
        let mut hits = Hits::default();
64
390
        transport
65
390
            .terminal_mut()
66
390
            .draw(|frame| draw(frame, app, &mut hits))
67
390
            .map_err(io::Error::other)?;
68
387
        app.hits = hits;
69
387
        if let Some(event) = transport.poll(wait)? {
70
234
            handle_event(app, event);
71
142
        }
72
376
        app.tick(Instant::now());
73
376
        for bytes in app.take_outbound() {
74
1
            transport.write_passthrough(&bytes)?;
75
        }
76
    }
77
15
    Ok(())
78
29
}
79

            
80
427
fn handle_event(app: &mut App, event: RawEvent) {
81
427
    match event {
82
        RawEvent::Key(key) => {
83
387
            keymap::handle_key(app, key);
84
        }
85
35
        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
5
        RawEvent::Resize(_, _) => {}
88
    }
89
427
}
90

            
91
#[cfg(test)]
92
mod button_tests;
93

            
94
#[cfg(test)]
95
mod 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
13
    fn key(code: KeyCode) -> RawEvent {
103
13
        RawEvent::Key(KeyEvent::new(code, KeyModifiers::NONE))
104
13
    }
105

            
106
    #[test]
107
1
    fn run_loop_exits_on_quit_intent() {
108
1
        let mut app = crate::test_support::app();
109
1
        let mut transport = ScriptedTransport::new(40, 10, quit_keys().into());
110
1
        run_loop(&mut transport, &mut app).unwrap();
111
1
        assert!(app.should_quit);
112
1
    }
113

            
114
    #[test]
115
1
    fn run_loop_gives_the_chart_the_terminal_geometry() {
116
1
        let mut app = crate::test_support::app();
117
1
        let mut transport = ScriptedTransport::new(40, 20, quit_keys().into());
118
1
        run_loop(&mut transport, &mut app).unwrap();
119
1
        let env = app.terminal.env().expect("geometry known");
120
1
        let cells = pane_cells(crate::draw::body_area(ratatui::layout::Rect::new(
121
1
            0, 0, 40, 20,
122
1
        )));
123
1
        let call = ChartPane::call(
124
1
            &forms::REPORT_BALANCE,
125
1
            &forms::FormValues::default(),
126
1
            env,
127
1
            cells,
128
1
            &app.theme,
129
1
        );
130
1
        assert!(call.contains(":width 380 :height 320 :text-px"), "{call}");
131
1
    }
132

            
133
    #[test]
134
1
    fn run_loop_sends_queued_clipboard_bytes_through_the_transport() {
135
        use crate::modal::{Csv, Modal};
136
1
        let mut app = crate::test_support::app();
137
1
        app.overlays.push(Modal::Csv(Csv::new(
138
1
            "a.csv".to_string(),
139
1
            "a,b\n".to_string(),
140
1
        )));
141
1
        let events = vec![key(KeyCode::Char('y')), key(KeyCode::Char('q'))];
142
1
        let events = [events, quit_keys().into()].concat();
143
1
        let mut transport = ScriptedTransport::new(40, 10, events);
144
1
        run_loop(&mut transport, &mut app).unwrap();
145
1
        assert_eq!(transport.passed, b"\x1b]52;c;YSxiCg==\x07");
146
1
        assert!(!app.local_files);
147
1
    }
148

            
149
    #[test]
150
1
    fn run_loop_applies_tab_selection() {
151
1
        let mut app = crate::test_support::app();
152
1
        let mut transport = ScriptedTransport::new(
153
1
            40,
154
1
            10,
155
1
            [vec![key(KeyCode::Char('1'))], quit_keys().into()].concat(),
156
1
        );
157
1
        run_loop(&mut transport, &mut app).unwrap();
158
1
        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
159
1
    }
160

            
161
    #[test]
162
1
    fn run_loop_ignores_a_click_on_nothing() {
163
        use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
164
1
        let mut app = crate::test_support::app();
165
1
        let click = RawEvent::Mouse(
166
1
            MouseEvent {
167
1
                kind: MouseEventKind::Down(MouseButton::Left),
168
1
                column: 5,
169
1
                row: 5,
170
1
                modifiers: KeyModifiers::NONE,
171
1
            },
172
1
            std::time::Instant::now(),
173
1
        );
174
        let mut transport =
175
1
            ScriptedTransport::new(40, 10, [vec![click], quit_keys().into()].concat());
176
1
        run_loop(&mut transport, &mut app).unwrap();
177
1
        assert!(app.should_quit);
178
1
        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
179
1
    }
180

            
181
    #[test]
182
1
    fn run_loop_keeps_the_areas_of_the_last_frame_it_drew() {
183
        use crate::hits::Target;
184
1
        let mut app = crate::test_support::app();
185
1
        let mut transport = ScriptedTransport::new(40, 10, quit_keys().into());
186
1
        run_loop(&mut transport, &mut app).unwrap();
187
1
        assert!(
188
1
            app.hits
189
1
                .entries()
190
1
                .iter()
191
6
                .any(|(_, target)| *target == Target::MenuTitle(0))
192
        );
193
1
    }
194

            
195
    #[test]
196
1
    fn run_loop_routes_cmdline_submit() {
197
        use crate::view::Tab;
198
1
        let mut app = crate::test_support::app();
199
1
        let events = vec![
200
1
            key(KeyCode::Char(':')),
201
1
            key(KeyCode::Char('v')),
202
1
            key(KeyCode::Char('e')),
203
1
            key(KeyCode::Char('r')),
204
1
            key(KeyCode::Char('s')),
205
1
            key(KeyCode::Char('i')),
206
1
            key(KeyCode::Char('o')),
207
1
            key(KeyCode::Char('n')),
208
1
            key(KeyCode::Enter),
209
        ];
210
1
        let events = [events, quit_keys().into()].concat();
211
1
        let mut transport = ScriptedTransport::new(60, 10, events);
212
1
        run_loop(&mut transport, &mut app).unwrap();
213
1
        assert!(!app.cmdline.active);
214
        // `version` is now an eval leaf: it submits the form and switches to Console.
215
1
        assert_eq!(app.front_kind(), Some(Tab::Console));
216
1
        assert!(
217
1
            app.console()
218
1
                .scrollback
219
1
                .iter()
220
1
                .any(|l| l.contains("(get-version)")),
221
            "form should appear in scrollback"
222
        );
223
1
    }
224

            
225
    #[test]
226
1
    fn handle_event_tolerates_resize() {
227
1
        let mut app = crate::test_support::app();
228
1
        handle_event(&mut app, RawEvent::Resize(80, 24));
229
1
        assert!(!app.should_quit);
230
1
        assert_eq!(app.front_kind(), Some(crate::view::Tab::Accounts));
231
1
    }
232

            
233
    #[test]
234
1
    fn run_loop_exits_without_polling_when_app_already_quitting() {
235
1
        let mut app = crate::test_support::app();
236
1
        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
1
        let mut transport = DisconnectedTransport::new(40, 10);
241
1
        run_loop(&mut transport, &mut app).expect("should return Ok");
242
1
    }
243

            
244
    #[test]
245
1
    fn run_loop_propagates_poll_errors() {
246
1
        let mut app = crate::test_support::app();
247
1
        let mut transport = DisconnectedTransport::new(40, 10);
248
1
        let err = run_loop(&mut transport, &mut app).expect_err("poll err bubbles");
249
1
        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
1
        assert!(!app.should_quit);
253
1
    }
254

            
255
    #[test]
256
1
    fn run_loop_ignores_unbound_keys() {
257
        // Keys with no binding must not panic or change state.
258
1
        let mut app = crate::test_support::app();
259
1
        let mut transport = ScriptedTransport::new(
260
1
            40,
261
1
            10,
262
1
            [vec![key(KeyCode::F(5))], quit_keys().into()].concat(),
263
1
        );
264
1
        run_loop(&mut transport, &mut app).unwrap();
265
1
        assert!(app.should_quit);
266
1
    }
267
}