diff: Refactor binary module

9e17abe4adebbb1c282dc85e2896d2e815ce3e28
Alexis Sellier committed ago 1 parent f142ff5e
crates/diff/src/bin/rustik-diff.rs +17 -324
1 1
//! Binary entry point for the `rustik-diff` pager.
2 2
3 +
#[path = "rustik-diff/builtins.rs"]
4 +
mod builtins;
5 +
#[path = "rustik-diff/error.rs"]
6 +
mod error;
7 +
#[path = "rustik-diff/session.rs"]
8 +
mod session;
9 +
3 10
use std::ffi::OsString;
4 11
use std::io::{self, IsTerminal as _, Read as _, Write as _};
5 12
use std::path::Path;
6 13
use std::process::{Command, ExitCode, Output};
7 -
use std::sync::mpsc;
8 -
use std::thread;
9 14
use std::{env, str};
10 15
11 -
use rustik_diff::{
12 -
    BuiltinHighlighter, ContextError, Decode, DecodeError, DiffDocument, DiffOptions, DiffViewer,
13 -
    FileTreeMode,
14 -
};
15 -
use rustik_diff::{HighlightRequest, HighlightResult};
16 -
use rustik_highlight as syntax;
17 -
use rustik_repo::{GitRepo, RepoError};
16 +
use rustik_diff::{Decode, DiffDocument, DiffOptions, DiffViewer, FileTreeMode};
17 +
use rustik_repo::GitRepo;
18 18
use rustik_tui as tui;
19 -
use rustik_tui::{Color, Control, Event, Label, Line, Rect, Style, Terminal};
19 +
use rustik_tui::Terminal;
20 20
use rustik_tui_termion as tui_termion;
21 21
22 +
use builtins::Builtins;
23 +
use error::Error;
24 +
22 25
/// Default static render width for non-terminal output.
23 26
const STATIC_COLS: usize = 100;
24 27
/// Maximum static render rows for non-terminal output.
25 28
const STATIC_MAX_ROWS: usize = 10_000;
26 -
/// Number of rows reserved for the bottom footer when possible.
27 -
const FOOTER_ROWS: usize = 1;
28 -
/// Foreground color for dim footer text.
29 -
const FOOTER_FG: Color = Color::Fixed(240);
30 -
/// Background color for the footer row.
31 -
const FOOTER_BG: Color = Color::Fixed(233);
32 -
/// Theme name used for built-in diff highlighting.
33 -
const BUILTIN_THEME_NAME: &str = "rustik-catppuccin-mocha";
34 -
/// Built-in syntax theme JSON.
35 -
const BUILTIN_THEME: &str = include_str!("../themes/rustik-catppuccin-mocha.json");
36 -
/// Common syntax grammars loaded by the interactive pager.
37 -
const COMMON_SYNTAXES: [CommonSyntax; 1] = [CommonSyntax {
38 -
    source: include_str!("../syntaxes/rust.json"),
39 -
    file_types: &["rs"],
40 -
}];
41 -
42 -
/// Terminal backend used by the interactive viewer.
43 -
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::StdoutScreen>>;
44 -
45 -
/// Built-in syntax source and path aliases.
46 -
struct CommonSyntax {
47 -
    /// TextMate grammar JSON source.
48 -
    source: &'static str,
49 -
    /// File names and extensions recognized by the registry.
50 -
    file_types: &'static [&'static str],
51 -
}
52 -
53 -
impl CommonSyntax {
54 -
    /// Returns whether this syntax matches any path in a diff document.
55 -
    fn matches_document(&self, document: &DiffDocument) -> bool {
56 -
        document.files.iter().any(|file| {
57 -
            file.header
58 -
                .old_path
59 -
                .as_deref()
60 -
                .is_some_and(|path| self.matches_path(path))
61 -
                || file
62 -
                    .header
63 -
                    .new_path
64 -
                    .as_deref()
65 -
                    .is_some_and(|path| self.matches_path(path))
66 -
        })
67 -
    }
68 -
69 -
    /// Returns whether this syntax matches a file path.
70 -
    fn matches_path(&self, path: &Path) -> bool {
71 -
        let file_name = path.file_name().and_then(|name| name.to_str());
72 -
        let extension = path.extension().and_then(|extension| extension.to_str());
73 -
74 -
        self.file_types.iter().any(|file_type| {
75 -
            file_name.is_some_and(|name| name.eq_ignore_ascii_case(file_type))
76 -
                || extension.is_some_and(|extension| extension.eq_ignore_ascii_case(file_type))
77 -
        })
78 -
    }
79 -
80 -
    /// Parses this grammar and attaches local path aliases.
81 -
    fn grammar(&self) -> Result<syntax::Grammar, syntax::Error> {
82 -
        let mut raw: syntax::RawGrammar = self.source.parse()?;
83 -
84 -
        for file_type in self.file_types {
85 -
            if !raw
86 -
                .file_types
87 -
                .iter()
88 -
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
89 -
            {
90 -
                raw.file_types.push((*file_type).to_owned());
91 -
            }
92 -
        }
93 -
        syntax::Grammar::compile(&raw)
94 -
    }
95 -
}
96 29
97 30
/// Program entry point.
98 31
fn main() -> ExitCode {
99 32
    match run(env::args_os().skip(1).collect()) {
100 33
        Ok(()) => ExitCode::SUCCESS,
133 66
            io::stdout().write_all(input)?;
134 67
            return Ok(());
135 68
        }
136 69
        Err(error) => return Err(Error::Parse(error)),
137 70
    };
138 -
    let raw_theme = BUILTIN_THEME.parse::<syntax::RawTheme>()?;
71 +
    let assets = Builtins::load(&document)?;
139 72
    let mut options = DiffOptions {
140 -
        diff_palette: (&raw_theme).into(),
73 +
        diff_palette: assets.palette,
141 74
        ..DiffOptions::default()
142 75
    };
76 +
143 77
    if !io::stdout().is_terminal() {
144 78
        let mut viewer = DiffViewer::new(document, options);
145 79
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, STATIC_MAX_ROWS));
146 80
147 81
        tui_termion::term::print_constrained(&mut viewer, constraints)?;
157 91
    options.file_tree = FileTreeMode::Auto;
158 92
    options.file_tree_root = root;
159 93
160 94
    let backend = tui_termion::term::screen()?;
161 95
    let mut terminal = Terminal::new(backend)?;
162 -
    let mut registry = syntax::Registry::default();
163 -
    let theme = syntax::Theme::compile(&raw_theme);
164 -
165 -
    registry.add_theme(theme);
166 -
167 -
    for syntax in COMMON_SYNTAXES
168 -
        .iter()
169 -
        .filter(|syntax| syntax.matches_document(&document))
170 -
    {
171 -
        registry.add_grammar(syntax.grammar()?);
172 -
    }
173 -
    let highlighter = BuiltinHighlighter::new(registry, BUILTIN_THEME_NAME);
174 96
    let mut viewer = DiffViewer::new(document, options);
175 97
176 98
    terminal.clear()?;
177 99
    terminal.set_cursor_visible(false)?;
178 100
179 101
    let repo = args.map(|args| GitRepo::new(cwd, args));
180 -
    let result = terminal_loop(&mut terminal, &mut viewer, highlighter, repo);
102 +
    let result = session::run(&mut terminal, &mut viewer, assets.highlighter, repo);
181 103
    let cursor = terminal.set_cursor_visible(true);
182 104
183 105
    result?;
184 106
    cursor.map_err(Error::Io)
185 107
}
186 108
187 -
/// Runs the terminal event loop.
188 -
fn terminal_loop(
189 -
    terminal: &mut DiffTerminal,
190 -
    viewer: &mut DiffViewer,
191 -
    highlighter: BuiltinHighlighter,
192 -
    repo: Option<GitRepo>,
193 -
) -> Result<(), Error> {
194 -
    let (events_tx, events_rx) = mpsc::channel();
195 -
    TerminalEvent::spawn_input_worker(events_tx.clone());
196 -
197 -
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx, highlighter);
198 -
    let mut session = TerminalSession {
199 -
        terminal,
200 -
        viewer,
201 -
        repo,
202 -
        highlights_tx,
203 -
    };
204 -
    session.redraw()?;
