diff: Implement diff file expansion control

98f722c7637f98fb29ce785d6090b8bf32a244f0
Alexis Sellier committed ago 1 parent 8d4e0e69
Cargo.lock +1 -0
120 120
[[package]]
121 121
name = "rustik-diff"
122 122
version = "0.1.0"
123 123
dependencies = [
124 124
 "rustik-highlight",
125 +
 "rustik-repo",
125 126
 "rustik-tui",
126 127
 "rustik-tui-termion",
127 128
]
128 129
129 130
[[package]]
crates/diff/Cargo.toml +1 -0
7 7
edition.workspace = true
8 8
license.workspace = true
9 9
10 10
[dependencies]
11 11
rustik-highlight.workspace = true
12 +
rustik-repo.workspace = true
12 13
rustik-tui = { workspace = true, features = ["widgets"] }
13 14
rustik-tui-termion.workspace = true
14 15
15 16
[[bench]]
16 17
name = "render"
crates/diff/benches/render.rs +10 -9
614 614
    viewer.apply(DiffAction::Resize, area);
615 615
}
616 616
617 617
/// Converts a highlight request into a deterministic synthetic result.
618 618
fn highlight_result(request: HighlightRequest) -> HighlightResult {
619 -
    let line = request
620 -
        .source
621 -
        .line(request.key.source_line)
622 -
        .unwrap_or_default();
623 -
624 -
    HighlightResult {
625 -
        key: request.key,
626 -
        line: Line::new(Label::from(line).fg(Color::Yellow)),
627 -
    }
619 +
    let line = Line::new(
620 +
        Label::from(
621 +
            request
622 +
                .source
623 +
                .line(request.key.source_line)
624 +
                .unwrap_or_default(),
625 +
        )
626 +
        .fg(Color::Yellow),
627 +
    );
628 +
    HighlightResult::new(request, line)
628 629
}
629 630
630 631
/// Creates a deterministic Git-style unified diff.
631 632
fn synthetic_diff(shape: DiffShape) -> String {
632 633
    let mut diff = String::new();
src/file_{file:04}.rs\n" +0 -0
crates/diff/src/bin/rustik-diff.rs +50 -30
7 7
use std::sync::mpsc;
8 8
use std::thread;
9 9
use std::{env, str};
10 10
11 11
use rustik_diff::{
12 -
    BuiltinHighlighter, Decode, DecodeError, DiffDocument, DiffOptions, DiffViewer, FileTreeMode,
12 +
    BuiltinHighlighter, ContextError, Decode, DecodeError, DiffDocument, DiffOptions, DiffViewer,
13 +
    FileTreeMode,
13 14
};
14 15
use rustik_diff::{HighlightRequest, HighlightResult};
15 16
use rustik_highlight as syntax;
17 +
use rustik_repo::{GitRepo, RepoError};
16 18
use rustik_tui as tui;
17 19
use rustik_tui::{Color, Control, Event, Label, Line, Rect, Style, Terminal};
18 20
use rustik_tui_termion as tui_termion;
19 21
20 22
/// Default static render width for non-terminal output.
103 105
    }
104 106
}
105 107
106 108
/// Runs the binary with forwarded Git arguments.
107 109
fn run(args: Vec<OsString>) -> Result<(), Error> {
108 -
    if io::stdin().is_terminal() {
109 -
        let cwd = env::current_dir()?;
110 +
    let cwd = env::current_dir()?;
111 +
    let input_from_git = io::stdin().is_terminal();
112 +
    let input = if input_from_git {
110 113
        let output = git_diff(&args, &cwd)?;
111 114
        if !output.status.success() {
112 115
            io::stderr().write_all(&output.stderr)?;
113 116
            return Err(Error::Git(output.status.code().unwrap_or(1)));
114 117
        }
115 -
        return run_or_forward(&output.stdout);
116 -
    }
117 -
    let mut input = Vec::new();
118 -
    io::stdin().read_to_end(&mut input)?;
118 +
        output.stdout
119 +
    } else {
120 +
        let mut buf = Vec::new();
121 +
        io::stdin().read_to_end(&mut buf)?;
122 +
        buf
123 +
    };
119 124
120 -
    run_or_forward(&input)
125 +
    run_or_forward(&input, &cwd, input_from_git.then_some(args.as_slice()))
121 126
}
122 127
123 128
/// Renders diff input or passes non-diff data through unchanged.
124 -
fn run_or_forward(input: &[u8]) -> Result<(), Error> {
129 +
fn run_or_forward(input: &[u8], cwd: &Path, args: Option<&[OsString]>) -> Result<(), Error> {
125 130
    let document = match DiffDocument::decode_bytes(input) {
126 131
        Ok(document) if !document.is_empty() => document,
127 132
        Ok(_) => {
128 133
            io::stdout().write_all(input)?;
129 134
            return Ok(());
130 135
        }
131 136
        Err(error) => return Err(Error::Parse(error)),
132 137
    };
133 138
    let raw_theme = BUILTIN_THEME.parse::<syntax::RawTheme>()?;
134 -
    let interactive = io::stdout().is_terminal();
135 139
    let mut options = DiffOptions {
136 140
        diff_palette: (&raw_theme).into(),
137 141
        ..DiffOptions::default()
138 142
    };
139 -
    if interactive {
140 -
        let cwd = env::current_dir()?;
141 -
        let root = cwd
142 -
            .file_name()
143 -
            .and_then(|name| name.to_str())
144 -
            .filter(|name| !name.is_empty())
145 -
            .map(str::to_owned)
146 -
            .unwrap_or_else(|| cwd.display().to_string());
147 -
148 -
        options.file_tree = FileTreeMode::Auto;
149 -
        options.file_tree_root = root;
150 -
    } else {
143 +
    if !io::stdout().is_terminal() {
151 144
        let mut viewer = DiffViewer::new(document, options);
152 145
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, STATIC_MAX_ROWS));
153 146
154 147
        tui_termion::term::print_constrained(&mut viewer, constraints)?;
155 148
        return Ok(());
156 149
    }
150 +
    let root = cwd
151 +
        .file_name()
152 +
        .and_then(|name| name.to_str())
153 +
        .filter(|name| !name.is_empty())
154 +
        .map(str::to_owned)
155 +
        .unwrap_or_else(|| cwd.display().to_string());
156 +
157 +
    options.file_tree = FileTreeMode::Auto;
158 +
    options.file_tree_root = root;
159 +
157 160
    let backend = tui_termion::term::screen()?;
158 161
    let mut terminal = Terminal::new(backend)?;
159 162
    let mut registry = syntax::Registry::default();
160 163
    let theme = syntax::Theme::compile(&raw_theme);
161 164
171 174
    let mut viewer = DiffViewer::new(document, options);
172 175
173 176
    terminal.clear()?;
174 177
    terminal.set_cursor_visible(false)?;
175 178
176 -
    let result = terminal_loop(&mut terminal, &mut viewer, highlighter);
179 +
    let repo = args.map(|args| GitRepo::new(cwd, args));
180 +
    let result = terminal_loop(&mut terminal, &mut viewer, highlighter, repo);
177 181
    let cursor = terminal.set_cursor_visible(true);
178 182
179 -
    result.and(cursor).map_err(Error::Io)
183 +
    result?;
184 +
    cursor.map_err(Error::Io)
180 185
}
181 186
182 187
/// Runs the terminal event loop.
183 188
fn terminal_loop(
184 189
    terminal: &mut DiffTerminal,
185 190
    viewer: &mut DiffViewer,
186 191
    highlighter: BuiltinHighlighter,
187 -
) -> io::Result<()> {
192 +
    repo: Option<GitRepo>,
193 +
) -> Result<(), Error> {
188 194
    let (events_tx, events_rx) = mpsc::channel();
189 195
    TerminalEvent::spawn_input_worker(events_tx.clone());
190 196
191 197
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx, highlighter);
192 198
    let mut session = TerminalSession {
193 199
        terminal,
194 200
        viewer,
201 +
        repo,
195 202
        highlights_tx,
196 203
    };
