diff: Move pager work out of terminal loop

043c8c95fdb5d3f1932869e91bb6d9216ed81da1
Run Git-backed context refetches and syntax highlighting on the pager
worker so redraw and input handling stay nonblocking. Load grammar
assets in that worker as well.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 10000371
crates/diff/src/bin/rustik-diff.rs +3 -2
66 66
            io::stdout().write_all(input)?;
67 67
            return Ok(());
68 68
        }
69 69
        Err(error) => return Err(Error::Parse(error)),
70 70
    };
71 -
    let assets = Builtins::load(&document)?;
71 +
    let assets = Builtins::load()?;
72 72
    let mut options = DiffOptions {
73 73
        diff_palette: assets.palette,
74 74
        ..DiffOptions::default()
75 75
    };
76 76
91 91
    options.file_tree = FileTreeMode::Auto;
92 92
    options.file_tree_root = root;
93 93
94 94
    let backend = tui_termion::term::screen()?;
95 95
    let mut terminal = Terminal::new(backend)?;
96 +
    let highlight_document = document.clone();
96 97
    let mut viewer = DiffViewer::new(document, options);
97 98
98 99
    terminal.clear()?;
99 100
    terminal.set_cursor_visible(false)?;
100 101
101 102
    let repo = args.map(|args| GitRepo::new(cwd, args));
102 -
    let result = session::run(&mut terminal, &mut viewer, assets.highlighter, repo);
103 +
    let result = session::run(&mut terminal, &mut viewer, highlight_document, repo);
103 104
    let cursor = terminal.set_cursor_visible(true);
104 105
105 106
    result?;
106 107
    cursor.map_err(Error::Io)