205 -
206 -
    while let Ok(event) = events_rx.recv() {
207 -
        match event {
208 -
            TerminalEvent::Input(event) => {
209 -
                let event = event?;
210 -
                let area = viewer_area(session.terminal.area());
211 -
                let control = if let Some(repo) = session.repo.as_ref() {
212 -
                    session.viewer.handle_input_with_repo(event, area, repo)?
213 -
                } else {
214 -
                    session.viewer.handle_input(event, area)
215 -
                };
216 -
                match control {
217 -
                    Control::Quit => break,
218 -
                    Control::Redraw => session.redraw()?,
219 -
                    Control::Continue | Control::Wait => {}
220 -
                }
221 -
            }
222 -
            TerminalEvent::Highlights(results) => {
223 -
                if session.viewer.apply_highlights(results) {
224 -
                    session.redraw()?;
225 -
                }
226 -
            }
227 -
        }
228 -
    }
229 -
    Ok(())
230 -
}
231 -
232 -
/// Interactive terminal session state.
233 -
struct TerminalSession<'a> {
234 -
    /// Terminal frame target.
235 -
    terminal: &'a mut DiffTerminal,
236 -
    /// Diff viewer state.
237 -
    viewer: &'a mut DiffViewer,
238 -
    /// Git-backed diff repo, present when the input came from Git.
239 -
    repo: Option<GitRepo>,
240 -
    /// Visible-row highlight request channel.
241 -
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
242 -
}
243 -
244 -
impl TerminalSession<'_> {
245 -
    /// Draws a frame and requests highlights for visible rows.
246 -
    fn redraw(&mut self) -> io::Result<()> {
247 -
        self.draw_frame()?;
248 -
        self.request_visible_highlights();
249 -
        Ok(())
250 -
    }
251 -
252 -
    /// Requests highlight work for currently visible rows.
253 -
    fn request_visible_highlights(&mut self) {
254 -
        let area = viewer_area(self.terminal.area());
255 -
        let requests = self.viewer.highlight_requests(area);
256 -
        if !requests.is_empty() {
257 -
            let _ = self.highlights_tx.send(requests);
258 -
        }
259 -
    }
260 -
261 -
    /// Draws one terminal frame without scheduling highlight work.
262 -
    fn draw_frame(&mut self) -> io::Result<()> {
263 -
        self.terminal.draw(|frame| {
264 -
            let body = viewer_area(frame.area);
265 -
            frame.render_widget(&mut *self.viewer, body);
266 -
            draw_status(frame);
267 -
        })
268 -
    }