197 204
    session.redraw()?;
198 205
199 206
    while let Ok(event) = events_rx.recv() {
200 207
        match event {
201 208
            TerminalEvent::Input(event) => {
202 209
                let event = event?;
203 210
                let area = viewer_area(session.terminal.area());
204 -
                match session.viewer.handle_input(event, 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 {
205 217
                    Control::Quit => break,
206 218
                    Control::Redraw => session.redraw()?,
207 219
                    Control::Continue | Control::Wait => {}
208 220
                }
209 221
            }
221 233
struct TerminalSession<'a> {
222 234
    /// Terminal frame target.
223 235
    terminal: &'a mut DiffTerminal,
224 236
    /// Diff viewer state.
225 237
    viewer: &'a mut DiffViewer,
238 +
    /// Git-backed diff repo, present when the input came from Git.
239 +
    repo: Option<GitRepo>,
226 240
    /// Visible-row highlight request channel.
227 241
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
228 242
}
229 243
230 244
impl TerminalSession<'_> {
365 379
    fn from(error: syntax::Error) -> Self {
366 380
        Self::Highlight(error)
367 381
    }
368 382
}
369 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 +
370 394
impl std::fmt::Display for Error {
371 395
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 396
        match self {
373 397
            Self::Io(error) => write!(f, "{error}"),
374 398
            Self::Git(code) => write!(f, "git diff exited with status {code}"),
383 407
#[cfg(test)]
384 408
#[allow(clippy::unwrap_used)]
385 409
mod tests {
386 410
    use super::*;
387 411
388 -
    #[test]
389 -
    fn ansi_colored_git_pager_input_decodes() {
390 -
        let input = b"\
391 -
\x1b[33m
a.rs\x1b[m +0 -0
crates/diff/src/commit.rs +6 -5
131 131
        })
132 132
    }
133 133
}
134 134
135 135
#[cfg(test)]
136 +
#[allow(clippy::unwrap_used)]
136 137
mod tests {
137 138
    use super::*;
138 139
139 140
    #[test]
140 141
    fn parses_headers_only() {
141 -
        let commit = Commit::from_str("commit abc\nAuthor: A\n\n").expect("parses");
142 +
        let commit = Commit::from_str("commit abc\nAuthor: A\n\n").unwrap();
142 143
143 144
        assert_eq!(commit.hash.as_str(), "abc");
144 145
        assert_eq!(commit.decoration, None);
145 146
        assert_eq!(commit.header("author"), Some("A"));
146 147
        assert!(commit.message.is_empty());
148 149
149 150
    #[test]
150 151
    fn parses_sha256_hash() {
151 152
        let oid = "0".repeat(64);
152 153
        let input = format!("commit {oid}\n\n");
153 -
        let commit = Commit::from_str(&input).expect("parses");
154 +
        let commit = Commit::from_str(&input).unwrap();
154 155
155 156
        assert_eq!(commit.hash.as_str(), oid);
156 157
    }
157 158
158 159
    #[test]
159 160
    fn parses_decoration_after_hash() {
160 -
        let commit = Commit::from_str("commit abc (HEAD -> main)\n\n").expect("parses");
161 +
        let commit = Commit::from_str("commit abc (HEAD -> main)\n\n").unwrap();
161 162
162 163
        assert_eq!(commit.hash.as_str(), "abc");
163 164
        assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)"));
164 165
    }
165 166
166 167
    #[test]
167 168
    fn parses_message_with_indent_preserved() {
168 169
        let input = "commit abc\nAuthor: A\n\n    Subject\n\n    Body\n";
169 -
        let commit = Commit::from_str(input).expect("parses");
170 +
        let commit = Commit::from_str(input).unwrap();
170 171
171 172
        assert_eq!(commit.message, "    Subject\n\n    Body\n");
172 173
    }
173 174
174 175
    #[test]
197 198
            "    Subject",
198 199
            "",
199 200
            "    Body",
200 201
            "",
201 202
        ];
202 -
        let commit: Commit = lines.join("\n").parse().expect("parses");
203 +
        let commit: Commit = lines.join("\n").parse().unwrap();
203 204
        let expected: String = lines.iter().map(|line| format!("{line}\n")).collect();
204 205
205 206
        assert_eq!(commit.to_string(), expected);
206 207
    }
207 208
}
crates/diff/src/context.rs added +231 -0
1 +
//! Diff context expansion bookkeeping.
2 +
//!
3 +
//! This module owns the pure logic for expanding and contracting the unchanged
4 +
//! context around hunks: the requested context width, the set of fully
5 +
//! expanded files, and stable id remapping for refetched diffs. The `git diff`
6 +
//! invocation itself is supplied by the caller as a closure, so the library
7 +
//! stays I/O-free.
8 +
9 +
use std::collections::{BTreeSet, HashMap};
10 +
use std::path::{Path, PathBuf};
11 +
12 +
use crate::{DiffDocument, FileDiff, FileId, HunkId, RowId};
13 +
14 +
/// Context line count Git uses when no explicit `-U` option is passed.
15 +
const DEFAULT_CONTEXT_LINES: usize = 3;
16 +
/// Unified diff context used for fully expanded files.
17 +
const FULL_CONTEXT_LINES: usize = 999_999;
18 +
19 +
/// Tracks the requested diff context width and the set of expanded files.
20 +
#[derive(Clone, Debug)]
21 +
pub(crate) struct ContextState {
22 +
    /// Requested context line count.
23 +
    context_lines: usize,
24 +
    /// Files currently expanded to their full source.
25 +
    expanded_files: BTreeSet<FileId>,
26 +
}
27 +
28 +
/// Change to the requested hunk context.
29 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30 +
pub(crate) enum ContextChange {
31 +
    /// Show one more unchanged line around each changed group.
32 +
    Increase,
33 +
    /// Show one fewer unchanged line around each changed group.
34 +
    Decrease,
35 +
    /// Toggle selected file(s) between bounded hunks and full source.
36 +
    ToggleFile,
37 +
}
38 +
39 +
impl ContextState {
40 +
    /// Creates a fresh tracker at Git's default context width.
41 +
    pub(crate) fn new() -> Self {
42 +
        Self {
43 +
            context_lines: DEFAULT_CONTEXT_LINES,
44 +
            expanded_files: BTreeSet::new(),
45 +
        }
46 +
    }
47 +
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,
54 +
        change: ContextChange,
55 +
        file_ids: &[FileId],
56 +
        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();
67 +
68 +
        match change {
69 +
            ContextChange::Increase => self.context_lines = self.context_lines.saturating_add(1),
70 +
            ContextChange::Decrease => {
71 +
                let Some(lines) = self.context_lines.checked_sub(1) else {
72 +
                    return Ok(None);
73 +
                };
74 +
                self.context_lines = lines;
75 +
            }
76 +
            ContextChange::ToggleFile => {
77 +
                let all_expanded = file_ids
78 +
                    .iter()
79 +
                    .all(|file_id| self.expanded_files.contains(file_id));
80 +
81 +
                for file_id in file_ids.iter().copied() {
82 +
                    if all_expanded {
83 +
                        self.expanded_files.remove(&file_id);
84 +
                    } else {
85 +
                        self.expanded_files.insert(file_id);
86 +
                    }
87 +
                }
88 +
            }
89 +
        }
90 +
        let mut target_context: Option<usize> = None;
91 +
        let mut files = Vec::with_capacity(file_ids.len());
92 +
93 +
        for file_id in file_ids.iter().copied() {
94 +
            let Some(file) = document
95 +
                .files
96 +
                .iter()
97 +
                .find(|candidate| candidate.id == file_id)
98 +
            else {
99 +
                continue;
100 +
            };
101 +
            let Some(path) = file.path() else {
102 +
                continue;
103 +
            };
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);
106 +
            if previous == target {
107 +
                continue;
108 +
            }
109 +
            // Every file touched by one input shares the same target context.
110 +
            debug_assert!(target_context.is_none_or(|shared| shared == target));
111 +
112 +
            target_context = Some(target);
113 +
            files.push((path.to_path_buf(), file_id));
114 +
        }
115 +
        let Some(target_context) = target_context else {
116 +
            return Ok(None);
117 +
        };
118 +
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
125 +
    }
126 +
127 +
    /// Returns the Git context size for a file given the active expansion set.
128 +
    fn context_size(expanded: &BTreeSet<FileId>, file: FileId, default: usize) -> usize {
129 +
        if expanded.contains(&file) {
130 +
            FULL_CONTEXT_LINES
131 +
        } else {
132 +
            default
133 +
        }
134 +
    }
135 +
}
136 +
137 +
impl Default for ContextState {
138 +
    fn default() -> Self {
139 +
        Self::new()
140 +
    }
141 +
}
142 +
143 +
impl FileDiff {
144 +
    /// Returns the diff path recorded for this file, preferring the new path.
145 +
    fn path(&self) -> Option<&Path> {
146 +
        self.header
147 +
            .new_path
148 +
            .as_deref()
149 +
            .or(self.header.old_path.as_deref())
150 +
    }
151 +
152 +
    /// 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) {
154 +
        for hunk in &mut self.hunks {
155 +
            hunk.id = HunkId::new(*next_hunk_id);
156 +
            *next_hunk_id += 1;
157 +
158 +
            for line in &mut hunk.lines {
159 +
                line.id = RowId::new(*next_row_id);
160 +
                *next_row_id += 1;
161 +
            }
162 +
        }
163 +
    }
164 +
}
165 +
166 +
/// Refetches `files` at `target_context_lines` and remaps their ids.
167 +
///
168 +
/// Returns `None` when Git's output does not cover every requested file.
169 +
fn rebuild<F, E>(
170 +
    next_ids: (usize, usize),
171 +
    files: &[(PathBuf, FileId)],
172 +
    target_context_lines: usize,
173 +
    fetch: F,
174 +
) -> Result<Option<Vec<FileDiff>>, E>
175 +
where
176 +
    F: FnOnce(usize, &[&Path]) -> Result<Vec<FileDiff>, E>,
