//! Highlight request and result protocol for diff rendering. use std::collections::{BTreeMap, hash_map::DefaultHasher}; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Arc; use rustik_highlight as syntax; use rustik_tui as tui; use rustik_tui::{Color, Label, Line, Style}; use crate::{DiffLine, FileDiff, FileId, Hunk, HunkId, RowId}; /// Side of the diff used as syntax-highlighting source context. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum DiffSide { /// Old side of a deleted or context line. Old, /// New side of an added or context line. New, } /// Cache key for one highlighted diff row. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct HighlightKey { /// File containing the row. pub file: FileId, /// Diff side to highlight. pub side: DiffSide, /// One-based source line number. pub source_line: u32, /// Hash of the row text. pub text_hash: u64, /// Syntax key or `auto`. pub syntax: String, /// Theme key. pub theme: String, } /// Request sent from a visible diff viewport to a highlighter. #[derive(Clone, Debug, Eq, PartialEq)] pub struct HighlightRequest { /// Stable cache key for this request. pub key: HighlightKey, /// Hunk containing the row. pub hunk: HunkId, /// Row to highlight. pub row: RowId, /// Source path used for syntax inference. pub path: Option, /// Source-side text used for range highlighting. pub source: HighlightSource, } /// Highlighted line returned by a worker. #[derive(Clone, Debug)] pub struct HighlightResult { /// Cache key copied from the original request. pub key: HighlightKey, /// Hunk containing the highlighted row. pub hunk: HunkId, /// Highlighted row. pub row: RowId, /// Renderable highlighted line. pub line: tui::Line, } /// File-side source text used to highlight a diff row with surrounding context. #[derive(Clone, Debug, Eq, PartialEq)] pub struct HighlightSource { /// Source-side text assembled from the diff. pub text: Arc, /// Source line represented by the head of [`HighlightSource::text`]. pub head: u32, /// Byte offset of each source line. line_starts: Arc<[u32]>, } /// Pure built-in highlighter for visible diff rows. #[derive(Debug)] pub struct BuiltinHighlighter { /// Grammar and theme registry. registry: syntax::Registry, /// Theme used when requests ask for automatic theme selection. default_theme: String, /// Per-source tokenizer caches reused across batches. blob_caches: BTreeMap, } /// Identifier for cached blob-highlight state. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] struct BlobCacheKey { /// Grammar name used to tokenize the source. grammar: String, /// Address of the cached source allocation. text_ptr: usize, /// Length of the cached source allocation. text_len: usize, } /// Cached tokenizer state for one source allocation. #[derive(Debug)] struct BlobCacheEntry { /// Source owner that keeps the cached allocation pinned. _source: Arc, /// Per-line parser state and scope cache. cache: syntax::BlobCache, } /// Highlights diff rows requested by a [`crate::DiffViewer`]. pub trait DiffHighlighter { /// Highlights one batch of visible diff rows. fn highlight_batch(&mut self, requests: Vec) -> Vec; } /// Grouping key for requests that can share one range highlighter. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] struct HighlightBatchKey { /// File containing the requested rows. file: FileId, /// Source side containing the requested rows. side: DiffSide, /// Syntax key requested by the viewer. syntax: String, /// Theme key requested by the viewer. theme: String, /// Path used for syntax inference. path: Option, /// Source allocation identity. source: HighlightSourceId, } /// Allocation identity for source text shared by highlight requests. #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] struct HighlightSourceId { /// Address of the source text allocation. ptr: usize, /// Length of the source text allocation. len: usize, /// Source line represented by the head of the source text. head: u32, } impl HighlightKey { /// Creates a key for a row of source text. pub fn new(input: HighlightKeyInput<'_>) -> Self { let mut hasher = DefaultHasher::new(); input.text.hash(&mut hasher); Self { file: input.file, side: input.side, source_line: input.source_line, text_hash: hasher.finish(), syntax: input.syntax.unwrap_or("auto").to_owned(), theme: input.theme.to_owned(), } } } impl HighlightSource { /// Creates source text beginning at a source line. pub fn new(text: impl Into>, head: u32) -> Self { let text = text.into(); let mut line_starts = Vec::new(); if !text.is_empty() { line_starts.push(0); line_starts.extend( text.bytes() .enumerate() .filter(|(index, byte)| *byte == b'\n' && index + 1 < text.len()) .map(|(index, _)| (index + 1) as u32), ); } Self { text, head, line_starts: line_starts.into(), } } /// Returns the zero-based source-text line index for a source line. pub fn line_index(&self, source_line: u32) -> Option { source_line.checked_sub(self.head).map(|line| line as usize) } /// Returns one source line without its trailing line terminator. pub fn line(&self, source_line: u32) -> Option<&str> { let index = self.line_index(source_line)?; self.indexed_line(index) } /// Returns one source line by its zero-based index. fn indexed_line(&self, index: usize) -> Option<&str> { let start = *self.line_starts.get(index)? as usize; let mut end = self .line_starts .get(index + 1) .map_or(self.text.len(), |next| *next as usize); if end > start && self.text.as_bytes()[end - 1] == b'\n' { end -= 1; } if end > start && self.text.as_bytes()[end - 1] == b'\r' { end -= 1; } Some(&self.text[start..end]) } /// Returns the bytes retained by this source and its line index. pub(crate) fn retained_bytes(&self) -> usize { self.text .len() .saturating_add(self.line_starts.len() * size_of::()) } /// Returns whether this source reproduces every row `hunk` shows on `side`. /// /// Highlighted rows are rendered from the source text, not the diff, so a /// source that has drifted from the patch would display lines the patch /// never contained. Worktree files drift whenever they are edited after the /// diff was produced. pub fn matches_hunk(&self, hunk: &Hunk, side: DiffSide) -> bool { let Some(mut line) = self.line_index(hunk_head(hunk, side)) else { return false; }; hunk.lines .iter() .filter(|line| source_len(line, side) != 0) .all(|expected| { let matches = self.indexed_line(line) == Some(expected.text.as_str()); line += 1; matches }) } /// Returns a compact identity for grouping requests that share this source. fn id(&self) -> HighlightSourceId { HighlightSourceId { ptr: self.text.as_ptr() as usize, len: self.text.len(), head: self.head, } } } impl Hunk { /// Builds contiguous source text for one hunk side. pub fn highlight_source(&self, side: DiffSide) -> HighlightSource { let mut text = String::new(); push_hunk_source_lines(self, side, &mut text); HighlightSource::new(text, hunk_head(self, side)) } } impl FileDiff { /// Returns the source path for a file side, falling back to the other side. pub fn source_path(&self, side: DiffSide) -> Option { let (primary, fallback) = match side { DiffSide::Old => (&self.header.old_path, &self.header.new_path), DiffSide::New => (&self.header.new_path, &self.header.old_path), }; primary.clone().or_else(|| fallback.clone()) } /// Builds contiguous source text for one file side. /// /// Returns `None` when the file's hunks are not contiguous on `side`. pub fn highlight_source(&self, side: DiffSide) -> Option { let mut text = String::new(); let mut head = None; let mut next_line = None; for hunk in &self.hunks { let hunk_head = hunk_head(hunk, side); if next_line.is_some_and(|line| line != hunk_head) { return None; } head.get_or_insert(hunk_head); push_hunk_source_lines(hunk, side, &mut text); let len = hunk .lines .iter() .map(|line| source_len(line, side)) .sum::(); next_line = Some(hunk_head + len); } head.map(|head| HighlightSource::new(text, head)) } } /// Appends source-side hunk lines to `text`. /// /// Blank lines are kept so a [`HighlightSource`] line index stays aligned with /// its source line number. fn push_hunk_source_lines(hunk: &Hunk, side: DiffSide, text: &mut String) { let mut first = text.is_empty(); for line in &hunk.lines { if source_len(line, side) == 0 { continue; } if first { first = false; } else { text.push('\n'); } text.push_str(&line.text); } } /// Returns the first source line for one hunk side. fn hunk_head(hunk: &Hunk, side: DiffSide) -> u32 { match side { DiffSide::Old => hunk.header.old_line_no, DiffSide::New => hunk.header.new_line_no, } } /// Returns how many source lines a diff line contributes on `side`. fn source_len(line: &DiffLine, side: DiffSide) -> u32 { match side { DiffSide::Old => line.kind.old_len(), DiffSide::New => line.kind.new_len(), } } impl BuiltinHighlighter { /// Creates a highlighter from caller-loaded grammars and themes. pub fn new(registry: syntax::Registry, default_theme: impl Into) -> Self { Self { registry, default_theme: default_theme.into(), blob_caches: BTreeMap::new(), } } /// Adds `grammar` to this highlighter if a grammar with the same name is absent. pub fn ensure_grammar(&mut self, grammar: syntax::Grammar) { if self.registry.grammar_by_name(&grammar.name).is_err() { self.registry.add_grammar(grammar); } } /// Returns whether a path selects a loaded non-plain grammar. pub fn has_path_grammar(&self, path: &Path) -> bool { self.registry .query(syntax::GrammarQuery { syntax: None, path: Some(path), head: None, }) .is_ok_and(|grammar| grammar.scope_name != "text.plain") } /// Highlights one request. pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult { self.highlight_group(vec![request]).remove(0) } /// Highlights multiple requests. pub fn highlight_requests(&mut self, requests: I) -> Vec where I: IntoIterator, { let mut batches: BTreeMap> = BTreeMap::new(); for request in requests { batches .entry(HighlightBatchKey::from(&request)) .or_default() .push(request); } batches .into_values() .flat_map(|requests| self.highlight_group(requests)) .collect() } /// Highlights grouped requests with one range highlighter. fn highlight_group(&mut self, requests: Vec) -> Vec { let Some(first) = requests.first() else { return Vec::new(); }; let Ok(grammar) = self.registry.query(syntax::GrammarQuery { syntax: (first.key.syntax != "auto").then_some(first.key.syntax.as_str()), path: first.path.as_deref(), head: first.source.text.lines().next(), }) else { return requests.into_iter().map(HighlightResult::plain).collect(); }; let theme_name = if first.key.theme == "auto" { self.default_theme.as_str() } else { &first.key.theme }; let Ok(theme) = self.registry.theme_by_name(theme_name) else { return requests.into_iter().map(HighlightResult::plain).collect(); }; let range = requests.iter().filter_map(|request| { request .source .line_index(request.key.source_line) .map(|line| line..line.saturating_add(1)) }); let mut start = usize::MAX; let mut end = 0; for range in range { start = start.min(range.start); end = end.max(range.end); } if start >= end { return requests.into_iter().map(HighlightResult::plain).collect(); } let source = first.source.text.clone(); let cache_key = BlobCacheKey { grammar: grammar.name.clone(), text_ptr: source.as_ptr() as usize, text_len: source.len(), }; let cache = self .blob_caches .remove(&cache_key) .map(|entry| entry.cache) .unwrap_or_default(); let mut lines = BTreeMap::new(); let cache = { let mut blob = syntax::BlobHighlighter::with_cache(grammar, source.as_ref(), cache); blob.highlight_styled_range(theme, start..end, |line| { lines.insert(line.line_index, line_from_spans(line.text, line.styles)); }); blob.into_cache() }; self.blob_caches.insert( cache_key, BlobCacheEntry { _source: source, cache, }, ); requests .into_iter() .map(|request| { let line = request .source .line_index(request.key.source_line) .and_then(|index| lines.remove(&index)) .unwrap_or_else(|| request.plain_line()); HighlightResult::new(request, line) }) .collect() } } impl DiffHighlighter for BuiltinHighlighter { fn highlight_batch(&mut self, requests: Vec) -> Vec { self.highlight_requests(requests) } } impl HighlightRequest { /// Returns the unhighlighted source row for this request. fn plain_line(&self) -> Line { self.source .line(self.key.source_line) .map(Line::new) .unwrap_or_default() } } impl HighlightResult { /// Pairs a highlighted line with the metadata copied from its request. pub fn new(request: HighlightRequest, line: Line) -> Self { Self { key: request.key, hunk: request.hunk, row: request.row, line, } } /// Returns a plain result for an unhighlightable request. fn plain(request: HighlightRequest) -> Self { let line = request.plain_line(); Self::new(request, line) } } impl From<&HighlightRequest> for HighlightBatchKey { fn from(request: &HighlightRequest) -> Self { Self { file: request.key.file, side: request.key.side, syntax: request.key.syntax.clone(), theme: request.key.theme.clone(), path: request.path.clone(), source: request.source.id(), } } } /// Converts style spans into a TUI line. fn line_from_spans(text: &str, spans: &[syntax::StyleSpan]) -> Line { if text.is_empty() || spans.is_empty() { return Line::new(text); } let mut line = Line::blank(); let mut cursor = 0; for span in spans { if cursor < span.start { line.push(Label::new(&text[cursor..span.start])); } if span.start < span.end { line.push(Label::new(&text[span.start..span.end]).style(span.style.tui_style())); } cursor = span.end; } if cursor < text.len() { line.push(Label::new(&text[cursor..])); } line } /// Input fields used to create a [`HighlightKey`]. #[derive(Clone, Copy, Debug)] pub struct HighlightKeyInput<'a> { /// File containing the row. pub file: FileId, /// Diff side to highlight. pub side: DiffSide, /// One-based source line number. pub source_line: u32, /// Source text. pub text: &'a str, /// Optional syntax override. pub syntax: Option<&'a str>, /// Theme name. pub theme: &'a str, } /// Converts syntax styles into TUI styles. trait SyntaxStyleExt { /// Converts this syntax style into a TUI style. fn tui_style(self) -> Style; } impl SyntaxStyleExt for syntax::Style { fn tui_style(self) -> Style { let mut out = Style::default(); if let Some(color) = self.foreground { out = out.fg(Color::RGB(color.r, color.g, color.b)); } if self.font_style.contains(syntax::FontStyle::BOLD) { out = out.bold(); } if self.font_style.contains(syntax::FontStyle::ITALIC) { out = out.italic(); } if self.font_style.contains(syntax::FontStyle::UNDERLINE) { out = out.underline(); } if self.font_style.contains(syntax::FontStyle::STRIKETHROUGH) { out = out.strikethrough(); } out } } #[cfg(test)] mod tests { use super::*; use crate::Decode; use std::str::FromStr; #[test] fn source_lines_before_head_are_absent() { let source = HighlightSource::new("two\nthree\n", 2); assert_eq!(source.line_index(1), None); assert_eq!(source.line(1), None); assert_eq!(source.line_index(2), Some(0)); assert_eq!(source.line(2), Some("two")); } #[test] fn indexed_source_lines_match_rust_line_boundaries() { let source = HighlightSource::new("one\r\ntwo\n\nthree", 1); assert_eq!(source.line(1), Some("one")); assert_eq!(source.line(2), Some("two")); assert_eq!(source.line(3), Some("")); assert_eq!(source.line(4), Some("three")); assert_eq!(source.line(5), None); } #[test] fn file_highlight_source_spans_the_new_side() { let document = crate::DiffDocument::decode_str( "\ diff --git a/a.css b/a.css index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.css +++ b/a.css @@ -1,3 +1,3 @@ .x { -background: url(old.svg); +background: url(new.svg); } ", ) .unwrap(); let source = document.files[0].highlight_source(DiffSide::New).unwrap(); assert_eq!(source.head, 1); assert_eq!(source.line(1), Some(".x {")); assert_eq!(source.line(2), Some("background: url(new.svg);")); assert_eq!(source.line(3), Some("}")); } #[test] fn highlight_source_keeps_a_leading_blank_line() { // A hunk whose first source line is blank must not collapse it away, // or every later line index shifts up by one against its line number. // The blank context line is a single space; spell the fixture with // `concat!` so that space cannot be mistaken for trailing whitespace. let document = crate::DiffDocument::decode_str(concat!( "diff --git a/a.rs b/a.rs\n", "index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n", "--- a/a.rs\n", "+++ b/a.rs\n", "@@ -2,3 +2,3 @@\n", " \n", "-old\n", "+new\n", " tail\n", )) .unwrap(); let hunk = &document.files[0].hunks[0]; let source = hunk.highlight_source(DiffSide::New); assert_eq!(source.head, 2); assert_eq!(source.line(2), Some("")); assert_eq!(source.line(3), Some("new")); assert_eq!(source.line(4), Some("tail")); let file = document.files[0].highlight_source(DiffSide::New).unwrap(); assert_eq!(file.line(2), Some("")); assert_eq!(file.line(3), Some("new")); } #[cfg(feature = "builtins")] #[test] fn css_custom_properties_use_variable_theme_style() { let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap(); let theme = syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(); let line = " --color-background-light: #dad8d8;"; let mut state = syntax::LineState::default(); let mut tokenizer = syntax::LineTokenizer::new(&grammar); let _ = tokenizer.tokenize_line(&mut state, ":root {"); let spans = tokenizer.tokenize_line(&mut state, line); let styles = theme.style_spans(&grammar, line, &spans); let custom_property = line.find("--color-background-light").unwrap(); let style = styles .iter() .find(|style| style.start <= custom_property && style.end > custom_property) .unwrap(); assert!(scopes_for_byte(&grammar, &spans, custom_property).contains(&"variable.css")); assert_eq!( style.style.foreground, Some(syntax::Rgb { r: 137, g: 180, b: 250 }) ); } #[cfg(feature = "builtins")] #[test] fn css_var_references_use_variable_theme_style() { let grammar = syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap(); let theme = syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(); let line = " color: var(--color-dimmer);"; let mut state = syntax::LineState::default(); let mut tokenizer = syntax::LineTokenizer::new(&grammar); let _ = tokenizer.tokenize_line(&mut state, ".note-meta {"); let spans = tokenizer.tokenize_line(&mut state, line); let styles = theme.style_spans(&grammar, line, &spans); let variable = line.find("--color-dimmer").unwrap(); let style = styles .iter() .find(|style| style.start <= variable && style.end > variable) .unwrap(); assert!(scopes_for_byte(&grammar, &spans, variable).contains(&"variable.argument.css")); assert_eq!( style.style.foreground, Some(syntax::Rgb { r: 235, g: 160, b: 172 }) ); } #[cfg(feature = "builtins")] #[test] fn rust_signature_parameters_use_normal_theme_style() { let grammar = syntax::Grammar::from_str(syntax::syntaxes::RUST).unwrap(); let theme = syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(); let line = " mut cursor: String,"; let mut state = syntax::LineState::default(); let mut tokenizer = syntax::LineTokenizer::new(&grammar); let _ = tokenizer.tokenize_line(&mut state, "fn reconcile_with("); let spans = tokenizer.tokenize_line(&mut state, line); let styles = theme.style_spans(&grammar, line, &spans); let parameter = line.find("cursor").unwrap(); let style = styles .iter() .find(|style| style.start <= parameter && style.end > parameter) .unwrap(); assert!(scopes_for_byte(&grammar, &spans, parameter).contains(&"variable.parameter.rust")); assert_eq!( style.style.foreground, Some(syntax::Rgb { r: 205, g: 214, b: 244 }) ); } fn scopes_for_byte<'a>( grammar: &'a syntax::Grammar, spans: &'a [syntax::ScopeSpan], byte: usize, ) -> Vec<&'a str> { spans .iter() .filter(|span| span.start <= byte && span.end > byte) .filter_map(|span| grammar.scopes.get(span.scope.index())) .map(String::as_str) .collect() } }