Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
markdown: Optimize `paint_search_highlights` (#59473)
Bennet Bo Fennerc7ad65e46817
diff --git a/Cargo.lock b/Cargo.lockindex 7e281c25640..f6790ba3677 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10649,6 +10649,7 @@ dependencies = ["node_runtime","pulldown-cmark 0.13.0","settings",+ "smallvec","stacksafe","sum_tree","theme",diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rsindex ae37d3fdd91..b64f65a37c5 100644--- a/crates/gpui/src/elements/text.rs+++ b/crates/gpui/src/elements/text.rs@@ -875,12 +875,6 @@ impl TextLayout {let element_state = element_state.as_ref().expect("measurement has not been performed");- let bounds = element_state- .bounds- .expect("prepaint has not been performed");- let line_height = element_state.line_height;-- let mut line_origin = bounds.origin;let mut line_start_ix = 0;for line in &element_state.lines {@@ -888,7 +882,6 @@ impl TextLayout {if index < line_start_ix {break;} else if index > line_end_ix {- line_origin.y += line.size(line_height).height;line_start_ix = line_end_ix + 1;continue;} else {@@ -899,6 +892,18 @@ impl TextLayout {None}+ /// Retrieve all line layouts in source order.+ pub fn line_layouts(&self) -> SmallVec<[Arc<WrappedLineLayout>; 1]> {+ self.0+ .borrow()+ .as_ref()+ .expect("measurement has not been performed")+ .lines+ .iter()+ .map(|line| line.layout.clone())+ .collect()+ }+/// The bounds of this layout.pub fn bounds(&self) -> Bounds<Pixels> {self.0.borrow().as_ref().unwrap().bounds.unwrap()diff --git a/crates/markdown/Cargo.toml b/crates/markdown/Cargo.tomlindex 3982cf9506a..77af7f396b4 100644--- a/crates/markdown/Cargo.toml+++ b/crates/markdown/Cargo.toml@@ -32,6 +32,7 @@ markup5ever_rcdom.workspace = truemermaid_render = { path = "../mermaid_render" }pulldown-cmark.workspace = truesettings.workspace = true+smallvec.workspace = truestacksafe.workspace = truesum_tree.workspace = truetheme.workspace = truediff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rsindex 9b61d322f01..b12523c98c9 100644--- a/crates/markdown/src/markdown.rs+++ b/crates/markdown/src/markdown.rs@@ -16,6 +16,7 @@ use mermaid::{};pub use path_range::{LineCol, PathWithRange};use settings::Settings as _;+use smallvec::SmallVec;use theme_settings::ThemeSettings;use util::maybe;@@ -36,7 +37,7 @@ use gpui::{ImageFormat, ImageSource, KeyContext, Length, MouseButton, MouseDownEvent, MouseEvent,MouseMoveEvent, MouseUpEvent, Point, ScrollHandle, Stateful, StrikethroughStyle,StyleRefinement, StyledImage, StyledText, Subscription, Task, TextAlign, TextLayout, TextRun,- TextStyle, TextStyleRefinement, actions, img, point, quad,+ TextStyle, TextStyleRefinement, WrappedLineLayout, actions, img, point, quad,};use language::{CharClassifier, Language, LanguageRegistry, Rope};use parser::CodeBlockMetadata;@@ -812,8 +813,17 @@ impl Markdown {active: Option<usize>,cx: &mut Context<Self>,) {- self.search_highlights = highlights;- self.active_search_highlight = active;+ let mut indexed_highlights = highlights.into_iter().enumerate().collect::<Vec<_>>();+ indexed_highlights.sort_by_key(|(_, range)| (range.start, range.end));+ self.active_search_highlight = active.and_then(|active| {+ indexed_highlights+ .iter()+ .position(|(original_ix, _)| *original_ix == active)+ });+ self.search_highlights = indexed_highlights+ .into_iter()+ .map(|(_, range)| range)+ .collect();cx.notify();}@@ -1646,19 +1656,27 @@ impl MarkdownElement {let active_index = markdown.active_search_highlight;let colors = cx.theme().colors();- for (i, highlight_range) in markdown.search_highlights.iter().enumerate() {- let color = if Some(i) == active_index {+ let highlight_bounds = rendered_text.bounds_for_sorted_source_ranges(+ markdown+ .search_highlights+ .iter()+ .enumerate()+ .map(|(ix, range)| (ix, range.clone())),+ );+ for (highlight_ix, bounds) in highlight_bounds {+ let color = if Some(highlight_ix) == active_index {colors.search_active_match_background} else {colors.search_match_background};- Self::paint_highlight_range(- highlight_range.start,- highlight_range.end,+ window.paint_quad(quad(+ bounds,+ Pixels::ZERO,color,- rendered_text,- window,- );+ Edges::default(),+ Hsla::transparent_black(),+ BorderStyle::default(),+ ));}}@@ -3564,6 +3582,13 @@ struct RenderedText {footnote_refs: Rc<[RenderedFootnoteRef]>,}+struct WrappedLineSegment {+ start: usize,+ end: usize,+ row_top: Pixels,+ layout: Arc<WrappedLineLayout>,+}+#[derive(Debug, Clone, Eq, PartialEq)]struct RenderedLink {source_range: Range<usize>,@@ -3578,81 +3603,158 @@ struct RenderedFootnoteRef {impl RenderedText {fn bounds_for_source_range(&self, range: Range<usize>) -> Vec<Bounds<Pixels>> {+ self.bounds_for_sorted_source_ranges([(0, range)])+ .into_iter()+ .map(|(_, bounds)| bounds)+ .collect()+ }++ fn bounds_for_sorted_source_ranges(+ &self,+ ranges: impl IntoIterator<Item = (usize, Range<usize>)>,+ ) -> Vec<(usize, Bounds<Pixels>)> {+ let ranges = ranges.into_iter().collect::<Vec<_>>();let mut all_bounds = Vec::new();+ let mut first_possible_range_ix = 0;for line in self.lines.iter() {let line_source_start = line.source_mappings.first().unwrap().source_index;- if line_source_start >= range.end {+ while ranges+ .get(first_possible_range_ix)+ .is_some_and(|(_, range)| range.end <= line_source_start)+ {+ first_possible_range_ix += 1;+ }++ let Some((_, first_possible_range)) = ranges.get(first_possible_range_ix) else {break;+ };+ if first_possible_range.start >= line.source_end {+ continue;}- if line.source_end <= range.start {++ let wrapped_line_segments = Self::wrapped_line_segments(line);+ if wrapped_line_segments.is_empty() {continue;}- let layout = &line.layout;- let line_bounds = layout.bounds();- let line_height = layout.line_height();+ let mut range_ix = first_possible_range_ix;+ while let Some((highlight_ix, range)) = ranges.get(range_ix) {+ if range.start >= line.source_end {+ break;+ }+ Self::push_bounds_for_line_source_range(+ &mut all_bounds,+ *highlight_ix,+ line,+ &wrapped_line_segments,+ range.start.max(line_source_start)..range.end.min(line.source_end),+ );+ range_ix += 1;+ }+ }++ all_bounds+ }- let rendered_start =- line.rendered_index_for_source_index(range.start.max(line_source_start));- let rendered_end = line.rendered_index_for_source_index(range.end.min(line.source_end));+ fn wrapped_line_segments(line: &RenderedLine) -> SmallVec<[WrappedLineSegment; 1]> {+ let layout = &line.layout;+ let line_height = layout.line_height();+ let mut row_top = layout.bounds().top();+ let mut wrapped_line_start = 0;+ let mut segments = SmallVec::new();++ for wrapped_line in layout.line_layouts() {+ let wrapped_line_end = wrapped_line_start + wrapped_line.len();+ let wrapped_line_height = wrapped_line.size(line_height).height;+ segments.push(WrappedLineSegment {+ start: wrapped_line_start,+ end: wrapped_line_end,+ row_top,+ layout: wrapped_line,+ });+ row_top += wrapped_line_height;+ wrapped_line_start = wrapped_line_end + 1;+ }- let mut wrapped_line_start = 0;- let mut row_top = line_bounds.top();+ segments+ }- while wrapped_line_start < rendered_end {- let Some(wrapped_line) = layout.line_layout_for_index(wrapped_line_start) else {- break;- };+ fn push_bounds_for_line_source_range(+ all_bounds: &mut Vec<(usize, Bounds<Pixels>)>,+ highlight_ix: usize,+ line: &RenderedLine,+ wrapped_line_segments: &[WrappedLineSegment],+ range: Range<usize>,+ ) {+ if range.start >= range.end {+ return;+ }- let unwrapped_layout = &wrapped_line.unwrapped_layout;- let wrapped_line_end = wrapped_line_start + wrapped_line.len();+ let layout = &line.layout;+ let line_bounds = layout.bounds();+ let line_height = layout.line_height();- let row_ends = wrapped_line- .wrap_boundaries()- .iter()- .map(|wrap_boundary| {- let glyph = &unwrapped_layout.runs[wrap_boundary.run_ix].glyphs- [wrap_boundary.glyph_ix];- (wrapped_line_start + glyph.index, glyph.position.x)- })- .chain([(wrapped_line_end, unwrapped_layout.width)]);+ let rendered_start = line.rendered_index_for_source_index(range.start);+ let rendered_end = line.rendered_index_for_source_index(range.end);- let mut row_start = wrapped_line_start;- let mut row_start_x = Pixels::ZERO;+ for wrapped_line_segment in wrapped_line_segments {+ if wrapped_line_segment.start >= rendered_end {+ break;+ }+ if wrapped_line_segment.end <= rendered_start {+ continue;+ }- for (row_end, row_end_x) in row_ends {- let selection_start = rendered_start.max(row_start);- let selection_end = rendered_end.min(row_end);+ let wrapped_line = &wrapped_line_segment.layout;+ let unwrapped_layout = &wrapped_line.unwrapped_layout;+ let wrapped_line_start = wrapped_line_segment.start;+ let wrapped_line_end = wrapped_line_segment.end;+ let mut row_top = wrapped_line_segment.row_top;++ let row_ends = wrapped_line+ .wrap_boundaries()+ .iter()+ .map(|wrap_boundary| {+ let glyph =+ &unwrapped_layout.runs[wrap_boundary.run_ix].glyphs[wrap_boundary.glyph_ix];+ (wrapped_line_start + glyph.index, glyph.position.x)+ })+ .chain([(wrapped_line_end, unwrapped_layout.width)]);- if selection_start < selection_end {- let alignment_offset = line.alignment_offset_for_segment(- line_bounds.size.width,- row_start_x,- row_end_x,- );- let x_for_index = |index| {- line_bounds.left()- + alignment_offset- + unwrapped_layout.x_for_index(index - wrapped_line_start)- - row_start_x- };- all_bounds.push(Bounds::from_corners(+ let mut row_start = wrapped_line_start;+ let mut row_start_x = Pixels::ZERO;++ for (row_end, row_end_x) in row_ends {+ let selection_start = rendered_start.max(row_start);+ let selection_end = rendered_end.min(row_end);++ if selection_start < selection_end {+ let alignment_offset = line.alignment_offset_for_segment(+ line_bounds.size.width,+ row_start_x,+ row_end_x,+ );+ let x_for_index = |index| {+ line_bounds.left()+ + alignment_offset+ + unwrapped_layout.x_for_index(index - wrapped_line_start)+ - row_start_x+ };+ all_bounds.push((+ highlight_ix,+ Bounds::from_corners(point(x_for_index(selection_start), row_top),point(x_for_index(selection_end), row_top + line_height),- ));- }-- row_start = row_end;- row_start_x = row_end_x;- row_top += line_height;+ ),+ ));}- wrapped_line_start = wrapped_line_end + 1;+ row_start = row_end;+ row_start_x = row_end_x;+ row_top += line_height;}}-- all_bounds}fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {