diff: Make the viewer reusable by host apps
39fa18a7d591b4aa0a6018af9cb7ae3a582c3f26
Expose the pieces a host application needs to build on the diff viewer without reimplementing its rendering, while keeping the plain `rustik-diff` pager behavior identical. * Add a `DiffDecorator` trait with `FileDecoration` and `HunkDecoration` so a host can overlay a status glyph and annotations onto file headers and corner markers plus a mute style onto hunks. Decorations are pure in-row overlays, so row counts, scrolling, focus, and sticky headers are unchanged when no decorator is set. * Promote the internal file tree to a public `FileTree` widget that can be placed independently of the diff body. * Move the built-in highlighting assets into the library as `Builtins`, behind a `builtins` feature, so callers that bring their own highlighting can opt out of the embedded grammars and theme. * Add `spawn_highlighter`, a background worker that serves the viewer's highlight and context-expansion requests, and rewire the pager binary onto it instead of its own duplicate worker. Assisted-by: Claude:claude-opus-4-8
1 parent
60d4ef19
crates/diff/Cargo.toml
+12 -1
| 5 | 5 | homepage = "https://crates.io/crates/rustik-diff" |
|
| 6 | 6 | version.workspace = true |
|
| 7 | 7 | edition.workspace = true |
|
| 8 | 8 | license.workspace = true |
|
| 9 | 9 | ||
| 10 | + | [features] |
|
| 11 | + | default = ["builtins"] |
|
| 12 | + | # Batteries-included highlighting: the embedded grammar/theme assets, the |
|
| 13 | + | # `Builtins` loader, and the background `spawn_highlighter` helper. |
|
| 14 | + | builtins = ["rustik-highlight/syntaxes"] |
|
| 15 | + | ||
| 10 | 16 | [dependencies] |
|
| 11 | - | rustik-highlight = { workspace = true, features = ["syntaxes"] } |
|
| 17 | + | rustik-highlight.workspace = true |
|
| 12 | 18 | rustik-repo.workspace = true |
|
| 13 | 19 | rustik-tui = { workspace = true, features = ["widgets"] } |
|
| 14 | 20 | rustik-tui-termion.workspace = true |
|
| 15 | 21 | ||
| 22 | + | [[bin]] |
|
| 23 | + | name = "rustik-diff" |
|
| 24 | + | path = "src/bin/rustik-diff.rs" |
|
| 25 | + | required-features = ["builtins"] |
|
| 26 | + | ||
| 16 | 27 | [[bench]] |
|
| 17 | 28 | name = "render" |
|
| 18 | 29 | harness = false |
|
| 19 | 30 | ||
| 20 | 31 | [[bench]] |
crates/diff/src/bin/rustik-diff.rs
+2 -6
| 1 | 1 | //! Binary entry point for the `rustik-diff` pager. |
|
| 2 | 2 | ||
| 3 | - | #[path = "rustik-diff/builtins.rs"] |
|
| 4 | - | mod builtins; |
|
| 5 | 3 | #[path = "rustik-diff/error.rs"] |
|
| 6 | 4 | mod error; |
|
| 7 | 5 | #[path = "rustik-diff/session.rs"] |
|
| 8 | 6 | mod session; |
|
| 9 | 7 |
| 11 | 9 | use std::io::{self, IsTerminal as _, Read as _, Write as _}; |
|
| 12 | 10 | use std::path::Path; |
|
| 13 | 11 | use std::process::{Command, ExitCode, Output}; |
|
| 14 | 12 | use std::{env, str}; |
|
| 15 | 13 | ||
| 16 | - | use rustik_diff::{Decode, DiffDocument, DiffOptions, DiffViewer, FileTreeMode}; |
|
| 14 | + | use rustik_diff::{Builtins, Decode, DiffDocument, DiffOptions, DiffViewer, FileTreeMode}; |
|
| 17 | 15 | use rustik_repo::GitRepo; |
|
| 18 | 16 | use rustik_tui as tui; |
|
| 19 | 17 | use rustik_tui::Terminal; |
|
| 20 | 18 | use rustik_tui_termion as tui_termion; |
|
| 21 | 19 | ||
| 22 | - | use builtins::Builtins; |
|
| 23 | 20 | use error::Error; |
|
| 24 | 21 | ||
| 25 | 22 | /// Default static render width for non-terminal output. |
|
| 26 | 23 | const STATIC_COLS: usize = 100; |
|
| 27 | 24 | /// Maximum static render rows for non-terminal output. |
| 113 | 110 | options.file_tree = FileTreeMode::Auto; |
|
| 114 | 111 | options.file_tree_root = root; |
|
| 115 | 112 | ||
| 116 | 113 | let backend = tui_termion::term::screen()?; |
|
| 117 | 114 | let mut terminal = Terminal::new(backend)?; |
|
| 118 | - | let highlight_document = document.clone(); |
|
| 119 | 115 | let mut viewer = DiffViewer::new(document, options); |
|
| 120 | 116 | ||
| 121 | 117 | terminal.clear()?; |
|
| 122 | 118 | terminal.set_cursor_visible(false)?; |
|
| 123 | 119 | ||
| 124 | 120 | let repo = args.map(|args| GitRepo::new(cwd, args)); |
|
| 125 | - | let result = session::run(&mut terminal, &mut viewer, highlight_document, repo, debug); |
|
| 121 | + | let result = session::run(&mut terminal, &mut viewer, repo, debug); |
|
| 126 | 122 | let cursor = terminal.set_cursor_visible(true); |
|
| 127 | 123 | ||
| 128 | 124 | result?; |
|
| 129 | 125 | cursor.map_err(Error::Io) |
|
| 130 | 126 | } |
crates/diff/src/bin/rustik-diff/session.rs
+41 -338
| 1 | 1 | //! Terminal session loop for the pager binary. |
|
| 2 | 2 | ||
| 3 | - | use std::collections::{BTreeMap, BTreeSet}; |
|
| 4 | 3 | use std::io; |
|
| 5 | - | use std::sync::mpsc::{self, SyncSender, TrySendError}; |
|
| 4 | + | use std::sync::mpsc; |
|
| 6 | 5 | use std::thread; |
|
| 7 | 6 | use std::time::{Duration, Instant}; |
|
| 8 | 7 | ||
| 9 | 8 | use rustik_diff::{ |
|
| 10 | - | BuiltinHighlighter, ContextChange, ContextRequest, ContextUpdate, Decode, DiffDocument, |
|
| 11 | - | DiffHighlighter, DiffSide, DiffViewer, FileId, HighlightRequest, HighlightResult, |
|
| 12 | - | HighlightSource, Oid, |
|
| 9 | + | ContextChange, DiffViewer, HighlightOutput, HighlightRequest, Highlighter, spawn_highlighter, |
|
| 13 | 10 | }; |
|
| 14 | - | use rustik_repo::{GitRepo, Repo}; |
|
| 11 | + | use rustik_repo::GitRepo; |
|
| 15 | 12 | use rustik_tui as tui; |
|
| 16 | 13 | use rustik_tui::{ |
|
| 17 | 14 | Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Style, Terminal, |
|
| 18 | 15 | }; |
|
| 19 | 16 | use rustik_tui_termion as tui_termion; |
|
| 20 | 17 | use tui::event::Modifiers; |
|
| 21 | 18 | ||
| 22 | - | use crate::builtins::Builtins; |
|
| 23 | 19 | use crate::error::Error; |
|
| 24 | 20 | ||
| 25 | 21 | /// Number of rows reserved for the bottom footer when possible. |
|
| 26 | 22 | const FOOTER_ROWS: usize = 1; |
|
| 27 | 23 | /// Foreground color for dim footer text. |
|
| 28 | 24 | const FOOTER_FG: Color = Color::Fixed(240); |
|
| 29 | 25 | /// Background color for the footer row. |
|
| 30 | 26 | const FOOTER_BG: Color = Color::Fixed(233); |
|
| 31 | - | /// Source context lines fetched around highlighted rows. |
|
| 32 | - | const HIGHLIGHT_CONTEXT_LINES: usize = 256; |
|
| 33 | 27 | ||
| 34 | 28 | /// Terminal backend used by the interactive viewer. |
|
| 35 | 29 | type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>; |
|
| 36 | 30 | ||
| 37 | 31 | /// Runs the terminal event loop. |
|
| 38 | 32 | pub(super) fn run( |
|
| 39 | 33 | terminal: &mut DiffTerminal, |
|
| 40 | 34 | viewer: &mut DiffViewer, |
|
| 41 | - | document: DiffDocument, |
|
| 42 | 35 | repo: Option<GitRepo>, |
|
| 43 | 36 | debug: bool, |
|
| 44 | 37 | ) -> Result<(), Error> { |
|
| 45 | 38 | let (events_tx, events_rx) = mpsc::channel(); |
|
| 46 | 39 | TerminalEvent::spawn_input_worker(events_tx.clone()); |
|
| 47 | 40 | ||
| 48 | - | let worker_tx = TerminalEvent::spawn_worker(events_tx, document, repo); |
|
| 41 | + | let highlighter = spawn_highlighter(viewer.document(), repo, move |output| { |
|
| 42 | + | let _ = events_tx.send(TerminalEvent::Highlight(output)); |
|
| 43 | + | }); |
|
| 49 | 44 | let mut session = TerminalSession { |
|
| 50 | 45 | terminal, |
|
| 51 | 46 | viewer, |
|
| 52 | - | worker_tx, |
|
| 47 | + | highlighter, |
|
| 53 | 48 | context_pending: false, |
|
| 54 | 49 | debug, |
|
| 55 | 50 | debug_status: None, |
|
| 51 | + | visible_started: None, |
|
| 56 | 52 | }; |
|
| 57 | 53 | session.redraw()?; |
|
| 58 | 54 | ||
| 59 | 55 | while let Ok(event) = events_rx.recv() { |
|
| 60 | 56 | let mut redraw = false; |
| 77 | 73 | struct TerminalSession<'a> { |
|
| 78 | 74 | /// Terminal frame target. |
|
| 79 | 75 | terminal: &'a mut DiffTerminal, |
|
| 80 | 76 | /// Diff viewer state. |
|
| 81 | 77 | viewer: &'a mut DiffViewer, |
|
| 82 | - | /// Background worker command channel. |
|
| 83 | - | worker_tx: SyncSender<WorkerCommand>, |
|
| 78 | + | /// Background highlighter handle. |
|
| 79 | + | highlighter: Highlighter, |
|
| 84 | 80 | /// Whether a context refetch is already in flight. |
|
| 85 | 81 | context_pending: bool, |
|
| 86 | 82 | /// Whether debug footer diagnostics are shown. |
|
| 87 | 83 | debug: bool, |
|
| 88 | 84 | /// Latest highlight timing shown in the debug footer. |
|
| 89 | 85 | debug_status: Option<String>, |
|
| 86 | + | /// Time the in-flight visible highlight batch was requested, for debug. |
|
| 87 | + | visible_started: Option<Instant>, |
|
| 90 | 88 | } |
|
| 91 | 89 | ||
| 92 | 90 | impl TerminalSession<'_> { |
|
| 93 | 91 | /// Applies one event and records whether the session should redraw. |
|
| 94 | 92 | fn update(&mut self, event: TerminalEvent, redraw: &mut bool) -> Result<Control, Error> { |
| 105 | 103 | if control == Control::Redraw || (resized && control != Control::Quit) { |
|
| 106 | 104 | *redraw = true; |
|
| 107 | 105 | } |
|
| 108 | 106 | Ok(control) |
|
| 109 | 107 | } |
|
| 110 | - | TerminalEvent::Highlights(update) => { |
|
| 111 | - | if self.debug && update.kind == HighlightWorkKind::Visible { |
|
| 112 | - | self.debug_status = |
|
| 113 | - | Some(update.timings.status(update.timings.started.elapsed())); |
|
| 114 | - | } |
|
| 115 | - | if self.viewer.apply_highlights(update.results) |
|
| 116 | - | || (self.debug && update.kind == HighlightWorkKind::Visible) |
|
| 108 | + | TerminalEvent::Highlight(HighlightOutput::Highlights(results)) => { |
|
| 109 | + | let mut refresh = self.viewer.apply_highlights(results); |
|
| 110 | + | if self.debug |
|
| 111 | + | && let Some(started) = self.visible_started.take() |
|
| 117 | 112 | { |
|
| 113 | + | self.debug_status = Some(format!("highlight {}", format_ms(started.elapsed()))); |
|
| 114 | + | refresh = true; |
|
| 115 | + | } |
|
| 116 | + | if refresh { |
|
| 118 | 117 | self.draw_frame()?; |
|
| 119 | 118 | } |
|
| 120 | 119 | Ok(Control::Continue) |
|
| 121 | 120 | } |
|
| 122 | - | TerminalEvent::Context(update) => { |
|
| 121 | + | TerminalEvent::Highlight(HighlightOutput::Context(update)) => { |
|
| 123 | 122 | self.context_pending = false; |
|
| 124 | 123 | if let Some(update) = update { |
|
| 125 | 124 | let area = viewer_area(self.terminal.area()); |
|
| 126 | 125 | self.viewer.apply_context_update(update, area); |
|
| 127 | 126 | *redraw = true; |
| 139 | 138 | Ok(()) |
|
| 140 | 139 | } |
|
| 141 | 140 | ||
| 142 | 141 | /// Requests highlight work for currently visible rows. |
|
| 143 | 142 | fn request_visible_highlights(&mut self) { |
|
| 144 | - | let mut timings = Timings { |
|
| 145 | - | started: Instant::now(), |
|
| 146 | - | view: Duration::ZERO, |
|
| 147 | - | context: Duration::ZERO, |
|
| 148 | - | syntax: Duration::ZERO, |
|
| 149 | - | }; |
|
| 150 | 143 | let area = viewer_area(self.terminal.area()); |
|
| 151 | 144 | let requests = self.viewer.visible_highlight_requests(area); |
|
| 152 | - | timings.view = timings.started.elapsed(); |
|
| 153 | - | self.queue_highlights(requests, timings, HighlightWorkKind::Visible); |
|
| 145 | + | if requests.is_empty() { |
|
| 146 | + | if self.debug { |
|
| 147 | + | self.debug_status = Some("highlight (cached)".to_owned()); |
|
| 148 | + | self.visible_started = None; |
|
| 149 | + | } |
|
| 150 | + | return; |
|
| 151 | + | } |
|
| 152 | + | if self.debug { |
|
| 153 | + | self.visible_started = Some(Instant::now()); |
|
| 154 | + | } |
|
| 155 | + | self.queue_highlights(requests); |
|
| 154 | 156 | } |
|
| 155 | 157 | ||
| 156 | 158 | /// Requests highlight work for rows after the visible viewport. |
|
| 157 | 159 | fn request_lookahead_highlights(&mut self) { |
|
| 158 | - | let mut timings = Timings { |
|
| 159 | - | started: Instant::now(), |
|
| 160 | - | view: Duration::ZERO, |
|
| 161 | - | context: Duration::ZERO, |
|
| 162 | - | syntax: Duration::ZERO, |
|
| 163 | - | }; |
|
| 164 | 160 | let area = viewer_area(self.terminal.area()); |
|
| 165 | 161 | let requests = self.viewer.lookahead_highlight_requests(area); |
|
| 166 | - | timings.view = timings.started.elapsed(); |
|
| 167 | - | self.queue_highlights(requests, timings, HighlightWorkKind::Lookahead); |
|
| 162 | + | self.queue_highlights(requests); |
|
| 168 | 163 | } |
|
| 169 | 164 | ||
| 170 | - | /// Queues highlight work and records request timings. |
|
| 171 | - | fn queue_highlights( |
|
| 172 | - | &mut self, |
|
| 173 | - | requests: Vec<HighlightRequest>, |
|
| 174 | - | timings: Timings, |
|
| 175 | - | kind: HighlightWorkKind, |
|
| 176 | - | ) { |
|
| 165 | + | /// Queues highlight work, cancelling rows the worker cannot accept. |
|
| 166 | + | fn queue_highlights(&mut self, requests: Vec<HighlightRequest>) { |
|
| 177 | 167 | if requests.is_empty() { |
|
| 178 | - | if self.debug && kind == HighlightWorkKind::Visible { |
|
| 179 | - | self.debug_status = Some(format!( |
|
| 180 | - | "view {} highlight {} (cached)", |
|
| 181 | - | format_ms(timings.view), |
|
| 182 | - | format_ms(timings.started.elapsed()) |
|
| 183 | - | )); |
|
| 184 | - | } |
|
| 185 | 168 | return; |
|
| 186 | 169 | } |
|
| 187 | - | ||
| 188 | - | match self |
|
| 189 | - | .worker_tx |
|
| 190 | - | .try_send(WorkerCommand::Highlight(HighlightWork { |
|
| 191 | - | requests, |
|
| 192 | - | timings, |
|
| 193 | - | kind, |
|
| 194 | - | })) { |
|
| 195 | - | Ok(()) => {} |
|
| 196 | - | Err( |
|
| 197 | - | TrySendError::Full(WorkerCommand::Highlight(work)) |
|
| 198 | - | | TrySendError::Disconnected(WorkerCommand::Highlight(work)), |
|
| 199 | - | ) => { |
|
| 200 | - | self.viewer.cancel_highlights(work.requests); |
|
| 201 | - | } |
|
| 202 | - | Err( |
|
| 203 | - | TrySendError::Full(WorkerCommand::Context(_)) |
|
| 204 | - | | TrySendError::Disconnected(WorkerCommand::Context(_)), |
|
| 205 | - | ) => {} |
|
| 170 | + | if let Some(dropped) = self.highlighter.highlight(requests) { |
|
| 171 | + | self.viewer.cancel_highlights(dropped); |
|
| 206 | 172 | } |
|
| 207 | 173 | } |
|
| 208 | 174 | ||
| 209 | 175 | /// Requests context refetch work for one context change. |
|
| 210 | 176 | fn request_context(&mut self, change: ContextChange) { |
| 212 | 178 | return; |
|
| 213 | 179 | } |
|
| 214 | 180 | let Some(request) = self.viewer.context_request(change) else { |
|
| 215 | 181 | return; |
|
| 216 | 182 | }; |
|
| 217 | - | match self.worker_tx.try_send(WorkerCommand::Context(request)) { |
|
| 218 | - | Ok(()) => self.context_pending = true, |
|
| 219 | - | Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => {} |
|
| 183 | + | if self.highlighter.context(request) { |
|
| 184 | + | self.context_pending = true; |
|
| 220 | 185 | } |
|
| 221 | 186 | } |
|
| 222 | 187 | ||
| 223 | 188 | /// Draws one terminal frame without scheduling highlight work. |
|
| 224 | 189 | fn draw_frame(&mut self) -> io::Result<()> { |
| 232 | 197 | ||
| 233 | 198 | /// Event delivered to the terminal loop. |
|
| 234 | 199 | enum TerminalEvent { |
|
| 235 | 200 | /// Terminal input event. |
|
| 236 | 201 | Input(io::Result<Event<()>>), |
|
| 237 | - | /// Background highlight results with timings. |
|
| 238 | - | Highlights(HighlightUpdate), |
|
| 239 | - | /// Background context update result. |
|
| 240 | - | Context(Option<ContextUpdate>), |
|
| 241 | - | } |
|
| 242 | - | ||
| 243 | - | /// Background worker command. |
|
| 244 | - | enum WorkerCommand { |
|
| 245 | - | /// Highlight visible source rows. |
|
| 246 | - | Highlight(HighlightWork), |
|
| 247 | - | /// Refetch and decode a context update. |
|
| 248 | - | Context(ContextRequest), |
|
| 249 | - | } |
|
| 250 | - | ||
| 251 | - | /// Highlight work requested by the terminal session. |
|
| 252 | - | struct HighlightWork { |
|
| 253 | - | /// Rows that need highlighting. |
|
| 254 | - | requests: Vec<HighlightRequest>, |
|
| 255 | - | /// Timings collected before the worker receives the request. |
|
| 256 | - | timings: Timings, |
|
| 257 | - | /// Whether this batch affects visible landing diagnostics. |
|
| 258 | - | kind: HighlightWorkKind, |
|
| 259 | - | } |
|
| 260 | - | ||
| 261 | - | /// Highlight result produced by the background worker. |
|
| 262 | - | struct HighlightUpdate { |
|
| 263 | - | /// Highlighted visible rows. |
|
| 264 | - | results: Vec<HighlightResult>, |
|
| 265 | - | /// Timings collected while producing the results. |
|
| 266 | - | timings: Timings, |
|
| 267 | - | /// Whether this batch affects visible landing diagnostics. |
|
| 268 | - | kind: HighlightWorkKind, |
|
| 269 | - | } |
|
| 270 | - | ||
| 271 | - | /// Highlight batch role. |
|
| 272 | - | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
|
| 273 | - | enum HighlightWorkKind { |
|
| 274 | - | /// Currently visible rows. |
|
| 275 | - | Visible, |
|
| 276 | - | /// Rows after the visible viewport. |
|
| 277 | - | Lookahead, |
|
| 278 | - | } |
|
| 279 | - | ||
| 280 | - | /// Debug timings for one highlight batch. |
|
| 281 | - | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
|
| 282 | - | struct Timings { |
|
| 283 | - | /// Time at which the visible highlight batch was requested. |
|
| 284 | - | started: Instant, |
|
| 285 | - | /// Time spent collecting visible highlight requests. |
|
| 286 | - | view: Duration, |
|
| 287 | - | /// Time spent loading repo-backed highlight context. |
|
| 288 | - | context: Duration, |
|
| 289 | - | /// Time spent syntax-highlighting rows. |
|
| 290 | - | syntax: Duration, |
|
| 291 | - | } |
|
| 292 | - | ||
| 293 | - | impl Timings { |
|
| 294 | - | /// Formats this timing breakdown after the batch lands in the UI. |
|
| 295 | - | fn status(&self, landed: Duration) -> String { |
|
| 296 | - | let measured = self.view + self.context + self.syntax; |
|
| 297 | - | let wait = landed.saturating_sub(measured); |
|
| 298 | - | format!( |
|
| 299 | - | "wait {} view {} ctx {} syn {} highlight {}", |
|
| 300 | - | format_ms(wait), |
|
| 301 | - | format_ms(self.view), |
|
| 302 | - | format_ms(self.context), |
|
| 303 | - | format_ms(self.syntax), |
|
| 304 | - | format_ms(landed) |
|
| 305 | - | ) |
|
| 306 | - | } |
|
| 307 | - | } |
|
| 308 | - | ||
| 309 | - | /// Background worker for blocking repo and syntax-highlighting work. |
|
| 310 | - | struct HighlightWorker { |
|
| 311 | - | /// Built-in syntax highlighter. |
|
| 312 | - | highlighter: BuiltinHighlighter, |
|
| 313 | - | /// Git-backed repo used for direct Git invocations. |
|
| 314 | - | repo: Option<GitRepo>, |
|
| 315 | - | /// Highlight source context cache keyed by diff file and side. |
|
| 316 | - | context_sources: BTreeMap<(FileId, DiffSide), Vec<HighlightSource>>, |
|
| 317 | - | /// Source object ids keyed by diff file and side. |
|
| 318 | - | head_oids: BTreeMap<(FileId, DiffSide), Oid>, |
|
| 319 | - | /// File-side heads already checked for first-line grammar metadata. |
|
| 320 | - | loaded_heads: BTreeSet<(FileId, DiffSide)>, |
|
| 321 | - | } |
|
| 322 | - | ||
| 323 | - | impl HighlightWorker { |
|
| 324 | - | /// Creates a background worker. |
|
| 325 | - | fn new(document: &DiffDocument, repo: Option<GitRepo>) -> Self { |
|
| 326 | - | let mut head_oids = BTreeMap::new(); |
|
| 327 | - | for file in &document.files { |
|
| 328 | - | if let Some(oid) = file.header.old_oid.clone() { |
|
| 329 | - | head_oids.insert((file.id, DiffSide::Old), oid); |
|
| 330 | - | } |
|
| 331 | - | if let Some(oid) = file.header.new_oid.clone() { |
|
| 332 | - | head_oids.insert((file.id, DiffSide::New), oid); |
|
| 333 | - | } |
|
| 334 | - | } |
|
| 335 | - | Self { |
|
| 336 | - | highlighter: Builtins::highlighter(document) |
|
| 337 | - | .unwrap_or_else(|_| BuiltinHighlighter::new(Default::default(), "")), |
|
| 338 | - | repo, |
|
| 339 | - | context_sources: BTreeMap::new(), |
|
| 340 | - | head_oids, |
|
| 341 | - | loaded_heads: BTreeSet::new(), |
|
| 342 | - | } |
|
| 343 | - | } |
|
| 344 | - | ||
| 345 | - | /// Highlights one batch with context and syntax timings. |
|
| 346 | - | fn highlight( |
|
| 347 | - | &mut self, |
|
| 348 | - | mut requests: Vec<HighlightRequest>, |
|
| 349 | - | mut timings: Timings, |
|
| 350 | - | ) -> (Vec<HighlightResult>, Timings) { |
|
| 351 | - | let context = Instant::now(); |
|
| 352 | - | self.load_context_sources(&requests); |
|
| 353 | - | timings.context = context.elapsed(); |
|
| 354 | - | let syntax = Instant::now(); |
|
| 355 | - | for request in &mut requests { |
|
| 356 | - | if let Some(source) = self.context_source_for(request) { |
|
| 357 | - | request.source = source.clone(); |
|
| 358 | - | } |
|
| 359 | - | self.load_head_grammar(request); |
|
| 360 | - | } |
|
| 361 | - | let results = self.highlighter.highlight_batch(requests); |
|
| 362 | - | timings.syntax = syntax.elapsed(); |
|
| 363 | - | (results, timings) |
|
| 364 | - | } |
|
| 365 | - | ||
| 366 | - | /// Loads first-line-selected grammars for a request's file side. |
|
| 367 | - | fn load_head_grammar(&mut self, request: &HighlightRequest) { |
|
| 368 | - | let key = (request.key.file, request.key.side); |
|
| 369 | - | if !self.loaded_heads.insert(key) { |
|
| 370 | - | return; |
|
| 371 | - | } |
|
| 372 | - | if request.source.head == 1 |
|
| 373 | - | && let Some(head) = request.source.text.lines().next() |
|
| 374 | - | { |
|
| 375 | - | let _ = Builtins::load_head_grammars(&mut self.highlighter, head); |
|
| 376 | - | return; |
|
| 377 | - | } |
|
| 378 | - | let Some(repo) = self.repo.as_ref() else { |
|
| 379 | - | return; |
|
| 380 | - | }; |
|
| 381 | - | let Some(path) = request.path.as_deref() else { |
|
| 382 | - | return; |
|
| 383 | - | }; |
|
| 384 | - | if self.highlighter.has_path_grammar(path) { |
|
| 385 | - | return; |
|
| 386 | - | } |
|
| 387 | - | let Some(oid) = self.head_oids.get(&key) else { |
|
| 388 | - | return; |
|
| 389 | - | }; |
|
| 390 | - | let head = repo.head_line(oid.as_str()); |
|
| 391 | - | if let Ok(Some(head)) = head { |
|
| 392 | - | let _ = Builtins::load_head_grammars(&mut self.highlighter, &head); |
|
| 393 | - | } |
|
| 394 | - | } |
|
| 395 | - | ||
| 396 | - | /// Loads bounded source context for uncached request paths. |
|
| 397 | - | fn load_context_sources(&mut self, requests: &[HighlightRequest]) { |
|
| 398 | - | let Some(repo) = self.repo.as_ref() else { |
|
| 399 | - | return; |
|
| 400 | - | }; |
|
| 401 | - | let mut targets = BTreeMap::new(); |
|
| 402 | - | for request in requests { |
|
| 403 | - | let key = (request.key.file, request.key.side); |
|
| 404 | - | if self.context_sources.contains_key(&key) { |
|
| 405 | - | continue; |
|
| 406 | - | } |
|
| 407 | - | if let Some(path) = request.path.as_deref() { |
|
| 408 | - | targets.insert((path.to_path_buf(), request.key.side), request.key.file); |
|
| 409 | - | } |
|
| 410 | - | } |
|
| 411 | - | if targets.is_empty() { |
|
| 412 | - | return; |
|
| 413 | - | } |
|
| 414 | - | ||
| 415 | - | let paths = targets |
|
| 416 | - | .keys() |
|
| 417 | - | .map(|(path, _)| path.as_path()) |
|
| 418 | - | .collect::<BTreeSet<_>>() |
|
| 419 | - | .into_iter() |
|
| 420 | - | .collect::<Vec<_>>(); |
|
| 421 | - | let Ok(patch) = repo.diff(HIGHLIGHT_CONTEXT_LINES, &paths) else { |
|
| 422 | - | return; |
|
| 423 | - | }; |
|
| 424 | - | let Ok(document) = DiffDocument::decode_bytes(&patch) else { |
|
| 425 | - | return; |
|
| 426 | - | }; |
|
| 427 | - | ||
| 428 | - | for file in &document.files { |
|
| 429 | - | for side in [DiffSide::Old, DiffSide::New] { |
|
| 430 | - | let Some(path) = file.source_path(side) else { |
|
| 431 | - | continue; |
|
| 432 | - | }; |
|
| 433 | - | let Some(file_id) = targets.get(&(path, side)).copied() else { |
|
| 434 | - | continue; |
|
| 435 | - | }; |
|
| 436 | - | let sources = file |
|
| 437 | - | .hunks |
|
| 438 | - | .iter() |
|
| 439 | - | .map(|hunk| hunk.highlight_source(side)) |
|
| 440 | - | .collect::<Vec<_>>(); |
|
| 441 | - | self.context_sources.insert((file_id, side), sources); |
|
| 442 | - | } |
|
| 443 | - | } |
|
| 444 | - | } |
|
| 445 | - | ||
| 446 | - | /// Returns cached context that contains the requested source row. |
|
| 447 | - | fn context_source_for(&self, request: &HighlightRequest) -> Option<&HighlightSource> { |
|
| 448 | - | let key = (request.key.file, request.key.side); |
|
| 449 | - | self.context_sources.get(&key)?.iter().find(|source| { |
|
| 450 | - | source.line(request.key.source_line) == request.source.line(request.key.source_line) |
|
| 451 | - | }) |
|
| 452 | - | } |
|
| 453 | - | ||
| 454 | - | /// Refetches and decodes one context update. |
|
| 455 | - | fn context(&mut self, request: ContextRequest) -> Option<ContextUpdate> { |
|
| 456 | - | let repo = self.repo.as_ref()?; |
|
| 457 | - | let paths = request.paths().collect::<Vec<_>>(); |
|
| 458 | - | let patch = repo.diff(request.context_lines(), &paths).ok()?; |
|
| 459 | - | drop(paths); |
|
| 460 | - | request.decode(&patch).ok().flatten() |
|
| 461 | - | } |
|
| 202 | + | /// Background highlighter output. |
|
| 203 | + | Highlight(HighlightOutput), |
|
| 462 | 204 | } |
|
| 463 | 205 | ||
| 464 | 206 | impl TerminalEvent { |
|
| 465 | 207 | /// Spawns the blocking input reader. |
|
| 466 | 208 | fn spawn_input_worker(tx: mpsc::Sender<Self>) { |
| 470 | 212 | break; |
|
| 471 | 213 | } |
|
| 472 | 214 | } |
|
| 473 | 215 | }); |
|
| 474 | 216 | } |
|
| 475 | - | ||
| 476 | - | /// Spawns the blocking background worker. |
|
| 477 | - | fn spawn_worker( |
|
| 478 | - | tx: mpsc::Sender<Self>, |
|
| 479 | - | document: DiffDocument, |
|
| 480 | - | repo: Option<GitRepo>, |
|
| 481 | - | ) -> SyncSender<WorkerCommand> { |
|
| 482 | - | let (requests_tx, requests_rx) = mpsc::sync_channel::<WorkerCommand>(4); |
|
| 483 | - | thread::spawn(move || { |
|
| 484 | - | let mut worker = HighlightWorker::new(&document, repo); |
|
| 485 | - | while let Ok(command) = requests_rx.recv() { |
|
| 486 | - | match command { |
|
| 487 | - | WorkerCommand::Highlight(work) => { |
|
| 488 | - | if work.requests.is_empty() { |
|
| 489 | - | continue; |
|
| 490 | - | } |
|
| 491 | - | let kind = work.kind; |
|
| 492 | - | let (results, timings) = worker.highlight(work.requests, work.timings); |
|
| 493 | - | if tx |
|
| 494 | - | .send(Self::Highlights(HighlightUpdate { |
|
| 495 | - | results, |
|
| 496 | - | timings, |
|
| 497 | - | kind, |
|
| 498 | - | })) |
|
| 499 | - | .is_err() |
|
| 500 | - | { |
|
| 501 | - | break; |
|
| 502 | - | } |
|
| 503 | - | } |
|
| 504 | - | WorkerCommand::Context(request) => { |
|
| 505 | - | if tx.send(Self::Context(worker.context(request))).is_err() { |
|
| 506 | - | break; |
|
| 507 | - | } |
|
| 508 | - | } |
|
| 509 | - | } |
|
| 510 | - | } |
|
| 511 | - | }); |
|
| 512 | - | requests_tx |
|
| 513 | - | } |
|
| 514 | 217 | } |
|
| 515 | 218 | ||
| 516 | 219 | /// Returns the context change represented by an input event. |
|
| 517 | 220 | fn context_change(event: &Event<()>) -> Option<ContextChange> { |
|
| 518 | 221 | match event { |
crates/diff/src/bin/rustik-diff/builtins.rs → crates/diff/src/builtins.rs
renamed
+37 -29
| 1 | - | //! Built-in highlighting assets for the pager binary. |
|
| 1 | + | //! Built-in highlighting assets for diff viewers. |
|
| 2 | + | //! |
|
| 3 | + | //! This module bundles a default syntax theme and a small set of common |
|
| 4 | + | //! TextMate grammars, compiling them into a [`BuiltinHighlighter`] selected for |
|
| 5 | + | //! the files in a diff. It is gated behind the `builtins` feature so callers |
|
| 6 | + | //! that bring their own highlighting do not pay for the embedded assets. |
|
| 2 | 7 | ||
| 3 | - | use std::path::Path; |
|
| 8 | + | use std::path::{Path, PathBuf}; |
|
| 4 | 9 | ||
| 5 | - | use rustik_diff::{BuiltinHighlighter, DiffDocument, DiffPalette}; |
|
| 6 | 10 | use rustik_highlight as syntax; |
|
| 7 | 11 | ||
| 12 | + | use crate::{BuiltinHighlighter, DiffDocument, DiffPalette}; |
|
| 13 | + | ||
| 8 | 14 | /// Theme name used for built-in diff highlighting. |
|
| 9 | 15 | const THEME_NAME: &str = "rustik-catppuccin-mocha"; |
|
| 10 | 16 | /// Built-in syntax theme JSON. |
|
| 11 | - | const THEME: &str = include_str!("../../themes/rustik-catppuccin-mocha.json"); |
|
| 17 | + | const THEME: &str = include_str!("themes/rustik-catppuccin-mocha.json"); |
|
| 12 | 18 | /// Common syntax grammars loaded by the interactive pager. |
|
| 13 | 19 | const SYNTAXES: [SyntaxAsset; 16] = [ |
|
| 14 | 20 | SyntaxAsset { |
|
| 15 | 21 | source: syntax::syntaxes::C, |
|
| 16 | 22 | file_types: &["c", "h"], |
| 101 | 107 | file_types: &["yaml", "yml"], |
|
| 102 | 108 | dependencies: &[], |
|
| 103 | 109 | }, |
|
| 104 | 110 | ]; |
|
| 105 | 111 | ||
| 106 | - | /// Binary-local highlight assets loaded for one diff document. |
|
| 107 | - | pub(super) struct Builtins { |
|
| 112 | + | /// Built-in highlight assets loaded for one diff document. |
|
| 113 | + | pub struct Builtins { |
|
| 108 | 114 | /// Diff chrome palette derived from the built-in theme. |
|
| 109 | - | pub(super) palette: DiffPalette, |
|
| 115 | + | pub palette: DiffPalette, |
|
| 110 | 116 | } |
|
| 111 | 117 | ||
| 112 | 118 | impl Builtins { |
|
| 113 | 119 | /// Loads the built-in diff chrome assets. |
|
| 114 | - | pub(super) fn load() -> Result<Self, syntax::Error> { |
|
| 120 | + | pub fn load() -> Result<Self, syntax::Error> { |
|
| 115 | 121 | let raw_theme = THEME.parse::<syntax::RawTheme>()?; |
|
| 116 | 122 | ||
| 117 | 123 | Ok(Self { |
|
| 118 | 124 | palette: (&raw_theme).into(), |
|
| 119 | 125 | }) |
|
| 120 | 126 | } |
|
| 121 | 127 | ||
| 122 | 128 | /// Loads a highlighter with grammars relevant to `document`. |
|
| 123 | - | pub(super) fn highlighter( |
|
| 124 | - | document: &DiffDocument, |
|
| 129 | + | pub fn highlighter(document: &DiffDocument) -> Result<BuiltinHighlighter, syntax::Error> { |
|
| 130 | + | Self::highlighter_for_paths(&Self::document_paths(document)) |
|
| 131 | + | } |
|
| 132 | + | ||
| 133 | + | /// Loads a highlighter with grammars relevant to the given changed paths. |
|
| 134 | + | pub(crate) fn highlighter_for_paths( |
|
| 135 | + | paths: &[PathBuf], |
|
| 125 | 136 | ) -> Result<BuiltinHighlighter, syntax::Error> { |
|
| 126 | 137 | let raw_theme = THEME.parse::<syntax::RawTheme>()?; |
|
| 127 | 138 | let mut registry = syntax::Registry::default(); |
|
| 128 | 139 | ||
| 129 | 140 | registry.add_theme(syntax::Theme::compile(&raw_theme)); |
|
| 130 | 141 | for syntax in SYNTAXES |
|
| 131 | 142 | .iter() |
|
| 132 | - | .filter(|syntax| syntax.matches_document(document)) |
|
| 143 | + | .filter(|syntax| paths.iter().any(|path| syntax.matches_path(path))) |
|
| 133 | 144 | { |
|
| 134 | 145 | registry.add_grammar(syntax.grammar()?); |
|
| 135 | 146 | } |
|
| 136 | 147 | Ok(BuiltinHighlighter::new(registry, THEME_NAME)) |
|
| 137 | 148 | } |
|
| 138 | 149 | ||
| 150 | + | /// Returns the old and new paths of every file in `document`. |
|
| 151 | + | pub(crate) fn document_paths(document: &DiffDocument) -> Vec<PathBuf> { |
|
| 152 | + | document |
|
| 153 | + | .files |
|
| 154 | + | .iter() |
|
| 155 | + | .flat_map(|file| [&file.header.old_path, &file.header.new_path]) |
|
| 156 | + | .flatten() |
|
| 157 | + | .cloned() |
|
| 158 | + | .collect() |
|
| 159 | + | } |
|
| 160 | + | ||
| 139 | 161 | /// Loads grammars selected by a source file's head line. |
|
| 140 | - | pub(super) fn load_head_grammars( |
|
| 162 | + | pub fn load_head_grammars( |
|
| 141 | 163 | highlighter: &mut BuiltinHighlighter, |
|
| 142 | 164 | head: &str, |
|
| 143 | 165 | ) -> Result<(), syntax::Error> { |
|
| 144 | 166 | if !head.starts_with("#!") { |
|
| 145 | 167 | return Ok(()); |
| 162 | 184 | /// Raw grammars required by cross-grammar includes in this syntax. |
|
| 163 | 185 | dependencies: &'static [&'static str], |
|
| 164 | 186 | } |
|
| 165 | 187 | ||
| 166 | 188 | impl SyntaxAsset { |
|
| 167 | - | /// Returns whether this syntax matches any path in a diff document. |
|
| 168 | - | fn matches_document(&self, document: &DiffDocument) -> bool { |
|
| 169 | - | document.files.iter().any(|file| { |
|
| 170 | - | file.header |
|
| 171 | - | .old_path |
|
| 172 | - | .as_deref() |
|
| 173 | - | .is_some_and(|path| self.matches_path(path)) |
|
| 174 | - | || file |
|
| 175 | - | .header |
|
| 176 | - | .new_path |
|
| 177 | - | .as_deref() |
|
| 178 | - | .is_some_and(|path| self.matches_path(path)) |
|
| 179 | - | }) |
|
| 180 | - | } |
|
| 181 | - | ||
| 182 | 189 | /// Returns whether this syntax matches a file path. |
|
| 183 | 190 | fn matches_path(&self, path: &Path) -> bool { |
|
| 184 | 191 | let file_name = path.file_name().and_then(|name| name.to_str()); |
|
| 185 | 192 | let extension = path.extension().and_then(|extension| extension.to_str()); |
|
| 186 | 193 |
| 225 | 232 | syntax::Grammar::compile_with(raw, &dependencies) |
|
| 226 | 233 | } |
|
| 227 | 234 | } |
|
| 228 | 235 | ||
| 229 | 236 | #[cfg(test)] |
|
| 237 | + | #[allow(clippy::unwrap_used)] |
|
| 230 | 238 | mod tests { |
|
| 231 | 239 | use super::*; |
|
| 232 | - | use rustik_diff::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest}; |
|
| 240 | + | use crate::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest}; |
|
| 233 | 241 | use rustik_tui::Color; |
|
| 234 | 242 | ||
| 235 | 243 | #[test] |
|
| 236 | 244 | fn syntax_assets_match_common_source_paths() { |
|
| 237 | 245 | for path in [ |
| 293 | 301 | result.line |
|
| 294 | 302 | ); |
|
| 295 | 303 | } |
|
| 296 | 304 | } |
|
| 297 | 305 | ||
| 298 | - | fn highlight_extensionless_full_source(head: &str, line: &str) -> rustik_diff::HighlightResult { |
|
| 306 | + | fn highlight_extensionless_full_source(head: &str, line: &str) -> crate::HighlightResult { |
|
| 299 | 307 | let patch = format!( |
|
| 300 | 308 | " |
script\n\
+0 -0
crates/diff/src/decorate.rs
added
+63 -0
| 1 | + | //! Host-supplied decorations for diff files and hunks. |
|
| 2 | + | //! |
|
| 3 | + | //! The diff viewer is review-agnostic: it renders a parsed patch and knows |
|
| 4 | + | //! nothing about approval state, comments, or any other host concept. A host |
|
| 5 | + | //! application owns those concerns and feeds per-file and per-hunk decorations |
|
| 6 | + | //! into the viewer through the [`DiffDecorator`] trait, which the renderer |
|
| 7 | + | //! queries by [`FileId`] and [`HunkId`] while drawing each frame. |
|
| 8 | + | ||
| 9 | + | use std::fmt; |
|
| 10 | + | ||
| 11 | + | use rustik_tui as tui; |
|
| 12 | + | use tui::{Line, Paint, Style}; |
|
| 13 | + | ||
| 14 | + | use crate::{FileId, HunkId}; |
|
| 15 | + | ||
| 16 | + | /// Source of per-file and per-hunk decorations overlaid on a rendered diff. |
|
| 17 | + | /// |
|
| 18 | + | /// Methods are queried during rendering, so they must be cheap and free of side |
|
| 19 | + | /// effects. The default implementations return empty decorations, so a host |
|
| 20 | + | /// only overrides the parts it uses. |
|
| 21 | + | pub trait DiffDecorator: fmt::Debug + Send + Sync { |
|
| 22 | + | /// Returns the decoration for the given file's header row. |
|
| 23 | + | fn file(&self, file: FileId) -> FileDecoration { |
|
| 24 | + | let _ = file; |
|
| 25 | + | FileDecoration::default() |
|
| 26 | + | } |
|
| 27 | + | ||
| 28 | + | /// Returns the decoration for the given hunk. |
|
| 29 | + | fn hunk(&self, file: FileId, hunk: HunkId) -> HunkDecoration { |
|
| 30 | + | let _ = (file, hunk); |
|
| 31 | + | HunkDecoration::default() |
|
| 32 | + | } |
|
| 33 | + | } |
|
| 34 | + | ||
| 35 | + | /// Decoration overlaid on a file header row. |
|
| 36 | + | /// |
|
| 37 | + | /// The header already renders an expand/collapse marker, the file path, an |
|
| 38 | + | /// optional file-kind badge, and a right-aligned diffstat. A decoration adds a |
|
| 39 | + | /// leading status glyph, extra right-aligned segments, and an optional |
|
| 40 | + | /// replacement for the diffstat. |
|
| 41 | + | #[derive(Clone, Debug, Default)] |
|
| 42 | + | pub struct FileDecoration { |
|
| 43 | + | /// Status glyph inserted before the path, for example an approval marker. |
|
| 44 | + | pub status: Option<Paint<char>>, |
|
| 45 | + | /// Right-aligned segments shown before the diffstat, outermost first. |
|
| 46 | + | pub annotations: Vec<Line>, |
|
| 47 | + | /// Replacement for the computed `+adds -dels` diffstat, when set. |
|
| 48 | + | pub stats: Option<Line>, |
|
| 49 | + | } |
|
| 50 | + | ||
| 51 | + | /// Decoration overlaid on a hunk. |
|
| 52 | + | /// |
|
| 53 | + | /// Decorations never add rows: the corner is drawn over the hunk's first body |
|
| 54 | + | /// row, and the style is composed onto the hunk's existing body rows. |
|
| 55 | + | #[derive(Clone, Debug, Default)] |
|
| 56 | + | pub struct HunkDecoration { |
|
| 57 | + | /// Markers drawn in the hunk's top-right corner, for example an approval |
|
| 58 | + | /// marker and a comment-count indicator. |
|
| 59 | + | pub corner: Line, |
|
| 60 | + | /// Style composed onto the hunk's body rows, used to mute approved or |
|
| 61 | + | /// otherwise inactive hunks. |
|
| 62 | + | pub style: Option<Style>, |
|
| 63 | + | } |
crates/diff/src/highlight.rs
+0 -0
a.css
+0 -0
a.rs\n",
+0 -0
crates/diff/src/highlighter.rs
added
+285 -0
| 1 | + | //! Background syntax highlighting and context expansion for diff viewers. |
|
| 2 | + | //! |
|
| 3 | + | //! [`spawn_highlighter`] runs the blocking repo and syntax-highlighting work on |
|
| 4 | + | //! a dedicated thread so an interactive viewer stays responsive. A viewer feeds |
|
| 5 | + | //! it the [`HighlightRequest`]s collected by |
|
| 6 | + | //! [`DiffViewer::visible_highlight_requests`](crate::DiffViewer::visible_highlight_requests) |
|
| 7 | + | //! and the [`ContextRequest`]s prepared by |
|
| 8 | + | //! [`DiffViewer::context_request`](crate::DiffViewer::context_request), then |
|
| 9 | + | //! applies each [`HighlightOutput`] it produces. |
|
| 10 | + | ||
| 11 | + | use std::collections::{BTreeMap, BTreeSet}; |
|
| 12 | + | use std::path::PathBuf; |
|
| 13 | + | use std::sync::mpsc::{self, SyncSender, TrySendError}; |
|
| 14 | + | use std::thread; |
|
| 15 | + | ||
| 16 | + | use rustik_repo::{GitRepo, Repo}; |
|
| 17 | + | ||
| 18 | + | use crate::builtins::Builtins; |
|
| 19 | + | use crate::{ |
|
| 20 | + | BuiltinHighlighter, ContextRequest, ContextUpdate, Decode, DiffDocument, DiffHighlighter, |
|
| 21 | + | DiffSide, FileId, HighlightRequest, HighlightResult, HighlightSource, Oid, |
|
| 22 | + | }; |
|
| 23 | + | ||
| 24 | + | /// Source context lines fetched around highlighted rows. |
|
| 25 | + | const HIGHLIGHT_CONTEXT_LINES: usize = 256; |
|
| 26 | + | /// Bound on queued highlight and context commands. |
|
| 27 | + | const COMMAND_QUEUE: usize = 4; |
|
| 28 | + | ||
| 29 | + | /// A running background highlighter. |
|
| 30 | + | /// |
|
| 31 | + | /// Submits highlight and context work to the worker thread spawned by |
|
| 32 | + | /// [`spawn_highlighter`]. Dropping the handle disconnects the command channel, |
|
| 33 | + | /// which stops the worker once it drains. |
|
| 34 | + | pub struct Highlighter { |
|
| 35 | + | /// Command channel to the worker thread. |
|
| 36 | + | commands: SyncSender<Command>, |
|
| 37 | + | } |
|
| 38 | + | ||
| 39 | + | impl Highlighter { |
|
| 40 | + | /// Queues a batch of rows for highlighting. |
|
| 41 | + | /// |
|
| 42 | + | /// Returns the requests back when the worker queue is full or gone, so the |
|
| 43 | + | /// caller can cancel them with |
|
| 44 | + | /// [`DiffViewer::cancel_highlights`](crate::DiffViewer::cancel_highlights). |
|
| 45 | + | /// Returns `None` once the batch is queued. |
|
| 46 | + | pub fn highlight(&self, requests: Vec<HighlightRequest>) -> Option<Vec<HighlightRequest>> { |
|
| 47 | + | // `try_send` errors return the command we sent, so the error always |
|
| 48 | + | // holds `Command::Highlight`. |
|
| 49 | + | match self.commands.try_send(Command::Highlight(requests)) { |
|
| 50 | + | Ok(()) => None, |
|
| 51 | + | Err( |
|
| 52 | + | TrySendError::Full(Command::Highlight(requests)) |
|
| 53 | + | | TrySendError::Disconnected(Command::Highlight(requests)), |
|
| 54 | + | ) => Some(requests), |
|
| 55 | + | Err(_) => None, |
|
| 56 | + | } |
|
| 57 | + | } |
|
| 58 | + | ||
| 59 | + | /// Queues a context refetch, returning whether it was accepted. |
|
| 60 | + | pub fn context(&self, request: ContextRequest) -> bool { |
|
| 61 | + | self.commands.try_send(Command::Context(request)).is_ok() |
|
| 62 | + | } |
|
| 63 | + | } |
|
| 64 | + | ||
| 65 | + | /// Result produced by the background highlighter. |
|
| 66 | + | pub enum HighlightOutput { |
|
| 67 | + | /// Highlighted source rows ready for |
|
| 68 | + | /// [`DiffViewer::apply_highlights`](crate::DiffViewer::apply_highlights). |
|
| 69 | + | Highlights(Vec<HighlightResult>), |
|
| 70 | + | /// A decoded context update, or `None` when the refetch produced nothing, |
|
| 71 | + | /// ready for |
|
| 72 | + | /// [`DiffViewer::apply_context_update`](crate::DiffViewer::apply_context_update). |
|
| 73 | + | Context(Option<ContextUpdate>), |
|
| 74 | + | } |
|
| 75 | + | ||
| 76 | + | /// Command sent to the worker thread. |
|
| 77 | + | enum Command { |
|
| 78 | + | /// Highlight a batch of source rows. |
|
| 79 | + | Highlight(Vec<HighlightRequest>), |
|
| 80 | + | /// Refetch and decode a context update. |
|
| 81 | + | Context(ContextRequest), |
|
| 82 | + | } |
|
| 83 | + | ||
| 84 | + | /// Spawns a background highlighter for `document`. |
|
| 85 | + | /// |
|
| 86 | + | /// `output` is invoked on the worker thread for each produced |
|
| 87 | + | /// [`HighlightOutput`]; forward it to the UI thread (for example over a |
|
| 88 | + | /// channel) and apply it to the viewer. |
|
| 89 | + | pub fn spawn_highlighter( |
|
| 90 | + | document: &DiffDocument, |
|
| 91 | + | repo: Option<GitRepo>, |
|
| 92 | + | output: impl Fn(HighlightOutput) + Send + 'static, |
|
| 93 | + | ) -> Highlighter { |
|
| 94 | + | let (commands, requests) = mpsc::sync_channel::<Command>(COMMAND_QUEUE); |
|
| 95 | + | let seed = Seed::new(document); |
|
| 96 | + | ||
| 97 | + | thread::spawn(move || { |
|
| 98 | + | // Theme parsing and grammar compilation are blocking, so the worker is |
|
| 99 | + | // built here rather than on the caller's thread. |
|
| 100 | + | let mut worker = HighlightWorker::new(seed, repo); |
|
| 101 | + | while let Ok(command) = requests.recv() { |
|
| 102 | + | match command { |
|
| 103 | + | Command::Highlight(requests) => { |
|
| 104 | + | if requests.is_empty() { |
|
| 105 | + | continue; |
|
| 106 | + | } |
|
| 107 | + | output(HighlightOutput::Highlights(worker.highlight(requests))); |
|
| 108 | + | } |
|
| 109 | + | Command::Context(request) => { |
|
| 110 | + | output(HighlightOutput::Context(worker.context(request))); |
|
| 111 | + | } |
|
| 112 | + | } |
|
| 113 | + | } |
|
| 114 | + | }); |
|
| 115 | + | Highlighter { commands } |
|
| 116 | + | } |
|
| 117 | + | ||
| 118 | + | /// Header-only document data the worker needs. |
|
| 119 | + | /// |
|
| 120 | + | /// Extracted on the caller's thread so the document itself โ which holds every |
|
| 121 | + | /// line of the patch โ does not have to be cloned into the worker. Its size is |
|
| 122 | + | /// proportional to the number of changed files, not diff lines. |
|
| 123 | + | struct Seed { |
|
| 124 | + | /// Changed file paths used to select built-in grammars. |
|
| 125 | + | paths: Vec<PathBuf>, |
|
| 126 | + | /// Source object ids keyed by diff file and side. |
|
| 127 | + | head_oids: BTreeMap<(FileId, DiffSide), Oid>, |
|
| 128 | + | } |
|
| 129 | + | ||
| 130 | + | impl Seed { |
|
| 131 | + | /// Extracts the worker's seed from `document`. |
|
| 132 | + | fn new(document: &DiffDocument) -> Self { |
|
| 133 | + | let mut head_oids = BTreeMap::new(); |
|
| 134 | + | for file in &document.files { |
|
| 135 | + | if let Some(oid) = file.header.old_oid.clone() { |
|
| 136 | + | head_oids.insert((file.id, DiffSide::Old), oid); |
|
| 137 | + | } |
|
| 138 | + | if let Some(oid) = file.header.new_oid.clone() { |
|
| 139 | + | head_oids.insert((file.id, DiffSide::New), oid); |
|
| 140 | + | } |
|
| 141 | + | } |
|
| 142 | + | Self { |
|
| 143 | + | paths: Builtins::document_paths(document), |
|
| 144 | + | head_oids, |
|
| 145 | + | } |
|
| 146 | + | } |
|
| 147 | + | } |
|
| 148 | + | ||
| 149 | + | /// Background worker for blocking repo and syntax-highlighting work. |
|
| 150 | + | struct HighlightWorker { |
|
| 151 | + | /// Built-in syntax highlighter. |
|
| 152 | + | highlighter: BuiltinHighlighter, |
|
| 153 | + | /// Git-backed repo used for direct Git invocations. |
|
| 154 | + | repo: Option<GitRepo>, |
|
| 155 | + | /// Highlight source context cache keyed by diff file and side. |
|
| 156 | + | context_sources: BTreeMap<(FileId, DiffSide), Vec<HighlightSource>>, |
|
| 157 | + | /// Source object ids keyed by diff file and side. |
|
| 158 | + | head_oids: BTreeMap<(FileId, DiffSide), Oid>, |
|
| 159 | + | /// File-side heads already checked for first-line grammar metadata. |
|
| 160 | + | loaded_heads: BTreeSet<(FileId, DiffSide)>, |
|
| 161 | + | } |
|
| 162 | + | ||
| 163 | + | impl HighlightWorker { |
|
| 164 | + | /// Creates a background worker. |
|
| 165 | + | fn new(seed: Seed, repo: Option<GitRepo>) -> Self { |
|
| 166 | + | Self { |
|
| 167 | + | highlighter: Builtins::highlighter_for_paths(&seed.paths) |
|
| 168 | + | .unwrap_or_else(|_| BuiltinHighlighter::new(Default::default(), "")), |
|
| 169 | + | repo, |
|
| 170 | + | context_sources: BTreeMap::new(), |
|
| 171 | + | head_oids: seed.head_oids, |
|
| 172 | + | loaded_heads: BTreeSet::new(), |
|
| 173 | + | } |
|
| 174 | + | } |
|
| 175 | + | ||
| 176 | + | /// Highlights one batch of source rows. |
|
| 177 | + | fn highlight(&mut self, mut requests: Vec<HighlightRequest>) -> Vec<HighlightResult> { |
|
| 178 | + | self.load_context_sources(&requests); |
|
| 179 | + | for request in &mut requests { |
|
| 180 | + | if let Some(source) = self.context_source_for(request) { |
|
| 181 | + | request.source = source.clone(); |
|
| 182 | + | } |
|
| 183 | + | self.load_head_grammar(request); |
|
| 184 | + | } |
|
| 185 | + | self.highlighter.highlight_batch(requests) |
|
| 186 | + | } |
|
| 187 | + | ||
| 188 | + | /// Loads first-line-selected grammars for a request's file side. |
|
| 189 | + | fn load_head_grammar(&mut self, request: &HighlightRequest) { |
|
| 190 | + | let key = (request.key.file, request.key.side); |
|
| 191 | + | if !self.loaded_heads.insert(key) { |
|
| 192 | + | return; |
|
| 193 | + | } |
|
| 194 | + | if request.source.head == 1 |
|
| 195 | + | && let Some(head) = request.source.text.lines().next() |
|
| 196 | + | { |
|
| 197 | + | let _ = Builtins::load_head_grammars(&mut self.highlighter, head); |
|
| 198 | + | return; |
|
| 199 | + | } |
|
| 200 | + | let Some(repo) = self.repo.as_ref() else { |
|
| 201 | + | return; |
|
| 202 | + | }; |
|
| 203 | + | let Some(path) = request.path.as_deref() else { |
|
| 204 | + | return; |
|
| 205 | + | }; |
|
| 206 | + | if self.highlighter.has_path_grammar(path) { |
|
| 207 | + | return; |
|
| 208 | + | } |
|
| 209 | + | let Some(oid) = self.head_oids.get(&key) else { |
|
| 210 | + | return; |
|
| 211 | + | }; |
|
| 212 | + | let head = repo.head_line(oid.as_str()); |
|
| 213 | + | if let Ok(Some(head)) = head { |
|
| 214 | + | let _ = Builtins::load_head_grammars(&mut self.highlighter, &head); |
|
| 215 | + | } |
|
| 216 | + | } |
|
| 217 | + | ||
| 218 | + | /// Loads bounded source context for uncached request paths. |
|
| 219 | + | fn load_context_sources(&mut self, requests: &[HighlightRequest]) { |
|
| 220 | + | let Some(repo) = self.repo.as_ref() else { |
|
| 221 | + | return; |
|
| 222 | + | }; |
|
| 223 | + | let mut targets = BTreeMap::new(); |
|
| 224 | + | for request in requests { |
|
| 225 | + | let key = (request.key.file, request.key.side); |
|
| 226 | + | if self.context_sources.contains_key(&key) { |
|
| 227 | + | continue; |
|
| 228 | + | } |
|
| 229 | + | if let Some(path) = request.path.as_deref() { |
|
| 230 | + | targets.insert((path.to_path_buf(), request.key.side), request.key.file); |
|
| 231 | + | } |
|
| 232 | + | } |
|
| 233 | + | if targets.is_empty() { |
|
| 234 | + | return; |
|
| 235 | + | } |
|
| 236 | + | ||
| 237 | + | let paths = targets |
|
| 238 | + | .keys() |
|
| 239 | + | .map(|(path, _)| path.as_path()) |
|
| 240 | + | .collect::<BTreeSet<_>>() |
|
| 241 | + | .into_iter() |
|
| 242 | + | .collect::<Vec<_>>(); |
|
| 243 | + | let Ok(patch) = repo.diff(HIGHLIGHT_CONTEXT_LINES, &paths) else { |
|
| 244 | + | return; |
|
| 245 | + | }; |
|
| 246 | + | let Ok(document) = DiffDocument::decode_bytes(&patch) else { |
|
| 247 | + | return; |
|
| 248 | + | }; |
|
| 249 | + | ||
| 250 | + | for file in &document.files { |
|
| 251 | + | for side in [DiffSide::Old, DiffSide::New] { |
|
| 252 | + | let Some(path) = file.source_path(side) else { |
|
| 253 | + | continue; |
|
| 254 | + | }; |
|
| 255 | + | let Some(file_id) = targets.get(&(path, side)).copied() else { |
|
| 256 | + | continue; |
|
| 257 | + | }; |
|
| 258 | + | let sources = file |
|
| 259 | + | .hunks |
|
| 260 | + | .iter() |
|
| 261 | + | .map(|hunk| hunk.highlight_source(side)) |
|
| 262 | + | .collect::<Vec<_>>(); |
|
| 263 | + | self.context_sources.insert((file_id, side), sources); |
|
| 264 | + | } |
|
| 265 | + | } |
|
| 266 | + | } |
|
| 267 | + | ||
| 268 | + | /// Returns cached context that contains the requested source row. |
|
| 269 | + | fn context_source_for(&self, request: &HighlightRequest) -> Option<&HighlightSource> { |
|
| 270 | + | let key = (request.key.file, request.key.side); |
|
| 271 | + | self.context_sources.get(&key)?.iter().find(|source| { |
|
| 272 | + | source.line(request.key.source_line) == request.source.line(request.key.source_line) |
|
| 273 | + | }) |
|
| 274 | + | } |
|
| 275 | + | ||
| 276 | + | /// Refetches and decodes one context update. |
|
| 277 | + | fn context(&mut self, request: ContextRequest) -> Option<ContextUpdate> { |
|
| 278 | + | let repo = self.repo.as_ref()?; |
|
| 279 | + | let paths = request.paths().collect::<Vec<_>>(); |
|
| 280 | + | let patch = repo.diff(request.context_lines(), &paths).ok()?; |
|
| 281 | + | ||
| 282 | + | drop(paths); |
|
| 283 | + | request.decode(&patch).ok().flatten() |
|
| 284 | + | } |
|
| 285 | + | } |
crates/diff/src/lib.rs
+16 -2
| 2 | 2 | //! |
|
| 3 | 3 | //! The viewer is intentionally I/O-free: it parses or accepts patch data, |
|
| 4 | 4 | //! owns read-only viewer state, and writes frames into a |
|
| 5 | 5 | //! [`rustik_tui::Buffer`]. Backend access is abstracted behind the |
|
| 6 | 6 | //! [`rustik_repo::Repo`] trait so the viewer stays testable. The `rustik-diff` |
|
| 7 | - | //! binary owns stdin/stdout, terminals, events, and background workers. |
|
| 7 | + | //! binary owns stdin/stdout, terminals, and events. |
|
| 8 | + | //! |
|
| 9 | + | //! The optional `builtins` feature (on by default) bundles default highlighting |
|
| 10 | + | //! assets ([`Builtins`]) and a background worker ([`spawn_highlighter`]) so |
|
| 11 | + | //! hosts get a batteries-included viewer; disable it to bring your own. |
|
| 8 | 12 | #![deny(unsafe_code)] |
|
| 9 | 13 | #![warn(missing_docs)] |
|
| 10 | 14 | #![warn(clippy::unwrap_used)] |
|
| 11 | 15 | ||
| 16 | + | #[cfg(feature = "builtins")] |
|
| 17 | + | mod builtins; |
|
| 12 | 18 | mod commit; |
|
| 13 | 19 | mod context; |
|
| 20 | + | mod decorate; |
|
| 14 | 21 | mod document; |
|
| 15 | 22 | mod highlight; |
|
| 23 | + | #[cfg(feature = "builtins")] |
|
| 24 | + | mod highlighter; |
|
| 16 | 25 | mod viewer; |
|
| 17 | 26 | mod word; |
|
| 18 | 27 | ||
| 19 | 28 | pub mod decode; |
|
| 20 | 29 | pub mod encode; |
|
| 21 | 30 | ||
| 31 | + | #[cfg(feature = "builtins")] |
|
| 32 | + | pub use builtins::Builtins; |
|
| 22 | 33 | pub use commit::{Commit, Header, ParseCommitError}; |
|
| 23 | 34 | pub use context::ContextChange; |
|
| 24 | 35 | pub use decode::Decode; |
|
| 36 | + | pub use decorate::{DiffDecorator, FileDecoration, HunkDecoration}; |
|
| 25 | 37 | pub use document::{ |
|
| 26 | 38 | DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind, |
|
| 27 | 39 | FileMode, FileStats, Hunk, HunkHeader, HunkId, Oid, OidError, RowId, Stats, |
|
| 28 | 40 | }; |
|
| 29 | 41 | pub use encode::Encode; |
|
| 30 | 42 | pub use highlight::{ |
|
| 31 | 43 | BuiltinHighlighter, DiffHighlighter, DiffSide, HighlightKey, HighlightKeyInput, |
|
| 32 | 44 | HighlightRequest, HighlightResult, HighlightSource, |
|
| 33 | 45 | }; |
|
| 46 | + | #[cfg(feature = "builtins")] |
|
| 47 | + | pub use highlighter::{HighlightOutput, Highlighter, spawn_highlighter}; |
|
| 34 | 48 | pub use viewer::{ |
|
| 35 | 49 | ContextRequest, ContextUpdate, DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffState, |
|
| 36 | - | DiffViewer, FileTreeMode, FileTreeTarget, ViewChange, |
|
| 50 | + | DiffViewer, FileTree, FileTreeMode, FileTreeTarget, ViewChange, |
|
| 37 | 51 | }; |
crates/diff/src/viewer.rs
+96 -11
| 5 | 5 | use std::collections::btree_map::Entry; |
|
| 6 | 6 | use std::collections::{BTreeMap, BTreeSet}; |
|
| 7 | 7 | use std::convert::Infallible; |
|
| 8 | 8 | use std::ops::Range; |
|
| 9 | 9 | use std::path::{Path, PathBuf}; |
|
| 10 | + | use std::sync::Arc; |
|
| 10 | 11 | ||
| 11 | 12 | use rustik_highlight as syntax; |
|
| 12 | 13 | use rustik_tui as tui; |
|
| 13 | 14 | use tui::{ |
|
| 14 | 15 | Badge, Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, |
|
| 15 | 16 | MouseButton, Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, |
|
| 16 | 17 | TableOptions, Text, TreeStyle, VStack, View, Viewport, Widget, colors, |
|
| 17 | 18 | }; |
|
| 18 | 19 | ||
| 19 | 20 | use crate::context::{self, ContextChange, ContextState}; |
|
| 21 | + | use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration}; |
|
| 20 | 22 | use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult}; |
|
| 21 | 23 | use crate::word; |
|
| 22 | 24 | use crate::{ |
|
| 23 | 25 | Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, |
|
| 24 | 26 | FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId, |
|
| 25 | 27 | }; |
|
| 26 | 28 | ||
| 27 | - | pub use tree::{FileTreeMode, FileTreeTarget}; |
|
| 29 | + | pub use tree::{FileTree, FileTreeMode, FileTreeTarget}; |
|
| 28 | 30 | ||
| 29 | 31 | /// Visible and lookahead row ranges that should be highlighted. |
|
| 30 | 32 | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 31 | 33 | struct HighlightWindow { |
|
| 32 | 34 | /// First row that can produce a visible highlight. |
| 233 | 235 | /// Cached intra-line word diffs, keyed by hunk. |
|
| 234 | 236 | word_diffs: BTreeMap<HunkId, word::WordChanges>, |
|
| 235 | 237 | /// Rendered commit-preamble rows for the most recent body width. |
|
| 236 | 238 | preamble: Vec<Line>, |
|
| 237 | 239 | /// File-tree state and model. |
|
| 238 | - | file_tree: tree::FileTreeViewer, |
|
| 240 | + | file_tree: tree::FileTree, |
|
| 239 | 241 | /// Interactive override for file-tree visibility. |
|
| 240 | 242 | file_tree_visibility: FileTreeVisibility, |
|
| 241 | 243 | /// Cached rendered row positions for visible files. |
|
| 242 | 244 | index: RowIndex, |
|
| 243 | 245 | /// Hunk-context expansion bookkeeping. |
|
| 244 | 246 | context: ContextState, |
|
| 247 | + | /// Optional host-supplied source of file and hunk decorations. |
|
| 248 | + | /// |
|
| 249 | + | /// Shared rather than boxed so the viewer keeps deriving `Clone`. `None` |
|
| 250 | + | /// renders the plain diff with no decorations. |
|
| 251 | + | decorator: Option<Arc<dyn DiffDecorator>>, |
|
| 245 | 252 | } |
|
| 246 | 253 | ||
| 247 | 254 | /// Cached rendered row positions for the current document visibility state. |
|
| 248 | 255 | /// |
|
| 249 | 256 | /// Visible files tile the content region contiguously, so each file is stored |
| 436 | 443 | ||
| 437 | 444 | impl DiffViewer { |
|
| 438 | 445 | /// Creates a viewer with plain initial rendering state. |
|
| 439 | 446 | pub fn new(document: DiffDocument, options: DiffOptions) -> Self { |
|
| 440 | 447 | let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS); |
|
| 441 | - | let file_tree = tree::FileTreeViewer::new(&document, options.file_tree_root.clone()); |
|
| 448 | + | let file_tree = tree::FileTree::new(&document, options.file_tree_root.clone()); |
|
| 442 | 449 | let state = DiffState::default(); |
|
| 443 | 450 | ||
| 444 | 451 | let mut viewer = Self { |
|
| 445 | 452 | document, |
|
| 446 | 453 | options, |
| 452 | 459 | preamble, |
|
| 453 | 460 | file_tree, |
|
| 454 | 461 | file_tree_visibility: FileTreeVisibility::default(), |
|
| 455 | 462 | index: RowIndex::default(), |
|
| 456 | 463 | context: ContextState::new(), |
|
| 464 | + | decorator: None, |
|
| 457 | 465 | }; |
|
| 458 | 466 | viewer.rebuild_index(); |
|
| 459 | 467 | viewer |
|
| 460 | 468 | } |
|
| 461 | 469 | ||
| 470 | + | /// Sets the source queried for per-file and per-hunk decorations. |
|
| 471 | + | /// |
|
| 472 | + | /// Decorations are pure overlays: they change what each file header and |
|
| 473 | + | /// hunk render without affecting row counts, scrolling, or focus. |
|
| 474 | + | pub fn set_decorator(&mut self, decorator: impl DiffDecorator + 'static) { |
|
| 475 | + | self.decorator = Some(Arc::new(decorator)); |
|
| 476 | + | } |
|
| 477 | + | ||
| 478 | + | /// Clears any decorator, restoring the plain diff rendering. |
|
| 479 | + | pub fn clear_decorator(&mut self) { |
|
| 480 | + | self.decorator = None; |
|
| 481 | + | } |
|
| 482 | + | ||
| 483 | + | /// Returns the decoration for a file header, or the empty default. |
|
| 484 | + | fn file_decoration(&self, file: FileId) -> FileDecoration { |
|
| 485 | + | self.decorator |
|
| 486 | + | .as_ref() |
|
| 487 | + | .map_or_else(FileDecoration::default, |decorator| decorator.file(file)) |
|
| 488 | + | } |
|
| 489 | + | ||
| 490 | + | /// Returns the decoration for a hunk, or the empty default. |
|
| 491 | + | fn hunk_decoration(&self, file: FileId, hunk: HunkId) -> HunkDecoration { |
|
| 492 | + | self.decorator |
|
| 493 | + | .as_ref() |
|
| 494 | + | .map_or_else(HunkDecoration::default, |decorator| { |
|
| 495 | + | decorator.hunk(file, hunk) |
|
| 496 | + | }) |
|
| 497 | + | } |
|
| 498 | + | ||
| 462 | 499 | /// Returns the viewed document. |
|
| 463 | 500 | pub const fn document(&self) -> &DiffDocument { |
|
| 464 | 501 | &self.document |
|
| 465 | 502 | } |
|
| 466 | 503 |
| 673 | 710 | ||
| 674 | 711 | /// Renders the file tree. |
|
| 675 | 712 | fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 676 | 713 | let active_file = self.visible_file(); |
|
| 677 | 714 | self.file_tree |
|
| 678 | - | .render(active_file, self.options.diff_palette, area, buf); |
|
| 715 | + | .draw(active_file, self.options.diff_palette, area, buf); |
|
| 679 | 716 | } |
|
| 680 | 717 | ||
| 681 | 718 | /// Renders the main diff view into `buf`. |
|
| 682 | 719 | fn render_diff(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 683 | 720 | let body_cols = ScrollView::body_cols(area); |
| 1134 | 1171 | line: border.top(inner_cols), |
|
| 1135 | 1172 | diff: None, |
|
| 1136 | 1173 | }; |
|
| 1137 | 1174 | } |
|
| 1138 | 1175 | FILE_HEADER_ROW => { |
|
| 1176 | + | let decoration = self.file_decoration(file.id); |
|
| 1139 | 1177 | return RenderRow { |
|
| 1140 | 1178 | line: wrap_child(file.header_line( |
|
| 1141 | 1179 | child_cols, |
|
| 1142 | 1180 | collapsed, |
|
| 1143 | 1181 | self.options.diff_palette, |
|
| 1182 | + | &decoration, |
|
| 1144 | 1183 | )), |
|
| 1145 | 1184 | diff: None, |
|
| 1146 | 1185 | }; |
|
| 1147 | 1186 | } |
|
| 1148 | 1187 | row if row == bottom => { |
| 1173 | 1212 | line: wrap_child(hunk_gap_line), |
|
| 1174 | 1213 | diff: None, |
|
| 1175 | 1214 | }; |
|
| 1176 | 1215 | } |
|
| 1177 | 1216 | if local < body_end { |
|
| 1178 | - | let row = self.hunk_row_at(file, hunk, local - body_start, child_cols); |
|
| 1217 | + | let mut row = self.hunk_row_at(file, hunk, local - body_start, child_cols); |
|
| 1218 | + | let decoration = self.hunk_decoration(file.id, hunk.id); |
|
| 1219 | + | if let Some(style) = decoration.style { |
|
| 1220 | + | row.line = row.line.style(style); |
|
| 1221 | + | } |
|
| 1222 | + | // The corner marker is drawn over the hunk's first body row. |
|
| 1223 | + | if local == body_start { |
|
| 1224 | + | row.line = Self::overlay_corner(row.line, &decoration.corner, child_cols); |
|
| 1225 | + | } |
|
| 1179 | 1226 | return RenderRow { |
|
| 1180 | 1227 | line: wrap_child(row.line), |
|
| 1181 | 1228 | diff: row.diff, |
|
| 1182 | 1229 | }; |
|
| 1183 | 1230 | } |
| 1692 | 1739 | /// Returns a marker cell. |
|
| 1693 | 1740 | fn marker_cell(marker: &str, foreground: Color) -> Line { |
|
| 1694 | 1741 | Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH) |
|
| 1695 | 1742 | } |
|
| 1696 | 1743 | ||
| 1744 | + | /// Overlays `corner` onto the right edge of a child-width row line. |
|
| 1745 | + | /// |
|
| 1746 | + | /// The hunk row already fills `cols`; truncating to leave room for the |
|
| 1747 | + | /// corner and re-padding preserves the row background, then the corner is |
|
| 1748 | + | /// appended so it sits flush in the hunk's top-right corner. A corner that |
|
| 1749 | + | /// does not fit is dropped rather than truncated. |
|
| 1750 | + | fn overlay_corner(mut line: Line, corner: &Line, cols: usize) -> Line { |
|
| 1751 | + | let width = corner.width(); |
|
| 1752 | + | if width == 0 || width >= cols { |
|
| 1753 | + | return line; |
|
| 1754 | + | } |
|
| 1755 | + | let left = cols - width; |
|
| 1756 | + | Line::truncate(&mut line, left, "โฆ"); |
|
| 1757 | + | Line::pad(&mut line, left); |
|
| 1758 | + | line.extend(corner.clone()) |
|
| 1759 | + | } |
|
| 1760 | + | ||
| 1697 | 1761 | /// Returns the diff scrollbar style. |
|
| 1698 | 1762 | fn scrollbar_style() -> ScrollbarStyle { |
|
| 1699 | 1763 | ScrollbarStyle::new( |
|
| 1700 | 1764 | Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)), |
|
| 1701 | 1765 | Cell::new(SCROLLBAR_THUMB, Style::default().fg(SCROLLBAR_THUMB_COLOR)), |
| 1780 | 1844 | *local += hunk.lines.len(); |
|
| 1781 | 1845 | Some((hunk, row)) |
|
| 1782 | 1846 | }) |
|
| 1783 | 1847 | } |
|
| 1784 | 1848 | ||
| 1785 | - | /// Returns a file header line. |
|
| 1786 | - | fn header_line(&self, cols: usize, collapsed: bool, palette: DiffPalette) -> Line { |
|
| 1849 | + | /// Returns a file header line, applying any host decoration. |
|
| 1850 | + | fn header_line( |
|
| 1851 | + | &self, |
|
| 1852 | + | cols: usize, |
|
| 1853 | + | collapsed: bool, |
|
| 1854 | + | palette: DiffPalette, |
|
| 1855 | + | decoration: &FileDecoration, |
|
| 1856 | + | ) -> Line { |
|
| 1787 | 1857 | let mut left = Line::blank(); |
|
| 1788 | 1858 | let marker = if collapsed { |
|
| 1789 | 1859 | TreeStyle::DEFAULT.collapsed_marker |
|
| 1790 | 1860 | } else { |
|
| 1791 | 1861 | TreeStyle::DEFAULT.expanded_marker |
|
| 1792 | 1862 | }; |
|
| 1793 | 1863 | left.push(Label::from_char(marker).fg(LINE_NUMBER_FG)); |
|
| 1794 | 1864 | left.push(Label::space()); |
|
| 1865 | + | if let Some(status) = &decoration.status { |
|
| 1866 | + | left.push(Label::from_char(status.item).style(status.style)); |
|
| 1867 | + | left.push(Label::space()); |
|
| 1868 | + | } |
|
| 1795 | 1869 | left = left.extend(self.path_line()); |
|
| 1796 | 1870 | ||
| 1797 | 1871 | if let Some(badge) = self.badge(palette) { |
|
| 1798 | 1872 | left.push(Label::space()); |
|
| 1799 | 1873 | left = left.extend(badge.line()); |
|
| 1800 | 1874 | } |
|
| 1875 | + | // Right-aligned segments: host annotations first, then the diffstat (or |
|
| 1876 | + | // its decoration override), joined by a fixed gap. |
|
| 1877 | + | let mut right = decoration.annotations.clone(); |
|
| 1878 | + | let stats = decoration.stats.clone().or_else(|| { |
|
| 1879 | + | let stats = self.stats(); |
|
| 1880 | + | Self::diffstat_line(stats.additions, stats.deletions, palette) |
|
| 1881 | + | }); |
|
| 1882 | + | if let Some(side) = stats { |
|
| 1883 | + | right.push(side); |
|
| 1884 | + | } |
|
| 1801 | 1885 | let mut header = HStack::default().child(left).spacer(); |
|
| 1802 | - | let stats = self.stats(); |
|
| 1803 | - | ||
| 1804 | - | if let Some(side) = Self::diffstat_line(stats.additions, stats.deletions, palette) { |
|
| 1805 | - | header = header.child(side); |
|
| 1886 | + | for (index, segment) in right.into_iter().enumerate() { |
|
| 1887 | + | if index > 0 { |
|
| 1888 | + | header = header.child(Line::new(" ")); |
|
| 1889 | + | } |
|
| 1890 | + | header = header.child(segment); |
|
| 1806 | 1891 | } |
|
| 1807 | 1892 | header.to_line(Constraint::tight(cols)) |
|
| 1808 | 1893 | } |
|
| 1809 | 1894 | ||
| 1810 | 1895 | /// Returns the file path display line. |
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
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
+0 -0
src/a.rs
+0 -0
src/b.rs
+0 -0
README.md
+0 -0
src/app/a.rs
+0 -0
src/lib/b.rs
+0 -0
README.md
+0 -0
a.rs
+0 -0
b.rs
+0 -0
assets/css/style.css
+0 -0
assets/css/style.css
+0 -0
a.rs
+0 -0
a.rs
+0 -0
a.rs
+0 -0
b.rs
+0 -0
crates/diff/src/viewer/tree.rs
+64 -20
| 3 | 3 | use std::collections::BTreeSet; |
|
| 4 | 4 | use std::path::PathBuf; |
|
| 5 | 5 | ||
| 6 | 6 | use rustik_tui as tui; |
|
| 7 | 7 | use tui::{ |
|
| 8 | - | Buffer, Color, Label, Line, Placement, Point, Rect, Style, Table, TableOptions, Tree, |
|
| 9 | - | TreeHitZone, TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, Widget, |
|
| 8 | + | Buffer, Color, Constraint, Label, Line, Placement, Point, Rect, Size, Style, Table, |
|
| 9 | + | TableOptions, Tree, TreeHitZone, TreeModel, TreeNodeKind, TreeRow, TreeState, TreeStyle, |
|
| 10 | + | Widget, |
|
| 10 | 11 | }; |
|
| 11 | 12 | ||
| 12 | 13 | use super::{DiffPalette, FILE_KIND_BADGE_FG, MIN_RENDER_COLS}; |
|
| 13 | 14 | use crate::{DiffDocument, FileId, FileKind, Stats}; |
|
| 14 | 15 |
| 97 | 98 | id: FileId, |
|
| 98 | 99 | /// Kind of file-level change. |
|
| 99 | 100 | kind: FileKind, |
|
| 100 | 101 | } |
|
| 101 | 102 | ||
| 102 | - | /// Stateful file tree owned by the diff viewer. |
|
| 103 | + | /// Stateful file tree over a diff document, usable as a standalone [`Widget`]. |
|
| 104 | + | /// |
|
| 105 | + | /// A host builds it from a [`DiffDocument`], drives selection through the |
|
| 106 | + | /// navigation methods, and renders it anywhere via its [`Widget`] |
|
| 107 | + | /// implementation. The diff viewer embeds one and renders it directly. |
|
| 103 | 108 | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 104 | - | pub(super) struct FileTreeViewer { |
|
| 109 | + | pub struct FileTree { |
|
| 105 | 110 | /// Path tree rendered in the file tree. |
|
| 106 | 111 | model: FileTreeModel, |
|
| 107 | 112 | /// Expansion and cursor state for the file tree. |
|
| 108 | 113 | state: TreeState<usize>, |
|
| 114 | + | /// File highlighted as active when rendered through [`Widget`]. |
|
| 115 | + | active_file: Option<FileId>, |
|
| 116 | + | /// Palette used for badges and stats when rendered through [`Widget`]. |
|
| 117 | + | palette: DiffPalette, |
|
| 109 | 118 | } |
|
| 110 | 119 | ||
| 111 | - | impl FileTreeViewer { |
|
| 112 | - | /// Creates a file-tree viewer from `document`. |
|
| 113 | - | pub(super) fn new(document: &DiffDocument, root: String) -> Self { |
|
| 120 | + | impl FileTree { |
|
| 121 | + | /// Creates a file tree from `document`, rooted at the folder named `root`. |
|
| 122 | + | pub fn new(document: &DiffDocument, root: String) -> Self { |
|
| 114 | 123 | let model = FileTreeModel::new(document, root); |
|
| 115 | 124 | let state = model.initial_state(); |
|
| 116 | 125 | ||
| 117 | - | Self { model, state } |
|
| 126 | + | Self { |
|
| 127 | + | model, |
|
| 128 | + | state, |
|
| 129 | + | active_file: None, |
|
| 130 | + | palette: DiffPalette::default(), |
|
| 131 | + | } |
|
| 132 | + | } |
|
| 133 | + | ||
| 134 | + | /// Sets the file highlighted as active when rendered through [`Widget`]. |
|
| 135 | + | #[must_use] |
|
| 136 | + | pub fn active_file(mut self, file: Option<FileId>) -> Self { |
|
| 137 | + | self.active_file = file; |
|
| 138 | + | self |
|
| 139 | + | } |
|
| 140 | + | ||
| 141 | + | /// Sets the palette used for badges and stats when rendered through [`Widget`]. |
|
| 142 | + | #[must_use] |
|
| 143 | + | pub fn palette(mut self, palette: DiffPalette) -> Self { |
|
| 144 | + | self.palette = palette; |
|
| 145 | + | self |
|
| 118 | 146 | } |
|
| 119 | 147 | ||
| 120 | 148 | /// Returns the file tree's expansion and cursor state. |
|
| 121 | 149 | /// |
|
| 122 | 150 | /// The `model` is immutable after construction, so this is the only part |
|
| 123 | 151 | /// that changes between actions. |
|
| 124 | - | pub(super) fn state(&self) -> &TreeState<usize> { |
|
| 152 | + | pub fn state(&self) -> &TreeState<usize> { |
|
| 125 | 153 | &self.state |
|
| 126 | 154 | } |
|
| 127 | 155 | ||
| 128 | 156 | /// Returns the file-tree target under the cursor. |
|
| 129 | - | #[cfg(test)] |
|
| 130 | - | pub(super) fn target(&self) -> Option<FileTreeTarget> { |
|
| 157 | + | pub fn target(&self) -> Option<FileTreeTarget> { |
|
| 131 | 158 | self.state |
|
| 132 | 159 | .selected() |
|
| 133 | 160 | .and_then(|id| self.model.target_for(id)) |
|
| 134 | 161 | } |
|
| 135 | 162 | ||
| 136 | 163 | /// Returns the file tree width for a viewport. |
|
| 137 | - | pub(super) fn cols(&self, view_cols: usize) -> usize { |
|
| 164 | + | pub fn cols(&self, view_cols: usize) -> usize { |
|
| 138 | 165 | let available = view_cols.saturating_sub(GAP_COLS + MIN_RENDER_COLS); |
|
| 139 | 166 | ||
| 140 | 167 | Tree::new(&self.model, &self.state) |
|
| 141 | 168 | .content_cols(DEFAULT_COLS) |
|
| 142 | 169 | .min(available) |
|
| 143 | 170 | } |
|
| 144 | 171 | ||
| 145 | - | /// Renders the file tree. |
|
| 146 | - | pub(super) fn render( |
|
| 172 | + | /// Renders the file tree into `area` with an explicit active file and palette. |
|
| 173 | + | /// |
|
| 174 | + | /// This is the workhorse the diff viewer calls directly; the [`Widget`] |
|
| 175 | + | /// implementation delegates here using the configured fields. |
|
| 176 | + | pub(super) fn draw( |
|
| 147 | 177 | &mut self, |
|
| 148 | 178 | active_file: Option<FileId>, |
|
| 149 | 179 | palette: DiffPalette, |
|
| 150 | 180 | area: Rect, |
|
| 151 | 181 | buf: &mut Buffer, |
| 200 | 230 | self.state.select(id); |
|
| 201 | 231 | } |
|
| 202 | 232 | } |
|
| 203 | 233 | ||
| 204 | 234 | /// Moves the file-tree cursor by `delta` visible rows. |
|
| 205 | - | pub(super) fn select(&mut self, delta: isize) -> Option<FileId> { |
|
| 235 | + | pub fn select(&mut self, delta: isize) -> Option<FileId> { |
|
| 206 | 236 | self.state.select_next(&self.model, delta); |
|
| 207 | 237 | self.selected_file() |
|
| 208 | 238 | } |
|
| 209 | 239 | ||
| 210 | 240 | /// Selects the visible file-tree row for `file`. |
|
| 211 | - | pub(super) fn select_file(&mut self, file: FileId) -> bool { |
|
| 241 | + | pub fn select_file(&mut self, file: FileId) -> bool { |
|
| 212 | 242 | let Some(id) = self.visible_node_for_file(file) else { |
|
| 213 | 243 | return false; |
|
| 214 | 244 | }; |
|
| 215 | 245 | self.state.select(id) |
|
| 216 | 246 | } |
| 232 | 262 | Some(FileTreeClick::Row) |
|
| 233 | 263 | } |
|
| 234 | 264 | } |
|
| 235 | 265 | ||
| 236 | 266 | /// Activates the current file-tree cursor. |
|
| 237 | - | pub(super) fn activate_target(&mut self) -> Option<FileId> { |
|
| 267 | + | pub fn activate_target(&mut self) -> Option<FileId> { |
|
| 238 | 268 | let id = self.state.selected()?; |
|
| 239 | 269 | if self.model.kind(id) == TreeNodeKind::Branch { |
|
| 240 | 270 | self.state.toggle(&self.model, id); |
|
| 241 | 271 | } |
|
| 242 | 272 | self.selected_file() |
|
| 243 | 273 | } |
|
| 244 | 274 | ||
| 245 | 275 | /// Returns the file represented by the selected file-tree row. |
|
| 246 | - | pub(super) fn selected_file(&self) -> Option<FileId> { |
|
| 276 | + | pub fn selected_file(&self) -> Option<FileId> { |
|
| 247 | 277 | self.state |
|
| 248 | 278 | .selected() |
|
| 249 | 279 | .and_then(|id| self.model.first_file_for(id)) |
|
| 250 | 280 | } |
|
| 251 | 281 | ||
| 252 | 282 | /// Collapses the focused file-tree folder. |
|
| 253 | - | pub(super) fn collapse_folder(&mut self) { |
|
| 283 | + | pub fn collapse_folder(&mut self) { |
|
| 254 | 284 | let Some(id) = self.state.selected() else { |
|
| 255 | 285 | return; |
|
| 256 | 286 | }; |
|
| 257 | 287 | if self.model.kind(id) == TreeNodeKind::Branch { |
|
| 258 | 288 | self.state.collapse(id); |
|
| 259 | 289 | } |
|
| 260 | 290 | } |
|
| 261 | 291 | ||
| 262 | 292 | /// Expands the focused file-tree folder. |
|
| 263 | - | pub(super) fn expand_folder(&mut self) { |
|
| 293 | + | pub fn expand_folder(&mut self) { |
|
| 264 | 294 | let Some(id) = self.state.selected() else { |
|
| 265 | 295 | return; |
|
| 266 | 296 | }; |
|
| 267 | 297 | if self.model.kind(id) == TreeNodeKind::Branch { |
|
| 268 | 298 | self.state.expand(id); |
| 327 | 357 | ||
| 328 | 358 | Some((Rect::new(body.x, body.y, body.cols, tree_rows), info)) |
|
| 329 | 359 | } |
|
| 330 | 360 | } |
|
| 331 | 361 | ||
| 362 | + | impl Widget for FileTree { |
|
| 363 | + | fn size(&self, parent: Constraint) -> Size { |
|
| 364 | + | let tree = Tree::new(&self.model, &self.state); |
|
| 365 | + | let cols = tree.content_cols(DEFAULT_COLS); |
|
| 366 | + | let rows = tree.visible_rows().len().saturating_add(TOP_PADDING_ROWS); |
|
| 367 | + | ||
| 368 | + | Size::new(cols, rows).constrain(parent) |
|
| 369 | + | } |
|
| 370 | + | ||
| 371 | + | fn render(&mut self, area: Rect, buf: &mut Buffer) { |
|
| 372 | + | self.draw(self.active_file, self.palette, area, buf); |
|
| 373 | + | } |
|
| 374 | + | } |
|
| 375 | + | ||
| 332 | 376 | /// Path tree built once from a diff document. Immutable after construction. |
|
| 333 | 377 | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 334 | 378 | pub(super) struct FileTreeModel { |
|
| 335 | 379 | /// Root node ids. |
|
| 336 | 380 | roots: Vec<usize>, |
a.rs
+0 -0
b.rs
+0 -0