107 108
}
crates/diff/src/bin/rustik-diff/builtins.rs +14 -8
100 100
101 101
/// Binary-local highlight assets loaded for one diff document.
102 102
pub(super) struct Builtins {
103 103
    /// Diff chrome palette derived from the built-in theme.
104 104
    pub(super) palette: DiffPalette,
105 -
    /// Highlighter with grammars relevant to the document.
106 -
    pub(super) highlighter: BuiltinHighlighter,
107 105
}
108 106
109 107
impl Builtins {
110 -
    /// Loads built-in highlighting assets for `document`.
111 -
    pub(super) fn load(document: &DiffDocument) -> Result<Self, syntax::Error> {
108 +
    /// Loads the built-in diff chrome assets.
109 +
    pub(super) fn load() -> Result<Self, syntax::Error> {
110 +
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
111 +
112 +
        Ok(Self {
113 +
            palette: (&raw_theme).into(),
114 +
        })
115 +
    }
116 +
117 +
    /// Loads a highlighter with grammars relevant to `document`.
118 +
    pub(super) fn highlighter(
119 +
        document: &DiffDocument,
120 +
    ) -> Result<BuiltinHighlighter, syntax::Error> {
112 121
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
113 122
        let mut registry = syntax::Registry::default();
114 123
115 124
        registry.add_theme(syntax::Theme::compile(&raw_theme));
116 125
        for syntax in SYNTAXES
118 127
            .filter(|syntax| syntax.matches_document(document))
119 128
        {
120 129
            registry.add_grammar(syntax.grammar()?);
121 130
        }
122 131
123 -
        Ok(Self {
124 -
            palette: (&raw_theme).into(),
125 -
            highlighter: BuiltinHighlighter::new(registry, THEME_NAME),
126 -
        })
132 +
        Ok(BuiltinHighlighter::new(registry, THEME_NAME))
127 133
    }
128 134
}
129 135
130 136
/// Built-in syntax source and path aliases.
131 137
struct SyntaxAsset {
crates/diff/src/bin/rustik-diff/error.rs +1 -12
1 1
//! Error handling for the pager binary.
2 2
3 3
use std::io;
4 4
5 -
use rustik_diff::{ContextError, DecodeError};
5 +
use rustik_diff::DecodeError;
6 6
use rustik_highlight as syntax;
7 -
use rustik_repo::RepoError;
8 7
9 8
/// Binary error type.
10 9
#[derive(Debug)]
11 10
pub(super) enum Error {
12 11
    /// I/O failed.
35 34
    fn from(error: syntax::Error) -> Self {
36 35
        Self::Highlight(error)
37 36
    }
38 37
}
39 38
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 39
impl std::fmt::Display for Error {
51 40
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52 41
        match self {
53 42
            Self::Io(error) => write!(f, "{error}"),
54 43
            Self::Git(code) => write!(f, "git diff exited with status {code}"),
crates/diff/src/bin/rustik-diff/session.rs +205 -35
1 1
//! Terminal session loop for the pager binary.
2 2
3 +
use std::collections::{BTreeMap, BTreeSet};
3 4
use std::io;
4 5
use std::sync::mpsc::{self, SyncSender, TrySendError};
5 6
use std::thread;
6 7
7 8
use rustik_diff::{
8 -
    BuiltinHighlighter, DiffHighlighter, DiffViewer, HighlightRequest, HighlightResult,
9 +
    BuiltinHighlighter, ContextChange, ContextRequest, ContextUpdate, Decode, DiffDocument,
10 +
    DiffHighlighter, DiffSide, DiffViewer, FileId, HighlightRequest, HighlightResult,
11 +
    HighlightSource,
9 12
};
10 -
use rustik_repo::GitRepo;
13 +
use rustik_repo::{GitRepo, Repo};
11 14
use rustik_tui as tui;
12 -
use rustik_tui::{Color, Control, Event, Label, Line, Rect, Style, Terminal};
15 +
use rustik_tui::{
16 +
    Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Style, Terminal,
17 +
};
13 18
use rustik_tui_termion as tui_termion;
19 +
use tui::event::Modifiers;
14 20
21 +
use crate::builtins::Builtins;
15 22
use crate::error::Error;
16 23
17 24
/// Number of rows reserved for the bottom footer when possible.
18 25
const FOOTER_ROWS: usize = 1;
19 26
/// Foreground color for dim footer text.
20 27
const FOOTER_FG: Color = Color::Fixed(240);
21 28
/// Background color for the footer row.
22 29
const FOOTER_BG: Color = Color::Fixed(233);
30 +
/// Unified context width used for full-file highlight context.
31 +
const HIGHLIGHT_CONTEXT_LINES: usize = 999_999;
23 32
24 33
/// Terminal backend used by the interactive viewer.
25 34
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
26 35
27 36
/// Runs the terminal event loop.
28 37
pub(super) fn run(
29 38
    terminal: &mut DiffTerminal,
30 39
    viewer: &mut DiffViewer,
31 -
    highlighter: BuiltinHighlighter,
40 +
    document: DiffDocument,
32 41
    repo: Option<GitRepo>,
33 42
) -> Result<(), Error> {
34 43
    let (events_tx, events_rx) = mpsc::channel();
35 44
    TerminalEvent::spawn_input_worker(events_tx.clone());
36 45
37 -
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx, highlighter);
46 +
    let worker_tx = TerminalEvent::spawn_worker(events_tx, document, repo);
38 47
    let mut session = TerminalSession {
39 48
        terminal,
40 49
        viewer,
41 -
        repo,
42 -
        highlights_tx,
50 +
        worker_tx,
51 +
        context_pending: false,
43 52
    };
44 53
    session.redraw()?;
45 54
46 55
    while let Ok(event) = events_rx.recv() {
47 56
        let mut redraw = false;
64 73
struct TerminalSession<'a> {
65 74
    /// Terminal frame target.
66 75
    terminal: &'a mut DiffTerminal,
67 76
    /// Diff viewer state.
68 77
    viewer: &'a mut DiffViewer,
69 -
    /// Git-backed diff repo, present when the input came from direct Git args.
70 -
    repo: Option<GitRepo>,
71 -
    /// Visible-row highlight request channel.
72 -
    highlights_tx: SyncSender<Vec<HighlightRequest>>,
78 +
    /// Background worker command channel.
79 +
    worker_tx: SyncSender<WorkerCommand>,
80 +
    /// Whether a context refetch is already in flight.
81 +
    context_pending: bool,
73 82
}
74 83
75 84
impl TerminalSession<'_> {
76 85
    /// Applies one event and records whether the session should redraw.
77 86
    fn update(&mut self, event: TerminalEvent, redraw: &mut bool) -> Result<Control, Error> {
78 87
        match event {
79 88
            TerminalEvent::Input(event) => {
80 89
                let event = event?;
81 90
                let resized = matches!(event, Event::Resize(_));
82 91
                let area = viewer_area(self.terminal.area());
83 -
                let control = if let Some(repo) = self.repo.as_ref() {
84 -
                    self.viewer.handle_input_with_repo(event, area, repo)?
85 -
                } else {
86 -
                    self.viewer.handle_input(event, area)
87 -
                };
92 +
                if let Some(change) = context_change(&event) {
93 +
                    self.request_context(change);
94 +
                    return Ok(Control::Continue);
95 +
                }
96 +
                let control = self.viewer.handle_input(event, area);
88 97
                if control == Control::Redraw || (resized && control != Control::Quit) {
89 98
                    *redraw = true;
90 99
                }
91 100
                Ok(control)
92 101
            }
93 102
            TerminalEvent::Highlights(results) => {
94 103
                *redraw |= self.viewer.apply_highlights(results);
95 104
                Ok(Control::Continue)
96 105
            }
106 +
            TerminalEvent::Context(update) => {
107 +
                self.context_pending = false;
108 +
                if let Some(update) = update {
109 +
                    let area = viewer_area(self.terminal.area());
110 +
                    self.viewer.apply_context_update(update, area);
111 +
                    *redraw = true;
112 +
                }
113 +
                Ok(Control::Continue)
114 +
            }
97 115
        }
98 116
    }
99 117
100 118
    /// Draws a frame and requests highlights for visible rows.
101 119
    fn redraw(&mut self) -> io::Result<()> {
105 123
    }
106 124
107 125
    /// Requests highlight work for currently visible rows.
108 126
    fn request_visible_highlights(&mut self) {
109 127
        let area = viewer_area(self.terminal.area());
110 -
        let requests = if let Some(repo) = self.repo.as_ref() {
111 -
            self.viewer.highlight_requests_with_repo(area, repo)
112 -
        } else {
113 -
            self.viewer.highlight_requests(area)
114 -
        };
128 +
        let requests = self.viewer.highlight_requests(area);
115 129
        if !requests.is_empty() {
116 -
            match self.highlights_tx.try_send(requests) {
130 +
            match self.worker_tx.try_send(WorkerCommand::Highlight(requests)) {
117 131
                Ok(()) => {}
118 -
                Err(TrySendError::Full(requests) | TrySendError::Disconnected(requests)) => {
132 +
                Err(
133 +
                    TrySendError::Full(WorkerCommand::Highlight(requests))
134 +
                    | TrySendError::Disconnected(WorkerCommand::Highlight(requests)),
135 +
                ) => {
119 136
                    self.viewer.cancel_highlights(requests);
120 137
                }
138 +
                Err(
139 +
                    TrySendError::Full(WorkerCommand::Context(_))
140 +
                    | TrySendError::Disconnected(WorkerCommand::Context(_)),
141 +
                ) => {}
121 142
            }
122 143
        }
123 144
    }
124 145
146 +
    /// Requests context refetch work for one context change.
147 +
    fn request_context(&mut self, change: ContextChange) {
148 +
        if self.context_pending {
149 +
            return;
150 +
        }
151 +
        let Some(request) = self.viewer.context_request(change) else {
152 +
            return;
153 +
        };
154 +
        match self.worker_tx.try_send(WorkerCommand::Context(request)) {
155 +
            Ok(()) => self.context_pending = true,
156 +
            Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => {}
157 +
        }
158 +
    }
159 +
125 160
    /// Draws one terminal frame without scheduling highlight work.
126 161
    fn draw_frame(&mut self) -> io::Result<()> {
127 162
        self.terminal.draw(|frame| {
128 163
            let body = viewer_area(frame.area);
129 164
            frame.render_widget(&mut *self.viewer, body);
136 171
enum TerminalEvent {
137 172
    /// Terminal input event.
138 173
    Input(io::Result<Event<()>>),
139 174
    /// Background highlight results.
140 175
    Highlights(Vec<HighlightResult>),
176 +
    /// Background context update result.
177 +
    Context(Option<ContextUpdate>),
178 +
}
179 +
180 +
/// Background worker command.
181 +
enum WorkerCommand {
182 +
    /// Highlight visible source rows.
183 +
    Highlight(Vec<HighlightRequest>),
184 +
    /// Refetch and decode a context update.
185 +
    Context(ContextRequest),
186 +
}
187 +
188 +
/// Background worker for blocking repo and syntax-highlighting work.
189 +
struct HighlightWorker {
190 +
    /// Built-in syntax highlighter.
191 +
    highlighter: BuiltinHighlighter,
192 +
    /// Git-backed repo used for direct Git invocations.
193 +
    repo: Option<GitRepo>,
194 +
    /// Full-file highlight source cache keyed by diff file and side.
195 +
    full_sources: BTreeMap<(FileId, DiffSide), HighlightSource>,
196 +
}
197 +
198 +
impl HighlightWorker {
199 +
    /// Creates a background worker.
200 +
    fn new(document: &DiffDocument, repo: Option<GitRepo>) -> Self {
201 +
        Self {
202 +
            highlighter: Builtins::highlighter(document)
203 +
                .unwrap_or_else(|_| BuiltinHighlighter::new(Default::default(), "")),
204 +
            repo,
205 +
            full_sources: BTreeMap::new(),
206 +
        }
207 +
    }
208 +
209 +
    /// Highlights one batch after enriching it with repo-backed context.
210 +
    fn highlight(&mut self, mut requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
211 +
        self.load_full_sources(&requests);
212 +
        for request in &mut requests {
213 +
            let key = (request.key.file, request.key.side);
214 +
            if let Some(source) = self.full_sources.get(&key)
215 +
                && source.line(request.key.source_line)
216 +
                    == request.source.line(request.key.source_line)
217 +
            {
218 +
                request.source = source.clone();
219 +
            }
220 +
        }
221 +
        self.highlighter.highlight_batch(requests)
222 +
    }
223 +
224 +
    /// Loads full-file source context for uncached request paths.
225 +
    fn load_full_sources(&mut self, requests: &[HighlightRequest]) {
226 +
        let Some(repo) = self.repo.as_ref() else {
227 +
            return;
228 +
        };
229 +
        let mut targets = BTreeMap::new();
230 +
        for request in requests {
231 +
            let key = (request.key.file, request.key.side);
232 +
            if self.full_sources.contains_key(&key) {
233 +
                continue;
234 +
            }
235 +
            if let Some(path) = request.path.as_deref() {
236 +
                targets.insert((path.to_path_buf(), request.key.side), request.key.file);
237 +
            }
238 +
        }
239 +
        if targets.is_empty() {
240 +
            return;
241 +
        }
242 +
243 +
        let paths = targets
244 +
            .keys()
245 +
            .map(|(path, _)| path.as_path())
246 +
            .collect::<BTreeSet<_>>()
247 +
            .into_iter()
248 +
            .collect::<Vec<_>>();
249 +
        let Ok(patch) = repo.diff(HIGHLIGHT_CONTEXT_LINES, &paths) else {
250 +
            return;
251 +
        };
252 +
        let Ok(document) = DiffDocument::decode_bytes(&patch) else {
253 +
            return;
254 +
        };
255 +
256 +
        for file in &document.files {
257 +
            for side in [DiffSide::Old, DiffSide::New] {
258 +
                let Some(path) = file.source_path(side) else {
259 +
                    continue;
260 +
                };
261 +
                let Some(file_id) = targets.get(&(path, side)).copied() else {
262 +
                    continue;
263 +
                };
264 +
                let Some(source) = file.highlight_source(side) else {
265 +
                    continue;
266 +
                };
267 +
                self.full_sources.insert((file_id, side), source);
268 +
            }
269 +
        }
270 +
    }
271 +
272 +
    /// Refetches and decodes one context update.
273 +
    fn context(&mut self, request: ContextRequest) -> Option<ContextUpdate> {
274 +
        let repo = self.repo.as_ref()?;
275 +
        let paths = request.paths().collect::<Vec<_>>();
276 +
        let patch = repo.diff(request.context_lines(), &paths).ok()?;
277 +
        drop(paths);
278 +
        request.decode(&patch).ok().flatten()
279 +
    }
141 280
}
142 281
143 282
impl TerminalEvent {
144 283
    /// Spawns the blocking input reader.
145 284
    fn spawn_input_worker(tx: mpsc::Sender<Self>) {
150 289
                }
151 290
            }
152 291
        });
153 292
    }
154 293
155 -
    /// Spawns the visible-row highlight worker.
156 -
    fn spawn_highlight_worker(
294 +
    /// Spawns the blocking background worker.
295 +
    fn spawn_worker(
157 296
        tx: mpsc::Sender<Self>,
158 -
        mut highlighter: BuiltinHighlighter,
159 -
    ) -> SyncSender<Vec<HighlightRequest>> {
160 -
        let (requests_tx, requests_rx) = mpsc::sync_channel::<Vec<HighlightRequest>>(0);
297 +
        document: DiffDocument,
298 +
        repo: Option<GitRepo>,
299 +
    ) -> SyncSender<WorkerCommand> {
300 +
        let (requests_tx, requests_rx) = mpsc::sync_channel::<WorkerCommand>(4);
161 301
        thread::spawn(move || {
162 -
            while let Ok(requests) = requests_rx.recv() {
163 -
                if requests.is_empty() {
164 -
                    continue;
165 -
                }
166 -
                let results = highlighter.highlight_batch(requests);
167 -
                if tx.send(Self::Highlights(results)).is_err() {
168 -
                    break;
302 +
            let mut worker = HighlightWorker::new(&document, repo);
303 +
            while let Ok(command) = requests_rx.recv() {
304 +
                match command {
305 +
                    WorkerCommand::Highlight(requests) => {
306 +
                        if requests.is_empty() {
307 +
                            continue;
308 +
                        }
309 +
                        let results = worker.highlight(requests);
310 +
                        if tx.send(Self::Highlights(results)).is_err() {
311 +
                            break;
312 +
                        }
313 +
                    }
314 +
                    WorkerCommand::Context(request) => {
315 +
                        if tx.send(Self::Context(worker.context(request))).is_err() {
316 +
                            break;
317 +
                        }
318 +
                    }
169 319
                }
170 320
            }
171 321
        });
172 322
        requests_tx
173 323
    }
174 324
}
175 325
326 +
/// Returns the context change represented by an input event.
327 +
fn context_change(event: &Event<()>) -> Option<ContextChange> {
328 +
    match event {
329 +
        Event::Key(Key::Char('.')) => Some(ContextChange::Increase),
330 +
        Event::Mouse(Mouse::Press {
331 +
            button: MouseButton::WheelUp,
332 +
            modifiers,
333 +
            ..
334 +
        }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Increase),
335 +
        Event::Key(Key::Char(',')) => Some(ContextChange::Decrease),
336 +
        Event::Mouse(Mouse::Press {
337 +
            button: MouseButton::WheelDown,
338 +
            modifiers,
339 +
            ..
340 +
        }) if modifiers.contains(Modifiers::CONTROL) => Some(ContextChange::Decrease),
341 +
        Event::Key(Key::Char('x')) => Some(ContextChange::ToggleFile),
342 +
        _ => None,
343 +
    }
344 +
}
345 +
176 346
/// Returns the viewer area above the footer chrome.
177 347
fn viewer_area(area: Rect) -> Rect {
178 348
    let footer_rows = FOOTER_ROWS.min(area.rows);
179 349
180 350
    Rect::new(
crates/diff/src/context.rs +35 -42
23 23
    context_lines: usize,
24 24
    /// Files currently expanded to their full source.
25 25
    expanded_files: BTreeSet<FileId>,
26 26
}
27 27
28 +
/// Planned context refetch for a set of files.
29 +
#[derive(Clone, Debug)]
30 +
pub(crate) struct ContextPlan {
31 +
    /// Context state to install after a successful refetch.
32 +
    pub(crate) state: ContextState,
33 +
    /// Git context width to request.
34 +
    pub(crate) context_lines: usize,
35 +
    /// Paths and file ids to refetch.
36 +
    pub(crate) files: Vec<(PathBuf, FileId)>,
37 +
}
38 +
28 39
/// Change to the requested hunk context.
29 40
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30 -
pub(crate) enum ContextChange {
41 +
pub enum ContextChange {
31 42
    /// Show one more unchanged line around each changed group.
32 43
    Increase,
33 44
    /// Show one fewer unchanged line around each changed group.
34 45
    Decrease,
35 46
    /// Toggle selected file(s) between bounded hunks and full source.
43 54
            context_lines: DEFAULT_CONTEXT_LINES,
44 55
            expanded_files: BTreeSet::new(),
45 56
        }
46 57
    }
47 58
48 -
    /// Applies one context change, refetching replacement diffs via `fetch`.
49 -
    ///
50 -
    /// `fetch` is invoked with the target context width and the affected file paths. Returns `None`
51 -
    /// when the input changes nothing. On failure the requested state is rolled back.
52 -
    pub(crate) fn apply<F, E>(
53 -
        &mut self,
59 +
    /// Returns the refetch needed for a context change without mutating state.
60 +
    pub(crate) fn plan(
61 +
        &self,
54 62
        change: ContextChange,
55 63
        file_ids: &[FileId],
56 64
        document: &DiffDocument,
57 -
        fetch: F,
58 -
    ) -> Result<Option<Vec<FileDiff>>, E>
59 -
    where
60 -
        F: FnOnce(usize, &[&Path]) -> Result<Vec<FileDiff>, E>,
61 -
    {
62 -
        if file_ids.is_empty() {
63 -
            return Ok(None);
64 -
        }
65 -
        let prev_context_lines = self.context_lines;
66 -
        let prev_expanded_files = self.expanded_files.clone();
65 +
    ) -> Option<ContextPlan> {
66 +
        let mut next = self.clone();
67 67
68 68
        match change {
69 -
            ContextChange::Increase => self.context_lines = self.context_lines.saturating_add(1),
69 +
            ContextChange::Increase => next.context_lines = next.context_lines.saturating_add(1),
70 70
            ContextChange::Decrease => {
71 -
                let Some(lines) = self.context_lines.checked_sub(1) else {
72 -
                    return Ok(None);
73 -
                };
74 -
                self.context_lines = lines;
71 +
                next.context_lines = next.context_lines.checked_sub(1)?;
75 72
            }
76 73
            ContextChange::ToggleFile => {
77 74
                let all_expanded = file_ids
78 75
                    .iter()
79 -
                    .all(|file_id| self.expanded_files.contains(file_id));
76 +
                    .all(|file_id| next.expanded_files.contains(file_id));
80 77
81 78
                for file_id in file_ids.iter().copied() {
82 79
                    if all_expanded {
83 -
                        self.expanded_files.remove(&file_id);
80 +
                        next.expanded_files.remove(&file_id);
84 81
                    } else {
85 -
                        self.expanded_files.insert(file_id);
82 +
                        next.expanded_files.insert(file_id);
86 83
                    }
87 84
                }
88 85
            }
89 86
        }
90 -
        let mut target_context: Option<usize> = None;
87 +
88 +
        let mut target_context = None;
91 89
        let mut files = Vec::with_capacity(file_ids.len());
92 90
93 91
        for file_id in file_ids.iter().copied() {
94 92
            let Some(file) = document
95 93
                .files
99 97
                continue;
100 98
            };
101 99
            let Some(path) = file.path() else {
102 100
                continue;
103 101
            };
104 -
            let previous = Self::context_size(&prev_expanded_files, file_id, prev_context_lines);
105 -
            let target = Self::context_size(&self.expanded_files, file_id, self.context_lines);
102 +
            let previous = Self::context_size(&self.expanded_files, file_id, self.context_lines);
103 +
            let target = Self::context_size(&next.expanded_files, file_id, next.context_lines);
106 104
            if previous == target {
107 105
                continue;
108 106
            }
109 -
            // Every file touched by one input shares the same target context.
110 107
            debug_assert!(target_context.is_none_or(|shared| shared == target));
111 108
112 109
            target_context = Some(target);
113 110
            files.push((path.to_path_buf(), file_id));
114 111
        }
115 -
        let Some(target_context) = target_context else {
116 -
            return Ok(None);
117 -
        };
118 112
119 -
        let result = rebuild(next_ids(&document.files), &files, target_context, fetch);
120 -
        if !matches!(result, Ok(Some(_))) {
121 -
            self.context_lines = prev_context_lines;
122 -
            self.expanded_files = prev_expanded_files;
123 -
        }
124 -
        result
113 +
        Some(ContextPlan {
114 +
            state: next,
115 +
            context_lines: target_context?,
116 +
            files,
117 +
        })
125 118
    }
126 119
127 120
    /// Returns the Git context size for a file given the active expansion set.
128 121
    fn context_size(expanded: &BTreeSet<FileId>, file: FileId, default: usize) -> usize {
129 122
        if expanded.contains(&file) {
140 133
    }
141 134
}
142 135
143 136
impl FileDiff {
144 137
    /// Returns the diff path recorded for this file, preferring the new path.
145 -
    fn path(&self) -> Option<&Path> {
138 +
    pub(crate) fn path(&self) -> Option<&Path> {
146 139
        self.header
147 140
            .new_path
148 141
            .as_deref()
149 142
            .or(self.header.old_path.as_deref())
150 143
    }
151 144
152 145
    /// Replaces local hunk and row ids after per-file document replacement.
153 -
    fn remap_ids(&mut self, next_hunk_id: &mut usize, next_row_id: &mut usize) {
146 +
    pub(crate) fn remap_ids(&mut self, next_hunk_id: &mut usize, next_row_id: &mut usize) {
154 147
        for hunk in &mut self.hunks {
155 148
            hunk.id = HunkId::new(*next_hunk_id);
156 149
            *next_hunk_id += 1;
157 150
158 151
            for line in &mut hunk.lines {
164 157
}
165 158
166 159
/// Refetches `files` at `target_context_lines` and remaps their ids.
167 160
///
168 161
/// Returns `None` when Git's output does not cover every requested file.
169 -
fn rebuild<F, E>(
162 +
pub(crate) fn rebuild<F, E>(
170 163
    next_ids: (usize, usize),
171 164
    files: &[(PathBuf, FileId)],
172 165
    target_context_lines: usize,
173 166
    fetch: F,
174 167
) -> Result<Option<Vec<FileDiff>>, E>
200 193
    }
201 194
    Ok(Some(rebuilt))
202 195
}
203 196
204 197
/// Returns the next hunk and row ids after existing content.
205 -
fn next_ids(files: &[FileDiff]) -> (usize, usize) {
198 +
pub(crate) fn next_ids(files: &[FileDiff]) -> (usize, usize) {
206 199
    let mut next_hunk_id = 0;
207 200
    let mut next_row_id = 0;
208 201
209 202
    for file in files {
210 203
        for hunk in &file.hunks {
a.txt +0 -0
a.txt +0 -0
crates/diff/src/highlight.rs +81 -1
7 7
8 8
use rustik_highlight as syntax;
9 9
use rustik_tui as tui;
10 10
use rustik_tui::{Color, Label, Line, Style};
11 11
12 -
use crate::{FileId, HunkId, RowId};
12 +
use crate::{DiffLine, FileDiff, FileId, Hunk, HunkId, RowId};
13 13
14 14
/// Side of the diff used as syntax-highlighting source context.
15 15
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
16 16
pub enum DiffSide {
17 17
    /// Old side of a deleted or context line.
162 162
            head: self.head,
163 163
        }
164 164
    }
165 165
}
166 166
167 +
impl Hunk {
168 +
    /// Builds contiguous source text for one hunk side.
169 +
    pub fn highlight_source(&self, side: DiffSide) -> HighlightSource {
170 +
        let mut text = String::new();
171 +
        push_hunk_source_lines(self, side, &mut text);
172 +
        HighlightSource::new(text, hunk_head(self, side))
173 +
    }
174 +
}
175 +
176 +
impl FileDiff {
177 +
    /// Returns the source path for a file side, falling back to the other side.
178 +
    pub fn source_path(&self, side: DiffSide) -> Option<PathBuf> {
179 +
        let (primary, fallback) = match side {
180 +
            DiffSide::Old => (&self.header.old_path, &self.header.new_path),
181 +
            DiffSide::New => (&self.header.new_path, &self.header.old_path),
182 +
        };
183 +
        primary.clone().or_else(|| fallback.clone())
184 +
    }
185 +
186 +
    /// Builds contiguous source text for one file side.
187 +
    ///
188 +
    /// Returns `None` when the file's hunks are not contiguous on `side`.
189 +
    pub fn highlight_source(&self, side: DiffSide) -> Option<HighlightSource> {
190 +
        let mut text = String::new();
191 +
        let mut head = None;
192 +
        let mut next_line = None;
193 +
194 +
        for hunk in &self.hunks {
195 +
            let hunk_head = hunk_head(hunk, side);
196 +
            if next_line.is_some_and(|line| line != hunk_head) {
197 +
                return None;
198 +
            }
199 +
            head.get_or_insert(hunk_head);
200 +
            push_hunk_source_lines(hunk, side, &mut text);
201 +
            let len = hunk
202 +
                .lines
203 +
                .iter()
204 +
                .map(|line| source_len(line, side))
205 +
                .sum::<u32>();
206 +
            next_line = Some(hunk_head + len);
207 +
        }
208 +
        head.map(|head| HighlightSource::new(text, head))
209 +
    }
210 +
}
211 +
212 +
/// Appends nonblank source-side hunk lines to `text`.
213 +
fn push_hunk_source_lines(hunk: &Hunk, side: DiffSide, text: &mut String) {
214 +
    for line in &hunk.lines {
215 +
        if source_len(line, side) == 0 {
216 +
            continue;
217 +
        }
218 +
        if !text.is_empty() {
219 +
            text.push('\n');
220 +
        }
221 +
        text.push_str(&line.text);
222 +
    }
223 +
}
224 +
225 +
/// Returns the first source line for one hunk side.
226 +
fn hunk_head(hunk: &Hunk, side: DiffSide) -> u32 {
227 +
    match side {
228 +
        DiffSide::Old => hunk.header.old_line_no,
229 +
        DiffSide::New => hunk.header.new_line_no,
230 +
    }
231 +
}
232 +
233 +
/// Returns how many source lines a diff line contributes on `side`.
234 +
fn source_len(line: &DiffLine, side: DiffSide) -> u32 {
235 +
    match side {
236 +
        DiffSide::Old => line.kind.old_len(),
237 +
        DiffSide::New => line.kind.new_len(),
238 +
    }
239 +
}
240 +
167 241
impl BuiltinHighlighter {
168 242
    /// Creates a highlighter from caller-loaded grammars and themes.
169 243
    pub fn new(registry: syntax::Registry, default_theme: impl Into<String>) -> Self {
170 244
        Self {
171 245
            registry,
368 442
}
369 443
370 444
#[cfg(test)]
371 445
mod tests {
372 446
    use super::*;
447 +
    use crate::Decode;
373 448
    use std::str::FromStr;
374 449
375 450
    #[test]
376 451
    fn source_lines_before_head_are_absent() {
377 452
        let source = HighlightSource::new("two\nthree\n", 2);
380 455
        assert_eq!(source.line(1), None);
381 456
        assert_eq!(source.line_index(2), Some(0));
382 457
        assert_eq!(source.line(2), Some("two"));
383 458
    }
384 459
460 +
    #[test]
461 +
    fn file_highlight_source_spans_the_new_side() {
462 +
        let document = crate::DiffDocument::decode_str(
463 +
            "\
464 +
a.css +0 -0
crates/diff/src/lib.rs +3 -2
18 18
19 19
pub mod decode;
20 20
pub mod encode;
21 21
22 22
pub use commit::{Commit, Header, ParseCommitError};
23 +
pub use context::ContextChange;
23 24
pub use decode::Decode;
24 25
pub use document::{
25 26
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
26 27
    FileMode, FileStats, Hunk, HunkHeader, HunkId, Oid, OidError, RowId, Stats,
27 28
};
29 30
pub use highlight::{
30 31
    BuiltinHighlighter, DiffHighlighter, DiffSide, HighlightKey, HighlightKeyInput,
31 32
    HighlightRequest, HighlightResult, HighlightSource,
32 33
};
33 34
pub use viewer::{
34 -
    ContextError, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane, DiffState, DiffViewer,
35 -
    FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
35 +
    ContextRequest, ContextUpdate, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane,
36 +
    DiffState, DiffViewer, FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
36 37
};
crates/diff/src/viewer.rs +116 -285
3 3
mod tree;
4 4
5 5
use std::collections::btree_map::Entry;
6 6
use std::collections::{BTreeMap, BTreeSet};
7 7
use std::convert::Infallible;
8 -
use std::path::PathBuf;
8 +
use std::path::{Path, PathBuf};
9 9
10 10
use rustik_highlight as syntax;
11 -
use rustik_repo::{Repo, RepoError};
12 11
use rustik_tui as tui;
13 12
use tui::event::Modifiers;
14 13
use tui::{
15 14
    Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton,
16 15
    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
17 16
    VStack, View, Viewport, Widget, colors,
18 17
};
19 18
20 -
use crate::context::{ContextChange, ContextState, FULL_CONTEXT_LINES};
19 +
use crate::context::{self, ContextChange, ContextState};
21 20
use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
22 21
use crate::word;
23 22
use crate::{
24 23
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
25 24
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
199 198
    pub negative_fg: Color,
200 199
    /// Foreground color for added stats, markers, and labels.
201 200
    pub positive_fg: Color,
202 201
}
203 202
203 +
/// Repo refetch request prepared by the viewer for asynchronous context updates.
204 +
#[derive(Clone, Debug)]
205 +
pub struct ContextRequest {
206 +
    /// Context state to install when the request completes.
207 +
    next_context: ContextState,
208 +
    /// File to focus after applying the fetched replacement.
209 +
    active: Option<FileId>,
210 +
    /// Paths and original file ids to replace.
211 +
    files: Vec<(PathBuf, FileId)>,
212 +
    /// Git context width to request.
213 +
    context_lines: usize,
214 +
    /// Next hunk and row ids used to remap fetched files.
215 +
    next_ids: (usize, usize),
216 +
}
217 +
218 +
/// Decoded replacement files for an asynchronous context update.
219 +
#[derive(Clone, Debug)]
220 +
pub struct ContextUpdate {
221 +
    /// Context state prepared when the request was started.
222 +
    next_context: ContextState,
223 +
    /// File to focus after applying the fetched replacement.
224 +
    active: Option<FileId>,
225 +
    /// Replacement file diffs with ids remapped to this viewer.
226 +
    files: Vec<FileDiff>,
227 +
}
228 +
204 229
/// Pure diff viewer that renders into a caller-owned buffer.
205 230
#[derive(Clone, Debug)]
206 231
pub struct DiffViewer {
207 232
    /// Diff document being viewed.
208 233
    document: DiffDocument,
212 237
    state: DiffState,
213 238
    /// Highlighted row cache.
214 239
    highlights: BTreeMap<HighlightKey, Line>,
215 240
    /// Requests already handed to a worker.
216 241
    pending_highlights: BTreeSet<HighlightKey>,
217 -
    /// File-side full-context sources used only for syntax highlighting.
218 -
    full_highlight_sources: BTreeMap<(FileId, DiffSide), HighlightSource>,
219 242
    /// Per-hunk source context reused across highlight-request batches.
220 243
    hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
221 244
    /// Cached intra-line word diffs, keyed by hunk.
222 245
    word_diffs: BTreeMap<HunkId, word::WordChanges>,
223 246
    /// Rendered commit-preamble rows for the most recent body width.
230 253
    index: RowIndex,
231 254
    /// Hunk-context expansion bookkeeping.
232 255
    context: ContextState,
233 256
}
234 257
235 -
/// A failure while refetching wider diff context for the viewer.
236 -
#[derive(Debug)]
237 -
pub enum ContextError {
238 -
    /// The repo backend failed to produce a diff.
239 -
    Repo(RepoError),
240 -
    /// The refetched diff could not be parsed.
241 -
    Decode(DecodeError),
242 -
}
243 -
244 -
impl From<RepoError> for ContextError {
245 -
    fn from(error: RepoError) -> Self {
246 -
        Self::Repo(error)
247 -
    }
248 -
}
249 -
250 -
impl From<DecodeError> for ContextError {
251 -
    fn from(error: DecodeError) -> Self {
252 -
        Self::Decode(error)
253 -
    }
254 -
}
255 -
256 -
impl std::fmt::Display for ContextError {
257 -
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258 -
        match self {
259 -
            Self::Repo(error) => write!(f, "{error}"),
260 -
            Self::Decode(error) => write!(f, "{error}"),
261 -
        }
262 -
    }
263 -
}
264 -
265 -
impl std::error::Error for ContextError {}
266 -
267 258
/// Cached rendered row positions for the current document visibility state.
268 259
///
269 260
/// Visible files tile the content region contiguously, so each file is stored
270 261
/// by its first rendered row only; its last row is the next file's start (or
271 262
/// [`RowIndex::rows`] for the final file).
419 410
        let color = colors.get(key)?.parse::<syntax::Rgb>().ok()?;
420 411
        Some(Color::RGB(color.r, color.g, color.b))
421 412
    }
422 413
}
423 414
415 +
impl ContextRequest {
416 +
    /// Returns the Git context width to fetch.
417 +
    pub const fn context_lines(&self) -> usize {
418 +
        self.context_lines
419 +
    }
420 +
421 +
    /// Returns the paths that should be fetched from the repo.
422 +
    pub fn paths(&self) -> impl Iterator<Item = &Path> {
423 +
        self.files.iter().map(|(path, _)| path.as_path())
424 +
    }
425 +
426 +
    /// Decodes a repo patch into a viewer update.
427 +
    pub fn decode(self, patch: &[u8]) -> Result<Option<ContextUpdate>, DecodeError> {
428 +
        let document = DiffDocument::decode_bytes(patch)?;
429 +
        let result: Result<Option<Vec<FileDiff>>, Infallible> =
430 +
            context::rebuild(self.next_ids, &self.files, self.context_lines, |_, _| {
431 +
                Ok(document.files)
432 +
            });
433 +
        let files = match result {
434 +
            Ok(Some(files)) => files,
435 +
            Ok(None) => return Ok(None),
436 +
            Err(error) => match error {},
437 +
        };
438 +
439 +
        Ok(Some(ContextUpdate {
440 +
            next_context: self.next_context,
441 +
            active: self.active,
442 +
            files,
443 +
        }))
444 +
    }
445 +
}
446 +
424 447
impl DiffViewer {
425 448
    /// Creates a viewer with plain initial rendering state.
426 449
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
427 450
        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
428 451
        let file_tree = tree::FileTreeViewer::new(&document, options.file_tree_root.clone());
432 455
            document,
433 456
            options,
434 457
            state,
435 458
            highlights: BTreeMap::new(),
436 459
            pending_highlights: BTreeSet::new(),
437 -
            full_highlight_sources: BTreeMap::new(),
438 460
            hunk_highlight_sources: BTreeMap::new(),
439 461
            word_diffs: BTreeMap::new(),
440 462
            preamble,
441 463
            file_tree,
442 464
            file_tree_visibility: FileTreeVisibility::default(),
483 505
            if let Some(existing) = existing {
484 506
                *existing = replacement;
485 507
            }
486 508
        }
487 509
        self.pending_highlights.clear();
488 -
        self.full_highlight_sources.clear();
489 510
        self.hunk_highlight_sources.clear();
490 511
        self.word_diffs.clear();
491 512
        self.rebuild_index();
492 513
    }
493 514
494 -
    /// Expands or contracts hunk context, refetching diffs through `repo`.
495 -
    ///
496 -
    /// Returns whether the document changed. `false` means the input was a
497 -
    /// no-op -- already at minimum width, or no file to target. On a failed
498 -
    /// refetch the requested context is rolled back.
499 -
    fn update_context(
500 -
        &mut self,
501 -
        change: ContextChange,
502 -
        repo: &dyn Repo,
503 -
    ) -> Result<bool, ContextError> {
504 -
        let active = self
505 -
            .focused_file()
506 -
            .or_else(|| self.document.files.first().map(|file| file.id));
507 -
        // An explicit multi-file selection targets exactly those files; any other
508 -
        // selection targets the active file alone, falling back to the first file.
509 -
        let file_ids: Vec<FileId> = match &self.state.file_selection {
515 +
    /// Prepares a repo refetch request for an asynchronous context update.
516 +
    pub fn context_request(&self, change: ContextChange) -> Option<ContextRequest> {
517 +
        let active = self.active_context_file();
518 +
        let file_ids = self.context_file_ids(active);
519 +
        let plan = self.context.plan(change, &file_ids, &self.document)?;
520 +
        if plan.files.is_empty() {
521 +
            return None;
522 +
        }
523 +
524 +
        Some(ContextRequest {
525 +
            next_context: plan.state,
526 +
            active,
527 +
            files: plan.files,
528 +
            context_lines: plan.context_lines,
529 +
            next_ids: context::next_ids(&self.document.files),
530 +
        })
531 +
    }
532 +
533 +
    /// Applies a completed asynchronous context update.
534 +
    pub fn apply_context_update(&mut self, update: ContextUpdate, area: Rect) -> bool {
535 +
        if update.files.is_empty() {
536 +
            return false;
537 +
        }
538 +
        let mut state = self.state.clone();
539 +
        if update.active.is_some() {
540 +
            state.focus = update.active.map(DiffFocus::File);
541 +
        }
542 +
        self.context = update.next_context;
543 +
        self.replace_file_diffs(update.files);
544 +
        self.set_state(state);
545 +
        self.apply(DiffAction::Resize, area) == ViewChange::Changed
546 +
    }
547 +
548 +
    /// Returns the active file targeted by context changes.
549 +
    fn active_context_file(&self) -> Option<FileId> {
550 +
        self.focused_file()
551 +
            .or_else(|| self.document.files.first().map(|file| file.id))
552 +
    }
553 +
554 +
    /// Returns the files targeted by a context change.
555 +
    fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
556 +
        match &self.state.file_selection {
510 557
            FileSelection::All => {
511 558
                let active =
512 559
                    active.filter(|id| self.document.files.iter().any(|file| file.id == *id));
513 560
514 561
                active
521 568
                .files
522 569
                .iter()
523 570
                .filter(|file| files.contains(&file.id))
524 571
                .map(|file| file.id)
525 572
                .collect(),
526 -
        };
527 -
        let replacements =
528 -
            self.context
529 -
                .apply(change, &file_ids, &self.document, |context_lines, paths| {
530 -
                    let patch = repo.diff(context_lines, paths)?;
531 -
                    let document = DiffDocument::decode_bytes(&patch)?;
532 -
                    Ok::<_, ContextError>(document.files)
533 -
                })?;
534 -
        let Some(replacements) = replacements else {
535 -
            return Ok(false);
536 -
        };
537 -
        let mut state = self.state.clone();
538 -
        if !file_ids.is_empty() {
539 -
            state.focus = active.map(DiffFocus::File);
540 573
        }
541 -
        self.replace_file_diffs(replacements);
542 -
        self.set_state(state);
543 -
544 -
        Ok(true)
545 574
    }
546 575
547 576
    /// Sets the first visible rendered row.
548 577
    pub fn set_scroll(&mut self, scroll: usize) {
549 578
        self.state.scroll = scroll;
748 777
            ViewChange::Changed
749 778
        }
750 779
    }
751 780
752 781
    /// Applies one input event to the viewer.
782 +
    ///
783 +
    /// Context-changing keys (`.`, `,`, `x`) are handled by the session loop,
784 +
    /// which refetches diffs off the terminal thread, so they fall through here.
753 785
    pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
754 -
        match self.handle_input_event(event, area, false, |_, _, _| {
755 -
            Ok::<Control, Infallible>(Control::Continue)
756 -
        }) {
757 -
            Ok(control) => control,
758 -
            Err(error) => match error {},
759 -
        }
760 -
    }
761 -
762 -
    /// Applies one input event to the viewer, including repo-backed context changes.
763 -
    pub fn handle_input_with_repo(
764 -
        &mut self,
765 -
        event: Event<()>,
766 -
        area: Rect,
767 -
        repo: &dyn Repo,
768 -
    ) -> Result<Control, ContextError> {
769 -
        self.handle_input_event(event, area, true, |viewer, change, area| {
770 -
            if !viewer.update_context(change, repo)? {
771 -
                return Ok(Control::Continue);
772 -
            }
773 -
            viewer.apply(DiffAction::Resize, area);
774 -
775 -
            Ok(Control::Redraw)
776 -
        })
777 -
    }
778 -
779 -
    /// Routes one input event into a viewer action.
780 -
    fn handle_input_event<E>(
781 -
        &mut self,
782 -
        event: Event<()>,
783 -
        area: Rect,
784 -
        context_wheel: bool,
785 -
        mut apply_context: impl FnMut(&mut Self, ContextChange, Rect) -> Result<Control, E>,
786 -
    ) -> Result<Control, E> {
787 786
        let action = match event {
788 -
            Event::Key(Key::Char('q')) => return Ok(Control::Quit),
787 +
            Event::Key(Key::Char('q')) => return Control::Quit,
789 788
            Event::Key(Key::Char('`')) => DiffAction::ToggleFileTree,
790 -
            Event::Key(Key::Char('.')) => {
791 -
                return apply_context(self, ContextChange::Increase, area);
792 -
            }
793 -
            Event::Key(Key::Char(',')) => {
794 -
                return apply_context(self, ContextChange::Decrease, area);
795 -
            }
796 -
            Event::Key(Key::Char('x')) => {
797 -
                return apply_context(self, ContextChange::ToggleFile, area);
798 -
            }
799 -
            Event::Mouse(Mouse::Press {
800 -
                button: MouseButton::WheelUp,
801 -
                modifiers,
802 -
                ..
803 -
            }) if modifiers.contains(Modifiers::CONTROL) && context_wheel => {
804 -
                return apply_context(self, ContextChange::Increase, area);
805 -
            }
806 -
            Event::Mouse(Mouse::Press {
807 -
                button: MouseButton::WheelDown,
808 -
                modifiers,
809 -
                ..
810 -
            }) if modifiers.contains(Modifiers::CONTROL) && context_wheel => {
811 -
                return apply_context(self, ContextChange::Decrease, area);
812 -
            }
813 789
            Event::Resize(_) => DiffAction::Resize,
814 790
            Event::Mouse(Mouse::Press {
815 791
                button: MouseButton::WheelDown,
816 792
                ..
817 793
            }) => DiffAction::Scroll(Scroll::Lines(WHEEL_SCROLL_ROWS)),
823 799
                button: MouseButton::Left,
824 800
                at,
825 801
                modifiers,
826 802
            }) => {
827 803
                let Some(tree) = self.layout(area).tree else {
828 -
                    return Ok(Control::Continue);
804 +
                    return Control::Continue;
829 805
                };
830 806
                if !self.file_tree.select_at(tree, at) {
831 -
                    return Ok(Control::Continue);
807 +
                    return Control::Continue;
832 808
                }
833 809
                self.state.pane = DiffPane::FileTree;
834 810
                if modifiers.contains(Modifiers::CONTROL) {
835 811
                    DiffAction::ToggleFileTreeTarget
836 812
                } else {
839 815
            }
840 816
            event => match (self.state.pane, event) {
841 817
                (DiffPane::Main, Event::Key(Key::Char('h'))) => DiffAction::EnterFileTree,
842 818
                (DiffPane::Main, Event::Key(Key::Esc)) => {
843 819
                    if self.apply(DiffAction::EnterFileTree, area) == ViewChange::Changed {
844 -
                        return Ok(Control::Redraw);
820 +
                        return Control::Redraw;
845 821
                    }
846 822
                    if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
847 -
                        return Ok(Control::Redraw);
823 +
                        return Control::Redraw;
848 824
                    }
849 -
                    return Ok(Control::Quit);
825 +
                    return Control::Quit;
850 826
                }
851 827
                (DiffPane::Main, Event::Key(Key::Char('j') | Key::Down)) => {
852 828
                    DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
853 829
                }
854 830
                (DiffPane::Main, Event::Key(Key::Char('k') | Key::Up)) => {
892 868
                    DiffAction::ExtendFileTreeSelection(1)
893 869
                }
894 870
                (DiffPane::FileTree, Event::Key(Key::Char('K'))) => {
895 871
                    DiffAction::ExtendFileTreeSelection(-1)
896 872
                }
897 -
                _ => return Ok(Control::Continue),
873 +
                _ => return Control::Continue,
898 874
            },
899 875
        };
900 876
        match self.apply(action, area) {
901 -
            ViewChange::Changed => Ok(Control::Redraw),
902 -
            ViewChange::Unchanged => Ok(Control::Continue),
877 +
            ViewChange::Changed => Control::Redraw,
878 +
            ViewChange::Unchanged => Control::Continue,
903 879
        }
904 880
    }
905 881
906 882
    /// Returns highlight requests for visible source rows plus configured lookahead.
907 883
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
932 908
            });
933 909
        }
934 910
        requests
935 911
    }
936 912
937 -
    /// Returns highlight requests enriched with repo-backed full file context.
938 -
    pub fn highlight_requests_with_repo(
939 -
        &mut self,
940 -
        area: Rect,
941 -
        repo: &dyn Repo,
942 -
    ) -> Vec<HighlightRequest> {
943 -
        let mut requests = self.highlight_requests(area);
944 -
        self.load_full_highlight_sources(&requests, repo);
945 -
946 -
        for request in &mut requests {
947 -
            let key = (request.key.file, request.key.side);
948 -
            if let Some(source) = self.full_highlight_sources.get(&key)
949 -
                && source.line(request.key.source_line)
950 -
                    == request.source.line(request.key.source_line)
951 -
            {
952 -
                request.source = source.clone();
953 -
            }
954 -
        }
955 -
        requests
956 -
    }
957 -
958 913
    /// Marks unprocessed highlight requests as requestable again.
959 914
    pub fn cancel_highlights(&mut self, requests: impl IntoIterator<Item = HighlightRequest>) {
960 915
        for request in requests {
961 916
            self.pending_highlights.remove(&request.key);
962 917
        }
963 918
    }
964 919
965 -
    /// Loads full-context source text for highlighted files.
966 -
    fn load_full_highlight_sources(&mut self, requests: &[HighlightRequest], repo: &dyn Repo) {
967 -
        let mut targets = BTreeMap::new();
968 -
        for request in requests {
969 -
            let key = (request.key.file, request.key.side);
970 -
            if self.full_highlight_sources.contains_key(&key) {
971 -
                continue;
972 -
            }
973 -
            if let Some(path) = request.path.as_deref() {
974 -
                targets.insert((path.to_path_buf(), request.key.side), request.key.file);
975 -
            }
976 -
        }
977 -
        if targets.is_empty() {
978 -
            return;
979 -
        }
980 -
981 -
        let paths = targets
982 -
            .keys()
983 -
            .map(|(path, _)| path.as_path())
984 -
            .collect::<BTreeSet<_>>()
985 -
            .into_iter()
986 -
            .collect::<Vec<_>>();
987 -
        let Ok(patch) = repo.diff(FULL_CONTEXT_LINES, &paths) else {
988 -
            return;
989 -
        };
990 -
        let Ok(document) = DiffDocument::decode_bytes(&patch) else {
991 -
            return;
992 -
        };
993 -
994 -
        for file in &document.files {
995 -
            for side in [DiffSide::Old, DiffSide::New] {
996 -
                let Some(path) = file.source_path(side) else {
997 -
                    continue;
998 -
                };
999 -
                let Some(file_id) = targets.get(&(path, side)).copied() else {
1000 -
                    continue;
1001 -
                };
1002 -
                let Some(source) = Self::file_highlight_source(file, side) else {
1003 -
                    continue;
1004 -
                };
1005 -
                self.full_highlight_sources.insert((file_id, side), source);
1006 -
            }
1007 -
        }
1008 -
    }
1009 -
1010 920
    /// Returns the highlight-cache key for one diff row.
1011 921
    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
1012 922
        HighlightKey::new(HighlightKeyInput {
1013 923
            file: meta.file,
1014 924
            side: meta.side,
1042 952
            return meta.single_row_source();
1043 953
        };
1044 954
        let Some(hunk) = file.hunks.iter().find(|hunk| hunk.id == meta.hunk) else {
1045 955
            return meta.single_row_source();
1046 956
        };
1047 -
        Self::hunk_highlight_source(hunk, meta.side)
1048 -
    }
1049 -
1050 -
    /// Builds contiguous source text for one file side.
1051 -
    fn file_highlight_source(file: &FileDiff, side: DiffSide) -> Option<HighlightSource> {
1052 -
        let mut text = String::new();
1053 -
        let mut head = None;
1054 -
        let mut next_line = None;
1055 -
1056 -
        for hunk in &file.hunks {
1057 -
            let hunk_head = Self::hunk_head(hunk, side);
1058 -
            if next_line.is_some_and(|line| line != hunk_head) {
1059 -
                return None;
1060 -
            }
1061 -
            if head.is_none() {
1062 -
                head = Some(hunk_head);
1063 -
            }
1064 -
            Self::push_hunk_source_lines(hunk, side, &mut text);
1065 -
            let len = hunk
1066 -
                .lines
1067 -
                .iter()
1068 -
                .map(|line| Self::source_len(line, side))
1069 -
                .sum::<u32>();
1070 -
            next_line = Some(hunk_head + len);
1071 -
        }
1072 -
1073 -
        head.map(|head| HighlightSource::new(text, head))
1074 -
    }
1075 -
1076 -
    /// Builds source text for one hunk side.
1077 -
    fn hunk_highlight_source(hunk: &Hunk, side: DiffSide) -> HighlightSource {
1078 -
        let head = Self::hunk_head(hunk, side);
1079 -
        let mut text = String::new();
1080 -
1081 -
        Self::push_hunk_source_lines(hunk, side, &mut text);
1082 -
        HighlightSource::new(text, head)
1083 -
    }
1084 -
1085 -
    /// Appends source-side hunk lines to `text`.
1086 -
    fn push_hunk_source_lines(hunk: &Hunk, side: DiffSide, text: &mut String) {
1087 -
        for line in &hunk.lines {
1088 -
            if Self::source_len(line, side) == 0 {
1089 -
                continue;
1090 -
            }
1091 -
            if !text.is_empty() {
1092 -
                text.push('\n');
1093 -
            }
1094 -
            text.push_str(&line.text);
1095 -
        }
1096 -
    }
1097 -
1098 -
    /// Returns the first source line for one hunk side.
1099 -
    fn hunk_head(hunk: &Hunk, side: DiffSide) -> u32 {
1100 -
        match side {
1101 -
            DiffSide::Old => hunk.header.old_line_no,
1102 -
            DiffSide::New => hunk.header.new_line_no,
1103 -
        }
1104 -
    }
1105 -
1106 -
    /// Returns how many source lines a diff line contributes on `side`.
1107 -
    fn source_len(line: &DiffLine, side: DiffSide) -> u32 {
1108 -
        match side {
1109 -
            DiffSide::Old => line.kind.old_len(),
1110 -
            DiffSide::New => line.kind.new_len(),
1111 -
        }
957 +
        hunk.highlight_source(meta.side)
1112 958
    }
1113 959
1114 960
    /// Merges highlighted rows and returns whether a redraw is needed.
1115 961
    ///
1116 962
    /// The word-diff overlay is applied here, once, so the cached `Line` is
1805 1651
                *local += hunk.lines.len();
1806 1652
                Some((hunk, row))
1807 1653
            })
1808 1654
    }
1809 1655
1810 -
    /// Returns the source path for a file side.
1811 -
    fn source_path(&self, side: DiffSide) -> Option<PathBuf> {
1812 -
        match side {
1813 -
            DiffSide::Old => self
1814 -
                .header
1815 -
                .old_path
1816 -
                .clone()
1817 -
                .or_else(|| self.header.new_path.clone()),
1818 -
            DiffSide::New => self
1819 -
                .header
1820 -
                .new_path
1821 -
                .clone()
1822 -
                .or_else(|| self.header.old_path.clone()),
1823 -
        }
1824 -
    }
1825 -
1826 1656
    /// Returns a file header line.
1827 1657
    fn header_line(&self, cols: usize, palette: DiffPalette) -> Line {
1828 1658
        let mut left = Line::blank();
1829 1659
        left.push(Label::from_char(self.header.kind.marker()).fg(LINE_NUMBER_FG));
1830 1660
        left.push(Label::space());
1961 1791
1962 1792
    use super::*;
1963 1793
1964 1794
    use crate::Decode;
1965 1795
    use crate::DiffDocument;
1796 +
    use rustik_repo::{Repo, RepoError};
1966 1797
    use rustik_tui::Point;
1967 1798
1968 1799
    /// Returns a left-click event for tests.
1969 1800
    fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
1970 1801
        Event::Mouse(Mouse::Press {
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.css +0 -11
1 -
+++ b/a.css
2 -
@@ -10 +10 @@
3 -
-background: url(old.svg);
4 -
+background: url(new.svg);
5 -
",
6 -
        )
7 -
        .unwrap();
8 -
        let mut viewer = DiffViewer::new(document, DiffOptions::default());
9 -
        let repo = FakeRepo::new(
10 -
            "\
11 -
a.css +0 -29
1 -
+++ b/a.css
2 -
@@ -1,11 +1,11 @@
3 -
 .x {
4 -
 one
5 -
 two
6 -
 three
7 -
 four
8 -
 five
9 -
 six
10 -
 seven
11 -
 eight
12 -
-background: url(old.svg);
13 -
+background: url(new.svg);
14 -
 }
15 -
",
16 -
        );
17 -
18 -
        let request = viewer
19 -
            .highlight_requests_with_repo(Rect::new(0, 0, 64, 20), &repo)
20 -
            .into_iter()
21 -
            .find(|request| request.key.side == DiffSide::New)
22 -
            .unwrap();
23 -
24 -
        assert_eq!(request.source.head, 1);
25 -
        assert_eq!(request.source.line(1), Some(".x {"));
26 -
        assert_eq!(request.source.line(10), Some("background: url(new.svg);"));
27 -
        assert_eq!(repo.calls.borrow()[0].0, FULL_CONTEXT_LINES);
28 -
    }
29 -
30 1
    #[test]
31 2
    fn repo_highlight_results_style_css_custom_properties_from_real_context() {
32 3
        let document = DiffDocument::decode_str(
33 4
            "\
34 5
assets/css/style.css +0 -0
assets/css/style.css +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +1 -25
1 -
+++ b/a.rs
2 -
@@ -1,5 +1,6 @@ fn main
3 -
 lead
4 -
 context
5 -
-old
6 -
+new
7 -
+extra
8 -
 tail
9 -
 trail
10 -
",
11 -
        );
12 -
13 -
        let changed = viewer
14 -
            .update_context(ContextChange::Increase, &repo)
15 -
            .unwrap();
16 -
17 -
        assert!(changed);
18 -
        let calls = repo.calls.borrow();
19 -
        assert_eq!(calls.len(), 1);
20 -
        assert_eq!(calls[0].0, 4);
21 -
        assert_eq!(calls[0].1, vec![PathBuf::from("a.rs")]);
22 -
    }
23 -
24 -
    #[test]
25 -
    fn expand_context_targets_explicit_multi_selection() {
1 +
    fn context_request_targets_explicit_multi_selection() {
26 2
        let mut viewer = two_file_viewer();
27 3
        let mut state = viewer.state().clone();
28 4
        state.file_selection =
29 5
            FileSelection::Files(BTreeSet::from([FileId::new(0), FileId::new(1)]));
30 6
        viewer.set_state(state);
a.rs +0 -0
b.rs +0 -0