Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
markdown: Fix search highlights hiding text with opaque theme colors (#64788)
Fabrício Limabda9c0bd43a8
diff --git a/crates/gpui/src/elements/text.rs b/crates/gpui/src/elements/text.rsindex b3e5a351754..d1896ad0a65 100644--- a/crates/gpui/src/elements/text.rs+++ b/crates/gpui/src/elements/text.rs@@ -613,6 +613,13 @@ impl IntoElement for StyledText {#[derive(Default, Clone)]pub struct TextLayout(Rc<RefCell<Option<TextLayoutInner>>>);+#[derive(Clone, Copy)]+enum TextPaintPass {+ All,+ Background,+ Foreground,+}+struct TextLayoutInner {len: usize,lines: SmallVec<[WrappedLine; 1]>,@@ -790,40 +797,66 @@ impl TextLayout {}fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {+ self.paint_lines(TextPaintPass::All, window, cx)+ .with_context(|| format!("failed to paint {text}"))+ .unwrap();+ }++ /// Paints the backgrounds of the text runs without the glyphs, so that callers can paint+ /// content, such as highlights, between the backgrounds and the text. Follow it with+ /// [`Self::paint_foreground`] to paint the glyphs.+ pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {+ self.paint_lines(TextPaintPass::Background, window, cx)+ }++ /// Paints the glyphs and decorations of the text without the run backgrounds.+ pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {+ self.paint_lines(TextPaintPass::Foreground, window, cx)+ }++ fn paint_lines(+ &self,+ pass: TextPaintPass,+ window: &mut Window,+ cx: &mut App,+ ) -> anyhow::Result<()> {let element_state = self.0.borrow();let element_state = element_state.as_ref()- .with_context(|| format!("measurement has not been performed on {text}"))- .unwrap();+ .context("measurement has not been performed")?;let bounds = element_state.bounds- .with_context(|| format!("prepaint has not been performed on {text}"))- .unwrap();+ .context("prepaint has not been performed")?;let line_height = element_state.line_height;let mut line_origin = bounds.origin;let text_style = window.text_style();for line in &element_state.lines {- line.paint_background(- line_origin,- line_height,- text_style.text_align,- Some(bounds),- window,- cx,- )- .log_err();- line.paint(- line_origin,- line_height,- text_style.text_align,- Some(bounds),- window,- cx,- )- .log_err();+ if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {+ line.paint_background(+ line_origin,+ line_height,+ text_style.text_align,+ Some(bounds),+ window,+ cx,+ )+ .log_err();+ }+ if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {+ line.paint(+ line_origin,+ line_height,+ text_style.text_align,+ Some(bounds),+ window,+ cx,+ )+ .log_err();+ }line_origin.y += line.size(line_height).height;}+ Ok(())}/// Get the byte index into the input of the pixel position.diff --git a/crates/gpui/src/text_system/line.rs b/crates/gpui/src/text_system/line.rsindex 780d1a6422c..f5210052e2b 100644--- a/crates/gpui/src/text_system/line.rs+++ b/crates/gpui/src/text_system/line.rs@@ -536,12 +536,13 @@ fn paint_line(&mut Window,),) -> Result<()> {- let line_bounds = Bounds::new(+ let line_bounds = line_paint_bounds(origin,- size(- layout.width,- line_height * (wrap_boundaries.len() as f32 + 1.),- ),+ layout,+ line_height,+ align,+ align_width,+ wrap_boundaries,);window.paint_layer(line_bounds, |window| {let padding_top = (line_height - layout.ascent - layout.descent) / 2.;@@ -798,12 +799,13 @@ fn paint_line_background(window: &mut Window,cx: &mut App,) -> Result<()> {- let line_bounds = Bounds::new(+ let line_bounds = line_paint_bounds(origin,- size(- layout.width,- line_height * (wrap_boundaries.len() as f32 + 1.),- ),+ layout,+ line_height,+ align,+ align_width,+ wrap_boundaries,);window.paint_layer(line_bounds, |window| {let mut decoration_runs = decoration_runs.iter();@@ -936,6 +938,51 @@ fn paint_line_background(})}+fn line_paint_bounds(+ origin: Point<Pixels>,+ layout: &LineLayout,+ line_height: Pixels,+ align: TextAlign,+ align_width: Option<Pixels>,+ wrap_boundaries: &[WrapBoundary],+) -> Bounds<Pixels> {+ let mut bounds = Bounds::new(+ origin,+ size(+ layout.width,+ line_height * (wrap_boundaries.len() as f32 + 1.),+ ),+ );+ if align == TextAlign::Left || layout.len == 0 {+ return bounds;+ }++ let align_width = align_width.unwrap_or(layout.width);+ let mut row_start = Pixels::ZERO;+ let row_ends = wrap_boundaries+ .iter()+ .map(|boundary| {+ layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix]+ .position+ .x+ })+ .chain([layout.width]);+ for (row, row_end) in row_ends.enumerate() {+ let width = row_end - row_start;+ let offset = match align {+ TextAlign::Left => Pixels::ZERO,+ TextAlign::Center => (align_width - width) / 2.,+ TextAlign::Right => align_width - width,+ };+ bounds = bounds.union(&Bounds::new(+ point(origin.x + offset, origin.y + line_height * row as f32),+ size(width, line_height),+ ));+ row_start = row_end;+ }+ bounds+}+fn aligned_origin_x(origin: Point<Pixels>,align_width: Pixels,@@ -1003,6 +1050,68 @@ mod tests {}}+ #[test]+ fn test_aligned_line_paint_bounds() {+ let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]);+ let origin = point(px(10.), px(20.));+ let line_height = px(16.);+ for (wrapped, align_width, expected_edges) in [+ (false, None, [(10., 50.), (10., 50.), (10., 50.)]),+ (true, None, [(10., 50.), (10., 50.), (10., 50.)]),+ (false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),+ (true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]),+ (false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]),+ (true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]),+ (false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]),+ (true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]),+ (false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]),+ (true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]),+ ] {+ let boundaries = if wrapped {+ vec![WrapBoundary {+ run_ix: 0,+ glyph_ix: 2,+ }]+ } else {+ Vec::new()+ };+ for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right]+ .into_iter()+ .zip(expected_edges)+ {+ assert_eq!(+ line_paint_bounds(+ origin,+ &line.layout,+ line_height,+ align,+ align_width.map(px),+ &boundaries,+ ),+ Bounds::new(+ point(px(left), origin.y),+ size(px(right - left), px(if wrapped { 32. } else { 16. })),+ ),+ "wrapped={wrapped}, align={align:?}, align_width={align_width:?}",+ );+ }+ }+ let empty = make_shaped_line("", &[], 0., &[]);+ for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] {+ assert_eq!(+ line_paint_bounds(+ origin,+ &empty.layout,+ line_height,+ align,+ Some(px(100.)),+ &[]+ ),+ Bounds::new(origin, size(Pixels::ZERO, line_height)),+ );+ }+ }+#[gpui::test]fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) {test_underline_handler_at_scales(cx, |window, cx| {diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rsindex d0f5cc90d82..a7591fc413d 100644--- a/crates/markdown/src/markdown.rs+++ b/crates/markdown/src/markdown.rs@@ -4222,7 +4222,7 @@ impl MarkdownElementBuilder {self.rendered_lines.push(rendered_line.clone());self.append_child(RenderedLineElement {- text: text.into_any(),+ text,line: rendered_line,}.into_any_element(),@@ -4247,7 +4247,7 @@ impl MarkdownElementBuilder {/// Wraps a rendered line so its code chips and highlights share the glyphs'/// ancestor content masks, and records the clipped bounds for platform text hit testing.struct RenderedLineElement {- text: AnyElement,+ text: StyledText,line: Rc<RenderedLine>,}@@ -4266,26 +4266,27 @@ impl Element for RenderedLineElement {fn request_layout(&mut self,_id: Option<&GlobalElementId>,- _inspector_id: Option<&gpui::InspectorElementId>,+ inspector_id: Option<&gpui::InspectorElementId>,window: &mut Window,cx: &mut App,) -> (gpui::LayoutId, Self::RequestLayoutState) {- (self.text.request_layout(window, cx), ())+ self.text.request_layout(None, inspector_id, window, cx)}fn prepaint(&mut self,_id: Option<&GlobalElementId>,- _inspector_id: Option<&gpui::InspectorElementId>,+ inspector_id: Option<&gpui::InspectorElementId>,bounds: Bounds<Pixels>,- _request_layout: &mut Self::RequestLayoutState,+ request_layout: &mut Self::RequestLayoutState,window: &mut Window,cx: &mut App,) -> Self::PrepaintState {self.line.visible_bounds.set(Some(bounds.intersect(&window.content_mask().bounds)));- self.text.prepaint(window, cx);+ self.text+ .prepaint(None, inspector_id, bounds, request_layout, window, cx);}fn paint(@@ -4298,9 +4299,11 @@ impl Element for RenderedLineElement {window: &mut Window,cx: &mut App,) {+ let layout = self.text.layout();self.line.paint_code_chips(window);- self.text.paint(window, cx);+ layout.paint_background(window, cx).log_err();self.line.paint_highlights(window);+ layout.paint_foreground(window, cx).log_err();}}@@ -4372,6 +4375,8 @@ impl RenderedLine {}}+ /// Painted between the text run backgrounds and the glyphs, so opaque highlight+ /// colors neither hide the text nor get hidden by run backgroundsfn paint_highlights(&self, window: &mut Window) {if self.highlights.is_empty() {return;@@ -5112,13 +5117,16 @@ impl InputHandler for MarkdownInputHandler {mod tests {use super::*;use gpui::{- Modifiers, RenderImage, ScrollDelta, ScrollWheelEvent, TestAppContext, TouchPhase,+ Background, DevicePixels, Font, FontId, FontMetrics, FontRun, GlyphId, LineLayout,+ Modifiers, NoopTextSystem, PlatformTextSystem, RenderGlyphParams, RenderImage, ScrollDelta,+ ScrollWheelEvent, Size, TestAppContext, TestDispatcher, TextRenderingMode, TouchPhase,UpdateGlobal, VisualTestContext, size,};use language::{Language, LanguageConfig, LanguageMatcher};+ use std::borrow::Cow;use std::cell::RefCell;use std::sync::{- Arc,+ Arc, Mutex,atomic::{AtomicUsize, Ordering},};@@ -7737,6 +7745,251 @@ mod tests {assert!(visible_bounds.right() <= window_width);}+ #[gpui::test]+ fn test_search_and_selection_below_aligned_inline_code(cx: &mut TestAppContext) {+ ensure_theme_initialized(cx);+ for alignment in ["---", ":---:", "---:"] {+ for text in ["xx", "é中🙂"] {+ let source = format!(+ "| WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW |\n| {alignment} |\n| ~~`{text}`~~ |\n"+ );+ let start = source.find(text).expect("inline code is present");+ let range = start..start + text.len();+ let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));+ markdown.update(cx, |markdown, cx| {+ markdown.selection.start = range.start;+ markdown.selection.end = range.end;+ markdown.set_search_highlights(vec![range], None, cx);+ });+ let (_, cx) = cx.add_window_view(move |_, _| MarkdownTestView {+ markdown,+ style: MarkdownStyle {+ inline_code: TextStyleRefinement {+ background_color: Some(gpui::green()),+ ..TextStyleRefinement::default()+ },+ selection_background_color: gpui::red(),+ ..MarkdownStyle::default()+ },+ code_span_link: None,+ rendered_text: Rc::new(RefCell::new(None)),+ });+ cx.run_until_parked();+ cx.update(|window, cx| {+ let quads = window.painted_quads();+ let selection_bounds = quads+ .iter()+ .find(|quad| quad.background == Background::from(gpui::red()))+ .expect("selection is painted")+ .bounds;+ let order_for_color = |color| {+ let orders = quads+ .iter()+ .filter(|quad| {+ quad.background == Background::from(color)+ && quad.bounds.intersects(&selection_bounds)+ })+ .map(|quad| quad.order)+ .collect::<Vec<_>>();+ assert_eq!(orders.len(), 1);+ orders[0]+ };+ let chip_order = order_for_color(gpui::green());+ let search_order = order_for_color(cx.theme().colors().search_match_background);+ let selection_order = order_for_color(gpui::red());+ let text_order = window+ .painted_underlines()+ .iter()+ .map(|underline| underline.order)+ .min()+ .expect("strikethrough is painted");+ assert!(chip_order < search_order);+ assert!(search_order < selection_order);+ assert!(+ selection_order < text_order,+ "alignment={alignment}, text={text}, selection={selection_order}, glyphs={text_order}",+ );+ });+ }+ }+ }++ #[gpui::test]+ fn test_search_highlights_are_painted_between_text_backgrounds_and_glyphs(+ cx: &mut TestAppContext,+ ) {+ ensure_theme_initialized(cx);+ let source = "~~[struck](https://zed.dev) through~~";+ let highlight_start = source+ .find("struck")+ .expect("highlighted text should be present");+ let highlight_range = highlight_start..highlight_start + "struck".len();+ let run_background_color = gpui::red();++ let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));+ markdown.update(cx, |markdown, cx| {+ markdown.set_search_highlights(vec![highlight_range], None, cx);+ });+ let (_, cx) = cx.add_window_view(move |_, _| MarkdownTestView {+ markdown,+ style: MarkdownStyle {+ link: TextStyleRefinement {+ background_color: Some(run_background_color),+ ..Default::default()+ },+ ..MarkdownStyle::default()+ },+ code_span_link: None,+ rendered_text: Rc::new(RefCell::new(None)),+ });+ cx.run_until_parked();++ let highlight_color = cx.update(|_, cx| cx.theme().colors().search_match_background);+ cx.update(|window, _| {+ let quads = window.painted_quads();+ let order_of_quad_with = |color: Hsla| {+ quads+ .iter()+ .find(|quad| quad.background == color.into())+ .map(|quad| quad.order)+ };+ let run_background_order =+ order_of_quad_with(run_background_color).expect("link background should be painted");+ let highlight_order =+ order_of_quad_with(highlight_color).expect("search highlight should be painted");+ // Strikethroughs are painted in the same layer as the glyphs+ let text_order = window+ .painted_underlines()+ .iter()+ .map(|underline| underline.order)+ .min()+ .expect("strikethrough should be painted");+ assert!(+ run_background_order < highlight_order,+ "text run backgrounds must not cover search highlights"+ );+ assert!(+ highlight_order < text_order,+ "search highlight must be drawn below the text, otherwise opaque theme colors hide it"+ );+ });+ }++ /// Records the font runs of every line it shapes, delegating everything else.+ struct FontRunRecordingTextSystem {+ text_system: NoopTextSystem,+ shaped_lines: Mutex<Vec<(String, Vec<usize>)>>,+ }++ impl PlatformTextSystem for FontRunRecordingTextSystem {+ fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> anyhow::Result<()> {+ self.text_system.add_fonts(fonts)+ }++ fn all_font_names(&self) -> Vec<String> {+ self.text_system.all_font_names()+ }++ fn font_id(&self, descriptor: &Font) -> anyhow::Result<FontId> {+ self.text_system.font_id(descriptor)+ }++ fn font_metrics(&self, font_id: FontId) -> FontMetrics {+ self.text_system.font_metrics(font_id)+ }++ fn typographic_bounds(+ &self,+ font_id: FontId,+ glyph_id: GlyphId,+ ) -> anyhow::Result<Bounds<f32>> {+ self.text_system.typographic_bounds(font_id, glyph_id)+ }++ fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {+ self.text_system.advance(font_id, glyph_id)+ }++ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {+ self.text_system.glyph_for_char(font_id, ch)+ }++ fn glyph_raster_bounds(+ &self,+ params: &RenderGlyphParams,+ ) -> anyhow::Result<Bounds<DevicePixels>> {+ self.text_system.glyph_raster_bounds(params)+ }++ fn rasterize_glyph(+ &self,+ params: &RenderGlyphParams,+ raster_bounds: Bounds<DevicePixels>,+ ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {+ self.text_system.rasterize_glyph(params, raster_bounds)+ }++ fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {+ self.shaped_lines+ .lock()+ .expect("shaped lines lock should not be poisoned")+ .push((text.to_string(), runs.iter().map(|run| run.len).collect()));+ self.text_system.layout_line(text, font_size, runs)+ }++ fn recommended_rendering_mode(+ &self,+ font_id: FontId,+ font_size: Pixels,+ ) -> TextRenderingMode {+ self.text_system+ .recommended_rendering_mode(font_id, font_size)+ }+ }++ #[test]+ fn test_runs_differing_only_in_background_are_shaped_separately() {+ let text_system = Arc::new(FontRunRecordingTextSystem {+ text_system: NoopTextSystem,+ shaped_lines: Mutex::default(),+ });+ let mut cx = TestAppContext::build_with_text_system(+ TestDispatcher::new(0),+ None,+ text_system.clone(),+ );+ ensure_theme_initialized(&mut cx);+ // Only the link background distinguishes `f` from its neighbors, so the+ // run boundaries around it must survive shaping to keep `f` and `i` from+ // forming a ligature across them+ let source = "a[f](https://zed.dev)i b";+ let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));+ let (_, cx) = cx.add_window_view(move |_, _| MarkdownTestView {+ markdown,+ style: MarkdownStyle {+ link: TextStyleRefinement {+ background_color: Some(gpui::red()),+ ..Default::default()+ },+ ..MarkdownStyle::default()+ },+ code_span_link: None,+ rendered_text: Rc::new(RefCell::new(None)),+ });+ cx.run_until_parked();++ let shaped_lines = text_system+ .shaped_lines+ .lock()+ .expect("shaped lines lock should not be poisoned");+ let (_, font_run_lengths) = shaped_lines+ .iter()+ .rev()+ .find(|(text, _)| text == "afi b")+ .expect("paragraph should be shaped");+ assert_eq!(font_run_lengths, &[1, 1, 3]);+ }+/// Renders a paragraph followed by a fenced code block at the given/// `buffer_line_height`, returning the rendered line heights of the/// paragraph and of the first code block row.