177 +
{
178 +
    let paths = files
179 +
        .iter()
180 +
        .map(|(path, _)| path.as_path())
181 +
        .collect::<Vec<_>>();
182 +
    let mut replacements = HashMap::new();
183 +
184 +
    for file in fetch(target_context_lines, &paths)? {
185 +
        let Some(path) = file.path() else {
186 +
            return Ok(None);
187 +
        };
188 +
        replacements.insert(path.to_path_buf(), file);
189 +
    }
190 +
    let (mut next_hunk_id, mut next_row_id) = next_ids;
191 +
    let mut rebuilt = Vec::with_capacity(files.len());
192 +
193 +
    for (path, file_id) in files {
194 +
        let Some(mut replacement) = replacements.remove(path) else {
195 +
            return Ok(None);
196 +
        };
197 +
        replacement.id = *file_id;
198 +
        replacement.remap_ids(&mut next_hunk_id, &mut next_row_id);
199 +
        rebuilt.push(replacement);
200 +
    }
201 +
    Ok(Some(rebuilt))
202 +
}
203 +
204 +
/// Returns the next hunk and row ids after existing content.
205 +
fn next_ids(files: &[FileDiff]) -> (usize, usize) {
206 +
    let mut next_hunk_id = 0;
207 +
    let mut next_row_id = 0;
208 +
209 +
    for file in files {
210 +
        for hunk in &file.hunks {
211 +
            next_hunk_id = next_hunk_id.max(*hunk.id + 1);
212 +
            for line in &hunk.lines {
213 +
                next_row_id = next_row_id.max(*line.id + 1);
214 +
            }
215 +
        }
216 +
    }
217 +
    (next_hunk_id, next_row_id)
218 +
}
219 +
220 +
#[cfg(test)]
221 +
#[allow(clippy::unwrap_used)]
222 +
mod tests {
223 +
    use crate::Decode;
224 +
225 +
    use super::*;
226 +
227 +
    /// A one-file diff with default (`-U3`) context.
228 +
    fn base_document() -> DiffDocument {
229 +
        DiffDocument::decode_str(
230 +
            "\
231 +
a.txt +0 -0
a.txt +0 -0
crates/diff/src/decode.rs +7 -0
99 99
    ///
100 100
    /// Non-UTF-8 bytes are replaced with U+FFFD and ANSI escape sequences are
101 101
    /// stripped before parsing, so output from colored Git pipes round-trips
102 102
    /// without caller-side preprocessing.
103 103
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
104 +
        if !input.contains(&b'\x1b')
105 +
            && let Ok(text) = std::str::from_utf8(input)
106 +
        {
107 +
            let mut reader = io::BufReader::new(text.as_bytes());
108 +
            return Self::decode(&mut reader);
109 +
        }
110 +
104 111
        let text = String::from_utf8_lossy(input);
105 112
        let stripped = rustik_tui::ansi::strip(&text);
106 113
        let mut reader = io::BufReader::new(stripped.as_bytes());
107 114
        Self::decode(&mut reader)
108 115
    }
{ +0 -0
+0 -0
=> break, +0 -0
a.rs +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
a +0 -0
a +0 -0
a +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs\x1b[m +0 -0
crates/diff/src/highlight.rs +20 -18
1 1
//! Highlight request and result protocol for diff rendering.
2 2
3 3
use std::collections::{BTreeMap, hash_map::DefaultHasher};
4 -
use std::hash::{Hash, Hasher as _};
4 +
use std::hash::{Hash, Hasher};
5 5
use std::path::PathBuf;
6 6
use std::sync::Arc;
7 7
8 8
use rustik_highlight as syntax;
9 9
use rustik_tui as tui;
23 23
/// Cache key for one highlighted diff row.
24 24
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25 25
pub struct HighlightKey {
26 26
    /// File containing the row.
27 27
    pub file: FileId,
28 -
    /// Hunk containing the row.
29 -
    pub hunk: HunkId,
30 -
    /// Row to highlight.
31 -
    pub row: RowId,
32 28
    /// Diff side to highlight.
33 29
    pub side: DiffSide,
34 30
    /// One-based source line number.
35 31
    pub source_line: u32,
36 32
    /// Hash of the row text.
44 40
/// Request sent from a visible diff viewport to a highlighter.
45 41
#[derive(Clone, Debug, Eq, PartialEq)]
46 42
pub struct HighlightRequest {
47 43
    /// Stable cache key for this request.
48 44
    pub key: HighlightKey,
45 +
    /// Hunk containing the row.
46 +
    pub hunk: HunkId,
47 +
    /// Row to highlight.
48 +
    pub row: RowId,
49 49
    /// Source path used for syntax inference.
50 50
    pub path: Option<PathBuf>,
51 51
    /// Source-side text used for range highlighting.
52 52
    pub source: HighlightSource,
53 53
}
55 55
/// Highlighted line returned by a worker.
56 56
#[derive(Clone, Debug)]
57 57
pub struct HighlightResult {
58 58
    /// Cache key copied from the original request.
59 59
    pub key: HighlightKey,
60 +
    /// Hunk containing the highlighted row.
61 +
    pub hunk: HunkId,
62 +
    /// Highlighted row.
63 +
    pub row: RowId,
60 64
    /// Renderable highlighted line.
61 65
    pub line: tui::Line,
62 66
}
63 67
64 68
/// File-side source text used to highlight a diff row with surrounding context.
113 117
        let mut hasher = DefaultHasher::new();
114 118
        input.text.hash(&mut hasher);
115 119
116 120
        Self {
117 121
            file: input.file,
118 -
            hunk: input.hunk,
119 -
            row: input.row,
120 122
            side: input.side,
121 123
            source_line: input.source_line,
122 124
            text_hash: hasher.finish(),
123 125
            syntax: input.syntax.unwrap_or("auto").to_owned(),
124 126
            theme: input.theme.to_owned(),
237 239
                let line = request
238 240
                    .source
239 241
                    .line_index(request.key.source_line)
240 242
                    .and_then(|index| lines.remove(&index))
241 243
                    .unwrap_or_else(|| request.plain_line());
242 -
                HighlightResult {
243 -
                    key: request.key,
244 -
                    line,
245 -
                }
244 +
                HighlightResult::new(request, line)
246 245
            })
247 246
            .collect()
248 247
    }
249 248
}
250 249
257 256
            .unwrap_or_default()
258 257
    }
259 258
}
260 259
261 260
impl HighlightResult {
262 -
    /// Returns a plain result for an unhighlightable request.
263 -
    fn plain(request: HighlightRequest) -> Self {
264 -
        let line = request.plain_line();
261 +
    /// Pairs a highlighted line with the metadata copied from its request.
262 +
    pub fn new(request: HighlightRequest, line: Line) -> Self {
265 263
        Self {
266 264
            key: request.key,
265 +
            hunk: request.hunk,
266 +
            row: request.row,
267 267
            line,
268 268
        }
269 269
    }
270 +
271 +
    /// Returns a plain result for an unhighlightable request.
272 +
    fn plain(request: HighlightRequest) -> Self {
273 +
        let line = request.plain_line();
274 +
        Self::new(request, line)
275 +
    }
270 276
}
271 277
272 278
impl From<&HighlightRequest> for HighlightBatchKey {
273 279
    fn from(request: &HighlightRequest) -> Self {
274 280
        Self {
308 314
/// Input fields used to create a [`HighlightKey`].
309 315
#[derive(Clone, Copy, Debug)]
310 316
pub struct HighlightKeyInput<'a> {
311 317
    /// File containing the row.
312 318
    pub file: FileId,
313 -
    /// Hunk containing the row.
314 -
    pub hunk: HunkId,
315 -
    /// Row to highlight.
316 -
    pub row: RowId,
317 319
    /// Diff side to highlight.
318 320
    pub side: DiffSide,
319 321
    /// One-based source line number.
320 322
    pub source_line: u32,
321 323
    /// Source text.
crates/diff/src/lib.rs +7 -5
1 1
//! Unified diff parsing and terminal-buffer rendering.
2 2
//!
3 -
//! The library side is intentionally I/O-free: it parses or accepts patch data,
4 -
//! owns read-only viewer state, and writes frames into a
5 -
//! [`rustik_tui::Buffer`]. The `rustik-diff` binary owns Git, stdin/stdout,
6 -
//! terminals, events, and background workers.
3 +
//! The viewer and renderer are intentionally I/O-free: they parse or accept
4 +
//! patch data, own read-only viewer state, and write frames into a
5 +
//! [`rustik_tui::Buffer`]. Backend access is abstracted behind the
6 +
//! [`rustik_repo::Repo`] trait so the viewer stays testable. The `rustik-diff`
7 +
//! binary owns stdin/stdout, terminals, events, and background workers.
7 8
#![deny(unsafe_code)]
8 9
#![warn(missing_docs)]
9 10
#![warn(clippy::unwrap_used)]
10 11
11 12
mod commit;
13 +
mod context;
12 14
mod document;
13 15
mod highlight;
14 16
mod renderer;
15 17
mod word;
16 18
27 29
pub use highlight::{
28 30
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
29 31
    HighlightResult, HighlightSource,
30 32
};
31 33
pub use renderer::{
32 -
    DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane, DiffState, DiffViewer,
34 +
    ContextError, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane, DiffState, DiffViewer,
33 35
    FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
34 36
};
crates/diff/src/renderer.rs +262 -108
2 2
3 3
mod tree;
4 4
5 5
use std::collections::btree_map::Entry;
6 6
use std::collections::{BTreeMap, BTreeSet};
7 +
use std::convert::Infallible;
7 8
use std::path::PathBuf;
8 9
9 10
use rustik_highlight as syntax;
11 +
use rustik_repo::{Repo, RepoError};
10 12
use rustik_tui as tui;
11 13
use tui::event::Modifiers;
12 14
use tui::{
13 15
    Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton,
14 16
    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
15 17
    VStack, View, Viewport, Widget, colors,
16 18
};
17 19
20 +
use crate::context::{ContextChange, ContextState};
18 21
use crate::highlight::{HighlightKeyInput, HighlightResult};
19 22
use crate::word;
20 23
use crate::{
21 -
    Commit, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind,
22 -
    HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
24 +
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
25 +
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
23 26
};
24 27
25 28
pub use tree::{FileSelection, FileTreeMode, FileTreeTarget};
26 29
27 30
/// Minimum width before the renderer attempts table-style diff rows.
211 214
    preamble: Vec<Line>,
212 215
    /// File-tree pane state and model.
213 216
    file_tree: tree::FileTreeViewer,
214 217
    /// Cached rendered row positions for visible files.
215 218
    index: RowIndex,
219 +
    /// Hunk-context expansion bookkeeping.
220 +
    context: ContextState,
216 221
}
217 222
223 +
/// A failure while refetching wider diff context for the viewer.
224 +
#[derive(Debug)]
225 +
pub enum ContextError {
226 +
    /// The repo backend failed to produce a diff.
227 +
    Repo(RepoError),
228 +
    /// The refetched diff could not be parsed.
229 +
    Decode(DecodeError),
230 +
}
231 +
232 +
impl From<RepoError> for ContextError {
233 +
    fn from(error: RepoError) -> Self {
234 +
        Self::Repo(error)
235 +
    }
236 +
}
237 +
238 +
impl From<DecodeError> for ContextError {
239 +
    fn from(error: DecodeError) -> Self {
240 +
        Self::Decode(error)
241 +
    }
242 +
}
243 +
244 +
impl std::fmt::Display for ContextError {
245 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 +
        match self {
247 +
            Self::Repo(error) => write!(f, "{error}"),
248 +
            Self::Decode(error) => write!(f, "{error}"),
249 +
        }
250 +
    }
251 +
}
252 +
253 +
impl std::error::Error for ContextError {}
254 +
218 255
/// Cached rendered row positions for the current document visibility state.
219 256
///
220 257
/// Visible files tile the content region contiguously, so each file is stored
221 258
/// by its first rendered row only; its last row is the next file's start (or
222 259
/// [`RowIndex::rows`] for the final file).
366 403
            pending_highlights: BTreeSet::new(),
367 404
            word_diffs: BTreeMap::new(),
368 405
            preamble,
369 406
            file_tree,
370 407
            index: RowIndex::default(),
408 +
            context: ContextState::new(),
371 409
        };
372 410
        viewer.rebuild_index();
373 411
        viewer
374 412
    }