269 -
}
270 -
271 -
/// Event delivered to the terminal loop.
272 -
enum TerminalEvent {
273 -
    /// Terminal input event.
274 -
    Input(io::Result<Event<()>>),
275 -
    /// Background highlight results.
276 -
    Highlights(Vec<HighlightResult>),
277 -
}
278 -
279 -
impl TerminalEvent {
280 -
    /// Spawns the blocking input reader.
281 -
    fn spawn_input_worker(tx: mpsc::Sender<Self>) {
282 -
        thread::spawn(move || {
283 -
            for event in tui_termion::term::events() {
284 -
                if tx.send(Self::Input(event)).is_err() {
285 -
                    break;
286 -
                }
287 -
            }
288 -
        });
289 -
    }
290 -
291 -
    /// Spawns the visible-row highlight worker.
292 -
    fn spawn_highlight_worker(
293 -
        tx: mpsc::Sender<Self>,
294 -
        mut highlighter: BuiltinHighlighter,
295 -
    ) -> mpsc::Sender<Vec<HighlightRequest>> {
296 -
        let (requests_tx, requests_rx) = mpsc::channel::<Vec<HighlightRequest>>();
297 -
        thread::spawn(move || {
298 -
            while let Ok(requests) = requests_rx.recv() {
299 -
                if requests.is_empty() {
300 -
                    continue;
301 -
                }
302 -
                let results = highlighter.highlight_requests(requests).collect();
303 -
                if tx.send(Self::Highlights(results)).is_err() {
304 -
                    break;
305 -
                }
306 -
            }
307 -
        });
308 -
        requests_tx
309 -
    }
310 -
}
311 -
312 -
/// Returns the viewer area above the footer chrome.
313 -
fn viewer_area(area: Rect) -> Rect {
314 -
    let footer_rows = FOOTER_ROWS.min(area.rows);
315 -
316 -
    Rect::new(
317 -
        area.x,
318 -
        area.y,
319 -
        area.cols,
320 -
        area.rows.saturating_sub(footer_rows),
321 -
    )
322 -
}
323 -
324 -
/// Draws the bottom status row.
325 -
fn draw_status(frame: &mut tui::Frame<'_>) {
326 -
    let area = frame.area;
327 -
    if area.rows == 0 {
328 -
        return;
329 -
    }
330 -
    let row = Rect::new(area.x, area.bottom().saturating_sub(1), area.cols, 1);
331 -
332 -
    frame.render_widget(status_line(area.cols), row);
333 -
}
334 -
335 -
/// Returns the padded bottom status line.
336 -
fn status_line(cols: usize) -> Line {
337 -
    Line::new(Label::new("rustik-diff").fg(FOOTER_FG))
338 -
        .style(Style::default().bg(FOOTER_BG))
339 -
        .padded(cols)
340 -
}
341 -
342 109
/// Runs `git diff` in `cwd`.
343 110
fn git_diff(args: &[OsString], cwd: &Path) -> io::Result<Output> {
344 111
    let mut command = Command::new("git");
345 112
    command
346 113
        .arg("diff")
347 114
        .args(args)
348 115
        .current_dir(cwd)
349 116
        .env("NO_COLOR", "1");
350 117
    command.output()
351 118
}
352 -
353 -
/// Binary error type.
354 -
#[derive(Debug)]
355 -
enum Error {
356 -
    /// I/O failed.
357 -
    Io(io::Error),
358 -
    /// Git returned a failing exit status.
359 -
    Git(i32),
360 -
    /// Diff parsing failed.
361 -
    Parse(DecodeError),
362 -
    /// Syntax highlighting setup failed.
363 -
    Highlight(syntax::Error),
364 -
}
365 -
366 -
impl From<io::Error> for Error {
367 -
    fn from(error: io::Error) -> Self {
368 -
        Self::Io(error)
369 -
    }
370 -
}
371 -
372 -
impl From<DecodeError> for Error {
373 -
    fn from(error: DecodeError) -> Self {
374 -
        Self::Parse(error)
375 -
    }
376 -
}
377 -
378 -
impl From<syntax::Error> for Error {
379 -
    fn from(error: syntax::Error) -> Self {
380 -
        Self::Highlight(error)
381 -
    }
382 -
}
383 -
384 -
impl From<ContextError> for Error {
385 -
    fn from(error: ContextError) -> Self {
386 -
        match error {
387 -
            ContextError::Repo(RepoError::Io(error)) => Self::Io(error),
388 -
            ContextError::Repo(RepoError::Status(code)) => Self::Git(code),
389 -
            ContextError::Decode(error) => Self::Parse(error),
390 -
        }
391 -
    }
392 -
}
393 -
394 -
impl std::fmt::Display for Error {
395 -
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396 -
        match self {
397 -
            Self::Io(error) => write!(f, "{error}"),
398 -
            Self::Git(code) => write!(f, "git diff exited with status {code}"),
399 -
            Self::Parse(error) => write!(f, "{error}"),
400 -
            Self::Highlight(error) => write!(f, "{error}"),
401 -
        }
402 -
    }
403 -
}
404 -
405 -
impl std::error::Error for Error {}
406 -
407 -
#[cfg(test)]
408 -
#[allow(clippy::unwrap_used)]
409 -
mod tests {
410 -
    use super::*;
411 -
412 -
    #[test]
413 -
    fn viewer_area_reserves_footer() {
414 -
        assert_eq!(
415 -
            viewer_area(Rect::new(0, 0, 80, 20)),
416 -
            Rect::new(0, 0, 80, 19)
417 -
        );
418 -
        assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0));
419 -
    }
420 -
421 -
    #[test]
422 -
    fn status_line_fills_footer_width() {
423 -
        assert_eq!(status_line(24).width(), 24);
424 -
    }
