crates/diff/src/bin/rustik-diff/session.rs 13.2 KiB raw
1
//! Terminal session loop for the pager binary.
2
3
use std::io;
4
use std::sync::mpsc;
5
use std::thread;
6
use std::time::{Duration, Instant};
7
8
use rustik_diff::{
9
    ContextChange, DiffPalette, DiffViewer, HighlightOutput, HighlightRequest, Highlighter, Stats,
10
    diffstat, file_count, recoverable_error, spawn_highlighter,
11
};
12
use rustik_repo::git;
13
use rustik_tui as tui;
14
use rustik_tui::{
15
    Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton, Rect, Style,
16
    Terminal, Widget, colors,
17
};
18
use rustik_tui_termion as tui_termion;
19
use tui::event::Modifiers;
20
21
use crate::error::Error;
22
23
/// Number of rows reserved for the bottom footer when possible.
24
const FOOTER_ROWS: usize = 1;
25
/// Empty columns between status content and the status bar's right edge.
26
const STATUS_RIGHT_PADDING: usize = 1;
27
/// Foreground color for dim footer text.
28
const FOOTER_FG: Color = Color::Fixed(240);
29
/// Background color for the footer row, matching file border chrome.
30
const FOOTER_BG: Color = colors::FAINT;
31
/// Dark purple background color for the application badge.
32
const APP_BADGE_BG: Color = Color::RGB(68, 36, 84);
33
/// Foreground color for neutral footer values.
34
const FOOTER_VALUE_FG: Color = Color::Fixed(250);
35
/// Separator shown between footer status segments: ·.
36
const FOOTER_SEPARATOR: &str = " · ";
37
38
/// Terminal backend used by the interactive viewer.
39
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
40
41
/// Runs the terminal event loop.
42
pub(super) fn run(
43
    terminal: &mut DiffTerminal,
44
    viewer: &mut DiffViewer,
45
    repo: Option<git::Repository>,
46
    debug: bool,
47
) -> Result<(), Error> {
48
    let (events_tx, events_rx) = mpsc::channel();
49
    TerminalEvent::spawn_input_worker(events_tx.clone());
50
51
    let highlighter = spawn_highlighter(viewer.document(), repo, move |output| {
52
        let _ = events_tx.send(TerminalEvent::Highlight(output));
53
    });
54
    let mut session = TerminalSession {
55
        terminal,
56
        viewer,
57
        highlighter,
58
        context_pending: false,
59
        debug,
60
        debug_status: None,
61
        visible_started: None,
62
        error: None,
63
    };
64
    session.redraw()?;
65
66
    while let Ok(event) = events_rx.recv() {
67
        let mut redraw = false;
68
        if session.update(event, &mut redraw)? == Control::Quit {
69
            break;
70
        }
71
        while let Ok(event) = events_rx.try_recv() {
72
            if session.update(event, &mut redraw)? == Control::Quit {
73
                return Ok(());
74
            }
75
        }
76
        if redraw {
77
            session.redraw()?;
78
        }
79
    }
80
    Ok(())
81
}
82
83
/// Interactive terminal session state.
84
struct TerminalSession<'a> {
85
    /// Terminal frame target.
86
    terminal: &'a mut DiffTerminal,
87
    /// Diff viewer state.
88
    viewer: &'a mut DiffViewer,
89
    /// Background highlighter handle.
90
    highlighter: Highlighter,
91
    /// Whether a context refetch is already in flight.
92
    context_pending: bool,
93
    /// Whether debug footer diagnostics are shown.
94
    debug: bool,
95
    /// Latest highlight timing shown in the debug footer.
96
    debug_status: Option<String>,
97
    /// Time the in-flight visible highlight batch was requested, for debug.
98
    visible_started: Option<Instant>,
99
    /// Most recent recoverable input error shown in the status bar.
100
    error: Option<String>,
101
}
102
103
impl TerminalSession<'_> {
104
    /// Applies one event and records whether the session should redraw.
105
    fn update(&mut self, event: TerminalEvent, redraw: &mut bool) -> Result<Control, Error> {
106
        match event {
107
            TerminalEvent::Input(event) => {
108
                let event = match event {
109
                    Ok(event) => {
110
                        if self.error.take().is_some() {
111
                            *redraw = true;
112
                        }
113
                        event
114
                    }
115
                    Err(error) => {
116
                        self.error = Some(error.to_string().replace('\n', " · "));
117
                        *redraw = true;
118
                        return Ok(Control::Continue);
119
                    }
120
                };
121
                let resized = matches!(event, Event::Resize(_));
122
                let area = viewer_area(self.terminal.area());
123
                if let Some(change) = context_change(&event) {
124
                    self.request_context(change);
125
                    return Ok(Control::Continue);
126
                }
127
                let control = self.viewer.handle_input(event, area);
128
                if control == Control::Redraw || (resized && control != Control::Quit) {
129
                    *redraw = true;
130
                }
131
                Ok(control)
132
            }
133
            TerminalEvent::Highlight(HighlightOutput::Highlights(results)) => {
134
                let mut refresh = self.viewer.apply_highlights(results);
135
                if self.debug
136
                    && let Some(started) = self.visible_started.take()
137
                {
138
                    self.debug_status = Some(format!("highlight {}", format_ms(started.elapsed())));
139
                    refresh = true;
140
                }
141
                if refresh {
142
                    self.draw_frame()?;
143
                }
144
                Ok(Control::Continue)
145
            }
146
            TerminalEvent::Highlight(HighlightOutput::Context(update)) => {
147
                self.context_pending = false;
148
                if let Some(update) = update {
149
                    let area = viewer_area(self.terminal.area());
150
                    self.viewer.apply_context_update(update, area);
151
                    *redraw = true;
152
                }
153
                Ok(Control::Continue)
154
            }
155
        }
156
    }
157
158
    /// Draws a frame and requests highlights for visible rows.
159
    fn redraw(&mut self) -> io::Result<()> {
160
        self.request_visible_highlights();
161
        self.draw_frame()?;
162
        self.request_lookahead_highlights();
163
        Ok(())
164
    }
165
166
    /// Requests highlight work for currently visible rows.
167
    fn request_visible_highlights(&mut self) {
168
        let area = viewer_area(self.terminal.area());
169
        let requests = self.viewer.visible_highlight_requests(area);
170
        if requests.is_empty() {
171
            if self.debug {
172
                self.debug_status = Some("highlight (cached)".to_owned());
173
                self.visible_started = None;
174
            }
175
            return;
176
        }
177
        if self.debug {
178
            self.visible_started = Some(Instant::now());
179
        }
180
        self.queue_highlights(requests);
181
    }
182
183
    /// Requests highlight work for rows after the visible viewport.
184
    fn request_lookahead_highlights(&mut self) {
185
        let area = viewer_area(self.terminal.area());
186
        let requests = self.viewer.lookahead_highlight_requests(area);
187
        self.queue_highlights(requests);
188
    }
189
190
    /// Queues highlight work, cancelling rows the worker cannot accept.
191
    fn queue_highlights(&mut self, requests: Vec<HighlightRequest>) {
192
        if requests.is_empty() {
193
            return;
194
        }
195
        if let Some(dropped) = self.highlighter.highlight(requests) {
196
            self.viewer.cancel_highlights(dropped);
197
        }
198
    }
199
200
    /// Requests context refetch work for one context change.
201
    fn request_context(&mut self, change: ContextChange) {
202
        if self.context_pending {
203
            return;
204
        }
205
        let Some(request) = self.viewer.context_request(change) else {
206
            return;
207
        };
208
        if self.highlighter.context(request) {
209
            self.context_pending = true;
210
        }
211
    }
212
213
    /// Draws one terminal frame without scheduling highlight work.
214
    fn draw_frame(&mut self) -> io::Result<()> {
215
        let error = self.error.as_deref();
216
        self.terminal.draw(|frame| {
217
            let body = viewer_area(frame.area);
218
            frame.render_widget(&mut *self.viewer, body);
219
            draw_status(
220
                frame,
221
                self.viewer.document().stats(),
222
                self.viewer.options().diff_palette,
223
                self.debug_status.as_deref(),
224
                error,
225
            );
226
        })
227
    }
228
}
229
230
/// Event delivered to the terminal loop.
231
enum TerminalEvent {
232
    /// Terminal input event.
233
    Input(io::Result<Event<()>>),
234
    /// Background highlighter output.
235
    Highlight(HighlightOutput),
236
}
237
238
impl TerminalEvent {
239
    /// Spawns the blocking input reader.
240
    fn spawn_input_worker(tx: mpsc::Sender<Self>) {
241
        thread::spawn(move || {
242
            for event in tui_termion::term::events() {
243
                if tx.send(Self::Input(event)).is_err() {
244
                    break;
245
                }
246
            }
247
        });
248
    }
249
}
250
251
/// Returns the context change represented by an input event.
252
fn context_change(event: &Event<()>) -> Option<ContextChange> {
253
    match event {
254
        Event::Key(Key::Char('.')) => Some(ContextChange::Increase),
255
        Event::Mouse(Mouse::Press {
256
            button: MouseButton::WheelUp,
257
            modifiers,
258
            ..
259
        }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Increase),
260
        Event::Key(Key::Char(',')) => Some(ContextChange::Decrease),
261
        Event::Mouse(Mouse::Press {
262
            button: MouseButton::WheelDown,
263
            modifiers,
264
            ..
265
        }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Decrease),
266
        Event::Key(Key::Char('x')) => Some(ContextChange::ToggleFile),
267
        _ => None,
268
    }
269
}
270
271
/// Returns the viewer area above the footer chrome.
272
fn viewer_area(area: Rect) -> Rect {
273
    let footer_rows = FOOTER_ROWS.min(area.rows);
274
275
    Rect::new(
276
        area.x,
277
        area.y,
278
        area.cols,
279
        area.rows.saturating_sub(footer_rows),
280
    )
281
}
282
283
/// Draws the bottom status row.
284
fn draw_status(
285
    frame: &mut tui::Frame<'_>,
286
    stats: Stats,
287
    palette: DiffPalette,
288
    debug: Option<&str>,
289
    error: Option<&str>,
290
) {
291
    let area = frame.area;
292
    if area.rows == 0 {
293
        return;
294
    }
295
    let row = Rect::new(area.x, area.bottom().saturating_sub(1), area.cols, 1);
296
297
    frame.render_widget(status_line(area.cols, stats, palette, debug, error), row);
298
}
299
300
/// Returns the padded bottom status line.
301
fn status_line(
302
    cols: usize,
303
    stats: Stats,
304
    palette: DiffPalette,
305
    debug: Option<&str>,
306
    error: Option<&str>,
307
) -> Line {
308
    if let Some(error) = error {
309
        return recoverable_error(error, FOOTER_VALUE_FG, FOOTER_BG)
310
            .padded(cols)
311
            .truncated(cols, "");
312
    }
313
    let badge = Line::new(
314
        Label::new(" diff ")
315
            .fg(Color::White)
316
            .bg(APP_BADGE_BG)
317
            .style(Style::default().bold()),
318
    );
319
    let stats_cols = cols
320
        .saturating_sub(badge.width())
321
        .saturating_sub(STATUS_RIGHT_PADDING)
322
        .saturating_sub(1);
323
324
    HStack::default()
325
        .child(badge)
326
        .spacer()
327
        .child(status_stats(stats, palette, debug).truncated(stats_cols, ""))
328
        .child(Line::new(Label::space().bg(FOOTER_BG)).padded(STATUS_RIGHT_PADDING))
329
        .to_line(Constraint::tight(cols))
330
        .style(Style::default().bg(FOOTER_BG))
331
        .padded(cols)
332
        .truncated(cols, "")
333
}
334
335
/// Returns the right-aligned status data for the footer.
336
fn status_stats(stats: Stats, palette: DiffPalette, debug: Option<&str>) -> Line {
337
    let mut line = diffstat(stats, palette)
338
        .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
339
        .item(Label::new(&file_count(stats.files_changed)).fg(FOOTER_VALUE_FG));
340
    if let Some(debug) = debug {
341
        line = line
342
            .item(Label::new(FOOTER_SEPARATOR).fg(FOOTER_FG))
343
            .item(Label::new(debug).fg(FOOTER_FG));
344
    }
345
    line.style(Style::default().bg(FOOTER_BG))
346
}
347
348
/// Formats debug timing in milliseconds.
349
fn format_ms(duration: Duration) -> String {
350
    format!("{:.1}ms", duration.as_secs_f64() * 1_000.0)
351
}
352
353
#[cfg(test)]
354
#[allow(clippy::unwrap_used)]
355
mod tests {
356
    use super::*;
357
358
    #[test]
359
    fn viewer_area_reserves_footer() {
360
        assert_eq!(
361
            viewer_area(Rect::new(0, 0, 80, 20)),
362
            Rect::new(0, 0, 80, 19)
363
        );
364
        assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0));
365
    }
366
367
    #[test]
368
    fn status_line_fills_footer_width() {
369
        assert_eq!(
370
            status_line(24, Stats::default(), DiffPalette::default(), None, None).width(),
371
            24
372
        );
373
    }
374
375
    #[test]
376
    fn status_line_renders_application_badge() {
377
        let line = status_line(24, Stats::default(), DiffPalette::default(), None, None);
378
379
        assert!(line.to_string().contains("diff"));
380
    }
381
382
    #[test]
383
    fn status_line_renders_recoverable_error() {
384
        let line = status_line(
385
            40,
386
            Stats::default(),
387
            DiffPalette::default(),
388
            Some("highlight 1.0ms"),
389
            Some("input failed"),
390
        );
391
        let text = line.to_string();
392
393
        assert!(text.contains("input failed"));
394
        assert!(!text.contains("diff"));
395
        assert!(!text.contains("highlight"));
396
    }
397
398
    #[test]
399
    fn resize_requests_redraw_even_when_viewer_continues() {
400
        let resized = true;
401
        let control = DiffViewer::new(Default::default(), Default::default()).handle_input(
402
            Event::Resize(tui::Size::new(80, 24)),
403
            Rect::new(0, 0, 80, 23),
404
        );
405
        let mut redraw = false;
406
        if control == Control::Redraw || (resized && control != Control::Quit) {
407
            redraw = true;
408
        }
409
        assert_eq!(control, Control::Continue);
410
        assert!(redraw);
411
    }
412
}