375 413
391 429
        if rebuild {
392 430
            self.rebuild_index();
393 431
        }
394 432
    }
395 433
434 +
    /// Replaces existing file diffs in place, matching them by id.
435 +
    pub fn replace_file_diffs(&mut self, files: impl IntoIterator<Item = FileDiff>) {
436 +
        for replacement in files {
437 +
            // File ids match list indices for the originally decoded document;
438 +
            // fall back to a scan when a refetch has perturbed that.
439 +
            let existing = match self.document.files.get_mut(*replacement.id) {
440 +
                Some(existing) if existing.id == replacement.id => Some(existing),
441 +
                _ => self
442 +
                    .document
443 +
                    .files
444 +
                    .iter_mut()
445 +
                    .find(|file| file.id == replacement.id),
446 +
            };
447 +
            if let Some(existing) = existing {
448 +
                *existing = replacement;
449 +
            }
450 +
        }
451 +
        self.pending_highlights.clear();
452 +
        self.word_diffs.clear();
453 +
        self.rebuild_index();
454 +
    }
455 +
456 +
    /// Expands or contracts hunk context, refetching diffs through `repo`.
457 +
    ///
458 +
    /// Returns whether the document changed. `false` means the input was a
459 +
    /// no-op -- already at minimum width, or no file to target. On a failed
460 +
    /// refetch the requested context is rolled back.
461 +
    fn update_context(
462 +
        &mut self,
463 +
        change: ContextChange,
464 +
        repo: &dyn Repo,
465 +
    ) -> Result<bool, ContextError> {
466 +
        let active = self
467 +
            .focused_file()
468 +
            .or_else(|| self.document.files.first().map(|file| file.id));
469 +
        // An explicit multi-file selection targets exactly those files; any other
470 +
        // selection targets the active file alone, falling back to the first file.
471 +
        let file_ids: Vec<FileId> = match &self.state.file_selection {
472 +
            FileSelection::All => {
473 +
                let active =
474 +
                    active.filter(|id| self.document.files.iter().any(|file| file.id == *id));
475 +
476 +
                active
477 +
                    .or_else(|| self.document.files.first().map(|file| file.id))
478 +
                    .into_iter()
479 +
                    .collect()
480 +
            }
481 +
            FileSelection::Files(files) => self
482 +
                .document
483 +
                .files
484 +
                .iter()
485 +
                .filter(|file| files.contains(&file.id))
486 +
                .map(|file| file.id)
487 +
                .collect(),
488 +
        };
489 +
        let replacements =
490 +
            self.context
491 +
                .apply(change, &file_ids, &self.document, |context_lines, paths| {
492 +
                    let patch = repo.diff(context_lines, paths)?;
493 +
                    let document = DiffDocument::decode_bytes(&patch)?;
494 +
                    Ok::<_, ContextError>(document.files)
495 +
                })?;
496 +
        let Some(replacements) = replacements else {
497 +
            return Ok(false);
498 +
        };
499 +
        let mut state = self.state.clone();
500 +
        if !file_ids.is_empty() {
501 +
            state.focus = active.map(DiffFocus::File);
502 +
        }
503 +
        self.replace_file_diffs(replacements);
504 +
        self.set_state(state);
505 +
506 +
        Ok(true)
507 +
    }
508 +
396 509
    /// Sets the first visible rendered row.
397 510
    pub fn set_scroll(&mut self, scroll: usize) {
398 511
        self.state.scroll = scroll;
399 512
    }
400 513
407 520
    pub fn set_collapsed_files(&mut self, collapsed_files: BTreeSet<FileId>) {
408 521
        self.state.collapsed_files = collapsed_files;
409 522
        self.rebuild_index();
410 523
    }
411 524
525 +
    /// Returns the file containing the current focus.
526 +
    pub fn focused_file(&self) -> Option<FileId> {
527 +
        match self.state.focus? {
528 +
            DiffFocus::File(file) => Some(file),
529 +
            DiffFocus::Hunk(hunk) => self
530 +
                .document
531 +
                .files
532 +
                .iter()
533 +
                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
534 +
                .map(|file| file.id),
535 +
        }
536 +
    }
537 +
412 538
    /// Renders the current frame into `buf`.
413 539
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
414 540
        if area.is_empty() {
415 541
            return;
416 542
        }
443 569
            diff,
444 570
            tree: Some(tree),
445 571
        }
446 572
    }
447 573
448 -
    /// Returns the file-tree target under the cursor.
449 -
    pub fn file_tree_target(&self) -> Option<FileTreeTarget> {
450 -
        self.file_tree.target()
451 -
    }
452 -
453 574
    /// Renders the file tree pane.
454 575
    fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
455 576
        let active = self.state.pane == DiffPane::FileTree;
456 577
        self.file_tree.render(
457 578
            &self.state.file_selection,
570 691
        }
571 692
    }
572 693
573 694
    /// Applies one input event to the viewer.
574 695
    pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
696 +
        match self.handle_input_event(event, area, false, |_, _, _| {
697 +
            Ok::<Control, Infallible>(Control::Continue)
698 +
        }) {
699 +
            Ok(control) => control,
700 +
            Err(error) => match error {},
701 +
        }
702 +
    }
703 +
704 +
    /// Applies one input event to the viewer, including repo-backed context changes.
705 +
    pub fn handle_input_with_repo(
706 +
        &mut self,
707 +
        event: Event<()>,
708 +
        area: Rect,
709 +
        repo: &dyn Repo,
710 +
    ) -> Result<Control, ContextError> {
711 +
        self.handle_input_event(event, area, true, |viewer, change, area| {
712 +
            if !viewer.update_context(change, repo)? {
713 +
                return Ok(Control::Continue);
714 +
            }
715 +
            viewer.apply(DiffAction::Resize, area);
716 +
717 +
            Ok(Control::Redraw)
718 +
        })
719 +
    }
720 +
721 +
    /// Routes one input event into a viewer action.
722 +
    fn handle_input_event<E>(
723 +
        &mut self,
724 +
        event: Event<()>,
725 +
        area: Rect,
726 +
        context_wheel: bool,
727 +
        mut apply_context: impl FnMut(&mut Self, ContextChange, Rect) -> Result<Control, E>,
728 +
    ) -> Result<Control, E> {
575 729
        let action = match event {
576 -
            Event::Key(Key::Char('q')) => return Control::Quit,
730 +
            Event::Key(Key::Char('q')) => return Ok(Control::Quit),
731 +
            Event::Key(Key::Char('.')) => {
732 +
                return apply_context(self, ContextChange::Increase, area);
733 +
            }
734 +
            Event::Key(Key::Char(',')) => {
735 +
                return apply_context(self, ContextChange::Decrease, area);
736 +
            }
737 +
            Event::Key(Key::Char('x')) => {
738 +
                return apply_context(self, ContextChange::ToggleFile, area);
739 +
            }
740 +
            Event::Mouse(Mouse::Press {
741 +
                button: MouseButton::WheelUp,
742 +
                modifiers,
743 +
                ..
744 +
            }) if modifiers.contains(Modifiers::CONTROL) && context_wheel => {
745 +
                return apply_context(self, ContextChange::Increase, area);
746 +
            }
747 +
            Event::Mouse(Mouse::Press {
748 +
                button: MouseButton::WheelDown,
749 +
                modifiers,
750 +
                ..
751 +
            }) if modifiers.contains(Modifiers::CONTROL) && context_wheel => {
752 +
                return apply_context(self, ContextChange::Decrease, area);
753 +
            }
577 754
            Event::Resize(_) => DiffAction::Resize,
578 755
            Event::Mouse(Mouse::Press {
579 756
                button: MouseButton::WheelDown,
580 757
                ..
581 758
            }) => DiffAction::Scroll(Scroll::Lines(WHEEL_SCROLL_ROWS)),
585 762
            }) => DiffAction::Scroll(Scroll::Lines(-WHEEL_SCROLL_ROWS)),
586 763
            Event::Mouse(Mouse::Press {
587 764
                button: MouseButton::Left,
588 765
                at,
589 766
                modifiers,
590 -
            }) => return self.handle_click(at, modifiers, area),
591 -
            _ => match self.state.pane {
592 -
                DiffPane::FileTree => return self.handle_file_tree_key(event, area),
593 -
                DiffPane::Main => return self.handle_main_key(event, area),
594 -
            },
595 -
        };
596 -
        self.apply(action, area);
597 -
598 -
        Control::Redraw
599 -
    }
600 -
601 -
    /// Applies a left-click event.
602 -
    fn handle_click(&mut self, at: tui::Point, modifiers: Modifiers, area: Rect) -> Control {
603 -
        let Some(tree) = self.layout(area).tree else {
604 -
            return Control::Continue;
605 -
        };
606 -
        if !self.file_tree.select_at(tree, at) {
607 -
            return Control::Continue;
608 -
        }
609 -
        self.state.pane = DiffPane::FileTree;
610 -
611 -
        let action = if modifiers.contains(Modifiers::CONTROL) {
612 -
            DiffAction::ToggleFileTreeTarget
613 -
        } else {
614 -
            DiffAction::ActivateFileTreeTarget
615 -
        };
616 -
        self.apply(action, area);
617 -
618 -
        Control::Redraw
619 -
    }
620 -
621 -
    /// Applies a key event while the main diff owns input.
622 -
    fn handle_main_key(&mut self, event: Event<()>, area: Rect) -> Control {
623 -
        let action = match event {
624 -
            Event::Key(Key::Char('h')) => DiffAction::EnterFileTree,
625 -
            Event::Key(Key::Esc) => {
626 -
                if self.apply(DiffAction::EnterFileTree, area) == ViewChange::Changed {
627 -
                    return Control::Redraw;
767 +
            }) => {
768 +
                let Some(tree) = self.layout(area).tree else {
769 +
                    return Ok(Control::Continue);
770 +
                };
771 +
                if !self.file_tree.select_at(tree, at) {
772 +
                    return Ok(Control::Continue);
628 773
                }
629 -
                if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
630 -
                    return Control::Redraw;
774 +
                self.state.pane = DiffPane::FileTree;
775 +
                if modifiers.contains(Modifiers::CONTROL) {
776 +
                    DiffAction::ToggleFileTreeTarget
777 +
                } else {
778 +
                    DiffAction::ActivateFileTreeTarget
631 779
                }
632 -
                return Control::Quit;
633 -
            }
634 -
            Event::Key(Key::Char('j') | Key::Down) => {
635 -
                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
636 -
            }
637 -
            Event::Key(Key::Char('k') | Key::Up) => {
638 -
                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
639 -
            }
640 -
            Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
641 -
            Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
642 -
            Event::Key(Key::Ctrl('d')) => {
643 -
                DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
644 -
            }
645 -
            Event::Key(Key::Ctrl('u')) => {
646 -
                DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
647 780
            }
648 -
            Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
649 -
            Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
650 -
            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
651 -
            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
652 -
            Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
653 -
            _ => return Control::Continue,
654 -
        };
655 -
        self.apply(action, area);
656 -
657 -
        Control::Redraw
658 -
    }
659 -
660 -
    /// Applies a key event while the file tree owns input.
661 -
    fn handle_file_tree_key(&mut self, event: Event<()>, area: Rect) -> Control {
662 -
        let action = match event {
663 -
            Event::Key(Key::Esc | Key::Char('l')) => DiffAction::LeaveFileTree,
664 -
            Event::Key(Key::Enter) => DiffAction::ActivateFileTreeTarget,
665 -
            Event::Key(Key::Char(' ')) => DiffAction::ToggleFileTreeTarget,
666 -
            Event::Key(Key::Char('j') | Key::Down) => DiffAction::MoveFileTree(1),
667 -
            Event::Key(Key::Char('k') | Key::Up) => DiffAction::MoveFileTree(-1),
668 -
            Event::Key(Key::Right) => DiffAction::ExpandFileTreeFolder,
669 -
            Event::Key(Key::Left) => DiffAction::CollapseFileTreeFolder,
670 -
            Event::Key(Key::Char('J')) => DiffAction::ExtendFileTreeSelection(1),
671 -
            Event::Key(Key::Char('K')) => DiffAction::ExtendFileTreeSelection(-1),
672 -
            _ => return Control::Continue,
781 +
            event => match (self.state.pane, event) {
782 +
                (DiffPane::Main, Event::Key(Key::Char('h'))) => DiffAction::EnterFileTree,
783 +
                (DiffPane::Main, Event::Key(Key::Esc)) => {
784 +
                    if self.apply(DiffAction::EnterFileTree, area) == ViewChange::Changed {
785 +
                        return Ok(Control::Redraw);
786 +
                    }
787 +
                    if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
788 +
                        return Ok(Control::Redraw);
789 +
                    }
790 +
                    return Ok(Control::Quit);
791 +
                }
792 +
                (DiffPane::Main, Event::Key(Key::Char('j') | Key::Down)) => {
793 +
                    DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
794 +
                }
795 +
                (DiffPane::Main, Event::Key(Key::Char('k') | Key::Up)) => {
796 +
                    DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
797 +
                }
798 +
                (DiffPane::Main, Event::Key(Key::Char(' ') | Key::PageDown)) => {
799 +
                    DiffAction::Scroll(Scroll::Pages(1))
800 +
                }
801 +
                (DiffPane::Main, Event::Key(Key::PageUp)) => DiffAction::Scroll(Scroll::Pages(-1)),
802 +
                (DiffPane::Main, Event::Key(Key::Ctrl('d'))) => {
803 +
                    DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
804 +
                }
805 +
                (DiffPane::Main, Event::Key(Key::Ctrl('u'))) => {
806 +
                    DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
807 +
                }
808 +
                (DiffPane::Main, Event::Key(Key::Char('g') | Key::Home)) => {
809 +
                    DiffAction::Scroll(Scroll::Top)
810 +
                }
811 +
                (DiffPane::Main, Event::Key(Key::Char('G') | Key::End)) => {
812 +
                    DiffAction::Scroll(Scroll::Bottom)
813 +
                }
814 +
                (DiffPane::Main, Event::Key(Key::Char('n'))) => DiffAction::FocusNext,
815 +
                (DiffPane::Main, Event::Key(Key::Char('p'))) => DiffAction::FocusPrevious,
816 +
                (DiffPane::Main, Event::Key(Key::Enter)) => DiffAction::ToggleFocusedFile,
817 +
                (DiffPane::FileTree, Event::Key(Key::Esc | Key::Char('l'))) => {
818 +
                    DiffAction::LeaveFileTree
819 +
                }
820 +
                (DiffPane::FileTree, Event::Key(Key::Enter)) => DiffAction::ActivateFileTreeTarget,
821 +
                (DiffPane::FileTree, Event::Key(Key::Char(' '))) => {
822 +
                    DiffAction::ToggleFileTreeTarget
823 +
                }
824 +
                (DiffPane::FileTree, Event::Key(Key::Char('j') | Key::Down)) => {
825 +
                    DiffAction::MoveFileTree(1)
826 +
                }
827 +
                (DiffPane::FileTree, Event::Key(Key::Char('k') | Key::Up)) => {
828 +
                    DiffAction::MoveFileTree(-1)
829 +
                }
830 +
                (DiffPane::FileTree, Event::Key(Key::Right)) => DiffAction::ExpandFileTreeFolder,
831 +
                (DiffPane::FileTree, Event::Key(Key::Left)) => DiffAction::CollapseFileTreeFolder,
832 +
                (DiffPane::FileTree, Event::Key(Key::Char('J'))) => {
833 +
                    DiffAction::ExtendFileTreeSelection(1)
834 +
                }
835 +
                (DiffPane::FileTree, Event::Key(Key::Char('K'))) => {
836 +
                    DiffAction::ExtendFileTreeSelection(-1)
837 +
                }
838 +
                _ => return Ok(Control::Continue),
839 +
            },
673 840
        };
674 841
        self.apply(action, area);
675 842
676 -
        Control::Redraw
843 +
        Ok(Control::Redraw)
677 844
    }
678 845
679 846
    /// Returns highlight requests for visible source rows plus configured lookahead.
680 847
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
681 848
        let diff = self.layout(area).diff;
695 862
                continue;
696 863
            }
697 864
            self.pending_highlights.insert(key.clone());
698 865
            requests.push(HighlightRequest {
699 866
                key,
867 +
                hunk: meta.hunk,
868 +
                row: meta.row,
700 869
                path: meta.path,
701 870
                source: HighlightSource::new(meta.text, meta.source_line),
702 871
            });
703 872
        }
704 873
        requests
706 875
707 876
    /// Returns the highlight-cache key for one diff row.
708 877
    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
709 878
        HighlightKey::new(HighlightKeyInput {
710 879
            file: meta.file,
711 -
            hunk: meta.hunk,
712 -
            row: meta.row,
713 880
            side: meta.side,
714 881
            source_line: meta.source_line,
715 882
            text: &meta.text,
716 883
            syntax: self.options.syntax.as_deref(),
717 884
            theme: &self.options.theme,
727 894
    pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
728 895
        let mut changed = false;
729 896
        for result in results {
730 897
            self.pending_highlights.remove(&result.key);
731 898
732 -
            if let Entry::Vacant(slot) = self.word_diffs.entry(result.key.hunk)
899 +
            if let Entry::Vacant(slot) = self.word_diffs.entry(result.hunk)
733 900
                && let Some(hunk) = self
734 901
                    .document
735 902
                    .files
736 903
                    .iter()
737 904
                    .find(|f| f.id == result.key.file)
738 -
                    .and_then(|f| f.hunks.iter().find(|h| h.id == result.key.hunk))
905 +
                    .and_then(|f| f.hunks.iter().find(|h| h.id == result.hunk))
739 906
            {
740 907
                slot.insert(crate::word::compute(hunk));
741 908
            }
742 909
            let bg = match result.key.side {
743 910
                DiffSide::New => self.options.diff_palette.positive_word_bg,
744 911
                DiffSide::Old => self.options.diff_palette.negative_word_bg,
745 912
            };
746 913
            let line = if let Some(ranges) = self
747 914
                .word_diffs
748 -
                .get(&result.key.hunk)
749 -
                .and_then(|changes| changes.get(&result.key.row))
915 +
                .get(&result.hunk)
916 +
                .and_then(|changes| changes.get(&result.row))
750 917
            {
751 918
                result.line.overlay_ranges(ranges, Style::default().bg(bg))
752 919
            } else {
753 920
                result.line
754 921
            };
1137 1304
        };
1138 1305
        self.state.collapsed_files.insert(file);
1139 1306
        self.state.focus = Some(DiffFocus::File(file));
1140 1307
    }
1141 1308
1142 -
    /// Returns the file containing the current focus.
1143 -
    fn focused_file(&self) -> Option<FileId> {
1144 -
        match self.state.focus? {
1145 -
            DiffFocus::File(file) => Some(file),
1146 -
            DiffFocus::Hunk(hunk) => self
1147 -
                .document
1148 -
                .files
1149 -
                .iter()
1150 -
                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
1151 -
                .map(|file| file.id),
1152 -
        }
1153 -
    }
1154 -
1155 1309
    /// Returns one rendered row inside a hunk.
1156 1310
    fn hunk_row_at(
1157 1311
        &self,
1158 1312
        file: &FileDiff,
1159 1313
        hunk: &crate::Hunk,
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
crates/diff/src/renderer/tree.rs +1 -0
121 121
122 122
        Self { model, state }
123 123
    }
124 124
125 125
    /// Returns the file-tree target under the cursor.
126 +
    #[cfg(test)]
126 127
    pub(super) fn target(&self) -> Option<FileTreeTarget> {
127 128
        self.state
128 129
            .selected()
129 130
            .and_then(|id| self.model.target_for(id))
130 131
    }
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden.rs +4 -4
186 186
    let request = viewer
187 187
        .highlight_requests(Rect::new(0, 0, 64, 5))
188 188
        .into_iter()
189 189
        .next()
190 190
        .unwrap();
191 -
    viewer.apply_highlights([HighlightResult {
192 -
        key: request.key,
193 -
        line: Line::new(Label::new("highlighted context").fg(Color::Red)),
194 -
    }]);
191 +
    viewer.apply_highlights([HighlightResult::new(
192 +
        request,
193 +
        Line::new(Label::new("highlighted context").fg(Color::Red)),
194 +
    )]);
195 195
196 196
    assert_golden(
197 197
        "highlighted_source_64x5.txt",
198 198
        include_str!("golden/highlighted_source_64x5.txt"),
199 199
        viewer,
crates/tui-termion/src/event.rs +8 -0
263 263
                button: MouseButton::Left,
264 264
                at: Point::new(0, 1),
265 265
                modifiers: Modifiers::NONE,
266 266
            })
267 267
        );
268 +
        assert_eq!(
269 +
            press(b"\x1B[<80;3;4M"),
270 +
            Event::Mouse(Mouse::Press {
271 +
                button: MouseButton::WheelUp,
272 +
                at: Point::new(2, 3),
273 +
                modifiers: Modifiers::CONTROL,
274 +
            })
275 +
        );
268 276
    }
269 277
270 278
    #[test]
271 279
    fn mouse_buttons_are_mapped() {
272 280
        assert_eq!(