425 -
}
crates/diff/src/bin/rustik-diff/builtins.rs added +97 -0
1 +
//! Built-in highlighting assets for the pager binary.
2 +
3 +
use std::path::Path;
4 +
5 +
use rustik_diff::{BuiltinHighlighter, DiffDocument, DiffPalette};
6 +
use rustik_highlight as syntax;
7 +
8 +
/// Theme name used for built-in diff highlighting.
9 +
const THEME_NAME: &str = "rustik-catppuccin-mocha";
10 +
/// Built-in syntax theme JSON.
11 +
const THEME: &str = include_str!("../../themes/rustik-catppuccin-mocha.json");
12 +
/// Common syntax grammars loaded by the interactive pager.
13 +
const SYNTAXES: [SyntaxAsset; 1] = [SyntaxAsset {
14 +
    source: include_str!("../../syntaxes/rust.json"),
15 +
    file_types: &["rs"],
16 +
}];
17 +
18 +
/// Binary-local highlight assets loaded for one diff document.
19 +
pub(super) struct Builtins {
20 +
    /// Diff chrome palette derived from the built-in theme.
21 +
    pub(super) palette: DiffPalette,
22 +
    /// Highlighter with grammars relevant to the document.
23 +
    pub(super) highlighter: BuiltinHighlighter,
24 +
}
25 +
26 +
impl Builtins {
27 +
    /// Loads built-in highlighting assets for `document`.
28 +
    pub(super) fn load(document: &DiffDocument) -> Result<Self, syntax::Error> {
29 +
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
30 +
        let mut registry = syntax::Registry::default();
31 +
32 +
        registry.add_theme(syntax::Theme::compile(&raw_theme));
33 +
        for syntax in SYNTAXES
34 +
            .iter()
35 +
            .filter(|syntax| syntax.matches_document(document))
36 +
        {
37 +
            registry.add_grammar(syntax.grammar()?);
38 +
        }
39 +
40 +
        Ok(Self {
41 +
            palette: (&raw_theme).into(),
42 +
            highlighter: BuiltinHighlighter::new(registry, THEME_NAME),
43 +
        })
44 +
    }
45 +
}
46 +
47 +
/// Built-in syntax source and path aliases.
48 +
struct SyntaxAsset {
49 +
    /// TextMate grammar JSON source.
50 +
    source: &'static str,
51 +
    /// File names and extensions recognized by the registry.
52 +
    file_types: &'static [&'static str],
53 +
}
54 +
55 +
impl SyntaxAsset {
56 +
    /// Returns whether this syntax matches any path in a diff document.
57 +
    fn matches_document(&self, document: &DiffDocument) -> bool {
58 +
        document.files.iter().any(|file| {
59 +
            file.header
60 +
                .old_path
61 +
                .as_deref()
62 +
                .is_some_and(|path| self.matches_path(path))
63 +
                || file
64 +
                    .header
65 +
                    .new_path
66 +
                    .as_deref()
67 +
                    .is_some_and(|path| self.matches_path(path))
68 +
        })
69 +
    }
70 +
71 +
    /// Returns whether this syntax matches a file path.
72 +
    fn matches_path(&self, path: &Path) -> bool {
73 +
        let file_name = path.file_name().and_then(|name| name.to_str());
74 +
        let extension = path.extension().and_then(|extension| extension.to_str());
75 +
76 +
        self.file_types.iter().any(|file_type| {
77 +
            file_name.is_some_and(|name| name.eq_ignore_ascii_case(file_type))
78 +
                || extension.is_some_and(|extension| extension.eq_ignore_ascii_case(file_type))
79 +
        })
80 +
    }
81 +
82 +
    /// Parses this grammar and attaches local path aliases.
83 +
    fn grammar(&self) -> Result<syntax::Grammar, syntax::Error> {
84 +
        let mut raw: syntax::RawGrammar = self.source.parse()?;
85 +
86 +
        for file_type in self.file_types {
87 +
            if !raw
88 +
                .file_types
89 +
                .iter()
90 +
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
91 +
            {
92 +
                raw.file_types.push((*file_type).to_owned());
93 +
            }
94 +
        }
95 +
        syntax::Grammar::compile(&raw)
96 +
    }
97 +
}
crates/diff/src/bin/rustik-diff/error.rs added +61 -0
1 +
//! Error handling for the pager binary.
2 +
3 +
use std::io;
4 +
5 +
use rustik_diff::{ContextError, DecodeError};
6 +
use rustik_highlight as syntax;
7 +
use rustik_repo::RepoError;
8 +
9 +
/// Binary error type.
10 +
#[derive(Debug)]
11 +
pub(super) enum Error {
12 +
    /// I/O failed.
13 +
    Io(io::Error),
14 +
    /// Git returned a failing exit status.
15 +
    Git(i32),
16 +
    /// Diff parsing failed.
17 +
    Parse(DecodeError),
18 +
    /// Syntax highlighting setup failed.
19 +
    Highlight(syntax::Error),
20 +
}
21 +
22 +
impl From<io::Error> for Error {
23 +
    fn from(error: io::Error) -> Self {
24 +
        Self::Io(error)
25 +
    }
26 +
}
27 +
28 +
impl From<DecodeError> for Error {
29 +
    fn from(error: DecodeError) -> Self {
30 +
        Self::Parse(error)
31 +
    }
32 +
}
33 +
34 +
impl From<syntax::Error> for Error {
35 +
    fn from(error: syntax::Error) -> Self {
36 +
        Self::Highlight(error)
37 +
    }
38 +
}
39 +
40 +
impl From<ContextError> for Error {
41 +
    fn from(error: ContextError) -> Self {
42 +
        match error {
43 +
            ContextError::Repo(RepoError::Io(error)) => Self::Io(error),
44 +
            ContextError::Repo(RepoError::Status(code)) => Self::Git(code),
45 +
            ContextError::Decode(error) => Self::Parse(error),
46 +
        }
47 +
    }
48 +
}
49 +
50 +
impl std::fmt::Display for Error {
51 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 +
        match self {
53 +
            Self::Io(error) => write!(f, "{error}"),
54 +
            Self::Git(code) => write!(f, "git diff exited with status {code}"),
55 +
            Self::Parse(error) => write!(f, "{error}"),
56 +
            Self::Highlight(error) => write!(f, "{error}"),
57 +
        }
58 +
    }
