Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

markdown: Add macOS lookup support for Markdown preview (#59297)

Xiaobo Liu5299a14401fd
diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs
index 9dc936e3c77..201d25da7fe 100644
--- a/crates/markdown/src/markdown.rs
+++ b/crates/markdown/src/markdown.rs
@@ -34,13 +34,15 @@ use collections::{HashMap, HashSet};
use gpui::{
AnyElement, App, BorderStyle, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity,
FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, Image,
- ImageFormat, ImageSource, KeyContext, Length, MouseButton, MouseDownEvent, MouseEvent,
- MouseMoveEvent, MouseUpEvent, Point, ScrollHandle, Stateful, StrikethroughStyle,
- StyleRefinement, StyledImage, StyledText, Subscription, Task, TextAlign, TextLayout, TextRun,
- TextStyle, TextStyleRefinement, WrappedLineLayout, actions, canvas, img, point, quad, relative,
- size,
+ ImageFormat, ImageSource, InputHandler, KeyContext, Length, MouseButton, MouseDownEvent,
+ MouseEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, ScrollHandle, Stateful,
+ StrikethroughStyle, StyleRefinement, StyledImage, StyledText, Subscription, Task, TextAlign,
+ TextLayout, TextRun, TextStyle, TextStyleRefinement, UTF16Selection, WrappedLineLayout,
+ actions, canvas, img, point, quad, relative, size,
+};
+use language::{
+ Bias, CharClassifier, Language, LanguageRegistry, OffsetUtf16, ResolvedHighlights, Rope,
};
-use language::{CharClassifier, Language, LanguageRegistry, ResolvedHighlights, Rope};
use parser::CodeBlockMetadata;
use parser::{
MarkdownEvent, MarkdownTag, MarkdownTagEnd, ParsedMetadataBlock, parse_links_only,
@@ -1713,6 +1715,7 @@ pub struct MarkdownElement {
markdown: Entity<Markdown>,
style: MarkdownStyle,
code_block_renderer: CodeBlockRenderer,
+ input_focus_handle: Option<FocusHandle>,
on_url_click: Option<Rc<dyn Fn(SharedString, &mut Window, &mut App)>>,
on_url_hover: Option<UrlHoverCallback>,
code_span_link: Option<CodeSpanLinkCallback>,
@@ -1739,6 +1742,7 @@ impl MarkdownElement {
wrap_button_visibility: WrapButtonVisibility::Hidden,
border: false,
},
+ input_focus_handle: None,
on_url_click: None,
on_url_hover: None,
code_span_link: None,
@@ -1779,6 +1783,11 @@ impl MarkdownElement {
self
}
+ pub fn input_focus_handle(mut self, focus_handle: FocusHandle) -> Self {
+ self.input_focus_handle = Some(focus_handle);
+ self
+ }
+
/// Registers a test-only callback invoked with the laid-out text each
/// time this element runs layout.
#[cfg(test)]
@@ -3330,6 +3339,23 @@ impl Element for MarkdownElement {
let mut context = KeyContext::default();
context.add("Markdown");
window.set_key_context(context);
+
+ let markdown_focus_handle = self.markdown.read(cx).focus_handle.clone();
+ let input_focus_handle = if markdown_focus_handle.is_focused(window) {
+ Some(markdown_focus_handle)
+ } else {
+ self.input_focus_handle
+ .clone()
+ .filter(|focus_handle| focus_handle.is_focused(window))
+ };
+ if let Some(input_focus_handle) = input_focus_handle {
+ window.handle_input(
+ &input_focus_handle,
+ MarkdownInputHandler::new(self.markdown.clone(), rendered_markdown.text.clone()),
+ cx,
+ );
+ }
+
window.on_action(std::any::TypeId::of::<crate::Copy>(), {
let entity = self.markdown.clone();
let text = rendered_markdown.text.clone();
@@ -4137,6 +4163,7 @@ impl MarkdownElementBuilder {
let styled_text = StyledText::new(text).with_runs(vec![text_style.to_run(text.len())]);
self.rendered_lines.push(Rc::new(RenderedLine {
layout: styled_text.layout().clone(),
+ visible_bounds: Cell::new(None),
source_mappings: vec![SourceMapping {
rendered_index: 0,
source_index: source_range.start,
@@ -4174,6 +4201,7 @@ impl MarkdownElementBuilder {
let text = StyledText::new(line.text).with_runs(line.runs);
let rendered_line = Rc::new(RenderedLine {
layout: text.layout().clone(),
+ visible_bounds: Cell::new(None),
source_mappings: line.source_mappings,
source_end: self.current_source_index,
language: self
@@ -4185,19 +4213,14 @@ impl MarkdownElementBuilder {
highlights,
code_chips: line.code_chips.into_iter().collect(),
});
- if rendered_line.highlights.is_empty() && rendered_line.code_chips.is_empty() {
- self.rendered_lines.push(rendered_line);
- self.append_child(text.into_any());
- } else {
- self.rendered_lines.push(rendered_line.clone());
- self.append_child(
- HighlightedLine {
- text: text.into_any(),
- line: rendered_line,
- }
- .into_any_element(),
- );
- }
+ self.rendered_lines.push(rendered_line.clone());
+ self.append_child(
+ RenderedLineElement {
+ text: text.into_any(),
+ line: rendered_line,
+ }
+ .into_any_element(),
+ );
}
fn build(mut self) -> RenderedMarkdown {
@@ -4215,15 +4238,14 @@ impl MarkdownElementBuilder {
}
}
-/// Wraps a rendered line's text and paints the line's highlight quads during the
-/// line's own paint, so the ancestor content masks clip them like they clip the
-/// glyphs themselves.
-struct HighlightedLine {
+/// 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,
line: Rc<RenderedLine>,
}
-impl Element for HighlightedLine {
+impl Element for RenderedLineElement {
type RequestLayoutState = ();
type PrepaintState = ();
@@ -4249,11 +4271,14 @@ impl Element for HighlightedLine {
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&gpui::InspectorElementId>,
- _bounds: Bounds<Pixels>,
+ bounds: Bounds<Pixels>,
_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);
}
@@ -4273,7 +4298,7 @@ impl Element for HighlightedLine {
}
}
-impl IntoElement for HighlightedLine {
+impl IntoElement for RenderedLineElement {
type Element = Self;
fn into_element(self) -> Self::Element {
@@ -4283,6 +4308,7 @@ impl IntoElement for HighlightedLine {
struct RenderedLine {
layout: TextLayout,
+ visible_bounds: Cell<Option<Bounds<Pixels>>>,
source_mappings: Vec<SourceMapping>,
source_end: usize,
language: Option<Arc<Language>>,
@@ -4695,7 +4721,6 @@ struct RenderedFootnoteRef {
}
impl RenderedText {
- #[cfg(test)]
fn bounds_for_source_range(&self, range: Range<usize>) -> Vec<Bounds<Pixels>> {
let mut all_bounds = Vec::new();
for line in self.lines.iter() {
@@ -4719,6 +4744,76 @@ impl RenderedText {
all_bounds
}
+ fn utf16_index_for_source_index(&self, source_index: usize) -> usize {
+ self.text_for_range(0..source_index).encode_utf16().count()
+ }
+
+ fn utf16_range_for_source_range(&self, range: Range<usize>) -> Range<usize> {
+ self.utf16_index_for_source_index(range.start)..self.utf16_index_for_source_index(range.end)
+ }
+
+ fn source_index_for_utf16_index(&self, utf16_index: usize) -> usize {
+ let mut line_start_utf16 = 0;
+ let mut last_source_end = 0;
+
+ for (line_index, line) in self.lines.iter().enumerate() {
+ let line_text = line.layout.text();
+ let line_utf16_len = line_text.encode_utf16().count();
+ let line_end_utf16 = line_start_utf16 + line_utf16_len;
+ last_source_end = line.source_end;
+
+ if utf16_index <= line_end_utf16 {
+ let local_utf16_index = utf16_index.saturating_sub(line_start_utf16);
+ let rendered_text = Rope::from(line_text.as_str());
+ let rendered_index = rendered_text.offset_utf16_to_offset(
+ rendered_text.clip_offset_utf16(OffsetUtf16(local_utf16_index), Bias::Left),
+ );
+ return line.source_index_for_rendered_index(rendered_index);
+ }
+
+ line_start_utf16 = line_end_utf16;
+ if line_index + 1 < self.lines.len() {
+ line_start_utf16 += 1;
+ }
+ }
+
+ last_source_end
+ }
+
+ fn source_range_for_utf16_range(&self, range_utf16: Range<usize>) -> Range<usize> {
+ self.source_index_for_utf16_index(range_utf16.start)
+ ..self.source_index_for_utf16_index(range_utf16.end)
+ }
+
+ fn text_for_utf16_range(
+ &self,
+ range_utf16: Range<usize>,
+ adjusted_range: &mut Option<Range<usize>>,
+ ) -> String {
+ let mut rendered_text = String::new();
+ for (line_index, line) in self.lines.iter().enumerate() {
+ if line_index > 0 {
+ rendered_text.push('\n');
+ }
+ rendered_text.push_str(&line.layout.text());
+ }
+
+ let rendered_text = Rope::from(rendered_text);
+ let start = rendered_text.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
+ let end = rendered_text.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
+
+ if (start.0..end.0) != range_utf16 {
+ adjusted_range.replace(start.0..end.0);
+ }
+
+ rendered_text
+ .chunks_in_range(
+ rendered_text.offset_utf16_to_offset(start)
+ ..rendered_text.offset_utf16_to_offset(end),
+ )
+ .collect()
+ }
+
fn source_index_for_position(&self, position: Point<Pixels>) -> Result<usize, usize> {
let mut lines = self.lines.iter().peekable();
let mut fallback_line: Option<&Rc<RenderedLine>> = None;
@@ -4754,6 +4849,16 @@ impl RenderedText {
Err(self.lines.last().map_or(0, |line| line.source_end))
}
+ fn source_index_for_visible_position(&self, position: Point<Pixels>) -> Option<usize> {
+ self.lines.iter().find_map(|line| {
+ if line.visible_bounds.get()?.contains(&position) {
+ line.source_index_for_position(position).ok()
+ } else {
+ None
+ }
+ })
+ }
+
fn position_for_source_index(&self, source_index: usize) -> Option<(Point<Pixels>, Pixels)> {
for line in self.lines.iter() {
if source_index > line.source_end {
@@ -4884,6 +4989,119 @@ impl RenderedText {
}
}
+struct MarkdownInputHandler {
+ markdown: Entity<Markdown>,
+ rendered_text: RenderedText,
+}
+
+impl MarkdownInputHandler {
+ fn new(markdown: Entity<Markdown>, rendered_text: RenderedText) -> Self {
+ Self {
+ markdown,
+ rendered_text,
+ }
+ }
+}
+
+impl InputHandler for MarkdownInputHandler {
+ fn selected_text_range(
+ &mut self,
+ _: bool,
+ _: &mut Window,
+ cx: &mut App,
+ ) -> Option<UTF16Selection> {
+ self.markdown.update(cx, |markdown, _cx| {
+ let range = markdown.selection.start..markdown.selection.end;
+ Some(UTF16Selection {
+ range: self.rendered_text.utf16_range_for_source_range(range),
+ reversed: markdown.selection.reversed,
+ })
+ })
+ }
+
+ fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
+ None
+ }
+
+ fn text_for_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ adjusted_range: &mut Option<Range<usize>>,
+ _: &mut Window,
+ _: &mut App,
+ ) -> Option<String> {
+ if range_utf16.start > range_utf16.end {
+ return None;
+ }
+
+ Some(
+ self.rendered_text
+ .text_for_utf16_range(range_utf16, adjusted_range),
+ )
+ }
+
+ fn replace_text_in_range(
+ &mut self,
+ _: Option<Range<usize>>,
+ _: &str,
+ _: &mut Window,
+ _: &mut App,
+ ) {
+ }
+
+ fn replace_and_mark_text_in_range(
+ &mut self,
+ _: Option<Range<usize>>,
+ _: &str,
+ _: Option<Range<usize>>,
+ _: &mut Window,
+ _: &mut App,
+ ) {
+ }
+
+ fn unmark_text(&mut self, _: &mut Window, _: &mut App) {}
+
+ fn bounds_for_range(
+ &mut self,
+ range_utf16: Range<usize>,
+ _: &mut Window,
+ _: &mut App,
+ ) -> Option<Bounds<Pixels>> {
+ let source_range = self.rendered_text.source_range_for_utf16_range(range_utf16);
+ self.rendered_text
+ .bounds_for_source_range(source_range.clone())
+ .into_iter()
+ .next()
+ .or_else(|| {
+ self.rendered_text
+ .position_for_source_index(source_range.start)
+ .map(|(position, line_height)| Bounds {
+ origin: position,
+ size: size(px(0.), line_height),
+ })
+ })
+ }
+
+ fn character_index_for_point(
+ &mut self,
+ point: Point<Pixels>,
+ _: &mut Window,
+ _: &mut App,
+ ) -> Option<usize> {
+ let source_index = self
+ .rendered_text
+ .source_index_for_visible_position(point)?;
+ Some(
+ self.rendered_text
+ .utf16_index_for_source_index(source_index),
+ )
+ }
+
+ fn accepts_text_input(&mut self, _: &mut Window, _: &mut App) -> bool {
+ false
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -5142,6 +5360,148 @@ mod tests {
);
}
+ #[gpui::test]
+ fn test_lookup_rejects_clipped_text(cx: &mut TestAppContext) {
+ struct ClippedMarkdownView(Entity<MarkdownTestView>);
+
+ impl Render for ClippedMarkdownView {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ div()
+ .id("clipped-markdown")
+ .w(px(300.))
+ .h(px(80.))
+ .overflow_y_scroll()
+ .restrict_scroll_to_axis()
+ .child(self.0.clone())
+ }
+ }
+
+ ensure_theme_initialized(cx);
+ let source = indoc::indoc! {r#"
+ ```txt
+ one_extremely_long_code_line_that_overflows_the_viewport_and_keeps_going_and_going
+ ```
+
+ first paragraph
+
+ second paragraph
+
+ last paragraph
+ "#};
+ let markdown = cx.new(|cx| Markdown::new(source.into(), None, None, cx));
+ cx.run_until_parked();
+ let rendered_text = Rc::new(RefCell::new(None));
+ let (_, cx) = cx.add_window_view({
+ let rendered_text = rendered_text.clone();
+ let markdown = markdown.clone();
+ move |_, cx| {
+ ClippedMarkdownView(cx.new(|_| MarkdownTestView {
+ markdown,
+ style: MarkdownStyle {
+ code_block_overflow_x_scroll: true,
+ ..MarkdownStyle::default()
+ },
+ code_span_link: None,
+ rendered_text,
+ }))
+ }
+ });
+ cx.simulate_resize(size(px(1000.), px(200.)));
+ cx.run_until_parked();
+ let rendered = rendered_text.borrow().clone().expect("rendered");
+ let first_line = &rendered.lines[0];
+ let clipped_character_index = 60;
+ let horizontal_clipped_position = first_line
+ .layout
+ .position_for_index(clipped_character_index)
+ .expect("clipped character position")
+ + point(px(0.1), first_line.layout.line_height() / 2.);
+ assert!(
+ horizontal_clipped_position.x > px(300.),
+ "test point must lie outside viewport: {horizontal_clipped_position:?}"
+ );
+ assert!(
+ horizontal_clipped_position.x < px(1000.),
+ "test point must remain inside the window"
+ );
+ let visible_character_index = 2;
+ let visible_position = first_line
+ .layout
+ .position_for_index(visible_character_index)
+ .expect("visible character position")
+ + point(px(0.1), first_line.layout.line_height() / 2.);
+ let last_line = rendered.lines.last().expect("last paragraph");
+ let vertical_clipped_position = last_line
+ .layout
+ .position_for_index(visible_character_index)
+ .expect("paragraph position")
+ + point(px(0.1), last_line.layout.line_height() / 2.);
+ assert!(vertical_clipped_position.y > px(80.));
+ assert!(vertical_clipped_position.y < px(200.));
+
+ let mut handler = MarkdownInputHandler::new(markdown.clone(), rendered);
+ assert_eq!(
+ cx.update(|window, cx| handler.character_index_for_point(
+ horizontal_clipped_position,
+ window,
+ cx
+ )),
+ None,
+ "point outside visible viewport must not expose clipped text: {horizontal_clipped_position:?}"
+ );
+ assert_eq!(
+ cx.update(|window, cx| handler.character_index_for_point(
+ vertical_clipped_position,
+ window,
+ cx
+ )),
+ None,
+ );
+ assert_eq!(
+ cx.update(|window, cx| handler.character_index_for_point(visible_position, window, cx)),
+ Some(visible_character_index),
+ );
+
+ cx.simulate_event(ScrollWheelEvent {
+ position: visible_position,
+ delta: ScrollDelta::Pixels(point(px(-400.), px(0.))),
+ modifiers: Modifiers::default(),
+ touch_phase: TouchPhase::Moved,
+ });
+ cx.run_until_parked();
+ let rendered = rendered_text
+ .borrow()
+ .clone()
+ .expect("rendered after scrolling");
+ let first_line = &rendered.lines[0];
+ let revealed_position = first_line
+ .layout
+ .position_for_index(clipped_character_index)
+ .expect("revealed character position")
+ + point(px(0.1), first_line.layout.line_height() / 2.);
+ assert!(revealed_position.x > px(0.) && revealed_position.x < px(300.));
+ let mut handler = MarkdownInputHandler::new(markdown, rendered);
+ assert_eq!(
+ cx.update(|window, cx| handler.character_index_for_point(
+ revealed_position,
+ window,
+ cx
+ )),
+ Some(clipped_character_index),
+ );
+ }
+
+ #[gpui::test]
+ fn test_text_for_utf16_range_uses_rendered_text(cx: &mut TestAppContext) {
+ let rendered = render_markdown("**世界** 😄", cx);
+ let mut adjusted_range = None;
+ assert_eq!(
+ rendered.text_for_utf16_range(3..4, &mut adjusted_range),
+ "😄"
+ );
+ assert_eq!(adjusted_range, Some(3..5));
+ }
+
fn render_markdown(markdown: &str, cx: &mut TestAppContext) -> RenderedText {
render_markdown_with_language_registry(markdown, None, cx)
}
diff --git a/crates/markdown_preview/src/markdown_preview_view.rs b/crates/markdown_preview/src/markdown_preview_view.rs
index 4d0f53da1e5..7a751c71b01 100644
--- a/crates/markdown_preview/src/markdown_preview_view.rs
+++ b/crates/markdown_preview/src/markdown_preview_view.rs
@@ -1087,6 +1087,7 @@ impl MarkdownPreviewView {
};
let mut markdown_element = MarkdownElement::new(self.markdown.clone(), markdown_style)
+ .input_focus_handle(self.focus_handle.clone())
.code_block_renderer(CodeBlockRenderer::Default {
copy_button_visibility: CopyButtonVisibility::VisibleOnHover,
wrap_button_visibility: markdown::WrapButtonVisibility::Hidden,