59 +
}
60 +
61 +
impl std::error::Error for Error {}
crates/diff/src/bin/rustik-diff/session.rs added +200 -0
1 +
//! Terminal session loop for the pager binary.
2 +
3 +
use std::io;
4 +
use std::sync::mpsc;
5 +
use std::thread;
6 +
7 +
use rustik_diff::{
8 +
    BuiltinHighlighter, DiffHighlighter, DiffViewer, HighlightRequest, HighlightResult,
9 +
};
10 +
use rustik_repo::GitRepo;
11 +
use rustik_tui as tui;
12 +
use rustik_tui::{Color, Control, Event, Label, Line, Rect, Style, Terminal};
13 +
use rustik_tui_termion as tui_termion;
14 +
15 +
use crate::error::Error;
16 +
17 +
/// Number of rows reserved for the bottom footer when possible.
18 +
const FOOTER_ROWS: usize = 1;
19 +
/// Foreground color for dim footer text.
20 +
const FOOTER_FG: Color = Color::Fixed(240);
21 +
/// Background color for the footer row.
22 +
const FOOTER_BG: Color = Color::Fixed(233);
23 +
24 +
/// Terminal backend used by the interactive viewer.
25 +
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::StdoutScreen>>;
26 +
27 +
/// Runs the terminal event loop.
28 +
pub(super) fn run(
29 +
    terminal: &mut DiffTerminal,
30 +
    viewer: &mut DiffViewer,
31 +
    highlighter: BuiltinHighlighter,
32 +
    repo: Option<GitRepo>,
33 +
) -> Result<(), Error> {
34 +
    let (events_tx, events_rx) = mpsc::channel();
35 +
    TerminalEvent::spawn_input_worker(events_tx.clone());
36 +
37 +
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx, highlighter);
38 +
    let mut session = TerminalSession {
39 +
        terminal,
40 +
        viewer,
41 +
        repo,
42 +
        highlights_tx,
43 +
    };
44 +
    session.redraw()?;
45 +
46 +
    while let Ok(event) = events_rx.recv() {
47 +
        match event {
48 +
            TerminalEvent::Input(event) => {
49 +
                let event = event?;
50 +
                let area = viewer_area(session.terminal.area());
51 +
                let control = if let Some(repo) = session.repo.as_ref() {
52 +
                    session.viewer.handle_input_with_repo(event, area, repo)?
53 +
                } else {
54 +
                    session.viewer.handle_input(event, area)
55 +
                };
56 +
                match control {
57 +
                    Control::Quit => break,
58 +
                    Control::Redraw => session.redraw()?,
59 +
                    Control::Continue | Control::Wait => {}
60 +
                }
61 +
            }
62 +
            TerminalEvent::Highlights(results) => {
63 +
                if session.viewer.apply_highlights(results) {
64 +
                    session.redraw()?;
65 +
                }
66 +
            }
67 +
        }
68 +
    }
69 +
    Ok(())
70 +
}
71 +
72 +
/// Interactive terminal session state.
73 +
struct TerminalSession<'a> {
74 +
    /// Terminal frame target.
75 +
    terminal: &'a mut DiffTerminal,
76 +
    /// Diff viewer state.
77 +
    viewer: &'a mut DiffViewer,
78 +
    /// Git-backed diff repo, present when the input came from Git.
79 +
    repo: Option<GitRepo>,
80 +
    /// Visible-row highlight request channel.
81 +
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
82 +
}
83 +
84 +
impl TerminalSession<'_> {
85 +
    /// Draws a frame and requests highlights for visible rows.
86 +
    fn redraw(&mut self) -> io::Result<()> {
87 +
        self.draw_frame()?;
88 +
        self.request_visible_highlights();
89 +
        Ok(())
90 +
    }
91 +
92 +
    /// Requests highlight work for currently visible rows.
93 +
    fn request_visible_highlights(&mut self) {
94 +
        let area = viewer_area(self.terminal.area());
95 +
        let requests = self.viewer.highlight_requests(area);
96 +
        if !requests.is_empty() {
97 +
            let _ = self.highlights_tx.send(requests);
98 +
        }
99 +
    }
100 +
101 +
    /// Draws one terminal frame without scheduling highlight work.
102 +
    fn draw_frame(&mut self) -> io::Result<()> {
103 +
        self.terminal.draw(|frame| {
104 +
            let body = viewer_area(frame.area);
105 +
            frame.render_widget(&mut *self.viewer, body);
106 +
            draw_status(frame);
107 +
        })
108 +
    }
109 +
}
110 +
111 +
/// Event delivered to the terminal loop.
112 +
enum TerminalEvent {
113 +
    /// Terminal input event.
114 +
    Input(io::Result<Event<()>>),
115 +
    /// Background highlight results.
116 +
    Highlights(Vec<HighlightResult>),
117 +
}
118 +
119 +
impl TerminalEvent {
120 +
    /// Spawns the blocking input reader.
121 +
    fn spawn_input_worker(tx: mpsc::Sender<Self>) {
122 +
        thread::spawn(move || {
123 +
            for event in tui_termion::term::events() {
124 +
                if tx.send(Self::Input(event)).is_err() {
125 +
                    break;
126 +
                }
127 +
            }
128 +
        });
129 +
    }
130 +
131 +
    /// Spawns the visible-row highlight worker.
132 +
    fn spawn_highlight_worker(
133 +
        tx: mpsc::Sender<Self>,
134 +
        mut highlighter: BuiltinHighlighter,
135 +
    ) -> mpsc::Sender<Vec<HighlightRequest>> {
136 +
        let (requests_tx, requests_rx) = mpsc::channel::<Vec<HighlightRequest>>();
137 +
        thread::spawn(move || {
138 +
            while let Ok(requests) = requests_rx.recv() {
139 +
                if requests.is_empty() {
140 +
                    continue;
141 +
                }
142 +
                let results = highlighter.highlight_batch(requests);
143 +
                if tx.send(Self::Highlights(results)).is_err() {
144 +
                    break;
145 +
                }
146 +
            }
147 +
        });
148 +
        requests_tx
149 +
    }
150 +
}
151 +
152 +
/// Returns the viewer area above the footer chrome.
153 +
fn viewer_area(area: Rect) -> Rect {
154 +
    let footer_rows = FOOTER_ROWS.min(area.rows);
155 +
156 +
    Rect::new(
157 +
        area.x,
158 +
        area.y,
159 +
        area.cols,
160 +
        area.rows.saturating_sub(footer_rows),
161 +
    )
162 +
}
163 +
164 +
/// Draws the bottom status row.
165 +
fn draw_status(frame: &mut tui::Frame<'_>) {
166 +
    let area = frame.area;
167 +
    if area.rows == 0 {
168 +
        return;
169 +
    }
170 +
    let row = Rect::new(area.x, area.bottom().saturating_sub(1), area.cols, 1);
171 +
172 +
    frame.render_widget(status_line(area.cols), row);
173 +
}
174 +
175 +
/// Returns the padded bottom status line.
176 +
fn status_line(cols: usize) -> Line {
177 +
    Line::new(Label::new("rustik-diff").fg(FOOTER_FG))
178 +
        .style(Style::default().bg(FOOTER_BG))
179 +
        .padded(cols)
180 +
}
181 +
182 +
#[cfg(test)]
183 +
#[allow(clippy::unwrap_used)]
184 +
mod tests {
185 +
    use super::*;
186 +
187 +
    #[test]
188 +
    fn viewer_area_reserves_footer() {
189 +
        assert_eq!(
190 +
            viewer_area(Rect::new(0, 0, 80, 20)),
191 +
            Rect::new(0, 0, 80, 19)
192 +
        );
193 +
        assert_eq!(viewer_area(Rect::new(0, 0, 80, 1)), Rect::new(0, 0, 80, 0));
194 +
    }
195 +
196 +
    #[test]
197 +
    fn status_line_fills_footer_width() {
198 +
        assert_eq!(status_line(24).width(), 24);
199 +
    }
200 +
}
crates/diff/src/highlight.rs +12 -0
81 81
    registry: syntax::Registry,
82 82
    /// Theme used when requests ask for automatic theme selection.
83 83
    default_theme: String,
84 84
}
85 85
86 +
/// Highlights diff rows requested by a [`crate::DiffViewer`].
87 +
pub trait DiffHighlighter {
88 +
    /// Highlights one batch of visible diff rows.
89 +
    fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult>;
90 +
}
91 +
86 92
/// Grouping key for requests that can share one range highlighter.
87 93
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
88 94
struct HighlightBatchKey {
89 95
    /// File containing the requested rows.
90 96
    file: FileId,
245 251
            })
246 252
            .collect()
247 253
    }
248 254
}
249 255
256 +
impl DiffHighlighter for BuiltinHighlighter {
257 +
    fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
258 +
        self.highlight_requests(requests).collect()
259 +
    }
260 +
}
261 +
250 262
impl HighlightRequest {
251 263
    /// Returns the unhighlighted source row for this request.
252 264
    fn plain_line(&self) -> Line {
253 265
        self.source
254 266
            .line(self.key.source_line)
crates/diff/src/lib.rs +2 -2
25 25
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
26 26
    FileMode, FileStats, Hunk, HunkHeader, HunkId, Oid, OidError, RowId, Stats,
27 27
};
28 28
pub use encode::Encode;
29 29
pub use highlight::{
30 -
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
31 -
    HighlightResult, HighlightSource,
30 +
    BuiltinHighlighter, DiffHighlighter, DiffSide, HighlightKey, HighlightKeyInput,
31 +
    HighlightRequest, HighlightResult, HighlightSource,
32 32
};
33 33
pub use viewer::{
34 34
    ContextError, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane, DiffState, DiffViewer,
35 35
    FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
36 36
};
crates/diff/src/viewer.rs +17 -1
16 16
    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
17 17
    VStack, View, Viewport, Widget, colors,
18 18
};
19 19
20 20
use crate::context::{ContextChange, ContextState};
21 -
use crate::highlight::{HighlightKeyInput, HighlightResult};
21 +
use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
22 22
use crate::word;
23 23
use crate::{
24 24
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
25 25
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
26 26
};
923 923
            changed = true;
924 924
        }
925 925
        changed
926 926
    }
927 927
928 +
    /// Highlights currently visible source rows through `highlighter`.
929 +
    ///
930 +
    /// Event-loop owners can still use [`Self::highlight_requests`] and
931 +
    /// [`Self::apply_highlights`] directly when highlight work runs
932 +
    /// asynchronously.
933 +
    pub fn apply_visible_highlights<H>(&mut self, area: Rect, highlighter: &mut H) -> bool
934 +
    where
935 +
        H: DiffHighlighter + ?Sized,
936 +
    {
937 +
        let requests = self.highlight_requests(area);
938 +
        if requests.is_empty() {
939 +
            return false;
940 +
        }
941 +
        self.apply_highlights(highlighter.highlight_batch(requests))
942 +
    }
943 +
928 944
    /// Returns whether `file` is shown in the main diff pane.
929 945
    fn file_visible(&self, file: FileId) -> bool {
930 946
        self.state.file_selection.contains(file)
931 947
    }
932 948
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0