Skip to main content

gpui_base/text/
text_view.rs

1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use gpui::prelude::FluentBuilder as _;
4use gpui::{
5    AnyElement, AnyView, App, Bounds, ClickEvent, ContentMask, Element, ElementId, Entity, Global,
6    GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement, IntoElement,
7    LayoutId, MouseButton, ParentElement, Pixels, Refineable as _, SharedString, StyleRefinement,
8    Styled, Window, div, point, px,
9};
10
11use crate::StyledExt;
12use crate::text::TextViewFormat;
13use crate::text::markdown_ext::{MarkdownExtensions, MarkdownNode, MarkdownPlugin};
14use crate::text::node::{CodeBlock, TableData};
15use crate::text::range_highlight::{PendingReveal, RevealProgress};
16use crate::text::state::{LineSpan, SelectionFormat, TextViewState};
17use crate::text::stream_fade::TextViewMotion;
18use crate::{GlobalState, TextSelection, text::TextViewStyle};
19
20/// Type for code block actions generator function.
21pub(crate) type CodeBlockActionsFn =
22    dyn Fn(&CodeBlock, &mut Window, &mut App) -> AnyElement + Send + Sync;
23
24pub(crate) type CodeBlockHighlighterFn =
25    dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync;
26
27/// Application-wide defaults for TextViews that do not provide explicit
28/// presentation or syntax-highlighting overrides.
29#[derive(Clone, Default)]
30pub struct TextViewDefaults {
31    style: Option<TextViewStyle>,
32    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
33    inherit_text_color: bool,
34}
35
36impl Global for TextViewDefaults {}
37
38impl TextViewDefaults {
39    /// Creates defaults that leave every text view as Base renders it.
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    /// Sets the style every text view starts from.
45    pub fn with_style(mut self, style: TextViewStyle) -> Self {
46        self.style = Some(style);
47        self
48    }
49
50    /// The style every text view starts from, when set.
51    pub(crate) fn style(&self) -> Option<&TextViewStyle> {
52        self.style.as_ref()
53    }
54
55    /// The syntax highlighter for fenced code blocks, when set.
56    pub(crate) fn code_block_highlighter(&self) -> Option<Arc<CodeBlockHighlighterFn>> {
57        self.code_block_highlighter.clone()
58    }
59
60    /// Sets the syntax highlighter used for fenced code blocks.
61    pub fn with_code_block_highlighter<F>(mut self, highlighter: F) -> Self
62    where
63        F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
64    {
65        self.code_block_highlighter = Some(Arc::new(highlighter));
66        self
67    }
68
69    /// Sets whether text views without an explicit [`TextView::style`] follow
70    /// the text color their container sets, default false.
71    ///
72    /// The body text takes that color. On a surface inverted from the page,
73    /// such as a `primary` fill, links, muted text, code, borders and
74    /// selection are derived from it too, and the installed syntax highlighter
75    /// is left out because its colors are made for the page. Enable this only
76    /// when every window sets a text color at its root, as Component's does.
77    pub fn with_inherit_text_color(mut self, inherit: bool) -> Self {
78        self.inherit_text_color = inherit;
79        self
80    }
81
82    /// Installs these defaults for the whole application.
83    pub fn install(self, cx: &mut App) {
84        cx.set_global(self);
85    }
86
87    /// Returns the installed defaults, or the Base ones when none were.
88    pub fn global(cx: &App) -> Self {
89        cx.try_global::<Self>().cloned().unwrap_or_default()
90    }
91
92    /// Whether a syntax highlighter was installed.
93    pub fn has_code_block_highlighter(&self) -> bool {
94        self.code_block_highlighter.is_some()
95    }
96
97    /// Whether text views follow the text color their container sets.
98    pub fn inherit_text_color(&self) -> bool {
99        self.inherit_text_color
100    }
101}
102
103/// Type for the table actions generator function.
104pub(crate) type TableActionsFn =
105    dyn Fn(&TableData, &mut Window, &mut App) -> AnyElement + Send + Sync;
106
107pub(crate) type ImageSourceFn = dyn Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync;
108
109pub(crate) type LinkFn = dyn Fn(&Link, &App) -> Option<Link> + Send + Sync;
110
111/// A link a [`TextView`] draws, as handed to [`TextView::link`].
112///
113/// Reference links (`[text][id]`) arrive resolved to their definition. New
114/// fields may be added later, so build one with [`Link::new`] or change a
115/// received one with the setters.
116#[derive(Debug, Clone, PartialEq, Eq)]
117#[non_exhaustive]
118pub struct Link {
119    /// Where the link points; this is what a click opens or hands to
120    /// [`TextView::on_link_click`].
121    pub url: SharedString,
122    /// The Markdown link title, `[text](url "title")`.
123    pub title: Option<SharedString>,
124}
125
126impl Link {
127    /// A link to `url` with no title.
128    pub fn new(url: impl Into<SharedString>) -> Self {
129        Self {
130            url: url.into(),
131            title: None,
132        }
133    }
134
135    /// Point the link at `url`.
136    pub fn url(mut self, url: impl Into<SharedString>) -> Self {
137        self.url = url.into();
138        self
139    }
140
141    /// Set the link title.
142    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
143        self.title = Some(title.into());
144        self
145    }
146}
147
148pub(crate) type LinkClickHandlerFn =
149    dyn Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync;
150
151pub(crate) type LinkTooltipFn =
152    dyn Fn(&SharedString, &mut Window, &mut App) -> AnyView + Send + Sync;
153pub(crate) type TaskToggleHandlerFn = dyn Fn(&TaskToggleEvent, &mut Window, &mut App) + Send + Sync;
154
155/// A click on the checkbox of a Markdown task list item, passed to the
156/// [`TextView::on_task_toggle`] handler.
157///
158/// The ranges are byte ranges in the view's source text.
159#[derive(Debug, Clone)]
160pub struct TaskToggleEvent {
161    checked: bool,
162    item_range: Range<usize>,
163    marker_range: Range<usize>,
164}
165
166impl TaskToggleEvent {
167    pub(crate) fn new(checked: bool, item_range: Range<usize>, marker_range: Range<usize>) -> Self {
168        Self {
169            checked,
170            item_range,
171            marker_range,
172        }
173    }
174
175    /// The checked state the item should now have: the opposite of the
176    /// state its checkbox shows.
177    pub fn checked(&self) -> bool {
178        self.checked
179    }
180
181    /// The list item's source span, starting at its list marker (`-`, `*`,
182    /// `1.`) and covering its content, nested lists included.
183    pub fn item_range(&self) -> Range<usize> {
184        self.item_range.clone()
185    }
186
187    /// The item's task marker: the `[ ]` or `[x]` itself, brackets included.
188    pub fn marker_range(&self) -> Range<usize> {
189        self.marker_range.clone()
190    }
191}
192
193/// Kept by the element only, so unlike the handlers the state carries, it
194/// may hold a `ScrollHandle`.
195pub(crate) type RevealHandlerFn = dyn Fn(Bounds<Pixels>, &mut Window, &mut App);
196
197pub(crate) fn handle_link_click(
198    handler: &Option<Arc<LinkClickHandlerFn>>,
199    url: SharedString,
200    event: ClickEvent,
201    window: &mut Window,
202    cx: &mut App,
203) {
204    if let Some(handler) = handler {
205        handler(&url, &event, window, cx);
206    } else if match &event {
207        ClickEvent::Mouse(click) => {
208            matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
209        }
210        ClickEvent::Keyboard(_) => true,
211        ClickEvent::Touch(click) => !click.long_press,
212    } {
213        cx.open_url(&url);
214    }
215}
216
217/// A text view that can render Markdown or HTML.
218///
219/// ## Goals
220///
221/// - Provide a rich text rendering component for such as Markdown or HTML,
222/// used to display rich text in GPUI application (e.g., Help messages, Release notes)
223/// - Support Markdown GFM and HTML (Simple HTML like Safari Reader Mode) for showing most common used markups.
224/// - Support Heading, Paragraph, Bold, Italic, StrikeThrough, Code, Link, Image, Blockquote, List, Table, HorizontalRule, CodeBlock ...
225///
226/// ## Not Goals
227///
228/// - Customization of the complex style (some simple styles will be supported)
229/// - As a Markdown editor or viewer (If you want to like this, you must fork your version).
230/// - As a HTML viewer, we not support CSS, we only support basic HTML tags for used to as a content reader.
231///
232/// See also [`MarkdownElement`], [`HtmlElement`]
233#[derive(Clone)]
234pub struct TextView {
235    id: ElementId,
236    format: Option<TextViewFormat>,
237    text: Option<SharedString>,
238    pub(crate) state: Option<Entity<TextViewState>>,
239    text_view_style: Option<TextViewStyle>,
240    inline_code_style: Option<StyleRefinement>,
241    list_style: Option<StyleRefinement>,
242    blockquote_style: Option<StyleRefinement>,
243    style: StyleRefinement,
244    selectable: bool,
245    selection_format: SelectionFormat,
246    scrollable: bool,
247    max_lines: Option<usize>,
248    code_block_actions: Option<Arc<CodeBlockActionsFn>>,
249    code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
250    table_actions: Option<Arc<TableActionsFn>>,
251    link_click_handler: Option<Arc<LinkClickHandlerFn>>,
252    link_hook: Option<Arc<LinkFn>>,
253    link_tooltip: Option<Arc<LinkTooltipFn>>,
254    task_toggle_handler: Option<Arc<TaskToggleHandlerFn>>,
255    image_source: Option<Arc<ImageSourceFn>>,
256    reveal_handler: Option<Rc<RevealHandlerFn>>,
257    markdown_extensions: Arc<MarkdownExtensions>,
258    motion: Option<TextViewMotion>,
259}
260
261/// A plugin that can configure a [`TextView`].
262pub trait TextViewPlugin {
263    fn setup(self, text_view: TextView) -> TextView;
264}
265
266impl<P> TextViewPlugin for P
267where
268    P: MarkdownPlugin,
269{
270    fn setup(self, mut text_view: TextView) -> TextView {
271        let extensions = Arc::make_mut(&mut text_view.markdown_extensions);
272        let current = std::mem::take(extensions);
273        *extensions = current.plugin(self);
274        text_view
275    }
276}
277
278impl Styled for TextView {
279    fn style(&mut self) -> &mut StyleRefinement {
280        &mut self.style
281    }
282}
283
284impl TextView {
285    /// Create new TextView with managed state.
286    pub fn new(state: &Entity<TextViewState>) -> Self {
287        Self {
288            id: ElementId::Name(state.entity_id().to_string().into()),
289            state: Some(state.clone()),
290            format: None,
291            text: None,
292            text_view_style: None,
293            inline_code_style: None,
294            list_style: None,
295            blockquote_style: None,
296            style: StyleRefinement::default(),
297            selectable: true,
298            selection_format: SelectionFormat::default(),
299            scrollable: false,
300            max_lines: None,
301            code_block_actions: None,
302            code_block_highlighter: None,
303            table_actions: None,
304            link_click_handler: None,
305            link_hook: None,
306            link_tooltip: None,
307            task_toggle_handler: None,
308            image_source: None,
309            reveal_handler: None,
310            markdown_extensions: Arc::default(),
311            motion: None,
312        }
313    }
314
315    /// Create a new markdown text view.
316    pub fn markdown(id: impl Into<ElementId>, markdown: impl Into<SharedString>) -> Self {
317        Self {
318            id: id.into(),
319            format: Some(TextViewFormat::Markdown),
320            text: Some(markdown.into()),
321            text_view_style: None,
322            inline_code_style: None,
323            list_style: None,
324            blockquote_style: None,
325            style: StyleRefinement::default(),
326            state: None,
327            selectable: true,
328            selection_format: SelectionFormat::default(),
329            scrollable: false,
330            max_lines: None,
331            code_block_actions: None,
332            code_block_highlighter: None,
333            table_actions: None,
334            link_click_handler: None,
335            link_hook: None,
336            link_tooltip: None,
337            task_toggle_handler: None,
338            image_source: None,
339            reveal_handler: None,
340            markdown_extensions: Arc::default(),
341            motion: None,
342        }
343    }
344
345    /// Create a new html text view.
346    pub fn html(id: impl Into<ElementId>, html: impl Into<SharedString>) -> Self {
347        Self {
348            id: id.into(),
349            format: Some(TextViewFormat::Html),
350            text: Some(html.into()),
351            text_view_style: None,
352            inline_code_style: None,
353            list_style: None,
354            blockquote_style: None,
355            style: StyleRefinement::default(),
356            state: None,
357            selectable: true,
358            selection_format: SelectionFormat::default(),
359            scrollable: false,
360            max_lines: None,
361            code_block_actions: None,
362            code_block_highlighter: None,
363            table_actions: None,
364            link_click_handler: None,
365            link_hook: None,
366            link_tooltip: None,
367            task_toggle_handler: None,
368            image_source: None,
369            reveal_handler: None,
370            markdown_extensions: Arc::default(),
371            motion: None,
372        }
373    }
374
375    /// Overrides the source of every document image, including embedded data URLs.
376    ///
377    /// Used for both rendering and intrinsic-size measurement. The returned source
378    /// is authoritative: pending or failed loads never fall back to the document URL.
379    /// Without this override, images use Base's default URI and data URL handling.
380    pub fn image_source<F>(mut self, resolver: F) -> Self
381    where
382        F: Fn(&gpui::SharedUri) -> gpui::ImageSource + Send + Sync + 'static,
383    {
384        self.image_source = Some(Arc::new(resolver));
385        self
386    }
387
388    /// Refines inline code typography, background, border, radius, and padding
389    /// over the resolved style. See [`TextViewStyle::with_inline_code_style`]
390    /// for the supported properties. Unspecified properties are inherited.
391    pub fn inline_code_style(mut self, style: StyleRefinement) -> Self {
392        self.inline_code_style = Some(super::style::normalize_inline_code_style(style));
393        self
394    }
395
396    /// Refines list markers over the resolved style. See
397    /// [`TextViewStyle::with_list_style`] for where it applies.
398    /// Unspecified properties are inherited.
399    pub fn list_style(mut self, style: StyleRefinement) -> Self {
400        self.list_style = Some(style);
401        self
402    }
403
404    /// Refines blockquotes over the resolved style. See
405    /// [`TextViewStyle::with_blockquote_style`] for where it applies.
406    /// Unspecified properties are inherited.
407    pub fn blockquote_style(mut self, style: StyleRefinement) -> Self {
408        self.blockquote_style = Some(style);
409        self
410    }
411
412    /// Set [`TextViewStyle`].
413    pub fn style(mut self, style: TextViewStyle) -> Self {
414        self.text_view_style = Some(style);
415        self
416    }
417
418    /// Set whether the text view is selectable, default is true.
419    ///
420    /// Hovering selectable text shows the I-beam cursor. A cursor set on the
421    /// text view itself, such as `.cursor_default()`, replaces it: use that for
422    /// text on a surface that opens on click. Links keep the pointing hand, and
423    /// the I-beam still shows while a drag selection is in progress.
424    pub fn selectable(mut self, selectable: bool) -> Self {
425        self.selectable = selectable;
426        self
427    }
428
429    /// Set the [`SelectionFormat`], default is [`SelectionFormat::Plain`].
430    ///
431    /// With [`SelectionFormat::Source`], selecting inside `**bold**` yields
432    /// `**bold**` (the Markdown source) rather than `bold`.
433    pub fn selection_format(mut self, selection_format: SelectionFormat) -> Self {
434        self.selection_format = selection_format;
435        self
436    }
437
438    /// Set the text view to be scrollable, default is false.
439    ///
440    /// ## If true for `scrollable`
441    ///
442    /// The `scrollable` mode used for large content,
443    /// will show scrollbar, but requires the parent to have a fixed height,
444    /// and use [`gpui::list`] to render the content in a virtualized way.
445    ///
446    /// ## If false to fit content
447    ///
448    /// The TextView will expand to fit all content, no scrollbar.
449    /// This mode is suitable for small content, such as a few lines of text, a label, etc.
450    pub fn scrollable(mut self, scrollable: bool) -> Self {
451        self.scrollable = scrollable;
452        self
453    }
454
455    /// Clamp the rendered content to at most `n` lines of body text.
456    ///
457    /// The view's height is capped at `n` × the base line height, and a line
458    /// of glyphs is never cut in half: a line that would straddle the bottom
459    /// of the box is left out whole, across paragraphs, lists, headings, code
460    /// blocks and tables. Nothing is shown with less than a line of itself to
461    /// show, so the border and padding a table row leads with never strands at
462    /// the bottom; whatever has more than that is cut on the box edge and keeps
463    /// the part that fits, rather than disappearing and leaving blank space
464    /// behind.
465    ///
466    /// Check [`TextViewState::is_clamped`] (which answers for the frame that
467    /// was last painted) to decide whether to show an "expand" affordance.
468    ///
469    /// `n` counts lines of body text, so paragraph spacing and taller lines
470    /// mean fewer of them fit inside the capped height. A line taller than the
471    /// whole budget keeps the part that fits rather than emptying the box.
472    /// Ignored when [`Self::scrollable`] is set.
473    pub fn max_lines(mut self, max_lines: usize) -> Self {
474        self.max_lines = Some(max_lines);
475        self
476    }
477
478    /// Set custom block actions for code blocks.
479    ///
480    /// The closure receives the [`CodeBlock`],
481    /// and returns an element to display.
482    pub fn code_block_actions<F, E>(mut self, f: F) -> Self
483    where
484        F: Fn(&CodeBlock, &mut Window, &mut App) -> E + Send + Sync + 'static,
485        E: IntoElement,
486    {
487        self.code_block_actions = Some(Arc::new(move |code_block, window, cx| {
488            f(&code_block, window, cx).into_any_element()
489        }));
490        self
491    }
492
493    /// Adds opt-in syntax highlighting for fenced code blocks.
494    ///
495    /// Returned byte ranges are relative to [`CodeBlock::code`]. Invalid
496    /// ranges are discarded. Without this callback, code is unhighlighted.
497    pub fn code_block_highlighter<F>(mut self, highlighter: F) -> Self
498    where
499        F: Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync + 'static,
500    {
501        self.code_block_highlighter = Some(Arc::new(highlighter));
502        self
503    }
504
505    /// Like [`Self::code_block_highlighter`], with a highlighter that can be
506    /// handed to every frame.
507    ///
508    /// A code block reuses its highlights only while the highlighter is the
509    /// same `Arc`, so a view built every frame with a fresh closure
510    /// re-highlights every code block on every frame.
511    #[doc(hidden)]
512    pub fn shared_code_block_highlighter(
513        mut self,
514        highlighter: Arc<
515            dyn Fn(&CodeBlock) -> Vec<(Range<usize>, gpui::HighlightStyle)> + Send + Sync,
516        >,
517    ) -> Self {
518        self.code_block_highlighter = Some(highlighter);
519        self
520    }
521
522    /// Set custom actions to be rendered below each Markdown table.
523    ///
524    /// The closure receives the [`TableData`],
525    /// and returns an element to display.
526    pub fn table_actions<F, E>(mut self, f: F) -> Self
527    where
528        F: Fn(&TableData, &mut Window, &mut App) -> E + Send + Sync + 'static,
529        E: IntoElement,
530    {
531        self.table_actions = Some(Arc::new(move |table, window, cx| {
532            f(table, window, cx).into_any_element()
533        }));
534        self
535    }
536
537    /// Handle pointer events on rendered links.
538    ///
539    /// The handler receives the resolved URL and the original GPUI click event.
540    /// Without a handler, links open through App::open_url.
541    pub fn on_link_click<F>(mut self, handler: F) -> Self
542    where
543        F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
544    {
545        self.link_click_handler = Some(Arc::new(handler));
546        self
547    }
548
549    /// Replace each link before it is drawn.
550    ///
551    /// `f` receives every link, inline links, reference links (resolved to
552    /// their definition) and linked images alike, and returns the link to
553    /// draw in its place: the same link, one with a different URL or title,
554    /// or `None` to draw the text like the text around it, with no link
555    /// color or underline, and not clickable.
556    ///
557    /// `f` runs each time the text is drawn, so what it returns may follow
558    /// application state (a record that was deleted, a URL resolved later);
559    /// keep it cheap, with no I/O or locks held across frames.
560    ///
561    /// ```ignore
562    /// TextView::markdown(id, text).link(|link, cx| {
563    ///     let record = parse_record_url(&link.url)?;
564    ///     records(cx).contains(record).then(|| link.clone().url(record.web_url()))
565    /// })
566    /// ```
567    pub fn link<F>(mut self, f: F) -> Self
568    where
569        F: Fn(&Link, &App) -> Option<Link> + Send + Sync + 'static,
570    {
571        self.link_hook = Some(Arc::new(f));
572        self
573    }
574
575    /// Show a tooltip that follows the pointer while it is over a link.
576    ///
577    /// The builder receives the link's URL. The view caches the tooltip
578    /// until a different destination is shown.
579    pub fn link_tooltip<F>(mut self, builder: F) -> Self
580    where
581        F: Fn(&SharedString, &mut Window, &mut App) -> AnyView + Send + Sync + 'static,
582    {
583        self.link_tooltip = Some(Arc::new(builder));
584        self
585    }
586
587    /// Make the checkboxes of Markdown task list items (`- [ ]`, `- [x]`)
588    /// clickable.
589    ///
590    /// The handler receives a [`TaskToggleEvent`] with the checked state the
591    /// item should now have and where the item and its `[ ]` / `[x]` marker
592    /// are in the source text. The view does not change its text: the caller
593    /// owns the source, replaces the marker and sets the new text. Without a
594    /// handler, the checkboxes are not interactive.
595    pub fn on_task_toggle<F>(mut self, handler: F) -> Self
596    where
597        F: Fn(&TaskToggleEvent, &mut Window, &mut App) + Send + Sync + 'static,
598    {
599        self.task_toggle_handler = Some(Arc::new(handler));
600        self
601    }
602
603    /// Scroll a container that does not follow scroll requests to the line
604    /// of [`TextViewState::reveal_range`].
605    ///
606    /// A `gpui::list` scrolls to that line by itself; a `div` with
607    /// `overflow_y_scroll`, for one, does not. After a frame in which the
608    /// line was laid out but not visible, the handler receives its bounds in
609    /// window coordinates, to scroll the container, e.g. through its
610    /// `ScrollHandle`, until the line is visible.
611    pub fn on_reveal<F>(mut self, handler: F) -> Self
612    where
613        F: Fn(Bounds<Pixels>, &mut Window, &mut App) + 'static,
614    {
615        self.reveal_handler = Some(Rc::new(handler));
616        self
617    }
618
619    /// Replace the Markdown extension registry.
620    pub fn markdown_extensions(mut self, extensions: MarkdownExtensions) -> Self {
621        self.markdown_extensions = Arc::new(extensions);
622        self
623    }
624
625    /// Set the motion policy; see [`TextViewMotion`]. Without one, the
626    /// state's own policy applies, which plays no motion by default.
627    pub fn motion(mut self, motion: TextViewMotion) -> Self {
628        self.motion = Some(motion);
629        self
630    }
631
632    /// Enable MDX JSX/expression parsing.
633    ///
634    /// This disables raw HTML parsing because `markdown-rs` gives HTML
635    /// priority over MDX when both are enabled.
636    pub fn markdown_mdx(mut self) -> Self {
637        let extensions = Arc::make_mut(&mut self.markdown_extensions);
638        *extensions = extensions.clone().mdx();
639        self
640    }
641
642    /// Set whether raw HTML in Markdown renders as HTML (the default) or
643    /// shows as the text it is written as. See [`MarkdownExtensions::raw_html`].
644    pub fn markdown_raw_html(mut self, enabled: bool) -> Self {
645        let extensions = Arc::make_mut(&mut self.markdown_extensions);
646        *extensions = extensions.clone().raw_html(enabled);
647        self
648    }
649
650    /// Register a custom block-level Markdown parser.
651    ///
652    /// The parser runs during Markdown AST conversion and must be independent
653    /// of [`Window`] / [`App`]. Store any parsed data in [`MarkdownNode`] and
654    /// render it later with [`Self::markdown_block_renderer`].
655    pub fn markdown_block_parser<F>(mut self, parser: F) -> Self
656    where
657        F: for<'a> Fn(
658                &markdown::mdast::Node,
659                &crate::text::MarkdownParseContext<'a>,
660            ) -> Option<MarkdownNode>
661            + Send
662            + Sync
663            + 'static,
664    {
665        Arc::make_mut(&mut self.markdown_extensions).push_block_parser(parser);
666        self
667    }
668
669    /// Register a renderer for a custom block-level Markdown node name.
670    pub fn markdown_block_renderer<F, E>(
671        mut self,
672        name: impl Into<SharedString>,
673        renderer: F,
674    ) -> Self
675    where
676        F: Fn(&MarkdownNode, &mut Window, &mut App) -> E + Send + Sync + 'static,
677        E: IntoElement,
678    {
679        Arc::make_mut(&mut self.markdown_extensions).push_block_renderer(name, renderer);
680        self
681    }
682
683    /// Apply a reusable text view plugin.
684    pub fn plugin<P>(self, plugin: P) -> Self
685    where
686        P: TextViewPlugin,
687    {
688        plugin.setup(self)
689    }
690}
691
692#[cfg(not(feature = "gpui-fast"))]
693impl IntoElement for TextView {
694    type Element = Self;
695
696    fn into_element(self) -> Self::Element {
697        self
698    }
699}
700
701pub struct TextViewLayoutState {
702    state: Entity<TextViewState>,
703    element: AnyElement,
704}
705
706pub struct TextViewPrepaintState {
707    hitbox: Hitbox,
708    /// Where paint has to pull the `max_lines` clip up to, because a glyph line
709    /// straddles the bottom of the box. `None` leaves the clip at the box edge,
710    /// where the container's hidden overflow already applies it.
711    clip_bottom: Option<Pixels>,
712    /// The touch handles this view owns, with their hitboxes.
713    touch_handles: crate::TouchHandleLayout,
714}
715
716/// Absorbs sub-pixel layout jitter: a line ending within a pixel of the box
717/// bottom counts as fitting inside it.
718const CLIP_EPSILON: Pixels = px(1.);
719
720/// The bottom of the last whole line at or above `y`, with the height of a line
721/// where it sits.
722fn last_line_bottom_above(spans: &[LineSpan], y: Pixels) -> Option<(Pixels, Pixels)> {
723    let mut last: Option<(Pixels, Pixels)> = None;
724    let mut keep = |bottom: Pixels, line_height: Pixels| {
725        if bottom <= y + CLIP_EPSILON && last.is_none_or(|(last, _)| bottom > last) {
726            last = Some((bottom, line_height));
727        }
728    };
729
730    for span in spans {
731        if span.line_height <= px(0.) {
732            continue;
733        }
734        let mut bottom = span.top + span.line_height;
735        while bottom <= span.bottom + CLIP_EPSILON {
736            keep(bottom, span.line_height);
737            bottom += span.line_height;
738        }
739        // The span's own bottom covers a last line taller than the rest.
740        keep(span.bottom, span.line_height);
741    }
742
743    last
744}
745
746/// Where to clip, given the lines a descendant `Inline` reported. `None` leaves
747/// the clip on the box edge.
748///
749/// Two things are never shown: half a line of glyphs, and anything with less
750/// than a line of itself to show. A line straddling `box_bottom` is left out
751/// whole, and so is the strip between it and the line before — the border and
752/// padding a table row leads with reads as a rendering fault rather than as a
753/// row. Whatever has more than a line to show is cut on the edge and keeps the
754/// part that fits, so the box holds no blank space it could have filled.
755fn line_safe_clip_bottom(
756    spans: &[LineSpan],
757    box_bottom: Pixels,
758    content_bottom: Pixels,
759) -> Option<Pixels> {
760    let mut clip = box_bottom;
761
762    for span in spans {
763        if span.line_height <= px(0.)
764            || span.top >= box_bottom
765            || span.bottom <= box_bottom + CLIP_EPSILON
766        {
767            continue;
768        }
769        let whole_lines = ((box_bottom - span.top) / span.line_height).floor();
770        let line_top = span.top + span.line_height * whole_lines;
771        // A line starting on the box edge is not straddling it.
772        if line_top < box_bottom - CLIP_EPSILON {
773            clip = clip.min(line_top);
774        }
775    }
776
777    let Some((last_line_bottom, line_height)) = last_line_bottom_above(spans, clip) else {
778        // Leaving the straddling line out would leave nothing at all — a first
779        // line taller than the whole budget, a heading in a one-line box. It
780        // keeps the part that fits instead, because an empty clamp reads as
781        // broken where a cut one reads as more to come.
782        return None;
783    };
784
785    // Snap away a scrap. Only content that continues past the box can leave
786    // one: the space under the last line of a document that fits is the box's
787    // own, not a piece of something below.
788    if content_bottom > box_bottom + CLIP_EPSILON {
789        let strip = clip - last_line_bottom;
790        if strip > CLIP_EPSILON && strip < line_height {
791            clip = last_line_bottom;
792        }
793    }
794
795    (clip < box_bottom - CLIP_EPSILON).then_some(clip)
796}
797
798impl Element for TextView {
799    type RequestLayoutState = TextViewLayoutState;
800    type PrepaintState = TextViewPrepaintState;
801
802    fn id(&self) -> Option<ElementId> {
803        Some(self.id.clone())
804    }
805
806    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
807        None
808    }
809
810    fn request_layout(
811        &mut self,
812        _: Option<&GlobalElementId>,
813        _: Option<&InspectorElementId>,
814        window: &mut Window,
815        cx: &mut App,
816    ) -> (LayoutId, Self::RequestLayoutState) {
817        let state = if let Some(state) = self.state.clone() {
818            state
819        } else {
820            let default_format = self.format.unwrap_or(TextViewFormat::Markdown);
821            let default_text = self.text.clone().unwrap_or_default();
822
823            let state = window.use_keyed_state(
824                SharedString::from(format!("{}/state", self.id)),
825                cx,
826                move |_, cx| {
827                    if default_format == TextViewFormat::Markdown {
828                        TextViewState::markdown(default_text.as_str(), cx)
829                    } else {
830                        TextViewState::html(default_text.as_str(), cx)
831                    }
832                },
833            );
834            self.state = Some(state.clone());
835            state
836        };
837
838        // `max_lines` needs the whole document laid out to snap the clip to a
839        // whole line, so it only applies to the fit-content mode.
840        let max_lines = self.max_lines.filter(|_| !self.scrollable);
841
842        // Resolve the style by reference: this runs every frame, and the
843        // style only reaches the state when it changed.
844        let defaults = cx.try_global::<TextViewDefaults>();
845        let theme_style;
846        let mut text_view_style = match (
847            &self.text_view_style,
848            defaults.and_then(|d| d.style.as_ref()),
849        ) {
850            (Some(style), _) | (None, Some(style)) => style,
851            (None, None) => {
852                theme_style = TextViewStyle::from_theme(&crate::Theme::global(cx));
853                &theme_style
854            }
855        };
856        // Follow the text color the container sets for its surface, so rich
857        // text stays readable in a filled bubble or a selected row.
858        let surface_style;
859        let mut on_inverted_surface = false;
860        if self.text_view_style.is_none() && defaults.is_some_and(|d| d.inherit_text_color) {
861            let color = self
862                .style
863                .text
864                .color
865                .unwrap_or_else(|| window.text_style().color);
866            if color != text_view_style.foreground() {
867                on_inverted_surface = text_view_style.is_inverted_by(color);
868                surface_style = text_view_style.on_text_color(color);
869                text_view_style = &surface_style;
870            }
871        }
872        let inline_style;
873        if let Some(refinement) = &self.inline_code_style {
874            let mut style = text_view_style.inline_code_style().clone();
875            style.refine(refinement);
876            inline_style = text_view_style.clone().with_inline_code_style(style);
877            text_view_style = &inline_style;
878        }
879        let block_style;
880        if self.list_style.is_some() || self.blockquote_style.is_some() {
881            let mut style = text_view_style.clone();
882            if let Some(refinement) = &self.list_style {
883                let mut marker = style.list_style().clone();
884                marker.refine(refinement);
885                style = style.with_list_style(marker);
886            }
887            if let Some(refinement) = &self.blockquote_style {
888                let mut quote = style.blockquote_style().clone();
889                quote.refine(refinement);
890                style = style.with_blockquote_style(quote);
891            }
892            block_style = style;
893            text_view_style = &block_style;
894        }
895        let foreground = text_view_style.foreground();
896        let text_view_style = (*state.read(cx).text_view_style != *text_view_style)
897            .then(|| Arc::new(text_view_style.clone()));
898        let code_block_highlighter = self.code_block_highlighter.clone().or_else(|| {
899            defaults
900                .filter(|_| !on_inverted_surface)
901                .and_then(|d| d.code_block_highlighter.clone())
902        });
903
904        state.update(cx, |state, cx| {
905            if text_view_style.is_some()
906                || match (&state.code_block_highlighter, &code_block_highlighter) {
907                    (Some(previous), Some(next)) => !Arc::ptr_eq(previous, next),
908                    (None, None) => false,
909                    _ => true,
910                }
911            {
912                state.preserve_selection_for_reflow();
913            }
914            state.code_block_actions = self.code_block_actions.clone();
915            state.code_block_highlighter = code_block_highlighter;
916            state.table_actions = self.table_actions.clone();
917            state.link_click_handler = self.link_click_handler.clone();
918            state.link_hook = self.link_hook.clone();
919            state.link_tooltip = self.link_tooltip.clone();
920            state.task_toggle_handler = self.task_toggle_handler.clone();
921            state.image_source = self.image_source.clone();
922            state.set_markdown_extensions(self.markdown_extensions.clone(), cx);
923            if let Some(motion) = &self.motion {
924                state.set_motion(motion.clone());
925            }
926            state.selectable = self.selectable;
927            state.hover_cursor = self.style.mouse_cursor;
928            state.selection_format = self.selection_format;
929            state.scrollable = self.scrollable;
930            state.max_lines = max_lines;
931            if let Some(text_view_style) = text_view_style {
932                state.text_view_style = text_view_style;
933            }
934
935            if let Some(text) = &self.text {
936                state.set_element_text(text, cx);
937            }
938        });
939
940        let focus_handle = state.read(cx).focus_handle.clone();
941        let list_state = state.read(cx).list_state.clone();
942        // Cap the box at `n` body-text lines (the effective text style may be
943        // refined by this view's own style, e.g. `.text_sm()`); hidden
944        // overflow also clips descendant hitboxes to the box during prepaint.
945        let max_lines_cap = max_lines.map(|max_lines| {
946            let mut text_style = window.text_style();
947            text_style.refine(&self.style.text);
948            text_style.line_height_in_pixels(window.rem_size()) * max_lines as f32
949        });
950
951        let mut el = div()
952            .id(("text-view-scroll", state.entity_id()))
953            .key_context("TextView")
954            .track_focus(&focus_handle)
955            .when(self.scrollable, |this| this.size_full())
956            .when_some(max_lines_cap, |this, cap| this.max_h(cap).overflow_hidden())
957            .relative()
958            // Paragraphs start on the start edge; LTR keeps the inherited
959            // alignment, and the view's own style still overrides both.
960            .when(crate::LayoutDirection::global(cx).is_rtl(), |this| {
961                crate::LogicalStyledExt::text_start(this, cx)
962            })
963            .text_color(foreground)
964            .on_action(move |_: &crate::input::Copy, window, cx| {
965                let text = TextSelection::selected_text(window, cx).trim().to_string();
966                if text.is_empty() {
967                    cx.propagate();
968                    return;
969                }
970                cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
971            })
972            .on_action(window.listener_for(&state, TextViewState::on_action_select_all))
973            .map(|this| {
974                if self.scrollable {
975                    this.child(crate::ScrollBounce::new(
976                        ("text-view-bounce", state.entity_id()),
977                        &list_state,
978                        state.clone(),
979                    ))
980                } else {
981                    this.child(state.clone())
982                }
983            })
984            // Overlay controls must paint after the document, otherwise rich
985            // content and selection backgrounds cover the thumb and hitbox.
986            .when(self.scrollable, |this| {
987                this.child(
988                    div().absolute().inset_0().child(
989                        crate::Scrollbar::vertical(&list_state)
990                            .id(("text-view-scrollbar", state.entity_id()))
991                            .viewport_from_layout(),
992                    ),
993                )
994            })
995            .refine_style(&self.style)
996            .into_any_element();
997        let layout_id = el.request_layout(window, cx);
998        (layout_id, TextViewLayoutState { state, element: el })
999    }
1000
1001    fn prepaint(
1002        &mut self,
1003        _: Option<&GlobalElementId>,
1004        _: Option<&InspectorElementId>,
1005        bounds: Bounds<Pixels>,
1006        request_layout: &mut Self::RequestLayoutState,
1007        window: &mut Window,
1008        cx: &mut App,
1009    ) -> Self::PrepaintState {
1010        let state = request_layout.state.clone();
1011        let max_lines_active = state.read(cx).max_lines.is_some();
1012        if max_lines_active {
1013            if let Ok(mut line_spans) = state.read(cx).line_spans.lock() {
1014                line_spans.clear();
1015            }
1016        }
1017        // Descendants read the view through the state stack during prepaint
1018        // (in addition to the paint-time push below): `Inline`s report their
1019        // line spans when `max_lines` is set, and table cells look for the
1020        // selection anchor.
1021        GlobalState::global(cx).push_text_view_state(state.clone());
1022        request_layout.element.prepaint(window, cx);
1023        GlobalState::global(cx).pop_text_view_state();
1024
1025        let mut clip_bottom = None;
1026        if max_lines_active {
1027            let (line_spans, content_bottom) = {
1028                let state = state.read(cx);
1029                (
1030                    state
1031                        .line_spans
1032                        .lock()
1033                        .map(|spans| spans.clone())
1034                        .unwrap_or_default(),
1035                    state.bounds().bottom(),
1036                )
1037            };
1038            // The content keeps its natural height inside the capped box, so
1039            // this sees everything the box cannot show — including a tall image
1040            // that reports no lines of its own.
1041            let clipped = content_bottom > bounds.bottom() + px(1.);
1042            // Notify on change so observers (e.g. an "expand" button gated on
1043            // `is_clamped`) re-render once the flag flips.
1044            if state.read(cx).clamped != clipped {
1045                state.update(cx, |state, cx| {
1046                    state.clamped = clipped;
1047                    cx.notify();
1048                });
1049            }
1050            if clipped {
1051                clip_bottom = line_safe_clip_bottom(&line_spans, bounds.bottom(), content_bottom);
1052            }
1053        }
1054
1055        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
1056        // Over the text, so after its hitbox.
1057        let touch_handles = if self.selectable {
1058            state
1059                .read(cx)
1060                .selection_adapter
1061                .prepaint_touch_handles(window, cx)
1062        } else {
1063            crate::TouchHandleLayout::default()
1064        };
1065        TextViewPrepaintState {
1066            hitbox,
1067            clip_bottom,
1068            touch_handles,
1069        }
1070    }
1071
1072    fn paint(
1073        &mut self,
1074        _: Option<&GlobalElementId>,
1075        _: Option<&InspectorElementId>,
1076        bounds: Bounds<Pixels>,
1077        request_layout: &mut Self::RequestLayoutState,
1078        prepaint: &mut Self::PrepaintState,
1079        window: &mut Window,
1080        cx: &mut App,
1081    ) {
1082        let state = &request_layout.state;
1083        if self.selectable {
1084            state.read(cx).selection_adapter.begin_frame();
1085        }
1086
1087        GlobalState::global(cx).push_text_view_state(state.clone());
1088        if let Some(clip_bottom) = prepaint.clip_bottom {
1089            // Snap the `max_lines` clip to the last whole line that fits, so a
1090            // line of glyphs is never cut in half.
1091            let mask = ContentMask {
1092                bounds: Bounds::from_corners(bounds.origin, point(bounds.right(), clip_bottom)),
1093            };
1094            window.with_content_mask(Some(mask), |window| {
1095                request_layout.element.paint(window, cx);
1096            });
1097        } else {
1098            request_layout.element.paint(window, cx);
1099        }
1100        GlobalState::global(cx).pop_text_view_state();
1101
1102        // Every list has scrolled by now, so the line of a reveal is where
1103        // it ends up this frame.
1104        if state.read(cx).pending_reveal.is_some() {
1105            let progress = state.update(cx, |state, _| {
1106                state.pending_reveal.as_mut().map(PendingReveal::progress)
1107            });
1108            match progress {
1109                Some(RevealProgress::Shown) => {
1110                    state.update(cx, |state, _| state.pending_reveal = None);
1111                }
1112                Some(RevealProgress::Hidden(line)) => {
1113                    if let Some(handler) = &self.reveal_handler {
1114                        handler(line, window, cx);
1115                    }
1116                }
1117                Some(RevealProgress::NotLaidOut) | None => {}
1118            }
1119        }
1120
1121        if self.selectable {
1122            let (adapter, scroll_offset, content_bounds, self_scroll, handle_color) = {
1123                let state = state.read(cx);
1124                (
1125                    state.selection_adapter.clone(),
1126                    state.scroll_offset(),
1127                    state.bounds(),
1128                    state.scrollable,
1129                    state.text_view_style.selection().alpha(1.),
1130                )
1131            };
1132            adapter.register(
1133                prepaint.hitbox.clone(),
1134                content_bounds,
1135                scroll_offset,
1136                self_scroll,
1137                window,
1138                cx,
1139            );
1140            // The handles of a touch selection go over the text, and under
1141            // whatever is painted over the text after it.
1142            adapter.paint_touch_handles(&prepaint.touch_handles, handle_color, window, cx);
1143        }
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use std::sync::{
1150        Arc,
1151        atomic::{AtomicUsize, Ordering},
1152    };
1153
1154    use super::{TaskToggleEvent, TextView, TextViewPlugin};
1155    use crate::text::{SelectionFormat, TableData, TextViewState, TextViewStyle};
1156    use gpui::{
1157        AppContext as _, Bounds, ClickEvent, Context, CursorStyle, Entity, InteractiveElement as _,
1158        IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, Overflow,
1159        ParentElement as _, Pixels, Render, SharedString, StatefulInteractiveElement as _,
1160        StyleRefinement, Styled as _, TestAppContext, VisualTestContext, Window, div, point,
1161        prelude::FluentBuilder as _, px, rems,
1162    };
1163
1164    struct TextViewTestRoot {
1165        text_view: Entity<TextViewState>,
1166    }
1167
1168    struct InlineHoverTestRoot {
1169        view: Entity<TextViewState>,
1170        builds: Arc<AtomicUsize>,
1171        format: crate::text::SelectionFormat,
1172    }
1173
1174    struct InlineHoverCard;
1175    impl Render for InlineHoverCard {
1176        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1177            div()
1178                .debug_selector(|| "inline-test-card".into())
1179                .w(px(120.))
1180                .h(px(40.))
1181                .child("Member profile")
1182        }
1183    }
1184
1185    impl Render for InlineHoverTestRoot {
1186        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1187            let builds = self.builds.clone();
1188            div()
1189                .pl(px(150.))
1190                .w(px(300.))
1191                .text_size(px(16.))
1192                .child(crate::TextSelectionLayer)
1193                .child(
1194                    TextView::new(&self.view)
1195                        .selection_format(self.format)
1196                        .plugin(
1197                            crate::text::markdown_ext::TestInlinePlugin::new("mention")
1198                                .parse_with(|node, _| {
1199                                    let markdown::mdast::Node::Link(link) = node else {
1200                                        return None;
1201                                    };
1202                                    let handle = link.url.strip_prefix("mention:")?;
1203                                    Some(
1204                                        crate::text::MarkdownNode::new("mention", ())
1205                                            .text(format!("@{handle}")),
1206                                    )
1207                                })
1208                                .render_with(move |_, _, _, _| {
1209                                    let builds = builds.clone();
1210                                    Some(crate::text::InlineElement::new(
1211                                        crate::HoverCard::new("mention-hover")
1212                                            .anchor(gpui::Anchor::TopCenter)
1213                                            .trigger(div().child("@member"))
1214                                            .content(move |_, _, cx| {
1215                                                builds.fetch_add(1, Ordering::Relaxed);
1216                                                div()
1217                                                    .id("hover-content")
1218                                                    .child(cx.new(|_| InlineHoverCard))
1219                                            }),
1220                                    ))
1221                                }),
1222                        ),
1223                )
1224        }
1225    }
1226
1227    #[gpui::test]
1228    fn text_view_follows_the_text_color_of_its_container(cx: &mut TestAppContext) {
1229        struct Root {
1230            inherited: Entity<TextViewState>,
1231            explicit: Entity<TextViewState>,
1232            surface_text: gpui::Hsla,
1233        }
1234        impl Render for Root {
1235            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1236                div()
1237                    .w(px(300.))
1238                    .text_color(crate::ColorTokens::light().foreground)
1239                    .child(
1240                        div()
1241                            .text_color(self.surface_text)
1242                            .child(TextView::new(&self.inherited))
1243                            .child(TextView::new(&self.explicit).style(TextViewStyle::default())),
1244                    )
1245            }
1246        }
1247
1248        let colors = crate::ColorTokens::light();
1249        cx.update(|cx| {
1250            crate::init(cx);
1251            super::TextViewDefaults::new()
1252                .with_style(TextViewStyle::default())
1253                .with_inherit_text_color(true)
1254                .install(cx);
1255        });
1256        let (root, cx) = cx.add_window_view(|_, cx| Root {
1257            inherited: cx.new(|cx| TextViewState::markdown("[link](https://a.b) `code`", cx)),
1258            explicit: cx.new(|cx| TextViewState::markdown("text", cx)),
1259            surface_text: colors.primary_foreground,
1260        });
1261        cx.run_until_parked();
1262        cx.update(|window, cx| {
1263            window.draw(cx).clear(cx);
1264        });
1265
1266        root.read_with(cx, |root, cx| {
1267            let inherited = &root.inherited.read(cx).text_view_style;
1268            assert_eq!(inherited.foreground(), colors.primary_foreground);
1269            assert_eq!(inherited.link(), colors.primary_foreground);
1270            assert!(inherited.is_dark());
1271
1272            let explicit = &root.explicit.read(cx).text_view_style;
1273            assert_eq!(explicit.foreground(), colors.foreground);
1274            assert_eq!(explicit.link(), TextViewStyle::default().link());
1275        });
1276    }
1277
1278    #[gpui::test]
1279    fn inline_plugin_reuses_render_and_preserves_native_child_events(cx: &mut TestAppContext) {
1280        use std::sync::Mutex;
1281        struct ControlPlugin(Arc<Mutex<Vec<String>>>);
1282        impl crate::text::MarkdownPlugin for ControlPlugin {
1283            fn name(&self) -> &str {
1284                "control"
1285            }
1286            fn parse(
1287                &self,
1288                node: &markdown::mdast::Node,
1289                _: &crate::text::MarkdownParseContext<'_>,
1290            ) -> Option<crate::text::MarkdownNode> {
1291                let markdown::mdast::Node::Link(link) = node else {
1292                    return None;
1293                };
1294                let label = link.url.strip_prefix("control:")?;
1295                Some(crate::text::MarkdownNode::new("control", ()).text(label.to_string()))
1296            }
1297            fn render(
1298                &self,
1299                node: &crate::text::MarkdownNode,
1300                _: &mut Window,
1301                _: &mut gpui::App,
1302            ) -> impl IntoElement {
1303                let clicks = self.0.clone();
1304                let label = node.as_text().to_string();
1305                div()
1306                    .id("same-control-id")
1307                    .w(px(60.))
1308                    .h(px(24.))
1309                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1310                    .on_click(move |_, _, _| clicks.lock().unwrap().push(label.clone()))
1311                    .child(node.as_text().to_string())
1312            }
1313        }
1314        struct Root {
1315            view: Entity<TextViewState>,
1316            clicks: Arc<Mutex<Vec<String>>>,
1317        }
1318        impl Render for Root {
1319            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1320                div()
1321                    .w(px(300.))
1322                    .child(crate::TextSelectionLayer)
1323                    .child(TextView::new(&self.view).plugin(ControlPlugin(self.clicks.clone())))
1324            }
1325        }
1326        cx.update(crate::init);
1327        let clicks = Arc::new(Mutex::new(Vec::new()));
1328        let captured = clicks.clone();
1329        let (root, cx) = cx.add_window_view(move |_, cx| Root {
1330            view: cx.new(|cx| TextViewState::markdown("[one](control:one)[two](control:two)", cx)),
1331            clicks,
1332        });
1333        cx.run_until_parked();
1334        cx.update(|window, cx| {
1335            window.draw(cx).clear(cx);
1336        });
1337        let bounds = root.read_with(cx, |root, cx| {
1338            root.view.read(cx).selection_adapter.text_bounds()
1339        });
1340        assert_eq!(bounds.len(), 2);
1341        for bounds in bounds {
1342            cx.simulate_click(bounds.center(), Modifiers::default());
1343            cx.update(|window, cx| {
1344                window.draw(cx).clear(cx);
1345            });
1346        }
1347        assert_eq!(*captured.lock().unwrap(), vec!["one", "two"]);
1348    }
1349
1350    #[gpui::test]
1351    fn inline_hover_card_is_lazy_and_retains_atomic_copy(cx: &mut TestAppContext) {
1352        cx.update(crate::init);
1353        let builds = Arc::new(AtomicUsize::new(0));
1354        let source = "[@member](mention:member)";
1355        let (root, cx) = cx.add_window_view(|_, cx| InlineHoverTestRoot {
1356            view: cx.new(|cx| TextViewState::markdown(source, cx)),
1357            builds: builds.clone(),
1358            format: crate::text::SelectionFormat::Plain,
1359        });
1360        cx.run_until_parked();
1361        cx.update(|window, cx| window.draw(cx).clear(cx));
1362        assert_eq!(builds.load(Ordering::Relaxed), 0);
1363        let view = root.read_with(cx, |root, _| root.view.clone());
1364        let bounds = view.read_with(cx, |view, _| view.selection_adapter.text_bounds()[0]);
1365        cx.update(|window, cx| {
1366            window.simulate_mouse_move(point(bounds.right() - px(1.), bounds.center().y), cx)
1367        });
1368        cx.run_until_parked();
1369        cx.executor()
1370            .advance_clock(std::time::Duration::from_secs(1));
1371        cx.run_until_parked();
1372        cx.update(|window, cx| window.draw(cx).clear(cx));
1373        assert!(
1374            builds.load(Ordering::Relaxed) > 0,
1375            "hover did not build the card"
1376        );
1377        cx.update(|window, cx| window.draw(cx).clear(cx));
1378        let card = cx
1379            .debug_bounds("inline-test-card")
1380            .expect("hover card should be painted");
1381        assert!(
1382            (card.center().x - bounds.center().x).abs() < px(1.),
1383            "card {card:?} must be centered on mention {bounds:?}"
1384        );
1385        assert!(
1386            card.top() >= bounds.bottom(),
1387            "card should be below the mention"
1388        );
1389        for (format, expected) in [
1390            (crate::text::SelectionFormat::Plain, "@member"),
1391            (crate::text::SelectionFormat::Source, source),
1392        ] {
1393            root.update(cx, |root, cx| {
1394                root.format = format;
1395                cx.notify();
1396            });
1397            view.update(cx, |view, cx| {
1398                view.set_selection_format(format, cx);
1399                view.select_all(cx);
1400            });
1401            cx.update(|window, cx| window.draw(cx).clear(cx));
1402            assert_eq!(
1403                view.read_with(cx, |view, _| view.selected_text()).trim(),
1404                expected
1405            );
1406        }
1407    }
1408
1409    struct InlinePluginTestRoot {
1410        text_view: Entity<TextViewState>,
1411        width: Pixels,
1412        font_size: Pixels,
1413        source_format: bool,
1414        prepared_size: Option<Arc<AtomicUsize>>,
1415    }
1416
1417    impl Render for InlinePluginTestRoot {
1418        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1419            let prepared_size = self.prepared_size.clone();
1420            div().w(self.width).text_size(self.font_size).child(crate::TextSelectionLayer).child(
1421                TextView::new(&self.text_view)
1422                    .selection_format(if self.source_format { crate::text::SelectionFormat::Source }
1423                        else { crate::text::SelectionFormat::Plain })
1424
1425                    .plugin(crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(|node, _| {
1426                        let markdown::mdast::Node::InlineMath(math) = node else { return None };
1427                        Some(crate::text::MarkdownNode::new("math", ()).text(format!("{}²", math.value)))
1428                    }).render_with(move |_, context, _, _| {
1429                        let value = prepared_size.as_ref()?.load(Ordering::Relaxed) as f32;
1430                        let image = Arc::new(gpui::Image::from_bytes(gpui::ImageFormat::Svg,
1431                            b"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"40\"><path d=\"M0 0L40 40\" stroke=\"black\"/></svg>".to_vec()));
1432                        let unit = context.font_size() / 16.;
1433                        Some(crate::text::InlineElement::new(gpui::img(image).w(unit * value).h(unit * value)).with_baseline(unit * value * 0.75))
1434                    })))
1435        }
1436    }
1437
1438    #[gpui::test]
1439    fn inline_plugins_drag_and_copy_across_formulas_in_both_directions(cx: &mut TestAppContext) {
1440        cx.update(crate::init);
1441        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1442            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1443            width: px(420.),
1444            font_size: px(16.),
1445            source_format: false,
1446            prepared_size: None,
1447        });
1448        let cx: &mut VisualTestContext = cx;
1449        for font_size in [16., 24., 32.] {
1450            for width in [60., 160., 420.] {
1451                for prepared in [None, Some(32)] {
1452                    for source_format in [false, true] {
1453                        root.update(cx, |root, cx| {
1454                            root.source_format = source_format;
1455                            root.width = px(width);
1456                            root.font_size = px(font_size);
1457                            root.prepared_size =
1458                                prepared.map(|value| Arc::new(AtomicUsize::new(value)));
1459                            cx.notify();
1460                        });
1461                        cx.run_until_parked();
1462                        cx.update(|window, cx| window.draw(cx).clear(cx));
1463                        let bounds =
1464                            root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1465                        let text_bounds = root.read_with(cx, |root, cx| {
1466                            root.text_view.read(cx).selection_adapter.text_bounds()
1467                        });
1468                        let first = text_bounds.first().unwrap();
1469                        let last = text_bounds.last().unwrap();
1470                        let left =
1471                            point(first.left() + px(0.1), first.top() + first.size.height / 2.);
1472                        let right =
1473                            point(last.right() - px(0.1), last.top() + last.size.height / 2.);
1474                        for (start, end) in [(left, right), (right, left)] {
1475                            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1476                            cx.update(|window, cx| window.draw(cx).clear(cx));
1477                            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1478                            cx.update(|window, cx| window.draw(cx).clear(cx));
1479                            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1480                            cx.update(|window, cx| window.draw(cx).clear(cx));
1481                            let selected = root
1482                                .read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
1483                            assert_eq!(
1484                                selected.trim(),
1485                                if source_format {
1486                                    "中文 $x$ $y$ English"
1487                                } else {
1488                                    "中文 x² y² English"
1489                                },
1490                                "start={start:?} end={end:?} bounds={bounds:?} width={width} font_size={font_size} prepared={prepared:?}"
1491                            );
1492                        }
1493                    }
1494                }
1495            }
1496        }
1497    }
1498
1499    #[gpui::test]
1500    fn inline_resource_size_update_reflows_without_changing_selection(cx: &mut TestAppContext) {
1501        cx.update(crate::init);
1502        let prepared_size = Arc::new(AtomicUsize::new(16));
1503        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1504            text_view: cx.new(|cx| TextViewState::markdown("中文 $x$ $y$ English", cx)),
1505            width: px(160.),
1506            font_size: px(16.),
1507            source_format: false,
1508            prepared_size: Some(prepared_size.clone()),
1509        });
1510        let cx: &mut VisualTestContext = cx;
1511        cx.run_until_parked();
1512        cx.update(|window, cx| window.draw(cx).clear(cx));
1513        let before = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1514        let regions = root.read_with(cx, |root, cx| {
1515            root.text_view.read(cx).selection_adapter.text_bounds()
1516        });
1517        let first = regions.first().unwrap();
1518        let last = regions.last().unwrap();
1519        let start = point(first.left() + px(0.1), first.top() + px(10.));
1520        let end = point(last.right() - px(0.1), last.top() + px(10.));
1521        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
1522        cx.update(|window, cx| window.draw(cx).clear(cx));
1523        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
1524        cx.update(|window, cx| window.draw(cx).clear(cx));
1525        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
1526        cx.update(|window, cx| window.draw(cx).clear(cx));
1527        assert_eq!(
1528            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1529                .trim(),
1530            "中文 x² y² English"
1531        );
1532        prepared_size.store(100, Ordering::Relaxed);
1533        root.update(cx, |root, cx| {
1534            root.text_view
1535                .update(cx, |state, cx| state.invalidate_inline_layout(cx))
1536        });
1537        cx.run_until_parked();
1538        cx.update(|window, cx| window.draw(cx).clear(cx));
1539        let after = root.read_with(cx, |root, cx| root.text_view.read(cx).bounds());
1540        assert!(after.size.height > before.size.height * 2.);
1541        assert_eq!(
1542            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1543                .trim(),
1544            "中文 x² y² English"
1545        );
1546    }
1547
1548    #[gpui::test]
1549    fn triple_click_on_formula_selects_its_entire_mixed_line(cx: &mut TestAppContext) {
1550        cx.update(crate::init);
1551        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1552            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1553            width: px(420.),
1554            font_size: px(16.),
1555            source_format: false,
1556            prepared_size: None,
1557        });
1558        let cx: &mut VisualTestContext = cx;
1559        cx.run_until_parked();
1560        cx.update(|window, cx| window.draw(cx).clear(cx));
1561        let regions = root.read_with(cx, |root, cx| {
1562            root.text_view.read(cx).selection_adapter.text_bounds()
1563        });
1564        let formula = regions[1];
1565        let position = formula.center();
1566        cx.simulate_event(MouseDownEvent {
1567            position,
1568            modifiers: Modifiers::default(),
1569            button: MouseButton::Left,
1570            click_count: 3,
1571            first_mouse: false,
1572        });
1573        cx.simulate_event(MouseUpEvent {
1574            position,
1575            modifiers: Modifiers::default(),
1576            button: MouseButton::Left,
1577            click_count: 3,
1578        });
1579        cx.update(|window, cx| window.draw(cx).clear(cx));
1580        assert_eq!(
1581            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1582                .trim(),
1583            "before x² after"
1584        );
1585        root.update(cx, |root, cx| {
1586            root.source_format = true;
1587            cx.notify();
1588        });
1589        cx.update(|window, cx| window.draw(cx).clear(cx));
1590        assert_eq!(
1591            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1592                .trim(),
1593            "before $x$ after"
1594        );
1595    }
1596
1597    /// Triple clicks the second row of the first paragraph of `markdown`,
1598    /// laid out 160px wide, and returns the selected text.
1599    fn triple_click_second_row(markdown: &'static str, cx: &mut TestAppContext) -> String {
1600        cx.update(crate::init);
1601        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1602            text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
1603            width: px(160.),
1604            font_size: px(16.),
1605            source_format: false,
1606            prepared_size: None,
1607        });
1608        let cx: &mut VisualTestContext = cx;
1609        cx.run_until_parked();
1610        cx.update(|window, cx| window.draw(cx).clear(cx));
1611        let regions = root.read_with(cx, |root, cx| {
1612            root.text_view.read(cx).selection_adapter.text_bounds()
1613        });
1614        let first_top = regions[0].top();
1615        let second_row = regions
1616            .iter()
1617            .filter(|region| region.top() > first_top + px(4.))
1618            .min_by(|a, b| a.top().partial_cmp(&b.top()).unwrap())
1619            .copied()
1620            .expect("the paragraph wraps");
1621        let position = second_row.center();
1622        cx.simulate_event(MouseDownEvent {
1623            position,
1624            modifiers: Modifiers::default(),
1625            button: MouseButton::Left,
1626            click_count: 3,
1627            first_mouse: false,
1628        });
1629        cx.simulate_event(MouseUpEvent {
1630            position,
1631            modifiers: Modifiers::default(),
1632            button: MouseButton::Left,
1633            click_count: 3,
1634        });
1635        cx.update(|window, cx| window.draw(cx).clear(cx));
1636        root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1637            .trim()
1638            .to_string()
1639    }
1640
1641    #[gpui::test]
1642    fn triple_click_selects_a_wrapped_paragraph_with_inline_code(cx: &mut TestAppContext) {
1643        assert_eq!(
1644            triple_click_second_row(
1645                "Call `foo` now, then keep typing until this paragraph wraps onto a few rows.\n\nNext paragraph.",
1646                cx,
1647            ),
1648            "Call foo now, then keep typing until this paragraph wraps onto a few rows."
1649        );
1650    }
1651
1652    #[gpui::test]
1653    fn triple_click_selects_a_wrapped_paragraph_with_several_inline_nodes(cx: &mut TestAppContext) {
1654        assert_eq!(
1655            triple_click_second_row(
1656                "Call `foo` and **bold** then `bar` with $x$ until this paragraph wraps onto rows.\n\nNext paragraph.",
1657                cx,
1658            ),
1659            "Call foo and bold then bar with x² until this paragraph wraps onto rows."
1660        );
1661    }
1662
1663    #[gpui::test]
1664    fn triple_click_selects_a_wrapped_plain_paragraph(cx: &mut TestAppContext) {
1665        assert_eq!(
1666            triple_click_second_row(
1667                "Plain words keep going until this paragraph wraps onto a few rows.\n\nNext paragraph.",
1668                cx,
1669            ),
1670            "Plain words keep going until this paragraph wraps onto a few rows."
1671        );
1672    }
1673
1674    #[gpui::test]
1675    fn double_click_on_formula_selects_only_that_object(cx: &mut TestAppContext) {
1676        cx.update(crate::init);
1677        let (root, cx) = cx.add_window_view(|_, cx| InlinePluginTestRoot {
1678            text_view: cx.new(|cx| TextViewState::markdown("before $x$ after", cx)),
1679            width: px(420.),
1680            font_size: px(16.),
1681            source_format: false,
1682            prepared_size: None,
1683        });
1684        let cx: &mut VisualTestContext = cx;
1685        cx.run_until_parked();
1686        cx.update(|window, cx| window.draw(cx).clear(cx));
1687        let regions = root.read_with(cx, |root, cx| {
1688            root.text_view.read(cx).selection_adapter.text_bounds()
1689        });
1690        let position = regions[1].center();
1691        cx.simulate_event(MouseDownEvent {
1692            position,
1693            modifiers: Modifiers::default(),
1694            button: MouseButton::Left,
1695            click_count: 2,
1696            first_mouse: false,
1697        });
1698        cx.simulate_event(MouseUpEvent {
1699            position,
1700            modifiers: Modifiers::default(),
1701            button: MouseButton::Left,
1702            click_count: 2,
1703        });
1704        cx.update(|window, cx| window.draw(cx).clear(cx));
1705        // Two clicks stop at the object; only three take the whole line.
1706        assert_eq!(
1707            root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
1708                .trim(),
1709            "x²"
1710        );
1711    }
1712
1713    /// A scrollable viewport, so the list has a bounded height to measure
1714    /// against and `max_offset_for_scrollbar` reports a real scroll extent.
1715    struct ScrollExtentTestRoot {
1716        text_view: Entity<TextViewState>,
1717    }
1718
1719    impl Render for ScrollExtentTestRoot {
1720        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1721            div()
1722                .w(px(400.))
1723                .h(px(200.))
1724                .overflow_hidden()
1725                .child(TextView::new(&self.text_view).scrollable(true))
1726        }
1727    }
1728
1729    /// `count` paragraphs, each `words` words long, so two documents can share
1730    /// a block count while differing wildly in height.
1731    fn document_of(count: usize, words: usize) -> String {
1732        (1..=count)
1733            .map(|i| format!("Block {i}: {}", "lorem ipsum dolor ".repeat(words)))
1734            .collect::<Vec<_>>()
1735            .join("\n\n")
1736    }
1737
1738    /// Replacing a document with one that happens to have the *same* block
1739    /// count must still re-measure. `Document::render_root` only resets the
1740    /// list when the count changes, so without an explicit re-measure every
1741    /// cached height stays with the previous document and the scroll extent
1742    /// keeps describing it.
1743    #[gpui::test]
1744    fn replacing_a_document_with_an_equal_block_count_remeasures(cx: &mut TestAppContext) {
1745        cx.update(crate::init);
1746
1747        const BLOCKS: usize = 24;
1748        let short = document_of(BLOCKS, 1);
1749        let tall = document_of(BLOCKS, 60);
1750
1751        let (root, cx) = cx.add_window_view(|_, cx| ScrollExtentTestRoot {
1752            text_view: cx.new(|cx| TextViewState::markdown(&short, cx)),
1753        });
1754        let cx: &mut VisualTestContext = cx;
1755
1756        // The list is populated and measured during layout, so every
1757        // assertion below has to follow a real frame.
1758        let settle = |cx: &mut VisualTestContext| {
1759            cx.run_until_parked();
1760            cx.update(|window, cx| window.draw(cx).clear(cx));
1761            cx.run_until_parked();
1762        };
1763        settle(cx);
1764
1765        let scroll_extent = |cx: &mut VisualTestContext| {
1766            root.read_with(cx, |root, cx| {
1767                root.text_view
1768                    .read(cx)
1769                    .list_state()
1770                    .max_offset_for_scrollbar()
1771                    .y
1772            })
1773        };
1774
1775        let short_extent = scroll_extent(cx);
1776
1777        root.update(cx, |root, cx| {
1778            root.text_view
1779                .update(cx, |state, cx| state.set_text(&tall, cx));
1780        });
1781        settle(cx);
1782
1783        root.read_with(cx, |root, cx| {
1784            assert_eq!(
1785                root.text_view.read(cx).list_state().item_count(),
1786                BLOCKS,
1787                "the replacement must keep the block count, or the list resets and the bug cannot occur"
1788            );
1789        });
1790
1791        let tall_extent = scroll_extent(cx);
1792        assert!(
1793            tall_extent > short_extent * 5.,
1794            "a much taller document must grow the scroll extent, but it went from \
1795             {short_extent:?} to {tall_extent:?}"
1796        );
1797    }
1798
1799    struct StatelessMarkdownRoot {
1800        renders: Arc<AtomicUsize>,
1801    }
1802
1803    impl Render for StatelessMarkdownRoot {
1804        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1805            self.renders.fetch_add(1, Ordering::Relaxed);
1806            div().child(
1807                TextView::markdown("stateless-markdown", include_str!("../../../../README.md"))
1808                    .markdown_block_parser(|_, _| None),
1809            )
1810        }
1811    }
1812
1813    struct DummyTextViewPlugin;
1814
1815    impl TextViewPlugin for DummyTextViewPlugin {
1816        fn setup(self, mut text_view: TextView) -> TextView {
1817            text_view.selectable = true;
1818            text_view
1819        }
1820    }
1821
1822    #[gpui::test]
1823    fn text_view_constructors_are_selectable_by_default(cx: &mut TestAppContext) {
1824        cx.update(crate::init);
1825        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1826
1827        assert!(TextView::new(&state).selectable);
1828        assert!(TextView::markdown("markdown", "text").selectable);
1829        assert!(TextView::html("html", "<p>text</p>").selectable);
1830    }
1831
1832    #[gpui::test]
1833    fn cursor_on_text_view_replaces_hover_ibeam(cx: &mut TestAppContext) {
1834        cx.update(crate::init);
1835        let state = cx.update(|cx| cx.new(|cx| TextViewState::markdown("state", cx)));
1836
1837        assert_eq!(TextView::new(&state).style.mouse_cursor, None);
1838        assert_eq!(
1839            TextView::new(&state).cursor_default().style.mouse_cursor,
1840            Some(CursorStyle::Arrow)
1841        );
1842
1843        state.update(cx, |state, _| {
1844            assert!(state.shows_text_cursor());
1845            state.hover_cursor = Some(CursorStyle::Arrow);
1846            assert!(!state.shows_text_cursor());
1847            state.is_selecting = true;
1848            assert!(state.shows_text_cursor());
1849        });
1850    }
1851
1852    #[gpui::test]
1853    fn stateless_markdown_with_rebuilt_parser_settles(cx: &mut TestAppContext) {
1854        cx.update(crate::init);
1855        let renders = Arc::new(AtomicUsize::new(0));
1856        let (_, cx) = cx.add_window_view({
1857            let renders = renders.clone();
1858            move |_, _| StatelessMarkdownRoot { renders }
1859        });
1860        let cx: &mut VisualTestContext = cx;
1861
1862        cx.run_until_parked();
1863        cx.update(|window, cx| window.draw(cx).clear(cx));
1864        let renders_after_redraw = renders.load(Ordering::Relaxed);
1865        cx.run_until_parked();
1866        assert_eq!(
1867            renders.load(Ordering::Relaxed),
1868            renders_after_redraw,
1869            "an unchanged TextView must not schedule another render after its parser is rebuilt",
1870        );
1871    }
1872
1873    #[gpui::test]
1874    fn markdown_data_url_image_is_decoded_inline(cx: &mut TestAppContext) {
1875        use gpui::{Image, ImageFormat, ImageSource};
1876
1877        // A 1x1 red PNG.
1878        const PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
1879
1880        cx.update(crate::init);
1881        let markdown = format!("Inline ![dot](data:image/png;base64,{PNG_BASE64}) image");
1882        let (_, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new(&markdown, cx));
1883        let cx: &mut VisualTestContext = cx;
1884
1885        cx.run_until_parked();
1886        cx.update(|window, cx| window.draw(cx).clear(cx));
1887
1888        // `Image` keys the asset system by a hash of its bytes, so rebuilding it
1889        // from the same body finds the entry the text view's `img` registered
1890        // when it rendered — proof the body was decoded in place instead of
1891        // being fetched over HTTP.
1892        let bytes = data_url::DataUrl::process(&format!("data:image/png;base64,{PNG_BASE64}"))
1893            .unwrap()
1894            .decode_to_vec()
1895            .unwrap()
1896            .0;
1897        let image = Arc::new(Image::from_bytes(ImageFormat::Png, bytes));
1898        assert!(
1899            cx.update(|_, cx| ImageSource::Image(image).is_asset_cached(cx)),
1900            "the data URL image must be handed to GPUI as decoded bytes",
1901        );
1902    }
1903
1904    #[gpui::test]
1905    fn unstyled_text_view_uses_base_tokens_for_link_and_input_selection(cx: &mut TestAppContext) {
1906        cx.update(crate::init);
1907        cx.update(|cx| {
1908            let colors = &mut crate::Theme::global_mut(cx).tokens.colors;
1909            colors.primary = gpui::rgb(0x55aaff).into();
1910            colors.selection = gpui::rgb(0x335577).into();
1911        });
1912        let (root, cx) = cx.add_window_view(|_, cx| TextViewTestRoot::new("[link](url)", cx));
1913        let cx: &mut VisualTestContext = cx;
1914
1915        cx.run_until_parked();
1916        root.read_with(cx, |root, cx| {
1917            let style = &root.text_view.read(cx).text_view_style;
1918            assert_eq!(style.link(), gpui::rgb(0x55aaff).into());
1919            assert_eq!(style.selection(), gpui::rgb(0x335577).into());
1920        });
1921    }
1922
1923    #[gpui::test]
1924    fn inline_code_view_refinement_keeps_unspecified_style_properties(cx: &mut TestAppContext) {
1925        use super::{TextViewDefaults, TextViewStyle};
1926        struct StyledCode(Entity<TextViewState>);
1927        impl Render for StyledCode {
1928            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1929                TextView::new(&self.0)
1930                    .inline_code_style(
1931                        StyleRefinement::default()
1932                            .border_1()
1933                            .border_color(gpui::blue()),
1934                    )
1935                    .into_any_element()
1936            }
1937        }
1938        cx.update(crate::init);
1939        cx.update(|cx| {
1940            cx.set_global(
1941                TextViewDefaults::default().with_style(
1942                    TextViewStyle::default().with_inline_code_style(
1943                        StyleRefinement::default()
1944                            .text_size(rems(1.))
1945                            .bg(gpui::red()),
1946                    ),
1947                ),
1948            )
1949        });
1950        let (root, cx) = cx.add_window_view(|_, cx| {
1951            StyledCode(cx.new(|cx| TextViewState::markdown("before `code` after", cx)))
1952        });
1953        cx.run_until_parked();
1954        cx.update(|window, cx| window.draw(cx).clear(cx));
1955        root.read_with(cx, |root, cx| {
1956            let state = root.0.read(cx);
1957            let style = state.text_view_style.inline_code_style();
1958            assert_eq!(style.text.font_size, Some(rems(1.).into()));
1959            assert_eq!(style.background, Some(gpui::red().into()));
1960            assert_eq!(style.border_color, Some(gpui::blue()));
1961            assert_eq!(style.border_widths.left, Some(px(1.).into()));
1962        });
1963    }
1964
1965    #[gpui::test]
1966    fn list_and_blockquote_view_refinements_keep_unspecified_style_properties(
1967        cx: &mut TestAppContext,
1968    ) {
1969        use super::{TextViewDefaults, TextViewStyle};
1970        struct StyledBlocks(Entity<TextViewState>);
1971        impl Render for StyledBlocks {
1972            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1973                TextView::new(&self.0)
1974                    .list_style(StyleRefinement::default().text_color(gpui::blue()))
1975                    .blockquote_style(StyleRefinement::default().border_color(gpui::blue()))
1976                    .into_any_element()
1977            }
1978        }
1979        cx.update(crate::init);
1980        cx.update(|cx| {
1981            cx.set_global(
1982                TextViewDefaults::default().with_style(
1983                    TextViewStyle::default()
1984                        .with_list_style(
1985                            StyleRefinement::default().font_weight(gpui::FontWeight::BOLD),
1986                        )
1987                        .with_blockquote_style(StyleRefinement::default().border_l_4()),
1988                ),
1989            )
1990        });
1991        let (root, cx) = cx.add_window_view(|_, cx| {
1992            StyledBlocks(cx.new(|cx| TextViewState::markdown("- item\n\n> quote", cx)))
1993        });
1994        cx.run_until_parked();
1995        cx.update(|window, cx| window.draw(cx).clear(cx));
1996        root.read_with(cx, |root, cx| {
1997            let style = &root.0.read(cx).text_view_style;
1998            let marker = style.list_style();
1999            assert_eq!(marker.text.color, Some(gpui::blue()));
2000            assert_eq!(marker.text.font_weight, Some(gpui::FontWeight::BOLD));
2001            let quote = style.blockquote_style();
2002            assert_eq!(quote.border_color, Some(gpui::blue()));
2003            assert_eq!(quote.border_widths.left, Some(px(4.).into()));
2004        });
2005    }
2006
2007    impl TextViewTestRoot {
2008        fn new(text: &str, cx: &mut Context<Self>) -> Self {
2009            let text = text.to_string();
2010            let text_view = cx.new(|cx| TextViewState::markdown(&text, cx));
2011            Self { text_view }
2012        }
2013    }
2014
2015    impl Render for TextViewTestRoot {
2016        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2017            div()
2018                .w(px(160.))
2019                .child(
2020                    div()
2021                        .h(px(24.))
2022                        .overflow_hidden()
2023                        .child(TextView::new(&self.text_view).selectable(true)),
2024                )
2025                .child(div().h(px(40.)).child("footer"))
2026        }
2027    }
2028
2029    struct TableSelectionTestRoot {
2030        text_view: Entity<TextViewState>,
2031    }
2032
2033    impl Render for TableSelectionTestRoot {
2034        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2035            div()
2036                .debug_selector(|| "table-selection-root".into())
2037                .w(px(520.))
2038                .child(crate::TextSelectionLayer)
2039                .child(TextView::new(&self.text_view))
2040        }
2041    }
2042
2043    #[gpui::test]
2044    fn table_drag_selection_settles_without_requesting_idle_frames(cx: &mut TestAppContext) {
2045        cx.update(crate::init);
2046        let (_, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
2047            text_view: cx.new(|cx| {
2048                TextViewState::markdown(
2049                    "| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
2050                    cx,
2051                )
2052            }),
2053        });
2054        let cx: &mut VisualTestContext = cx;
2055
2056        cx.run_until_parked();
2057        let bounds = cx
2058            .debug_bounds("table-selection-root")
2059            .expect("table bounds");
2060        let start = point(bounds.left() + px(24.), bounds.top() + px(16.));
2061        let end = point(bounds.right() - px(24.), bounds.bottom() - px(16.));
2062        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2063        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2064        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2065
2066        assert!(cx.update(|window, cx| crate::TextSelection::has_selection(window, cx)));
2067        assert_eq!(
2068            cx.update(|window, cx| window.simulate_next_frame(cx)),
2069            0,
2070            "finished table selection must not continuously request frames"
2071        );
2072    }
2073
2074    /// A drag that starts in a table cell selects only in that cell, also when
2075    /// the pointer leaves the cell. A drag that starts outside the table still
2076    /// selects through it.
2077    #[gpui::test]
2078    fn table_drag_from_a_cell_stays_in_that_cell(cx: &mut TestAppContext) {
2079        cx.update(crate::init);
2080        let (root, cx) = cx.add_window_view(|_, cx| TableSelectionTestRoot {
2081            text_view: cx.new(|cx| {
2082                TextViewState::markdown(
2083                    "Intro\n\n| Header 1 | Header 2 |\n| --- | --- |\n| Cell A | Cell B |\n| Cell C | Cell D |",
2084                    cx,
2085                )
2086            }),
2087        });
2088        let cx: &mut VisualTestContext = cx;
2089        cx.run_until_parked();
2090        cx.update(|window, cx| window.draw(cx).clear(cx));
2091
2092        let text_bounds = root.read_with(cx, |root, cx| {
2093            root.text_view.read(cx).selection_adapter.text_bounds()
2094        });
2095        assert_eq!(text_bounds.len(), 7, "{text_bounds:?}");
2096        let [intro, _, _, cell_a, cell_b, _, cell_d] = text_bounds[..] else {
2097            unreachable!()
2098        };
2099        let table = cx
2100            .debug_bounds("table-selection-root")
2101            .expect("table bounds");
2102        let start_of = |bounds: Bounds<Pixels>| point(bounds.left() + px(0.1), bounds.center().y);
2103        let end_of = |bounds: Bounds<Pixels>| point(bounds.right() - px(0.1), bounds.center().y);
2104
2105        let mut drag = |start, end| {
2106            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2107            cx.update(|window, cx| window.draw(cx).clear(cx));
2108            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2109            cx.update(|window, cx| window.draw(cx).clear(cx));
2110            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2111            cx.update(|window, cx| window.draw(cx).clear(cx));
2112            let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2113            let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2114            (selected.trim().to_string(), copied.trim().to_string())
2115        };
2116
2117        // Down and right, out of the table: the rest of the cell, nothing else.
2118        let below = point(table.right() - px(2.), table.bottom() - px(1.));
2119        let expected = ("Cell A".to_string(), "Cell A".to_string());
2120        assert_eq!(drag(start_of(cell_a), below), expected);
2121
2122        // Back along its line into the cell before it, and up and out of the
2123        // table: the start of the cell, nothing else.
2124        let expected = ("Cell B".to_string(), "Cell B".to_string());
2125        let left = point(cell_a.center().x, cell_b.center().y);
2126        assert_eq!(drag(end_of(cell_b), left), expected);
2127        let above = point(table.left() + px(2.), intro.top());
2128        assert_eq!(drag(end_of(cell_b), above), expected);
2129
2130        // From the paragraph before the table, the selection goes through it.
2131        let (selected, copied) = drag(start_of(intro), end_of(cell_d));
2132        for text in ["Intro", "Header 1", "Cell A", "Cell B", "Cell C", "Cell D"] {
2133            assert!(selected.contains(text), "{text} not in {selected:?}");
2134            assert!(copied.contains(text), "{text} not in {copied:?}");
2135        }
2136
2137        // Copy before the frame that paints the last move: Copy projects the
2138        // selection itself and keeps it in the cell too.
2139        cx.simulate_mouse_down(start_of(cell_a), MouseButton::Left, Modifiers::default());
2140        cx.update(|window, cx| window.draw(cx).clear(cx));
2141        cx.simulate_mouse_move(end_of(cell_a), MouseButton::Left, Modifiers::default());
2142        cx.update(|window, cx| window.draw(cx).clear(cx));
2143        cx.simulate_mouse_move(below, MouseButton::Left, Modifiers::default());
2144        cx.simulate_mouse_up(below, MouseButton::Left, Modifiers::default());
2145        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2146        assert_eq!(copied.trim(), "Cell A");
2147    }
2148
2149    /// Text in a right-aligned or centered column is selected where it is
2150    /// painted: a drag over it selects it, and the highlight covers it.
2151    #[gpui::test]
2152    fn table_drag_selects_aligned_cell_text_where_it_is_painted(cx: &mut TestAppContext) {
2153        const SELECTION: u32 = 0xf020b0;
2154
2155        struct AlignedTableRoot {
2156            text_view: Entity<TextViewState>,
2157        }
2158
2159        impl Render for AlignedTableRoot {
2160            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2161                // The underline is painted under the glyphs, so it shows
2162                // where the text is drawn.
2163                div()
2164                    .w(px(520.))
2165                    .underline()
2166                    .child(crate::TextSelectionLayer)
2167                    .child(TextView::new(&self.text_view).style(
2168                        TextViewStyle::default().with_selection(gpui::rgb(SELECTION).into()),
2169                    ))
2170            }
2171        }
2172
2173        cx.update(crate::init);
2174        let (root, cx) = cx.add_window_view(|_, cx| AlignedTableRoot {
2175            text_view: cx.new(|cx| {
2176                TextViewState::markdown(
2177                    "| Quarterly revenue | Review status |\n| ---: | :---: |\n| 42 | ok |",
2178                    cx,
2179                )
2180            }),
2181        });
2182        let cx: &mut VisualTestContext = cx;
2183        cx.run_until_parked();
2184        cx.update(|window, cx| window.draw(cx).clear(cx));
2185
2186        let mut underlines = cx.update(|window, _| {
2187            let scale_factor = window.scale_factor();
2188            window
2189                .painted_underlines()
2190                .into_iter()
2191                .map(|underline| underline.bounds.map(|value| px(value.0 / scale_factor)))
2192                .collect::<Vec<_>>()
2193        });
2194        underlines.sort_by(|a, b| {
2195            (a.top(), a.left())
2196                .partial_cmp(&(b.top(), b.left()))
2197                .expect("finite bounds")
2198        });
2199        let [right_head, center_head, right, center] = underlines[..] else {
2200            panic!("expected one underline per cell, got {underlines:?}");
2201        };
2202        // The body text is narrower than its header, so it is drawn at the
2203        // end or in the middle of its column.
2204        assert!((right.right() - right_head.right()).abs() < px(1.));
2205        assert!(right.left() > right_head.left() + px(1.));
2206        assert!((center.center().x - center_head.center().x).abs() < px(1.));
2207        assert!(center.left() > center_head.left() + px(1.));
2208
2209        for (underline, expected) in [(right, "42"), (center, "ok")] {
2210            // A few pixels above the underline is inside the text's line.
2211            let y = underline.top() - px(4.);
2212            let start = point(underline.left() + px(0.1), y);
2213            let end = point(underline.right() - px(0.1), y);
2214            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2215            cx.update(|window, cx| window.draw(cx).clear(cx));
2216            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2217            cx.update(|window, cx| window.draw(cx).clear(cx));
2218            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2219            cx.update(|window, cx| window.draw(cx).clear(cx));
2220
2221            let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2222            let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2223            assert_eq!(selected.trim(), expected);
2224            assert_eq!(copied.trim(), expected);
2225            let highlights = cx.update(|window, _| {
2226                let selection: gpui::Background = gpui::rgb(SELECTION).into();
2227                let scale_factor = window.scale_factor();
2228                window
2229                    .painted_quads()
2230                    .into_iter()
2231                    .filter(|quad| quad.background == selection)
2232                    .map(|quad| quad.bounds.map(|value| px(value.0 / scale_factor)))
2233                    .collect::<Vec<_>>()
2234            });
2235            assert!(
2236                highlights.iter().any(|highlight| {
2237                    highlight.left() <= underline.left() + px(1.)
2238                        && highlight.right() >= underline.right() - px(1.)
2239                        && highlight.top() <= y
2240                        && highlight.bottom() >= underline.bottom()
2241                }),
2242                "the highlight {highlights:?} must cover the text above {underline:?}"
2243            );
2244        }
2245    }
2246
2247    struct CellSelectionTestRoot {
2248        text_view: Entity<TextViewState>,
2249        scrollable: bool,
2250    }
2251
2252    impl Render for CellSelectionTestRoot {
2253        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2254            div()
2255                .w(px(520.))
2256                .h(px(400.))
2257                .child(crate::TextSelectionLayer)
2258                .child(TextView::new(&self.text_view).scrollable(self.scrollable))
2259        }
2260    }
2261
2262    #[gpui::test]
2263    fn table_cell_copy_excludes_following_blocks_in_a_scrollable_view(cx: &mut TestAppContext) {
2264        cx.update(crate::init);
2265        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2266            text_view: cx.new(|cx| TextViewState::markdown(
2267                "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |\n\nMiddle paragraph\n\nLast paragraph", cx)),
2268            scrollable: true,
2269        });
2270        cx.run_until_parked();
2271        cx.update(|window, cx| window.draw(cx).clear(cx));
2272        let rows = root.read_with(cx, |root, cx| {
2273            root.text_view.read(cx).selection_adapter.text_bounds()
2274        });
2275        assert_eq!(rows.len(), 6, "{rows:?}");
2276        let start = point(rows[2].left() + px(0.1), rows[2].center().y);
2277        let inside = point(rows[2].right() - px(0.1), rows[2].center().y);
2278        let end = point(rows[5].right() - px(0.1), rows[5].center().y);
2279        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2280        cx.simulate_mouse_move(inside, MouseButton::Left, Modifiers::default());
2281        cx.update(|window, cx| window.draw(cx).clear(cx));
2282        // The copy callback must constrain the logical block range even before paint.
2283        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2284        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2285        for format in [SelectionFormat::Plain, SelectionFormat::Source] {
2286            root.update(cx, |root, cx| {
2287                root.text_view
2288                    .update(cx, |state, cx| state.set_selection_format(format, cx))
2289            });
2290            let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2291            assert_eq!(copied.trim(), "Cell A", "{format:?}");
2292        }
2293        cx.update(|window, cx| window.draw(cx).clear(cx));
2294        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2295        assert_eq!(selected.trim(), "Cell A");
2296    }
2297
2298    #[gpui::test]
2299    fn table_cell_touch_select_all_includes_every_cell(cx: &mut TestAppContext) {
2300        cx.update(crate::init);
2301        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2302            text_view: cx.new(|cx| {
2303                TextViewState::markdown(
2304                    "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
2305                    cx,
2306                )
2307            }),
2308            scrollable: false,
2309        });
2310        cx.run_until_parked();
2311        cx.update(|window, cx| window.draw(cx).clear(cx));
2312        let rows = root.read_with(cx, |root, cx| {
2313            root.text_view.read(cx).selection_adapter.text_bounds()
2314        });
2315        let position = rows[2].center();
2316        for phase in [gpui::TouchPhase::Started, gpui::TouchPhase::Ended] {
2317            cx.simulate_event(gpui::LongPressEvent {
2318                phase,
2319                start_position: position,
2320                position,
2321            });
2322        }
2323        cx.update(|window, cx| {
2324            window.draw(cx).clear(cx);
2325            crate::TextSelection::select_all(window, cx);
2326            window.draw(cx).clear(cx);
2327        });
2328        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2329        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2330        for text in ["Header", "Other", "Cell A", "Cell B"] {
2331            assert!(selected.contains(text), "{selected:?}");
2332            assert!(copied.contains(text), "{copied:?}");
2333        }
2334    }
2335
2336    #[gpui::test]
2337    fn table_cell_selection_does_not_leak_into_another_window(cx: &mut TestAppContext) {
2338        cx.update(crate::init);
2339        let start = {
2340            let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2341                text_view: cx.new(|cx| {
2342                    TextViewState::markdown(
2343                        "| Header | Other |\n| --- | --- |\n| Cell A | Cell B |",
2344                        cx,
2345                    )
2346                }),
2347                scrollable: false,
2348            });
2349            cx.run_until_parked();
2350            cx.update(|window, cx| window.draw(cx).clear(cx));
2351            let rows = root.read_with(cx, |root, cx| {
2352                root.text_view.read(cx).selection_adapter.text_bounds()
2353            });
2354            let start = point(rows[0].left() + px(0.1), rows[0].center().y);
2355            let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2356            cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2357            cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2358            cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2359            cx.update(|window, cx| window.draw(cx).clear(cx));
2360            assert_eq!(
2361                cx.update(|window, cx| crate::TextSelection::selected_text(window, cx))
2362                    .trim(),
2363                "Header"
2364            );
2365            start
2366        };
2367        let (root, cx) = cx.add_window_view(|_, cx| CellSelectionTestRoot {
2368            text_view: cx.new(|cx| TextViewState::markdown("ordinary text in another window", cx)),
2369            scrollable: false,
2370        });
2371        cx.run_until_parked();
2372        cx.update(|window, cx| window.draw(cx).clear(cx));
2373        let rows = root.read_with(cx, |root, cx| {
2374            root.text_view.read(cx).selection_adapter.text_bounds()
2375        });
2376        assert!(rows[0].contains(&start), "{start:?}, {rows:?}");
2377        let end = point(rows[0].right() - px(0.1), rows[0].center().y);
2378        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
2379        cx.simulate_mouse_move(end, MouseButton::Left, Modifiers::default());
2380        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
2381        cx.update(|window, cx| window.draw(cx).clear(cx));
2382        let selected = root.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
2383        let copied = cx.update(|window, cx| crate::TextSelection::selected_text(window, cx));
2384        assert!(!selected.trim().is_empty());
2385        assert_eq!(copied, selected);
2386    }
2387
2388    struct InlineImageTextViewTestRoot {
2389        text_view: Entity<TextViewState>,
2390    }
2391
2392    impl InlineImageTextViewTestRoot {
2393        fn new(cx: &mut Context<Self>) -> Self {
2394            let text_view = cx.new(|cx| {
2395                TextViewState::markdown(
2396                    "Build Status ![inline image](https://example.com/image.svg) after",
2397                    cx,
2398                )
2399            });
2400            Self { text_view }
2401        }
2402    }
2403
2404    impl Render for InlineImageTextViewTestRoot {
2405        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2406            div()
2407                .w(px(420.))
2408                .child(TextView::new(&self.text_view).selectable(true))
2409        }
2410    }
2411
2412    #[gpui::test]
2413    fn inline_image_keeps_surrounding_text_on_same_line(cx: &mut TestAppContext) {
2414        cx.update(crate::init);
2415        let (content, cx) = cx.add_window_view(|_, cx| InlineImageTextViewTestRoot::new(cx));
2416        let cx: &mut VisualTestContext = cx;
2417
2418        cx.run_until_parked();
2419        cx.update(|window, cx| {
2420            let _ = window.draw(cx);
2421        });
2422
2423        let inline_bounds = content.read_with(cx, |content, cx| {
2424            content.text_view.read(cx).selection_adapter.text_bounds()
2425        });
2426
2427        assert_eq!(inline_bounds.len(), 2);
2428        assert_eq!(
2429            inline_bounds[0].top(),
2430            inline_bounds[1].top(),
2431            "text before and after an inline image should share a rendered line"
2432        );
2433        assert!(
2434            inline_bounds[1].left() - inline_bounds[0].right() > px(8.),
2435            "inline image should reserve horizontal space in the text layout"
2436        );
2437        assert!(
2438            inline_bounds[1].left() - inline_bounds[0].right() < px(40.),
2439            "unloaded inline image fallback should stay generic and compact"
2440        );
2441    }
2442
2443    #[gpui::test]
2444    fn inline_html_image_after_newline_does_not_panic(cx: &mut TestAppContext) {
2445        cx.update(crate::init);
2446        let (_, cx) = cx.add_window_view(|_, cx| {
2447            TextViewTestRoot::new(
2448                "Hi\n[<img src=\"https://example.com/image.svg\">](https://google.com/)",
2449                cx,
2450            )
2451        });
2452        let cx: &mut VisualTestContext = cx;
2453
2454        cx.run_until_parked();
2455        cx.update(|window, cx| {
2456            let _ = window.draw(cx);
2457        });
2458    }
2459
2460    struct FittedListTestRoot {
2461        text_view: Entity<TextViewState>,
2462        width: Pixels,
2463    }
2464
2465    impl Render for FittedListTestRoot {
2466        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2467            div()
2468                .w(self.width)
2469                .flex()
2470                .flex_col()
2471                .items_end()
2472                .text_size(px(16.))
2473                .child(crate::TextSelectionLayer)
2474                .child(
2475                    div()
2476                        .debug_selector(|| "fitted-list".into())
2477                        .flex()
2478                        .flex_col()
2479                        .min_w_0()
2480                        .max_w_full()
2481                        .p_4()
2482                        .child(TextView::new(&self.text_view).selectable(true)),
2483                )
2484        }
2485    }
2486
2487    fn fitted_list_bounds(
2488        source: &str,
2489        width: f32,
2490        cx: &mut TestAppContext,
2491    ) -> (Bounds<Pixels>, Vec<Bounds<Pixels>>) {
2492        let (root, cx) = cx.add_window_view(|_, cx| FittedListTestRoot {
2493            text_view: cx.new(|cx| TextViewState::markdown(source, cx)),
2494            width: px(width),
2495        });
2496        cx.run_until_parked();
2497        cx.update(|window, cx| window.draw(cx).clear(cx));
2498        let bubble = cx.debug_bounds("fitted-list").unwrap();
2499        let rows = root.read_with(cx, |root, cx| {
2500            root.text_view.read(cx).selection_adapter.text_bounds()
2501        });
2502        assert!(!rows.is_empty(), "list text must be painted: {source:?}");
2503        for row in &rows {
2504            assert!(
2505                row.left() >= bubble.left() && row.right() <= bubble.right(),
2506                "text must remain visible inside the fitted container: {source:?}, {bubble:?}, {row:?}"
2507            );
2508        }
2509        (bubble, rows)
2510    }
2511
2512    #[gpui::test]
2513    fn fitted_lists_include_their_body_width(cx: &mut TestAppContext) {
2514        cx.update(crate::init);
2515        let (plain, _) = fitted_list_bounds("Hello world", 600., cx);
2516        for source in [
2517            "3. Hello world",
2518            "- Hello world",
2519            "- [ ] Hello world",
2520            "- [x] Hello world",
2521            "Intro\n\n- Hello world",
2522            "- Outer\n  - Hello world",
2523        ] {
2524            let (bubble, _) = fitted_list_bounds(source, 600., cx);
2525            assert!(
2526                bubble.size.width > plain.size.width,
2527                "the marker must leave room for the full body: {source:?}, {bubble:?}, {plain:?}"
2528            );
2529        }
2530    }
2531
2532    #[gpui::test]
2533    fn fitted_lists_wrap_their_body_within_the_available_width(cx: &mut TestAppContext) {
2534        cx.update(crate::init);
2535        let body = "Visible text that wraps without being clipped. ".repeat(12);
2536        for width in [600., 180.] {
2537            for prefix in ["3. ", "- ", "- [ ] ", "- [x] ", "- Outer\n  - "] {
2538                let (bubble, rows) = fitted_list_bounds(&format!("{prefix}{body}"), width, cx);
2539                assert!(bubble.size.width <= px(width));
2540                assert!(rows.len() > 1, "the body must wrap: {prefix:?}, {width}");
2541            }
2542        }
2543    }
2544
2545    #[gpui::test]
2546    fn list_item_renders_fenced_code_block_at_document_width(cx: &mut TestAppContext) {
2547        struct ListItemBlockRoot;
2548
2549        impl Render for ListItemBlockRoot {
2550            fn render(
2551                &mut self,
2552                _window: &mut Window,
2553                _cx: &mut Context<Self>,
2554            ) -> impl IntoElement {
2555                div().w(px(840.)).h(px(400.)).child(
2556                    crate::h_resizable("markdown-width-test")
2557                        .child(crate::resizable_panel().child(div()))
2558                        .child(crate::resizable_panel().child(
2559                            TextView::markdown(
2560                                "list-with-code",
2561                                "1. List item\n   ```rust\n   nested code\n   ```\n\n```rust\ntop-level code\n```",
2562                            )
2563                            .code_block_actions(|code_block, _, _| {
2564                                let selector = if code_block.code().contains("nested") {
2565                                    "nested-code-action"
2566                                } else {
2567                                    "top-level-code-action"
2568                                };
2569                                div()
2570                                    .debug_selector(move || selector.into())
2571                                    .child("Copy")
2572                            })
2573                            .scrollable(true)
2574                            .p_5()
2575                            .flex_none(),
2576                        )),
2577                )
2578            }
2579        }
2580
2581        cx.update(crate::init);
2582        let (_, cx) = cx.add_window_view(|_, _| ListItemBlockRoot);
2583        let cx: &mut VisualTestContext = cx;
2584
2585        cx.run_until_parked();
2586        cx.update(|window, cx| {
2587            let _ = window.draw(cx);
2588        });
2589
2590        let nested_action = cx.debug_bounds("nested-code-action").unwrap();
2591        let top_level_action = cx.debug_bounds("top-level-code-action").unwrap();
2592        assert!(
2593            top_level_action.right() - nested_action.right() < px(32.),
2594            "nested code block should fill the list item's available width"
2595        );
2596    }
2597
2598    /// Height cap of the scrolling code block in [`ScrollingCodeRoot`].
2599    const CODE_HEIGHT: Pixels = px(60.);
2600
2601    struct ScrollingCodeRoot {
2602        text_view: Entity<TextViewState>,
2603        actions: bool,
2604    }
2605
2606    impl Render for ScrollingCodeRoot {
2607        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2608            let mut code_block = StyleRefinement::default().max_h(CODE_HEIGHT);
2609            code_block.overflow.y = Some(Overflow::Scroll);
2610
2611            div().w(px(320.)).h(px(200.)).child(
2612                TextView::new(&self.text_view)
2613                    .style(TextViewStyle::default().with_code_block(code_block))
2614                    .when(self.actions, |this| {
2615                        this.code_block_actions(|_, _, _| {
2616                            div().debug_selector(|| "code-action".into()).child("Copy")
2617                        })
2618                    })
2619                    .scrollable(true),
2620            )
2621        }
2622    }
2623
2624    #[gpui::test]
2625    fn scrolling_code_block_keeps_wheel_from_the_list(cx: &mut TestAppContext) {
2626        cx.update(crate::init);
2627        let code = (0..50).map(|i| format!("line {i}\n")).collect::<String>();
2628        let tail = "Paragraph after the code.\n\n".repeat(20);
2629        let markdown = format!("```\n{code}```\n\n{tail}");
2630
2631        // Scrolling must not depend on `code_block_actions`, which is what
2632        // gives a non-scrolling block its id.
2633        for actions in [false, true] {
2634            let (root, cx) = cx.add_window_view(|_, cx| ScrollingCodeRoot {
2635                text_view: cx.new(|cx| TextViewState::markdown(&markdown, cx)),
2636                actions,
2637            });
2638            let cx: &mut VisualTestContext = cx;
2639            let draw = |cx: &mut VisualTestContext| {
2640                cx.run_until_parked();
2641                cx.update(|window, cx| window.draw(cx).clear(cx));
2642            };
2643            let step = px(20.);
2644            let wheel_at = |cx: &mut VisualTestContext, y: Pixels| {
2645                cx.simulate_event(gpui::ScrollEvent {
2646                    position: point(px(20.), y),
2647                    delta: gpui::ScrollDelta::Pixels(point(px(0.), -step)),
2648                    ..Default::default()
2649                });
2650            };
2651            // The code block is first in the view, and painted lines are
2652            // clipped to its viewport: the first code line's bottom moves with
2653            // the code, the first line below the viewport moves with the list.
2654            let edges = |cx: &mut VisualTestContext| {
2655                let lines = root.read_with(cx, |root, cx| {
2656                    root.text_view.read(cx).selection_adapter.text_bounds()
2657                });
2658                let paragraph = lines.iter().find(|line| line.top() >= CODE_HEIGHT).unwrap();
2659                (lines[0].bottom(), paragraph.top())
2660            };
2661            draw(cx);
2662            let (code_bottom, paragraph_top) = edges(cx);
2663            let action = cx.debug_bounds("code-action");
2664
2665            // Over the code block: the code scrolls, the list and the pinned
2666            // actions stay put.
2667            wheel_at(cx, CODE_HEIGHT / 2.);
2668            draw(cx);
2669            assert_eq!(
2670                edges(cx),
2671                (code_bottom - step, paragraph_top),
2672                "actions: {actions}"
2673            );
2674            assert_eq!(cx.debug_bounds("code-action"), action);
2675
2676            // Below the code block the list still scrolls. Only inequality
2677            // holds: once the paragraph moves into the code's band, `edges`
2678            // picks the next one down.
2679            wheel_at(cx, CODE_HEIGHT * 2.5);
2680            draw(cx);
2681            assert_ne!(edges(cx).1, paragraph_top, "actions: {actions}");
2682        }
2683    }
2684
2685    /// Draw a Markdown table with a `table_actions` hook installed, and return
2686    /// the painted bounds of the actions element plus the data it received.
2687    /// `scroll` opts into the horizontally scrollable table layout.
2688    fn draw_table_with_actions(
2689        cx: &mut TestAppContext,
2690        scroll: bool,
2691    ) -> (Bounds<Pixels>, TableData) {
2692        use std::sync::{Arc, Mutex};
2693
2694        struct TableRoot {
2695            scroll: bool,
2696            captured: Arc<Mutex<Vec<TableData>>>,
2697        }
2698
2699        impl Render for TableRoot {
2700            fn render(
2701                &mut self,
2702                _window: &mut Window,
2703                _cx: &mut Context<Self>,
2704            ) -> impl IntoElement {
2705                let captured = self.captured.clone();
2706                let mut table_style = StyleRefinement::default();
2707                if self.scroll {
2708                    table_style.overflow.x = Some(Overflow::Scroll);
2709                }
2710
2711                div().w(px(320.)).child(
2712                    TextView::markdown(
2713                        "table-actions",
2714                        "| Name | Age |\n|:--|--:|\n| Alice | 30 |\n| Bob | 41 |",
2715                    )
2716                    .style(TextViewStyle::default().with_table(table_style))
2717                    .table_actions(move |table, _, _| {
2718                        if let Ok(mut captured) = captured.lock() {
2719                            captured.push(table.clone());
2720                        }
2721                        div().debug_selector(|| "table-action".into()).child("Copy")
2722                    }),
2723                )
2724            }
2725        }
2726
2727        cx.update(crate::init);
2728        let captured = Arc::new(Mutex::new(Vec::new()));
2729        let (_, cx) = cx.add_window_view({
2730            let captured = captured.clone();
2731            move |_, _| TableRoot { scroll, captured }
2732        });
2733        let cx: &mut VisualTestContext = cx;
2734
2735        cx.run_until_parked();
2736        cx.update(|window, cx| {
2737            let _ = window.draw(cx);
2738        });
2739
2740        let bounds = cx
2741            .debug_bounds("table-action")
2742            .expect("table actions should be painted");
2743        let data = captured
2744            .lock()
2745            .expect("captured table data")
2746            .last()
2747            .cloned()
2748            .expect("table actions hook should receive the table");
2749
2750        (bounds, data)
2751    }
2752
2753    #[gpui::test]
2754    fn table_actions_render_below_the_table(cx: &mut TestAppContext) {
2755        for scroll in [false, true] {
2756            let (bounds, data) = draw_table_with_actions(cx, scroll);
2757
2758            // Header plus two data rows are painted above the actions row.
2759            assert!(
2760                bounds.top() > px(40.),
2761                "actions should sit below the table (scroll: {scroll}), got {:?}",
2762                bounds.top()
2763            );
2764            assert_eq!(data.headers, vec!["Name", "Age"]);
2765            assert_eq!(data.rows, vec![vec!["Alice", "30"], vec!["Bob", "41"]]);
2766            assert_eq!(
2767                data.markdown,
2768                "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n| Bob | 41 |"
2769            );
2770            assert_eq!(data.span, Some(0..52));
2771        }
2772    }
2773
2774    /// A task under each list marker, one of them nested.
2775    const TASK_LIST: &str =
2776        "- [ ] Open\n  - [x] Nested\n* [X] Star\n+ [ ] Plus\n1. [x] One\n2) [ ] Two\n";
2777    const TASK_LABELS: [&str; 6] = ["Open", "Nested", "Star", "Plus", "One", "Two"];
2778
2779    type TaskToggles = Arc<std::sync::Mutex<Vec<TaskToggleEvent>>>;
2780
2781    struct TaskListTestRoot {
2782        text_view: Entity<TextViewState>,
2783        toggles: Option<TaskToggles>,
2784        container_clicks: Arc<AtomicUsize>,
2785    }
2786
2787    impl Render for TaskListTestRoot {
2788        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2789            let container_clicks = self.container_clicks.clone();
2790            div()
2791                .id("task-list-container")
2792                .w(px(300.))
2793                .text_size(px(16.))
2794                .on_click(move |_, _, _| {
2795                    container_clicks.fetch_add(1, Ordering::Relaxed);
2796                })
2797                .child(crate::TextSelectionLayer)
2798                .child(TextView::new(&self.text_view).when_some(
2799                    self.toggles.clone(),
2800                    |this, toggles| {
2801                        this.on_task_toggle(move |event, _, _| {
2802                            toggles.lock().unwrap().push(event.clone());
2803                        })
2804                    },
2805                ))
2806        }
2807    }
2808
2809    /// Clicks the checkbox of each item of [`TASK_LIST`], then the text of
2810    /// its first item, and returns how many clicks reached the container.
2811    fn click_task_list(toggles: Option<TaskToggles>, cx: &mut TestAppContext) -> usize {
2812        cx.update(crate::init);
2813        let container_clicks = Arc::new(AtomicUsize::new(0));
2814        let (root, cx) = cx.add_window_view({
2815            let container_clicks = container_clicks.clone();
2816            move |_, cx| TaskListTestRoot {
2817                text_view: cx.new(|cx| TextViewState::markdown(TASK_LIST, cx)),
2818                toggles,
2819                container_clicks,
2820            }
2821        });
2822        cx.run_until_parked();
2823        cx.update(|window, cx| window.draw(cx).clear(cx));
2824        let text = |label: &str, cx: &mut VisualTestContext| {
2825            root.read_with(cx, |root, cx| {
2826                root.text_view
2827                    .read(cx)
2828                    .selection_adapter
2829                    .text_position(label, 0)
2830            })
2831        };
2832        for label in TASK_LABELS {
2833            // The checkbox sits just before the item's text.
2834            let checkbox = text(label, cx) - point(px(16.), px(0.));
2835            cx.simulate_click(checkbox, Modifiers::default());
2836            cx.update(|window, cx| window.draw(cx).clear(cx));
2837        }
2838        let open = text("Open", cx);
2839        cx.simulate_click(open, Modifiers::default());
2840        container_clicks.load(Ordering::Relaxed)
2841    }
2842
2843    #[gpui::test]
2844    fn task_checkbox_click_reports_its_new_state_item_and_marker(cx: &mut TestAppContext) {
2845        let toggles = TaskToggles::default();
2846        let container_clicks = click_task_list(Some(toggles.clone()), cx);
2847
2848        let reported: Vec<_> = toggles
2849            .lock()
2850            .unwrap()
2851            .iter()
2852            .map(|event| (event.checked(), event.item_range(), event.marker_range()))
2853            .collect();
2854        let task = |checked, item: &str, marker: &str| {
2855            let item_start = TASK_LIST.find(item).unwrap();
2856            let marker_start = item_start + item.find(marker).unwrap();
2857            (
2858                checked,
2859                item_start..item_start + item.len(),
2860                marker_start..marker_start + marker.len(),
2861            )
2862        };
2863        assert_eq!(
2864            reported,
2865            vec![
2866                task(true, "- [ ] Open\n  - [x] Nested", "[ ]"),
2867                task(false, "- [x] Nested", "[x]"),
2868                task(false, "* [X] Star", "[X]"),
2869                task(true, "+ [ ] Plus", "[ ]"),
2870                task(false, "1. [x] One", "[x]"),
2871                task(true, "2) [ ] Two", "[ ]"),
2872            ],
2873            "each checkbox reports the flipped state, its item with any nested \
2874             list and exactly its `[ ]` / `[x]`, and a click on the item text \
2875             toggles nothing",
2876        );
2877        assert_eq!(
2878            container_clicks, 1,
2879            "only the click on the text reaches the container"
2880        );
2881    }
2882
2883    #[gpui::test]
2884    fn task_checkboxes_without_a_handler_are_not_interactive(cx: &mut TestAppContext) {
2885        let container_clicks = click_task_list(None, cx);
2886
2887        assert_eq!(
2888            container_clicks,
2889            TASK_LABELS.len() + 1,
2890            "every click, including those on a checkbox, reaches the container"
2891        );
2892    }
2893
2894    #[test]
2895    fn plugin_accepts_text_view_plugins_beyond_markdown() {
2896        let view = TextView::markdown("plugin-test", "").plugin(DummyTextViewPlugin);
2897
2898        assert!(view.selectable);
2899    }
2900
2901    #[test]
2902    fn syntax_highlighting_is_opt_in() {
2903        let default_view = TextView::markdown("default-code", "```rust\nfn main() {}\n```");
2904        assert!(default_view.code_block_highlighter.is_none());
2905
2906        let view = default_view.code_block_highlighter(|block| {
2907            vec![(
2908                0..block.code().len(),
2909                gpui::HighlightStyle {
2910                    color: Some(gpui::rgb(0x3366ff).into()),
2911                    ..Default::default()
2912                },
2913            )]
2914        });
2915        assert!(view.code_block_highlighter.is_some());
2916    }
2917
2918    #[gpui::test]
2919    fn clipped_markdown_link_does_not_open(cx: &mut TestAppContext) {
2920        cx.update(crate::init);
2921        let (_, cx) = cx.add_window_view(|_, cx| {
2922            TextViewTestRoot::new("visible\n\n[hidden](https://example.com)", cx)
2923        });
2924        let cx: &mut VisualTestContext = cx;
2925
2926        cx.simulate_click(point(px(10.), px(34.)), Modifiers::default());
2927
2928        assert_eq!(cx.opened_url(), None);
2929    }
2930
2931    struct MaxLinesTestRoot {
2932        text_view: Entity<TextViewState>,
2933        max_lines: usize,
2934    }
2935
2936    impl MaxLinesTestRoot {
2937        fn new(text: &str, max_lines: usize, cx: &mut Context<Self>) -> Self {
2938            let text_view = cx.new(|cx| TextViewState::markdown(text, cx));
2939            Self {
2940                text_view,
2941                max_lines,
2942            }
2943        }
2944    }
2945
2946    impl Render for MaxLinesTestRoot {
2947        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2948            div()
2949                .w(px(200.))
2950                .child(TextView::new(&self.text_view).max_lines(self.max_lines))
2951        }
2952    }
2953
2954    #[test]
2955    fn the_clip_only_moves_for_a_straddling_glyph_line() {
2956        use super::line_safe_clip_bottom;
2957        use crate::text::state::LineSpan;
2958
2959        let spans = [
2960            // Lines end at 20 / 40 / 60.
2961            LineSpan {
2962                top: px(0.),
2963                bottom: px(60.),
2964                line_height: px(20.),
2965            },
2966            // A second block after an 8px gap; lines end at 88 / 108 / 128.
2967            LineSpan {
2968                top: px(68.),
2969                bottom: px(128.),
2970                line_height: px(20.),
2971            },
2972        ];
2973
2974        // Content continues well past the box in every case but the last.
2975        let below = px(400.);
2976
2977        // A box ending inside the line 88..108 leaves that line out whole.
2978        assert_eq!(
2979            line_safe_clip_bottom(&spans, px(100.), below),
2980            Some(px(88.))
2981        );
2982
2983        // A box ending on a line boundary has nothing to pull the clip up for.
2984        assert_eq!(line_safe_clip_bottom(&spans, px(88.), below), None);
2985
2986        // A strip below the last line shorter than a line — the border and
2987        // padding a block leads with — is not worth showing.
2988        assert_eq!(line_safe_clip_bottom(&spans, px(64.), below), Some(px(60.)));
2989
2990        // One taller than a line is: whatever crosses the edge keeps the part
2991        // that fits rather than leaving the box half empty.
2992        let one_block = [LineSpan {
2993            top: px(0.),
2994            bottom: px(60.),
2995            line_height: px(20.),
2996        }];
2997        assert_eq!(line_safe_clip_bottom(&one_block, px(200.), below), None);
2998
2999        // Nothing crosses the edge at all: the space under the last line is
3000        // the box's own, not a scrap of something below.
3001        assert_eq!(line_safe_clip_bottom(&spans, px(130.), px(128.)), None);
3002    }
3003
3004    #[test]
3005    fn a_line_taller_than_the_budget_keeps_the_part_that_fits() {
3006        use super::line_safe_clip_bottom;
3007        use crate::text::state::LineSpan;
3008
3009        // A heading line of 28px, in a box capped at one 26px body line.
3010        let heading = [LineSpan {
3011            top: px(70.),
3012            bottom: px(98.),
3013            line_height: px(28.),
3014        }];
3015
3016        assert_eq!(line_safe_clip_bottom(&heading, px(96.), px(400.)), None);
3017    }
3018
3019    #[test]
3020    fn the_clip_does_not_stop_on_a_row_of_border_and_padding() {
3021        use super::line_safe_clip_bottom;
3022        use crate::text::state::LineSpan;
3023
3024        // Two table rows, each one line of text, 9px of border and padding
3025        // between them.
3026        let rows = [
3027            LineSpan {
3028                top: px(100.),
3029                bottom: px(126.),
3030                line_height: px(26.),
3031            },
3032            LineSpan {
3033                top: px(135.),
3034                bottom: px(161.),
3035                line_height: px(26.),
3036            },
3037        ];
3038
3039        // Leaving out the second row's text would strand the 9px it leads
3040        // with, so the clip goes back to the row above it.
3041        assert_eq!(
3042            line_safe_clip_bottom(&rows, px(148.), px(400.)),
3043            Some(px(126.))
3044        );
3045    }
3046
3047    /// A clamped view nested the way an application nests one: inside a card,
3048    /// inside a region that fills a window of a known height. The height an
3049    /// ancestor hands down must not reach the clamped content and hide the
3050    /// overflow the clamp measures — with the content stretched to the capped
3051    /// box, nothing looks clipped and lines get cut in half.
3052    struct ClampedPageRoot {
3053        text_view: Entity<TextViewState>,
3054        max_lines: usize,
3055    }
3056
3057    impl Render for ClampedPageRoot {
3058        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3059            use crate::{h_flex, v_flex};
3060
3061            v_flex()
3062                .size_full()
3063                .p_4()
3064                .gap_4()
3065                .child(h_flex().max_w(px(480.)).gap_3().child("header"))
3066                .child(
3067                    v_flex()
3068                        .flex_1()
3069                        .min_h_0()
3070                        .gap_4()
3071                        .id("clamped-page-scroll")
3072                        .child(
3073                            v_flex()
3074                                .max_w(px(480.))
3075                                .p_3()
3076                                .gap_2()
3077                                .child(TextView::new(&self.text_view).max_lines(self.max_lines)),
3078                        )
3079                        .overflow_y_scroll(),
3080                )
3081        }
3082    }
3083
3084    #[gpui::test]
3085    fn max_lines_measures_overflow_inside_a_sized_page(cx: &mut TestAppContext) {
3086        cx.update(crate::init);
3087        let (root, cx) = cx.add_window_view(|_, cx| {
3088            let text_view = cx.new(|cx| {
3089                TextViewState::markdown(
3090                    "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth\n\nseventh",
3091                    cx,
3092                )
3093            });
3094            ClampedPageRoot {
3095                text_view,
3096                max_lines: 3,
3097            }
3098        });
3099        let cx: &mut VisualTestContext = cx;
3100
3101        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3102    }
3103
3104    #[gpui::test]
3105    fn max_lines_clamps_overflowing_content(cx: &mut TestAppContext) {
3106        cx.update(crate::init);
3107        let (root, cx) = cx.add_window_view(|_, cx| {
3108            MaxLinesTestRoot::new(
3109                "first\n\nsecond\n\nthird\n\nfourth\n\nfifth\n\nsixth",
3110                2,
3111                cx,
3112            )
3113        });
3114        let cx: &mut VisualTestContext = cx;
3115
3116        assert!(root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3117    }
3118
3119    #[gpui::test]
3120    fn max_lines_leaves_short_content_unclamped(cx: &mut TestAppContext) {
3121        cx.update(crate::init);
3122        let (root, cx) = cx.add_window_view(|_, cx| MaxLinesTestRoot::new("only line", 3, cx));
3123        let cx: &mut VisualTestContext = cx;
3124
3125        assert!(!root.read_with(cx, |root, cx| root.text_view.read(cx).is_clamped()));
3126    }
3127
3128    #[gpui::test]
3129    fn heading_refinement_changes_rendered_heading_geometry(cx: &mut TestAppContext) {
3130        struct HeadingStyleRoot;
3131
3132        impl Render for HeadingStyleRoot {
3133            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3134                div()
3135                    .flex()
3136                    .items_start()
3137                    .child(
3138                        div()
3139                            .debug_selector(|| "default-h1".into())
3140                            .child(TextView::markdown("default-h1-view", "# Heading")),
3141                    )
3142                    .child(div().debug_selector(|| "custom-h1".into()).child(
3143                        TextView::markdown("custom-heading-view", "# Heading").style(
3144                            TextViewStyle::default().with_heading(|level| {
3145                                if level == 1 {
3146                                    StyleRefinement::default().pb(rems(2.))
3147                                } else {
3148                                    StyleRefinement::default()
3149                                }
3150                            }),
3151                        ),
3152                    ))
3153                    .child(
3154                        div()
3155                            .debug_selector(|| "default-h2".into())
3156                            .child(TextView::markdown("default-h2-view", "## Heading")),
3157                    )
3158                    .child(div().debug_selector(|| "custom-h2".into()).child(
3159                        TextView::markdown("custom-h2-view", "## Heading").style(
3160                            TextViewStyle::default().with_heading(|level| {
3161                                if level == 1 {
3162                                    StyleRefinement::default().pb(rems(2.))
3163                                } else {
3164                                    StyleRefinement::default()
3165                                }
3166                            }),
3167                        ),
3168                    ))
3169            }
3170        }
3171
3172        cx.update(crate::init);
3173        let (_, cx) = cx.add_window_view(|_, _| HeadingStyleRoot);
3174        cx.update(|window, cx| window.draw(cx).clear(cx));
3175
3176        let default_h1 = cx.debug_bounds("default-h1").unwrap();
3177        let custom_h1 = cx.debug_bounds("custom-h1").unwrap();
3178        let default_h2 = cx.debug_bounds("default-h2").unwrap();
3179        let custom_h2 = cx.debug_bounds("custom-h2").unwrap();
3180        assert!(custom_h1.size.height > default_h1.size.height);
3181        assert_eq!(custom_h2.size.height, default_h2.size.height);
3182    }
3183
3184    #[gpui::test]
3185    fn max_lines_disables_links_hidden_by_the_clamp(cx: &mut TestAppContext) {
3186        cx.update(crate::init);
3187        let (_, cx) = cx.add_window_view(|_, cx| {
3188            MaxLinesTestRoot::new(
3189                "first\n\nsecond\n\nthird\n\n[hidden](https://example.com)",
3190                2,
3191                cx,
3192            )
3193        });
3194        let cx: &mut VisualTestContext = cx;
3195
3196        // Click far below the clamped box, where the link would sit unclamped.
3197        cx.simulate_click(point(px(10.), px(150.)), Modifiers::default());
3198
3199        assert_eq!(cx.opened_url(), None);
3200    }
3201
3202    #[gpui::test]
3203    fn scaled_inline_code_keeps_links_and_drag_selection(cx: &mut TestAppContext) {
3204        struct SelectionRoot {
3205            text_view: Entity<TextViewState>,
3206            format: crate::text::SelectionFormat,
3207        }
3208        impl Render for SelectionRoot {
3209            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3210                div()
3211                    .w(px(160.))
3212                    .child(crate::TextSelectionLayer)
3213                    .child(TextView::new(&self.text_view).selection_format(self.format))
3214            }
3215        }
3216        cx.update(crate::init);
3217        let (view, cx) = cx.add_window_view(|_, cx| SelectionRoot {
3218            format: crate::text::SelectionFormat::Plain,
3219            text_view: cx
3220                .new(|cx| TextViewState::markdown("[`code`](https://example.com) after", cx)),
3221        });
3222        let cx: &mut VisualTestContext = cx;
3223        cx.run_until_parked();
3224        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
3225        assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
3226        // Just past the code span's leading padding, on its first glyph.
3227        cx.simulate_mouse_down(
3228            point(px(5.), px(8.)),
3229            MouseButton::Left,
3230            Modifiers::default(),
3231        );
3232        cx.update(|window, cx| {
3233            let _ = window.draw(cx);
3234        });
3235        cx.simulate_mouse_move(
3236            point(px(155.), px(20.)),
3237            Some(MouseButton::Left),
3238            Modifiers::default(),
3239        );
3240        cx.update(|window, cx| {
3241            let _ = window.draw(cx);
3242        });
3243        cx.simulate_mouse_up(
3244            point(px(155.), px(20.)),
3245            MouseButton::Left,
3246            Modifiers::default(),
3247        );
3248        cx.update(|window, cx| {
3249            let _ = window.draw(cx);
3250        });
3251        let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
3252        assert_eq!(selected.trim(), "code after");
3253        view.update(cx, |view, cx| {
3254            view.format = crate::text::SelectionFormat::Source;
3255            cx.notify();
3256        });
3257        cx.update(|window, cx| {
3258            let _ = window.draw(cx);
3259        });
3260        let selected = view.read_with(cx, |view, cx| view.text_view.read(cx).selected_text());
3261        assert_eq!(selected.trim(), "[`code`](https://example.com) after");
3262    }
3263
3264    /// Inline-code Markdown takes the deferred `InlineFlow` path. Its layout
3265    /// must use the heading's resolved typography rather than the ambient body
3266    /// style that remains after the heading's style stack has been popped.
3267    ///
3268    /// This is a real request-layout → measured-layout → prepaint → paint test:
3269    /// the deterministic text system makes bold glyphs wider than body glyphs.
3270    /// Before the fix, the code heading was allocated using normal body metrics
3271    /// but its fragments painted bold, so the wrapped heading text crossed into
3272    /// the following paragraph.
3273    #[test]
3274    fn inline_code_heading_reserves_painted_wrapped_lines_and_list_baseline() {
3275        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3276        use gpui::{TestApp, rems};
3277
3278        const MARKDOWN: &str = "The same words with inline code.\n\nThe same words with `inline code`.\n\n- The same words with inline code.\n- The same words with `inline code`.\n\n# Heading with inline code\n# Heading with `inline code`\n\nthis is a test";
3279
3280        struct MarkdownRoot {
3281            text_view: Entity<TextViewState>,
3282            width: Pixels,
3283            preview_zoom: f32,
3284        }
3285
3286        impl Render for MarkdownRoot {
3287            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3288                div()
3289                    .w(self.width)
3290                    // Match example-markdown: preview zoom changes TextView's
3291                    // inherited text size, not the window rem size.
3292                    .text_size(rems(self.preview_zoom))
3293                    .child(crate::TextSelectionLayer)
3294                    .child(TextView::new(&self.text_view).selectable(true))
3295            }
3296        }
3297
3298        fn draw(
3299            app: &mut TestApp,
3300            width: Pixels,
3301            preview_zoom: f32,
3302        ) -> (Bounds<Pixels>, Vec<Bounds<Pixels>>, String) {
3303            let mut window = app.open_window(|_, cx| MarkdownRoot {
3304                text_view: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
3305                width,
3306                preview_zoom,
3307            });
3308            window.draw();
3309            app.run_until_parked();
3310            window.draw();
3311            window.update(|root, _, cx| {
3312                root.text_view.update(cx, |state, cx| state.select_all(cx));
3313            });
3314            window.draw();
3315            window.read(|root, cx| {
3316                let state = root.text_view.read(cx);
3317                (
3318                    state.bounds(),
3319                    state.selection_adapter.text_bounds(),
3320                    state.selected_text(),
3321                )
3322            })
3323        }
3324
3325        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3326        app.update(|cx| {
3327            crate::init(cx);
3328            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3329        });
3330
3331        for (case, width, preview_zoom) in [
3332            // At the root 16px size the plain heading fits, while bold inline
3333            // fragments need their own measured widths.
3334            ("default-16px", px(600.), 1.),
3335            // A narrow view exercises intentional heading wrapping.
3336            ("narrow-16px", px(320.), 1.),
3337            // Preview zoom applies through `.text_size(rems(zoom))`.
3338            ("zoom-1.25", px(600.), 1.25),
3339        ] {
3340            let (view_bounds, text_bounds, selected_text) = draw(&mut app, width, preview_zoom);
3341            assert!(
3342                text_bounds.len() > 8,
3343                "{case}: expected all markdown fragments"
3344            );
3345            assert_eq!(
3346                selected_text.trim(),
3347                "The same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nThe same words with inline code.\nHeading with inline code\nHeading with inline code\nthis is a test",
3348                "{case}: wrapped inline-code text was lost or duplicated"
3349            );
3350            let following = text_bounds.last().expect("following paragraph must paint");
3351            let painted_bottom = text_bounds
3352                .iter()
3353                .map(|bounds| bounds.bottom())
3354                .max()
3355                .expect("markdown must paint text");
3356            // This is intentionally not a fragment-count or selection-only
3357            // assertion: `text_bounds` are the shaped Inline layouts produced
3358            // during paint. No painted wrapped line may reach the following
3359            // paragraph's origin, and the TextView allocation must contain the
3360            // complete painted document.
3361            assert!(
3362                text_bounds[..text_bounds.len() - 1]
3363                    .iter()
3364                    .all(|bounds| bounds.bottom() <= following.top()),
3365                "{case}: heading/list text painted through the following paragraph;                  following={following:?}, text_bounds={text_bounds:?}, view={view_bounds:?}"
3366            );
3367            assert!(
3368                painted_bottom <= view_bounds.bottom(),
3369                "{case}: TextView height did not reserve its painted text;                  painted_bottom={painted_bottom:?}, view={view_bounds:?}"
3370            );
3371        }
3372    }
3373
3374    #[test]
3375    fn ordered_markdown_list_start_reaches_layout_marker() {
3376        use crate::text::inline::test_fonts::{WideMonoTextSystem, record_shaped_lines};
3377        use gpui::TestApp;
3378
3379        struct MarkdownRoot {
3380            text_view: Entity<TextViewState>,
3381        }
3382
3383        impl Render for MarkdownRoot {
3384            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3385                div().w(px(400.)).child(TextView::new(&self.text_view))
3386            }
3387        }
3388
3389        #[derive(Clone, Copy)]
3390        enum Format {
3391            Markdown,
3392            Html,
3393        }
3394
3395        fn shaped_markers(format: Format, source: &str) -> Vec<String> {
3396            let (_, shaped_lines) = record_shaped_lines(|| {
3397                let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3398                app.update(crate::init);
3399                let mut window = app.open_window(|_, cx| MarkdownRoot {
3400                    text_view: cx.new(|cx| match format {
3401                        Format::Markdown => TextViewState::markdown(source, cx),
3402                        Format::Html => TextViewState::html(source, cx),
3403                    }),
3404                });
3405                window.draw();
3406                app.run_until_parked();
3407                window.draw();
3408            });
3409
3410            let mut markers = shaped_lines
3411                .into_iter()
3412                .filter(|line| line.len() <= 3 && line.ends_with('.'))
3413                .collect::<Vec<_>>();
3414            markers.dedup();
3415            markers
3416        }
3417
3418        let starts_at_one = "1. one\n2. two";
3419        assert_eq!(
3420            shaped_markers(Format::Markdown, starts_at_one),
3421            ["1.", "2."]
3422        );
3423        assert_eq!(
3424            shaped_markers(Format::Html, "<ol><li>one</li><li>two</li></ol>"),
3425            ["1.", "2."]
3426        );
3427
3428        assert_eq!(
3429            shaped_markers(Format::Markdown, "3. hello\n4. world"),
3430            ["3.", "4."]
3431        );
3432
3433        let nested_starts_at_four = "1. outer\n\n   4. nested\n   5. again";
3434        assert_eq!(
3435            shaped_markers(Format::Markdown, nested_starts_at_four),
3436            ["1.", "D.", "E."]
3437        );
3438
3439        let nested_starts_at_zero = "1. outer\n\n   0. zero";
3440        assert_eq!(
3441            shaped_markers(Format::Markdown, nested_starts_at_zero),
3442            ["1.", "0."]
3443        );
3444    }
3445
3446    /// A line with inline code takes `InlineFlow` and a plain line takes the
3447    /// ordinary text path; both must be the same height, or a list with one
3448    /// code item is unevenly spaced (#3162). The fractional scale factor and
3449    /// zooms give line heights that are not whole logical pixels.
3450    #[test]
3451    fn inline_code_line_is_as_tall_as_a_plain_line() {
3452        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3453        use gpui::{TestApp, rems};
3454
3455        struct LineRoot {
3456            plain: Entity<TextViewState>,
3457            code: Entity<TextViewState>,
3458            preview_zoom: f32,
3459        }
3460
3461        impl Render for LineRoot {
3462            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3463                div()
3464                    .w(px(600.))
3465                    .text_size(rems(self.preview_zoom))
3466                    .child(TextView::new(&self.plain))
3467                    .child(TextView::new(&self.code))
3468            }
3469        }
3470
3471        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3472        app.update(|cx| {
3473            crate::init(cx);
3474            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3475        });
3476        for scale_factor in [1.6, 2.] {
3477            for preview_zoom in [1., 1.25] {
3478                let mut window = app.open_window(|_, cx| LineRoot {
3479                    plain: cx.new(|cx| TextViewState::markdown("plain body words", cx)),
3480                    code: cx.new(|cx| TextViewState::markdown("plain `code` words", cx)),
3481                    preview_zoom,
3482                });
3483                window.simulate_scale_factor_change(scale_factor);
3484                window.draw();
3485                app.run_until_parked();
3486                window.draw();
3487                let (plain, code) = window.read(|root, cx| {
3488                    (
3489                        root.plain.read(cx).bounds().size.height,
3490                        root.code.read(cx).bounds().size.height,
3491                    )
3492                });
3493                assert_eq!(code, plain, "scale {scale_factor}, zoom {preview_zoom}");
3494            }
3495        }
3496    }
3497
3498    /// The code-bearing list item takes `InlineFlow`; the plain item takes the
3499    /// ordinary text path. Their first body glyphs must begin at the same row
3500    /// position relative to their own TextView origins.
3501    #[test]
3502    fn inline_code_list_body_paint_origin_matches_plain_list_item() {
3503        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3504        use gpui::{TestApp, rems};
3505
3506        struct ListRoot {
3507            plain: Entity<TextViewState>,
3508            code: Entity<TextViewState>,
3509            preview_zoom: f32,
3510        }
3511
3512        impl Render for ListRoot {
3513            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3514                div()
3515                    .w(px(600.))
3516                    .text_size(rems(self.preview_zoom))
3517                    .child(crate::TextSelectionLayer)
3518                    .child(TextView::new(&self.plain).selectable(true))
3519                    .child(TextView::new(&self.code).selectable(true))
3520            }
3521        }
3522
3523        fn draw(app: &mut TestApp, preview_zoom: f32) -> (Pixels, Pixels) {
3524            let mut window = app.open_window(|_, cx| ListRoot {
3525                plain: cx.new(|cx| TextViewState::markdown("- plain body words", cx)),
3526                code: cx.new(|cx| TextViewState::markdown("- plain `code` words", cx)),
3527                preview_zoom,
3528            });
3529            window.draw();
3530            app.run_until_parked();
3531            window.draw();
3532            window.read(|root, cx| {
3533                let first_body_line_top = |view: &Entity<TextViewState>| {
3534                    let view = view.read(cx);
3535                    let painted_line = view
3536                        .selection_adapter
3537                        .text_bounds()
3538                        .into_iter()
3539                        .next()
3540                        .expect("list item should paint its first body line");
3541                    painted_line.top() - view.bounds().top()
3542                };
3543                (
3544                    first_body_line_top(&root.plain),
3545                    first_body_line_top(&root.code),
3546                )
3547            })
3548        }
3549
3550        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3551        app.update(|cx| {
3552            crate::init(cx);
3553            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3554        });
3555        for (case, preview_zoom) in [("16px", 1.), ("zoom-1.25", 1.25), ("zoom-1.5", 1.5)] {
3556            let (plain_origin, code_origin) = draw(&mut app, preview_zoom);
3557            assert_eq!(
3558                code_origin, plain_origin,
3559                "{case}: code list body paint origin {code_origin:?} must match plain {plain_origin:?}"
3560            );
3561        }
3562    }
3563
3564    #[test]
3565    fn inline_code_fragment_does_not_paint_past_its_reserved_row() {
3566        use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
3567        use gpui::TestApp;
3568
3569        const TEXT_BACKGROUND: u32 = 0x20f0b0;
3570
3571        struct MarkdownRoot {
3572            text_view: Entity<TextViewState>,
3573        }
3574
3575        impl Render for MarkdownRoot {
3576            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3577                div()
3578                    .w(px(640.))
3579                    .text_size(px(17.9))
3580                    .text_bg(gpui::rgb(TEXT_BACKGROUND))
3581                    .child(TextView::new(&self.text_view))
3582            }
3583        }
3584
3585        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3586        app.update(|cx| {
3587            crate::init(cx);
3588            crate::Theme::global_mut(cx).tokens.typography.mono = MONO.into();
3589        });
3590        let mut window = app.open_window(|_, cx| MarkdownRoot {
3591            text_view: cx.new(|cx| TextViewState::markdown("`main` starts the paragraph", cx)),
3592        });
3593        window.draw();
3594        app.run_until_parked();
3595        window.draw();
3596
3597        let (view_bounds, painted) = window.update(|root, window, cx| {
3598            let view_bounds = root
3599                .text_view
3600                .read(cx)
3601                .bounds()
3602                .scale(window.scale_factor());
3603            let text_background: gpui::Background = gpui::rgb(TEXT_BACKGROUND).into();
3604            let painted = window
3605                .painted_quads()
3606                .into_iter()
3607                .filter(|quad| quad.background == text_background)
3608                .map(|quad| quad.bounds)
3609                .collect::<Vec<_>>();
3610            (view_bounds, painted)
3611        });
3612
3613        assert!(
3614            !painted.is_empty(),
3615            "the inherited text background must make actual text paint observable"
3616        );
3617        assert!(
3618            painted
3619                .iter()
3620                .all(|bounds| bounds.bottom() <= view_bounds.bottom()),
3621            "an inline-code fragment wrapped a second time after InlineFlow reserved one row; \
3622             text background quads={painted:?}, reserved TextView bounds={view_bounds:?}"
3623        );
3624    }
3625
3626    #[test]
3627    fn table_row_backgrounds_follow_the_frame_corner_radius() {
3628        use gpui::TestApp;
3629
3630        const HEAD_BACKGROUND: u32 = 0x11aa77;
3631        const RADIUS: f32 = 8.;
3632
3633        struct RoundedTableRoot {
3634            text_view: Entity<TextViewState>,
3635            scroll: bool,
3636        }
3637
3638        impl Render for RoundedTableRoot {
3639            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3640                let mut table = StyleRefinement::default();
3641                table.corner_radii.top_left = Some(px(RADIUS).into());
3642                table.corner_radii.top_right = Some(px(RADIUS).into());
3643                table.corner_radii.bottom_left = Some(px(RADIUS).into());
3644                table.corner_radii.bottom_right = Some(px(RADIUS).into());
3645                if self.scroll {
3646                    table.overflow.x = Some(gpui::Overflow::Scroll);
3647                }
3648                let style = TextViewStyle::default()
3649                    .with_code_background(gpui::rgb(HEAD_BACKGROUND).into())
3650                    .with_table(table);
3651                div()
3652                    .w(px(400.))
3653                    .child(TextView::new(&self.text_view).style(style))
3654            }
3655        }
3656
3657        for scroll in [false, true] {
3658            let mode = if scroll { "scroll" } else { "wrap" };
3659            let mut app = TestApp::new();
3660            app.update(crate::init);
3661            let mut window = app.open_window(|_, cx| RoundedTableRoot {
3662                text_view: cx
3663                    .new(|cx| TextViewState::markdown("| a | b |\n| --- | --- |\n| 1 | 2 |", cx)),
3664                scroll,
3665            });
3666            window.draw();
3667            app.run_until_parked();
3668            window.draw();
3669
3670            let (quad, scale) = window.update(|_, window, _| {
3671                let head: gpui::Background = gpui::rgb(HEAD_BACKGROUND).into();
3672                let quad = window
3673                    .painted_quads()
3674                    .into_iter()
3675                    .find(|quad| quad.background == head)
3676                    .unwrap_or_else(|| panic!("{mode}: the header background quad is painted"));
3677                (quad, window.scale_factor())
3678            });
3679
3680            // GPUI clips children with a rectangular mask, so the header fill
3681            // must carry the frame radius itself, inset by the 1px border.
3682            let expected = px(RADIUS - 1.).scale(scale);
3683            assert_eq!(quad.corner_radii.top_left, expected, "{mode}: top left");
3684            assert_eq!(quad.corner_radii.top_right, expected, "{mode}: top right");
3685            let square = px(0.).scale(scale);
3686            assert_eq!(quad.corner_radii.bottom_left, square, "{mode}: bottom left");
3687            assert_eq!(
3688                quad.corner_radii.bottom_right, square,
3689                "{mode}: bottom right"
3690            );
3691        }
3692    }
3693
3694    /// A table body row under the pointer takes the hover background and the
3695    /// header does not. Every row of every table keeps its own hover state, so
3696    /// each move onto or off a row notifies the view, even a move between the
3697    /// same row of two tables.
3698    #[test]
3699    fn table_body_row_under_the_pointer_takes_the_hover_background() {
3700        use gpui::TestApp;
3701        use std::{cell::Cell, rc::Rc};
3702
3703        const HEAD_BACKGROUND: u32 = 0x11aa77;
3704        const ROW_HOVER: u32 = 0x7711aa;
3705
3706        struct HoverTableRoot {
3707            text_view: Entity<TextViewState>,
3708            scroll: bool,
3709        }
3710
3711        impl Render for HoverTableRoot {
3712            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3713                let mut table = StyleRefinement::default();
3714                if self.scroll {
3715                    table.overflow.x = Some(Overflow::Scroll);
3716                }
3717                let style = TextViewStyle::default()
3718                    .with_code_background(gpui::rgb(HEAD_BACKGROUND).into())
3719                    .with_table(table)
3720                    .with_table_row_hover(gpui::rgb(ROW_HOVER).into());
3721                div()
3722                    .w(px(400.))
3723                    .child(TextView::new(&self.text_view).style(style))
3724            }
3725        }
3726
3727        let table = "| a | b |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |";
3728        let source = format!("{table}\n\nBetween\n\n{table}");
3729        for scroll in [false, true] {
3730            let mode = if scroll { "scroll" } else { "wrap" };
3731            let mut app = TestApp::new();
3732            app.update(crate::init);
3733            let mut window = app.open_window(|_, cx| HoverTableRoot {
3734                text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
3735                scroll,
3736            });
3737            window.draw();
3738            app.run_until_parked();
3739            window.draw();
3740
3741            // The text view's own view paints the rows, so it is the one
3742            // their hover notifies.
3743            let notifications = Rc::new(Cell::new(0));
3744            let text_view = window.update(|root, _, _| root.text_view.clone());
3745            app.update(|cx| {
3746                let notifications = notifications.clone();
3747                cx.observe(&text_view, move |_, _| {
3748                    notifications.set(notifications.get() + 1)
3749                })
3750                .detach();
3751            });
3752
3753            // The header rows, top to bottom, in logical pixels.
3754            let (heads, scale) = window.update(|_, window, _| {
3755                let scale = window.scale_factor();
3756                let head: gpui::Background = gpui::rgb(HEAD_BACKGROUND).into();
3757                let mut heads = window
3758                    .painted_quads()
3759                    .into_iter()
3760                    .filter(|quad| quad.background == head)
3761                    .map(|quad| quad.bounds.map(|value| px(value.as_f32() / scale)))
3762                    .collect::<Vec<_>>();
3763                heads.sort_by_key(|bounds| bounds.origin.y);
3764                (heads, scale)
3765            });
3766            assert_eq!(heads.len(), 2, "{mode}: two header rows");
3767            let first_body_row =
3768                |head: Bounds<Pixels>| point(head.center().x, head.bottom() + px(4.));
3769            let first_head = heads[0].center();
3770            let first_row = first_body_row(heads[0]);
3771            let second_row = first_body_row(heads[1]);
3772            let outside = point(px(600.), first_row.y);
3773
3774            for (step, position, highlighted) in [
3775                ("first table's body row", first_row, true),
3776                ("first table's header", first_head, false),
3777                ("second table's body row", second_row, true),
3778                ("same row of the first table", first_row, true),
3779                ("outside the tables", outside, false),
3780            ] {
3781                let before = notifications.get();
3782                window.simulate_mouse_move(position);
3783                assert!(
3784                    notifications.get() > before,
3785                    "{mode}: moving onto the {step} notifies the view"
3786                );
3787                window.draw();
3788
3789                let hovered = window.update(|_, window, _| {
3790                    let hover: gpui::Background = gpui::rgb(ROW_HOVER).into();
3791                    window
3792                        .painted_quads()
3793                        .into_iter()
3794                        .filter(|quad| quad.background == hover)
3795                        .map(|quad| quad.bounds)
3796                        .collect::<Vec<_>>()
3797                });
3798                if highlighted {
3799                    assert_eq!(
3800                        hovered.len(),
3801                        1,
3802                        "{mode}: one row is highlighted on the {step}"
3803                    );
3804                    assert!(
3805                        hovered[0].contains(&position.scale(scale)),
3806                        "{mode}: the {step} is highlighted, not {:?}",
3807                        hovered[0]
3808                    );
3809                } else {
3810                    assert!(
3811                        hovered.is_empty(),
3812                        "{mode}: nothing is highlighted on the {step}"
3813                    );
3814                }
3815            }
3816        }
3817    }
3818
3819    /// A table wider than its frame shrinks its widest column. A narrower
3820    /// column keeps its content width rather than shrinking by the same
3821    /// ratio and wrapping the end of its text onto a line of its own, in the
3822    /// header and the body alike, and with the cell and frame refinements
3823    /// the text renders with.
3824    #[test]
3825    fn table_keeps_narrow_columns_on_one_line_while_wide_ones_wrap() {
3826        use crate::text::inline::test_fonts::WideMonoTextSystem;
3827        use gpui::TestApp;
3828        use std::sync::Arc;
3829
3830        const CELL_BACKGROUND: u32 = 0x11aa77;
3831
3832        struct TableRoot {
3833            text_view: Entity<TextViewState>,
3834            width: Pixels,
3835            style: TextViewStyle,
3836        }
3837
3838        impl Render for TableRoot {
3839            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3840                div()
3841                    .w(self.width)
3842                    .child(TextView::new(&self.text_view).style(self.style.clone()))
3843            }
3844        }
3845
3846        let short = "Operating revenue (USD)";
3847        let source = format!(
3848            "| {short} | Note |\n| --- | --- |\n| {short} | x |\n| 1 | {} |",
3849            "word ".repeat(30)
3850        );
3851        // Heights of the first column's cells, top to bottom.
3852        let first_column = |width: f32, style: TextViewStyle| {
3853            let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
3854            app.update(crate::init);
3855            let cell = style.table_cell().clone().bg(gpui::rgb(CELL_BACKGROUND));
3856            let style = style.with_table_cell(cell);
3857            let mut window = app.open_window(|_, cx| TableRoot {
3858                text_view: cx.new(|cx| TextViewState::markdown(&source, cx)),
3859                width: px(width),
3860                style,
3861            });
3862            window.draw();
3863            app.run_until_parked();
3864            window.draw();
3865            window.update(|_, window, _| {
3866                let background: gpui::Background = gpui::rgb(CELL_BACKGROUND).into();
3867                let cells: Vec<_> = window
3868                    .painted_quads()
3869                    .into_iter()
3870                    .filter(|quad| quad.background == background)
3871                    .map(|quad| quad.bounds)
3872                    .collect();
3873                let left = cells.iter().map(|bounds| bounds.origin.x).min().unwrap();
3874                let mut column: Vec<_> = cells
3875                    .into_iter()
3876                    .filter(|bounds| bounds.origin.x == left)
3877                    .collect();
3878                column.sort_by_key(|bounds| bounds.origin.y);
3879                column
3880                    .iter()
3881                    .map(|bounds| bounds.size.height)
3882                    .collect::<Vec<_>>()
3883            })
3884        };
3885        let scroll = || {
3886            let mut table = StyleRefinement::default();
3887            table.overflow.x = Some(gpui::Overflow::Scroll);
3888            TextViewStyle::default().with_table(table)
3889        };
3890
3891        for (layout, style) in [("wrap", TextViewStyle::default()), ("scroll", scroll())] {
3892            let fits = first_column(4000., style.clone());
3893            let narrow = first_column(700., style);
3894            assert_eq!(fits.len(), 3, "{layout}: three rows");
3895            assert_eq!(fits[0], fits[2], "{layout}: the header fits on one line");
3896            assert_eq!(narrow[..2], fits[..2], "{layout}: the short column wraps");
3897        }
3898
3899        let single_line = first_column(4000., TextViewStyle::default())[0];
3900        let padded = TextViewStyle::default().with_table_cell(StyleRefinement::default().px_4());
3901        assert_eq!(
3902            first_column(4000., padded)[0],
3903            single_line,
3904            "the cell padding refinement leaves the text its measured width"
3905        );
3906        let bold = TextViewStyle::default()
3907            .with_table(StyleRefinement::default().font_weight(gpui::FontWeight::BOLD));
3908        assert_eq!(
3909            first_column(4000., bold)[0],
3910            single_line,
3911            "the table text refinement is measured"
3912        );
3913    }
3914
3915    #[gpui::test]
3916    fn link_tooltip_shows_on_one_of_two_renderings_of_a_document(cx: &mut TestAppContext) {
3917        struct Preview;
3918        impl Render for Preview {
3919            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3920                div()
3921                    .debug_selector(|| "link-destination-preview".into())
3922                    .child("/tmp/report.json")
3923            }
3924        }
3925        struct Twice {
3926            view: Entity<TextViewState>,
3927        }
3928        impl Render for Twice {
3929            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3930                div()
3931                    .child(
3932                        TextView::new(&self.view)
3933                            .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
3934                    )
3935                    .child(
3936                        TextView::new(&self.view)
3937                            .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
3938                    )
3939            }
3940        }
3941        cx.update(crate::init);
3942        let (root, cx) = cx.add_window_view(|_, cx| Twice {
3943            view: cx.new(|cx| {
3944                TextViewState::markdown("[preview destination](file:///tmp/report.json)", cx)
3945            }),
3946        });
3947        cx.run_until_parked();
3948        cx.update(|window, cx| window.draw(cx).clear(cx));
3949        let bounds = root.read_with(cx, |root, cx| {
3950            root.view.read(cx).selection_adapter.text_bounds()[0]
3951        });
3952        let start = point(bounds.left() + px(2.), bounds.center().y);
3953        cx.update(|window, cx| window.simulate_mouse_move(start, cx));
3954        cx.run_until_parked();
3955        let mut requested = 0;
3956        for _ in 0..3 {
3957            cx.update(|window, cx| window.draw(cx).clear(cx));
3958            requested = cx.update(|window, cx| window.simulate_next_frame(cx));
3959            cx.run_until_parked();
3960        }
3961        assert_eq!(requested, 0, "a settled hover stops redrawing");
3962        cx.update(|window, cx| window.draw(cx).clear(cx));
3963        assert!(
3964            cx.debug_bounds("link-destination-preview").is_some(),
3965            "the hovered rendering shows its destination"
3966        );
3967    }
3968
3969    #[gpui::test]
3970    fn link_tooltip_follows_the_pointer_and_clears_on_exit(cx: &mut TestAppContext) {
3971        struct Preview;
3972        impl Render for Preview {
3973            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3974                div()
3975                    .debug_selector(|| "link-destination-preview".into())
3976                    .w(px(180.))
3977                    .h(px(24.))
3978                    .child("/tmp/report.json")
3979            }
3980        }
3981        struct Root {
3982            view: Entity<TextViewState>,
3983            covered: bool,
3984        }
3985        impl Render for Root {
3986            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3987                div()
3988                    .relative()
3989                    .child(
3990                        TextView::new(&self.view)
3991                            .w(px(160.))
3992                            .link_tooltip(|_, _, cx| cx.new(|_| Preview).into()),
3993                    )
3994                    .when(self.covered, |view| {
3995                        view.child(div().absolute().top_0().left_0().size_full().occlude())
3996                    })
3997            }
3998        }
3999        cx.update(crate::init);
4000        let (root, cx) = cx.add_window_view(|_, cx| Root {
4001            covered: true,
4002            view: cx.new(|cx| {
4003                TextViewState::markdown("[preview destination with a label that wraps over several lines](file:///tmp/report.json)", cx)
4004            }),
4005        });
4006        cx.run_until_parked();
4007        cx.update(|window, cx| window.draw(cx).clear(cx));
4008        let rows = root.read_with(cx, |root, cx| {
4009            root.view.read(cx).selection_adapter.text_bounds()
4010        });
4011        assert!(rows.len() > 1, "the native link label wraps");
4012        let bounds = rows[0];
4013        let start = point(bounds.left() + px(2.), bounds.center().y);
4014        cx.update(|window, cx| window.simulate_mouse_move(start, cx));
4015        cx.run_until_parked();
4016        cx.update(|window, cx| window.draw(cx).clear(cx));
4017        assert!(
4018            cx.debug_bounds("link-destination-preview").is_none(),
4019            "an occluded link cannot activate a preview"
4020        );
4021        root.update(cx, |root, cx| {
4022            root.covered = false;
4023            cx.notify();
4024        });
4025        cx.run_until_parked();
4026        cx.update(|window, cx| window.draw(cx).clear(cx));
4027        assert_eq!(
4028            cx.update(|window, cx| window.simulate_next_frame(cx)),
4029            1,
4030            "a new hover requests the frame that shows its preview",
4031        );
4032        cx.run_until_parked();
4033        cx.update(|window, cx| window.draw(cx).clear(cx));
4034        let first = cx
4035            .debug_bounds("link-destination-preview")
4036            .expect("hovering a native link paints its destination preview");
4037        assert_eq!(
4038            cx.update(|window, cx| window.simulate_next_frame(cx)),
4039            0,
4040            "an idle preview does not request more frames",
4041        );
4042        cx.update(|window, cx| window.simulate_mouse_move(start + point(px(20.), px(0.)), cx));
4043        cx.run_until_parked();
4044        cx.update(|window, cx| window.draw(cx).clear(cx));
4045        let second = cx.debug_bounds("link-destination-preview").unwrap();
4046        assert_eq!(second.left() - first.left(), px(20.));
4047        assert_eq!(second.top(), first.top());
4048        cx.update(|window, cx| window.simulate_mouse_move(rows[1].center(), cx));
4049        cx.run_until_parked();
4050        cx.update(|window, cx| window.draw(cx).clear(cx));
4051        assert!(cx.debug_bounds("link-destination-preview").is_some());
4052        root.update(cx, |root, cx| {
4053            root.covered = true;
4054            cx.notify();
4055        });
4056        cx.run_until_parked();
4057        cx.update(|window, cx| window.draw(cx).clear(cx));
4058        assert!(
4059            cx.debug_bounds("link-destination-preview").is_none(),
4060            "covering an active link clears its preview"
4061        );
4062        root.update(cx, |root, cx| {
4063            root.covered = false;
4064            cx.notify();
4065        });
4066        cx.run_until_parked();
4067        cx.update(|window, cx| {
4068            window.simulate_mouse_move(point(bounds.right() + px(30.), bounds.center().y), cx)
4069        });
4070        cx.run_until_parked();
4071        cx.update(|window, cx| window.draw(cx).clear(cx));
4072        assert!(cx.debug_bounds("link-destination-preview").is_none());
4073    }
4074
4075    #[gpui::test]
4076    fn markdown_link_opens_url_without_handler(cx: &mut TestAppContext) {
4077        cx.update(crate::init);
4078        let (_, cx) =
4079            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
4080        let cx: &mut VisualTestContext = cx;
4081
4082        cx.simulate_click(point(px(10.), px(10.)), Modifiers::default());
4083
4084        assert_eq!(cx.opened_url(), Some("https://example.com".to_string()));
4085    }
4086
4087    #[gpui::test]
4088    fn right_click_does_not_open_url_without_handler(cx: &mut TestAppContext) {
4089        cx.update(crate::init);
4090        let (_, cx) =
4091            cx.add_window_view(|_, cx| TextViewTestRoot::new("[example](https://example.com)", cx));
4092        let cx: &mut VisualTestContext = cx;
4093
4094        cx.simulate_mouse_down(
4095            point(px(10.), px(10.)),
4096            MouseButton::Right,
4097            Modifiers::default(),
4098        );
4099        cx.simulate_mouse_up(
4100            point(px(10.), px(10.)),
4101            MouseButton::Right,
4102            Modifiers::default(),
4103        );
4104
4105        assert_eq!(cx.opened_url(), None);
4106    }
4107
4108    #[gpui::test]
4109    fn link_handler_receives_button_and_modifiers(cx: &mut TestAppContext) {
4110        use std::sync::{Arc, Mutex};
4111
4112        struct LinkRoot {
4113            text_view: Entity<TextViewState>,
4114            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
4115        }
4116
4117        impl Render for LinkRoot {
4118            fn render(
4119                &mut self,
4120                _window: &mut Window,
4121                _cx: &mut Context<Self>,
4122            ) -> impl IntoElement {
4123                let clicks = self.clicks.clone();
4124                div()
4125                    .w(px(240.))
4126                    .child(
4127                        TextView::new(&self.text_view).on_link_click(move |url, event, _, _| {
4128                            clicks.lock().unwrap().push((url.clone(), event.clone()));
4129                        }),
4130                    )
4131            }
4132        }
4133
4134        cx.update(crate::init);
4135        let clicks = Arc::new(Mutex::new(Vec::new()));
4136        let captured = clicks.clone();
4137        let (_, cx) = cx.add_window_view(move |_, cx| LinkRoot {
4138            text_view: cx.new(|cx| TextViewState::markdown("[example](https://example.com)", cx)),
4139            clicks,
4140        });
4141        let cx: &mut VisualTestContext = cx;
4142
4143        let mut modifiers = Modifiers::default();
4144        modifiers.control = true;
4145        cx.simulate_click(point(px(10.), px(10.)), modifiers);
4146        cx.simulate_mouse_down(
4147            point(px(10.), px(10.)),
4148            MouseButton::Middle,
4149            Modifiers::default(),
4150        );
4151        cx.simulate_mouse_up(
4152            point(px(10.), px(10.)),
4153            MouseButton::Middle,
4154            Modifiers::default(),
4155        );
4156        cx.simulate_mouse_down(
4157            point(px(10.), px(10.)),
4158            MouseButton::Right,
4159            Modifiers::default(),
4160        );
4161        cx.simulate_mouse_up(
4162            point(px(10.), px(10.)),
4163            MouseButton::Right,
4164            Modifiers::default(),
4165        );
4166
4167        let clicks = captured.lock().unwrap();
4168        assert_eq!(clicks.len(), 3);
4169        assert_eq!(clicks[0].0, "https://example.com");
4170        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
4171        assert!(clicks[0].1.modifiers().control);
4172        assert!(clicks[1].1.is_middle_click());
4173        assert!(clicks[2].1.is_right_click());
4174        assert_eq!(cx.opened_url(), None);
4175    }
4176
4177    #[gpui::test]
4178    fn inline_object_inherits_bold_and_link_clicks_without_opening_on_drag(
4179        cx: &mut TestAppContext,
4180    ) {
4181        use std::sync::{Arc, Mutex};
4182        struct Root {
4183            state: Entity<TextViewState>,
4184            clicks: Arc<Mutex<Vec<SharedString>>>,
4185        }
4186        impl Render for Root {
4187            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4188                let clicks = self.clicks.clone();
4189                let extensions = crate::text::MarkdownExtensions::default().plugin(
4190                    crate::text::markdown_ext::TestInlinePlugin::new("math")
4191                        .parse_with(|node, _| {
4192                            matches!(node, markdown::mdast::Node::InlineMath(_)).then(|| {
4193                                super::super::MarkdownNode::new("math", ()).text("formula")
4194                            })
4195                        })
4196                        .render_with(|_, context, _, _| {
4197                            assert_eq!(context.text_style().font_weight, gpui::FontWeight::BOLD);
4198                            Some(super::super::InlineElement::new(div().child("formula")))
4199                        }),
4200                );
4201                div().w(px(300.)).child(crate::TextSelectionLayer).child(
4202                    TextView::new(&self.state)
4203                        .markdown_extensions(extensions)
4204                        .on_link_click(move |url, _, _, _| {
4205                            clicks.lock().unwrap().push(url.clone())
4206                        }),
4207                )
4208            }
4209        }
4210        cx.update(crate::init);
4211        let clicks = Arc::new(Mutex::new(Vec::new()));
4212        let captured = clicks.clone();
4213        let (root, cx) = cx.add_window_view(move |_, cx| Root {
4214            state: cx.new(|cx| TextViewState::markdown("**[$x$](https://example.com)**", cx)),
4215            clicks,
4216        });
4217        let cx: &mut VisualTestContext = cx;
4218        cx.run_until_parked();
4219        cx.update(|window, cx| {
4220            let _ = window.draw(cx);
4221        });
4222        let bounds = root.read_with(cx, |root, cx| {
4223            root.state.read(cx).selection_adapter.text_bounds()[0]
4224        });
4225        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
4226            cx.simulate_mouse_down(bounds.center(), button, Modifiers::default());
4227            cx.simulate_mouse_up(bounds.center(), button, Modifiers::default());
4228        }
4229        assert_eq!(captured.lock().unwrap().len(), 3);
4230        let start = point(bounds.left() + px(1.), bounds.center().y);
4231        let end = point(bounds.right() - px(1.), bounds.center().y);
4232        cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::default());
4233        cx.update(|window, cx| {
4234            let _ = window.draw(cx);
4235        });
4236        cx.simulate_mouse_move(end, Some(MouseButton::Left), Modifiers::default());
4237        cx.update(|window, cx| {
4238            let _ = window.draw(cx);
4239        });
4240        cx.simulate_mouse_up(end, MouseButton::Left, Modifiers::default());
4241        assert_eq!(captured.lock().unwrap().len(), 3);
4242    }
4243
4244    #[gpui::test]
4245    fn linked_image_handler_receives_left_middle_and_right_clicks(cx: &mut TestAppContext) {
4246        use std::sync::{Arc, Mutex};
4247
4248        struct LinkedImageRoot {
4249            text_view: Entity<TextViewState>,
4250            clicks: Arc<Mutex<Vec<(SharedString, ClickEvent)>>>,
4251        }
4252
4253        impl Render for LinkedImageRoot {
4254            fn render(
4255                &mut self,
4256                _window: &mut Window,
4257                _cx: &mut Context<Self>,
4258            ) -> impl IntoElement {
4259                let clicks = self.clicks.clone();
4260                div().w(px(160.)).child(
4261                    TextView::new(&self.text_view)
4262                        .selectable(true)
4263                        .on_link_click(move |url, event, _, _| {
4264                            clicks.lock().unwrap().push((url.clone(), event.clone()));
4265                        }),
4266                )
4267            }
4268        }
4269
4270        cx.update(crate::init);
4271        let clicks = Arc::new(Mutex::new(Vec::new()));
4272        let captured = clicks.clone();
4273        let (content, cx) = cx.add_window_view(move |_, cx| LinkedImageRoot {
4274                text_view: cx.new(|cx| {
4275                    TextViewState::markdown(
4276                        r#"Before [<img src="https://example.com/image.svg" width="32" height="32">](https://example.com/image-link) after."#,
4277                        cx,
4278                    )
4279                }),
4280                clicks,
4281            }
4282        );
4283        let cx: &mut VisualTestContext = cx;
4284        cx.run_until_parked();
4285        cx.update(|window, cx| {
4286            let _ = window.draw(cx);
4287        });
4288
4289        let inline_bounds = content.read_with(cx, |content, cx| {
4290            content.text_view.read(cx).selection_adapter.text_bounds()
4291        });
4292        assert!(
4293            inline_bounds.len() >= 2,
4294            "linked image needs text bounds on both sides: {inline_bounds:?}"
4295        );
4296        assert!(
4297            inline_bounds[1].left() - inline_bounds[0].right() >= px(24.),
4298            "linked image did not reserve the expected click target: {inline_bounds:?}"
4299        );
4300        let position = point(
4301            inline_bounds[0].right() + (inline_bounds[1].left() - inline_bounds[0].right()) * 0.5,
4302            inline_bounds[0].top() + px(8.),
4303        );
4304        for button in [MouseButton::Left, MouseButton::Middle, MouseButton::Right] {
4305            cx.simulate_mouse_down(position, button, Modifiers::default());
4306            cx.simulate_mouse_up(position, button, Modifiers::default());
4307        }
4308
4309        let clicks = captured.lock().unwrap();
4310        assert_eq!(clicks.len(), 3);
4311        assert!(
4312            clicks
4313                .iter()
4314                .all(|(url, _)| url == "https://example.com/image-link")
4315        );
4316        assert!(!clicks[0].1.is_right_click() && !clicks[0].1.is_middle_click());
4317        assert!(clicks[1].1.is_middle_click());
4318        assert!(clicks[2].1.is_right_click());
4319        assert_eq!(cx.opened_url(), None);
4320    }
4321
4322    #[gpui::test]
4323    fn clipped_markdown_cannot_start_selection(cx: &mut TestAppContext) {
4324        cx.update(crate::init);
4325        let (view, cx) = cx
4326            .add_window_view(|_, cx| TextViewTestRoot::new("visible\n\nhidden selection text", cx));
4327        let cx: &mut VisualTestContext = cx;
4328
4329        cx.simulate_mouse_down(
4330            point(px(10.), px(34.)),
4331            MouseButton::Left,
4332            Modifiers::default(),
4333        );
4334        cx.simulate_mouse_move(
4335            point(px(90.), px(34.)),
4336            Some(MouseButton::Left),
4337            Modifiers::default(),
4338        );
4339        cx.simulate_mouse_up(
4340            point(px(90.), px(34.)),
4341            MouseButton::Left,
4342            Modifiers::default(),
4343        );
4344
4345        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4346        assert!(
4347            selected_text.is_empty(),
4348            "unexpected selection: {selected_text:?}"
4349        );
4350    }
4351
4352    /// A tall selectable TextView clipped by a short `overflow_hidden` viewport,
4353    /// with a large blank footer below so a drag can extend the selection band
4354    /// past the bottom of the clip while still proxy-anchoring to the view.
4355    struct ClippedTallTextViewTestRoot {
4356        text_view: Entity<TextViewState>,
4357    }
4358
4359    impl ClippedTallTextViewTestRoot {
4360        fn new(cx: &mut Context<Self>) -> Self {
4361            // Four separate blocks; only the first (and maybe part of the
4362            // second) fit inside the 40px clip. "charlie"/"delta" render well
4363            // below it.
4364            let text_view =
4365                cx.new(|cx| TextViewState::markdown("alpha\n\nbravo\n\ncharlie\n\ndelta", cx));
4366            Self { text_view }
4367        }
4368    }
4369
4370    impl Render for ClippedTallTextViewTestRoot {
4371        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
4372            div()
4373                .w(px(200.))
4374                .child(crate::TextSelectionLayer)
4375                .child(
4376                    div()
4377                        .h(px(40.))
4378                        .overflow_hidden()
4379                        .child(TextView::new(&self.text_view).selectable(true)),
4380                )
4381                // A tall blank footer so a drag can reach a y below the clipped
4382                // text; a press there proxy-anchors to the TextView above.
4383                .child(div().h(px(160.)))
4384        }
4385    }
4386
4387    /// Regression for copying a selection taller than the visible viewport.
4388    ///
4389    /// The selection band runs from visible text at the top down to a point
4390    /// far below the clip. Every glyph of the painted TextView is laid out even
4391    /// though the lower ones are clipped away, so the copied text must include
4392    /// the clipped-out "charlie"/"delta" — not just what is on screen. This
4393    /// guards against re-adding a `content_mask` gate in
4394    /// `Inline::layout_selections`.
4395    #[gpui::test]
4396    fn selection_band_beyond_clip_copies_offscreen_text(cx: &mut TestAppContext) {
4397        cx.update(crate::init);
4398        let (content, cx) = cx.add_window_view(|_, cx| ClippedTallTextViewTestRoot::new(cx));
4399        let cx: &mut VisualTestContext = cx;
4400
4401        cx.run_until_parked();
4402        cx.update(|window, cx| {
4403            let _ = window.draw(cx);
4404        });
4405
4406        // Anchor on visible text near the top, then drag to a point well below
4407        // the 40px clip (into the blank footer) and to the far right so the
4408        // last line is fully covered.
4409        cx.simulate_mouse_down(
4410            point(px(2.), px(8.)),
4411            MouseButton::Left,
4412            Modifiers::default(),
4413        );
4414        cx.update(|window, cx| {
4415            let _ = window.draw(cx);
4416        });
4417        cx.simulate_mouse_move(
4418            point(px(180.), px(150.)),
4419            Some(MouseButton::Left),
4420            Modifiers::default(),
4421        );
4422        cx.update(|window, cx| {
4423            let _ = window.draw(cx);
4424        });
4425        cx.simulate_mouse_up(
4426            point(px(180.), px(150.)),
4427            MouseButton::Left,
4428            Modifiers::default(),
4429        );
4430        cx.update(|window, cx| {
4431            let _ = window.draw(cx);
4432        });
4433
4434        let selected_text =
4435            content.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4436        assert!(
4437            selected_text.contains("delta"),
4438            "clipped-out text was not copied: {selected_text:?}"
4439        );
4440        assert!(
4441            selected_text.contains("charlie"),
4442            "clipped-out text was not copied: {selected_text:?}"
4443        );
4444    }
4445
4446    #[gpui::test]
4447    fn double_click_selects_word(cx: &mut TestAppContext) {
4448        cx.update(crate::init);
4449        let (view, cx) =
4450            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
4451
4452        let cx: &mut VisualTestContext = cx;
4453        cx.run_until_parked();
4454        cx.update(|window, cx| {
4455            let _ = window.draw(cx);
4456        });
4457        let position = point(px(10.), px(16.));
4458        cx.simulate_event(MouseDownEvent {
4459            position,
4460            modifiers: Modifiers::default(),
4461            button: MouseButton::Left,
4462            click_count: 2,
4463            first_mouse: false,
4464        });
4465        cx.simulate_event(MouseUpEvent {
4466            position,
4467            modifiers: Modifiers::default(),
4468            button: MouseButton::Left,
4469            click_count: 2,
4470        });
4471        cx.update(|window, cx| {
4472            let _ = window.draw(cx);
4473        });
4474
4475        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4476        assert_eq!(selected_text.trim(), "quick");
4477    }
4478
4479    #[gpui::test]
4480    fn long_press_selects_word_then_drag_extends_selection(cx: &mut TestAppContext) {
4481        struct TouchRoot {
4482            text_view: Entity<TextViewState>,
4483        }
4484        impl Render for TouchRoot {
4485            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4486                div()
4487                    .w(px(300.))
4488                    .child(crate::TextSelectionLayer)
4489                    .child(TextView::new(&self.text_view).selectable(true))
4490            }
4491        }
4492        cx.update(crate::init);
4493        let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
4494            text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
4495        });
4496        cx.run_until_parked();
4497        cx.update(|window, cx| {
4498            let _ = window.draw(cx);
4499        });
4500        let start_position = point(px(10.), px(16.));
4501        cx.simulate_event(gpui::LongPressEvent {
4502            phase: gpui::TouchPhase::Started,
4503            start_position,
4504            position: start_position,
4505        });
4506        cx.update(|window, cx| {
4507            let _ = window.draw(cx);
4508        });
4509        assert_eq!(
4510            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4511                .trim(),
4512            "quick"
4513        );
4514        for phase in [gpui::TouchPhase::Moved, gpui::TouchPhase::Ended] {
4515            cx.simulate_event(gpui::LongPressEvent {
4516                phase,
4517                start_position,
4518                position: point(px(220.), px(16.)),
4519            });
4520        }
4521        cx.update(|window, cx| {
4522            let _ = window.draw(cx);
4523        });
4524        assert_eq!(
4525            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4526                .trim(),
4527            "quick select value"
4528        );
4529    }
4530
4531    #[gpui::test]
4532    fn long_press_release_keeps_handles_which_drag_the_selection(cx: &mut TestAppContext) {
4533        use crate::{SelectionEdge, TextSelection};
4534
4535        struct TouchRoot {
4536            text_view: Entity<TextViewState>,
4537        }
4538        impl Render for TouchRoot {
4539            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4540                div()
4541                    .w(px(300.))
4542                    .child(crate::TextSelectionLayer)
4543                    .child(TextView::new(&self.text_view).selectable(true))
4544            }
4545        }
4546        cx.update(crate::init);
4547        let (view, cx) = cx.add_window_view(|_, cx| TouchRoot {
4548            text_view: cx.new(|cx| TextViewState::markdown("quick select value", cx)),
4549        });
4550        let draw = |cx: &mut VisualTestContext| {
4551            cx.update(|window, cx| {
4552                let _ = window.draw(cx);
4553            });
4554        };
4555        let selected = |cx: &mut VisualTestContext| {
4556            view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text())
4557                .trim()
4558                .to_string()
4559        };
4560        cx.run_until_parked();
4561        draw(cx);
4562
4563        let start_position = point(px(70.), px(16.));
4564        for phase in [gpui::TouchPhase::Started, gpui::TouchPhase::Ended] {
4565            cx.simulate_event(gpui::LongPressEvent {
4566                phase,
4567                start_position,
4568                position: start_position,
4569            });
4570            draw(cx);
4571        }
4572        assert_eq!(selected(cx), "select");
4573        let snapshot = cx
4574            .update(|window, cx| TextSelection::touch_selection(window, cx))
4575            .expect("a released long press keeps its handles");
4576        assert!(snapshot.is_menu_open());
4577        assert!(!snapshot.is_empty());
4578        assert!(snapshot.start().left() < snapshot.end().left());
4579
4580        // Drag the end handle to the end of the line. The finger holds the
4581        // knob below the line, the selection follows along the line.
4582        let end = snapshot.end();
4583        let finger = point(end.left(), end.bottom() + px(20.));
4584        cx.update(|window, cx| {
4585            TextSelection::begin_edge_drag(SelectionEdge::End, finger, window, cx);
4586        });
4587        draw(cx);
4588        let snapshot = cx
4589            .update(|window, cx| TextSelection::touch_selection(window, cx))
4590            .unwrap();
4591        assert_eq!(snapshot.dragging(), Some(SelectionEdge::End));
4592        assert!(!snapshot.is_menu_open());
4593        cx.update(|window, cx| {
4594            TextSelection::update_edge_drag(point(px(290.), finger.y), window, cx);
4595        });
4596        draw(cx);
4597        assert_eq!(selected(cx), "select value");
4598        cx.update(|window, cx| TextSelection::end_edge_drag(window, cx));
4599        draw(cx);
4600        let snapshot = cx
4601            .update(|window, cx| TextSelection::touch_selection(window, cx))
4602            .unwrap();
4603        assert!(snapshot.is_menu_open());
4604        assert_eq!(snapshot.dragging(), None);
4605        let select_start = snapshot.start().left();
4606
4607        // Select All from the menu is a view-local selection; its handles
4608        // still drag, turning it back into a point selection.
4609        cx.update(|_, cx| {
4610            view.update(cx, |root, cx| {
4611                root.text_view.update(cx, |state, cx| state.select_all(cx));
4612            });
4613        });
4614        draw(cx);
4615        assert_eq!(selected(cx), "quick select value");
4616        let snapshot = cx
4617            .update(|window, cx| TextSelection::touch_selection(window, cx))
4618            .expect("select all keeps the touch selection");
4619        let start = snapshot.start();
4620        cx.update(|window, cx| {
4621            TextSelection::begin_edge_drag(SelectionEdge::Start, start.origin, window, cx);
4622            TextSelection::update_edge_drag(point(select_start, start.origin.y), window, cx);
4623            TextSelection::end_edge_drag(window, cx);
4624        });
4625        draw(cx);
4626        assert_eq!(selected(cx), "select value");
4627
4628        // A press on the menu leaves the selection alone; one on the text
4629        // clears it.
4630        let menu = gpui::Bounds::new(point(px(0.), px(200.)), gpui::size(px(120.), px(32.)));
4631        cx.update(|window, cx| TextSelection::register_touch_ui(menu, window, cx));
4632        cx.simulate_event(MouseDownEvent {
4633            position: point(px(10.), px(210.)),
4634            modifiers: Modifiers::default(),
4635            button: MouseButton::Left,
4636            click_count: 1,
4637            first_mouse: false,
4638        });
4639        assert_eq!(selected(cx), "select value");
4640        cx.simulate_event(MouseDownEvent {
4641            position: point(px(10.), px(16.)),
4642            modifiers: Modifiers::default(),
4643            button: MouseButton::Left,
4644            click_count: 1,
4645            first_mouse: false,
4646        });
4647        cx.simulate_event(MouseUpEvent {
4648            position: point(px(10.), px(16.)),
4649            modifiers: Modifiers::default(),
4650            button: MouseButton::Left,
4651            click_count: 1,
4652        });
4653        draw(cx);
4654        assert!(
4655            cx.update(|window, cx| TextSelection::touch_selection(window, cx))
4656                .is_none()
4657        );
4658    }
4659
4660    #[gpui::test]
4661    fn triple_click_selects_paragraph(cx: &mut TestAppContext) {
4662        cx.update(crate::init);
4663        let (view, cx) =
4664            cx.add_window_view(|_, cx| TextViewTestRoot::new("quick select value", cx));
4665
4666        let cx: &mut VisualTestContext = cx;
4667        cx.run_until_parked();
4668        cx.update(|window, cx| {
4669            let _ = window.draw(cx);
4670        });
4671
4672        let position = point(px(10.), px(10.));
4673        cx.simulate_event(MouseDownEvent {
4674            position,
4675            modifiers: Modifiers::default(),
4676            button: MouseButton::Left,
4677            click_count: 3,
4678            first_mouse: false,
4679        });
4680        cx.simulate_event(MouseUpEvent {
4681            position,
4682            modifiers: Modifiers::default(),
4683            button: MouseButton::Left,
4684            click_count: 3,
4685        });
4686        cx.update(|window, cx| {
4687            let _ = window.draw(cx);
4688        });
4689
4690        let selected_text = view.read_with(cx, |root, cx| root.text_view.read(cx).selected_text());
4691        assert_eq!(selected_text.trim(), "quick select value");
4692    }
4693
4694    mod multi_click_drag {
4695        use super::*;
4696
4697        struct Root {
4698            text_view: Entity<TextViewState>,
4699        }
4700
4701        impl Render for Root {
4702            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4703                div()
4704                    .w(px(400.))
4705                    .child(crate::TextSelectionLayer)
4706                    .child(TextView::new(&self.text_view).selectable(true))
4707            }
4708        }
4709
4710        fn setup<'a>(
4711            markdown: &str,
4712            cx: &'a mut TestAppContext,
4713        ) -> (Entity<TextViewState>, &'a mut VisualTestContext) {
4714            cx.update(crate::init);
4715            let (root, cx) = cx.add_window_view(|_, cx| Root {
4716                text_view: cx.new(|cx| TextViewState::markdown(markdown, cx)),
4717            });
4718            cx.run_until_parked();
4719            cx.update(|window, cx| window.draw(cx).clear(cx));
4720            (root.read_with(cx, |root, _| root.text_view.clone()), cx)
4721        }
4722
4723        /// Just inside the character at `index` of the painted `text`.
4724        fn position(
4725            state: &Entity<TextViewState>,
4726            text: &str,
4727            index: usize,
4728            cx: &mut VisualTestContext,
4729        ) -> gpui::Point<Pixels> {
4730            state.read_with(cx, |state, _| {
4731                state.selection_adapter.text_position(text, index)
4732            })
4733        }
4734
4735        fn press(
4736            position: gpui::Point<Pixels>,
4737            click_count: usize,
4738            shift: bool,
4739            cx: &mut VisualTestContext,
4740        ) {
4741            cx.simulate_event(MouseDownEvent {
4742                position,
4743                modifiers: Modifiers {
4744                    shift,
4745                    ..Default::default()
4746                },
4747                button: MouseButton::Left,
4748                click_count,
4749                first_mouse: false,
4750            });
4751        }
4752
4753        fn drag(position: gpui::Point<Pixels>, cx: &mut VisualTestContext) {
4754            cx.simulate_event(gpui::MouseMoveEvent {
4755                position,
4756                pressed_button: Some(MouseButton::Left),
4757                modifiers: Modifiers::default(),
4758            });
4759        }
4760
4761        fn release(position: gpui::Point<Pixels>, click_count: usize, cx: &mut VisualTestContext) {
4762            cx.simulate_event(MouseUpEvent {
4763                position,
4764                modifiers: Modifiers::default(),
4765                button: MouseButton::Left,
4766                click_count,
4767            });
4768        }
4769
4770        fn selected(state: &Entity<TextViewState>, cx: &mut VisualTestContext) -> String {
4771            cx.update(|window, cx| window.draw(cx).clear(cx));
4772            state.read_with(cx, |state, _| state.selected_text().trim().to_string())
4773        }
4774
4775        #[gpui::test]
4776        fn double_click_drag_extends_the_selection_by_words(cx: &mut TestAppContext) {
4777            let (first, second) = ("alpha beta gamma", "delta epsilon zeta");
4778            let (state, cx) = setup(&format!("{first}\n\n{second}"), cx);
4779
4780            press(position(&state, first, 7, cx), 2, false, cx);
4781            assert_eq!(selected(&state, cx), "beta");
4782            drag(position(&state, first, 8, cx), cx);
4783            assert_eq!(selected(&state, cx), "beta");
4784            drag(position(&state, first, 13, cx), cx);
4785            assert_eq!(selected(&state, cx), "beta gamma");
4786            // Backward, the whole of the word the drag started from stays.
4787            drag(position(&state, first, 1, cx), cx);
4788            assert_eq!(selected(&state, cx), "alpha beta");
4789            let end = position(&state, second, 8, cx);
4790            drag(end, cx);
4791            assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
4792            release(end, 2, cx);
4793            assert_eq!(selected(&state, cx), "beta gamma\ndelta epsilon");
4794        }
4795
4796        #[gpui::test]
4797        fn triple_click_drag_extends_the_selection_by_paragraphs(cx: &mut TestAppContext) {
4798            let (state, cx) = setup("first one\n\nsecond one\n\nthird one", cx);
4799
4800            press(position(&state, "second one", 2, cx), 3, false, cx);
4801            assert_eq!(selected(&state, cx), "second one");
4802            drag(position(&state, "third one", 2, cx), cx);
4803            assert_eq!(selected(&state, cx), "second one\nthird one");
4804            let end = position(&state, "first one", 2, cx);
4805            drag(end, cx);
4806            assert_eq!(selected(&state, cx), "first one\nsecond one");
4807            release(end, 3, cx);
4808            assert_eq!(selected(&state, cx), "first one\nsecond one");
4809        }
4810
4811        /// A hard break adds a line to a paragraph without ending that paragraph.
4812        #[gpui::test]
4813        fn triple_click_drag_and_shift_click_keep_hard_break_paragraphs_whole(
4814            cx: &mut TestAppContext,
4815        ) {
4816            let first = "first top\nfirst bottom";
4817            let last = "last top\nlast bottom";
4818            let (state, cx) = setup(
4819                "first top  \nfirst bottom\n\nmiddle\n\nlast top  \nlast bottom",
4820                cx,
4821            );
4822
4823            press(position(&state, "middle", 2, cx), 3, false, cx);
4824            assert_eq!(selected(&state, cx), "middle");
4825            let after = position(&state, last, 2, cx);
4826            drag(after, cx);
4827            assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4828            let before = position(&state, first, "first top\n".len() + 2, cx);
4829            drag(before, cx);
4830            assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4831            release(before, 3, cx);
4832
4833            press(after, 1, true, cx);
4834            release(after, 1, cx);
4835            assert_eq!(selected(&state, cx), format!("middle\n{last}"));
4836            press(before, 1, true, cx);
4837            release(before, 1, cx);
4838            assert_eq!(selected(&state, cx), format!("{first}\nmiddle"));
4839        }
4840
4841        /// Inline code lays a paragraph out in pieces; the drag snaps the same.
4842        #[gpui::test]
4843        fn multi_click_drag_snaps_across_inline_code(cx: &mut TestAppContext) {
4844            let (state, cx) = setup("plain words\n\nuse `code` in here", cx);
4845
4846            press(position(&state, "plain words", 8, cx), 2, false, cx);
4847            drag(position(&state, " in here", 6, cx), cx);
4848            assert_eq!(selected(&state, cx), "words\nuse code in here");
4849            release(position(&state, " in here", 6, cx), 2, cx);
4850
4851            press(position(&state, "plain words", 2, cx), 3, false, cx);
4852            assert_eq!(selected(&state, cx), "plain words");
4853            drag(position(&state, "use ", 1, cx), cx);
4854            assert_eq!(selected(&state, cx), "plain words\nuse code in here");
4855        }
4856
4857        #[gpui::test]
4858        fn shift_click_after_a_double_click_extends_by_words(cx: &mut TestAppContext) {
4859            let text = "alpha beta gamma";
4860            let (state, cx) = setup(text, cx);
4861
4862            let word = position(&state, text, 7, cx);
4863            press(word, 2, false, cx);
4864            release(word, 2, cx);
4865            let after = position(&state, text, 13, cx);
4866            press(after, 1, true, cx);
4867            release(after, 1, cx);
4868            assert_eq!(selected(&state, cx), "beta gamma");
4869            let before = position(&state, text, 1, cx);
4870            press(before, 1, true, cx);
4871            release(before, 1, cx);
4872            assert_eq!(selected(&state, cx), "alpha beta");
4873        }
4874    }
4875
4876    mod copy_before_paint {
4877        use super::*;
4878        use crate::{TextSelection, text::SelectionFormat};
4879
4880        const MARKDOWN: &str = "中文 **café**\n\nβeta `\u{2009}code\u{2009}` 👩‍💻\n\n終わり";
4881        const PLAIN: &str = "中文 café\nβeta \u{2009}code\u{2009} 👩‍💻\n終わり\n";
4882
4883        struct Root {
4884            state: Entity<TextViewState>,
4885            format: SelectionFormat,
4886            width: Pixels,
4887            scrollable: bool,
4888        }
4889
4890        impl Render for Root {
4891            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4892                div()
4893                    .w(self.width)
4894                    .when(self.scrollable, |el| el.h(px(160.)))
4895                    .child(crate::TextSelectionLayer)
4896                    .child(
4897                        TextView::new(&self.state)
4898                            .scrollable(self.scrollable)
4899                            .selection_format(self.format),
4900                    )
4901            }
4902        }
4903
4904        fn setup(
4905            format: SelectionFormat,
4906            cx: &mut TestAppContext,
4907        ) -> (Entity<TextViewState>, &mut VisualTestContext) {
4908            cx.update(crate::init);
4909            let (root, cx) = cx.add_window_view(|_, cx| Root {
4910                state: cx.new(|cx| TextViewState::markdown(MARKDOWN, cx)),
4911                format,
4912                width: px(520.),
4913                scrollable: false,
4914            });
4915            cx.run_until_parked();
4916            cx.update(|window, cx| window.draw(cx).clear(cx));
4917            (root.read_with(cx, |root, _| root.state.clone()), cx)
4918        }
4919
4920        fn document<'a>(
4921            markdown: &str,
4922            format: SelectionFormat,
4923            scrollable: bool,
4924            cx: &'a mut TestAppContext,
4925        ) -> (Entity<Root>, &'a mut VisualTestContext) {
4926            cx.update(crate::init);
4927            let (root, cx) = cx.add_window_view(|_, cx| Root {
4928                state: cx.new(|cx| TextViewState::markdown(markdown, cx)),
4929                format,
4930                width: px(520.),
4931                scrollable,
4932            });
4933            cx.run_until_parked();
4934            cx.update(|window, cx| window.draw(cx).clear(cx));
4935            (root, cx)
4936        }
4937
4938        fn scroll_to(state: &Entity<TextViewState>, ix: usize, cx: &mut VisualTestContext) {
4939            state.read_with(cx, |state, _| {
4940                state.list_state.scroll_to(gpui::ListOffset {
4941                    item_ix: ix,
4942                    offset_in_item: px(0.),
4943                })
4944            });
4945            cx.update(|window, cx| window.draw(cx).clear(cx));
4946        }
4947
4948        fn endpoints(
4949            state: &Entity<TextViewState>,
4950            cx: &mut VisualTestContext,
4951        ) -> (
4952            gpui::Point<Pixels>,
4953            gpui::Point<Pixels>,
4954            gpui::Point<Pixels>,
4955        ) {
4956            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
4957            let first = rows.first().unwrap();
4958            let last = rows.last().unwrap();
4959            (
4960                point(first.left() + px(0.1), first.center().y),
4961                point(first.right() - px(0.1), first.center().y),
4962                point(last.right() - px(0.1), last.center().y),
4963            )
4964        }
4965
4966        // Raw dispatch is intentional: simulate_event may draw after each
4967        // packet, concealing the exact native before-paint race.
4968        fn press(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
4969            window.dispatch_event(
4970                gpui::PlatformInput::MouseDown(MouseDownEvent {
4971                    position,
4972                    button: MouseButton::Left,
4973                    click_count: 1,
4974                    ..Default::default()
4975                }),
4976                cx,
4977            );
4978        }
4979
4980        fn extend(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
4981            window.dispatch_event(
4982                gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent {
4983                    position,
4984                    pressed_button: Some(MouseButton::Left),
4985                    ..Default::default()
4986                }),
4987                cx,
4988            );
4989        }
4990
4991        fn release(position: gpui::Point<Pixels>, window: &mut Window, cx: &mut gpui::App) {
4992            window.dispatch_event(
4993                gpui::PlatformInput::MouseUp(MouseUpEvent {
4994                    position,
4995                    button: MouseButton::Left,
4996                    modifiers: Modifiers::default(),
4997                    click_count: 1,
4998                }),
4999                cx,
5000            );
5001        }
5002
5003        fn assert_copy(expected: &str, window: &mut Window, cx: &mut gpui::App) {
5004            // Dispatch synchronously on the native current focus, without
5005            // focusing a different entity or using deferred window dispatch.
5006            let focus = window.focused(cx).expect("gesture focuses TextView");
5007            focus.dispatch_action(&crate::input::Copy, window, cx);
5008            assert_eq!(
5009                cx.read_from_clipboard().and_then(|item| item.text()),
5010                Some(expected.trim().to_string())
5011            );
5012            assert!(focus.is_focused(window));
5013            assert_eq!(TextSelection::selected_text(window, cx), expected);
5014        }
5015
5016        #[gpui::test]
5017        fn custom_inline_and_block_copy_project_with_the_text(cx: &mut TestAppContext) {
5018            struct CustomRoot {
5019                state: Entity<TextViewState>,
5020                format: SelectionFormat,
5021                extensions: crate::text::MarkdownExtensions,
5022            }
5023            impl Render for CustomRoot {
5024                fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5025                    div().w(px(520.)).child(crate::TextSelectionLayer).child(
5026                        TextView::new(&self.state)
5027                            .selection_format(self.format)
5028                            .markdown_extensions(self.extensions.clone()),
5029                    )
5030                }
5031            }
5032            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5033                cx.update(crate::init);
5034                let extensions = crate::text::MarkdownExtensions::default()
5035                    .plugin(
5036                        crate::text::markdown_ext::TestInlinePlugin::new("math").parse_with(
5037                            |node, _| {
5038                                let markdown::mdast::Node::InlineMath(math) = node else {
5039                                    return None;
5040                                };
5041                                Some(
5042                                    crate::text::MarkdownNode::new("math", ())
5043                                        .text(format!("{}²", math.value)),
5044                                )
5045                            },
5046                        ),
5047                    )
5048                    .block_parser(|node, _| {
5049                        matches!(node, markdown::mdast::Node::ThematicBreak(_)).then(|| {
5050                            crate::text::MarkdownNode::new("block", ())
5051                                .text("BLOCK")
5052                                .markdown("---")
5053                        })
5054                    })
5055                    .block_renderer("block", |_, _, _| {
5056                        div()
5057                            .debug_selector(|| "copy-custom-block".into())
5058                            .w(px(520.))
5059                            .h(px(40.))
5060                    });
5061                let (root, cx) = cx.add_window_view(|_, cx| CustomRoot {
5062                    state: cx
5063                        .new(|cx| TextViewState::markdown("before $x$ after\n\n---\n\nlast", cx)),
5064                    format,
5065                    extensions,
5066                });
5067                cx.run_until_parked();
5068                cx.update(|window, cx| window.draw(cx).clear(cx));
5069                let state = root.read_with(cx, |root, _| root.state.clone());
5070                let (start, _, end) = endpoints(&state, cx);
5071                let expected = if format == SelectionFormat::Plain {
5072                    "before x² after\nBLOCK\nlast\n"
5073                } else {
5074                    "before $x$ after\n\n---\n\nlast"
5075                };
5076                cx.update(|window, cx| {
5077                    press(start, window, cx);
5078                    extend(end, window, cx);
5079                    assert_copy(expected, window, cx);
5080                    release(end, window, cx);
5081                });
5082                cx.update(|window, cx| window.draw(cx).clear(cx));
5083                cx.update(|window, cx| assert_copy(expected, window, cx));
5084                let block = cx.debug_bounds("copy-custom-block").unwrap();
5085                cx.update(|window, cx| {
5086                    press(block.center(), window, cx);
5087                    extend(point(block.center().x, block.bottom() + px(1.)), window, cx);
5088                    assert_copy(
5089                        if format == SelectionFormat::Plain {
5090                            "BLOCK\n"
5091                        } else {
5092                            "---"
5093                        },
5094                        window,
5095                        cx,
5096                    );
5097                });
5098            }
5099        }
5100
5101        #[gpui::test]
5102        fn unicode_180_paragraph_copy_extends_and_retracts_before_paint(cx: &mut TestAppContext) {
5103            let markdown = (0..180)
5104                .map(|ix| format!("p{ix:03} **café** 中文 👩‍💻 `\u{2009}code\u{2009}`"))
5105                .collect::<Vec<_>>()
5106                .join("\n\n");
5107            // Expected bytes are constructed independently of rendered_text(),
5108            // selected_text(), and the document's selection serializer.
5109            let expected = (0..180)
5110                .map(|ix| format!("p{ix:03} café 中文 👩‍💻 \u{2009}code\u{2009}\n"))
5111                .collect::<String>();
5112            let (root, cx) = document(&markdown, SelectionFormat::Plain, false, cx);
5113            cx.simulate_resize(gpui::size(px(800.), px(12000.)));
5114            cx.update(|window, cx| window.draw(cx).clear(cx));
5115            let state = root.read_with(cx, |root, _| root.state.clone());
5116            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5117            let first = rows.first().unwrap();
5118            let first_end = rows
5119                .iter()
5120                .take_while(|row| row.top() < first.bottom())
5121                .last()
5122                .unwrap();
5123            let last = rows.last().unwrap();
5124            assert!(last.top() > first.top() + px(3000.));
5125            let start = point(first.left() + px(0.1), first.center().y);
5126            let short_end = point(first_end.right() - px(0.1), first_end.center().y);
5127            let end = point(last.right() - px(0.1), last.center().y);
5128            let short = "p000 café 中文 👩‍💻 \u{2009}code\u{2009}\n";
5129            cx.update(|window, cx| {
5130                press(start, window, cx);
5131                extend(short_end, window, cx);
5132                assert_copy(short, window, cx);
5133            });
5134            cx.update(|window, cx| window.draw(cx).clear(cx));
5135            cx.update(|window, cx| {
5136                extend(end, window, cx);
5137                assert_copy(&expected, window, cx);
5138                extend(short_end, window, cx);
5139                assert_copy(short, window, cx);
5140            });
5141        }
5142
5143        #[gpui::test]
5144        fn scrolling_before_paint_keeps_the_completed_frame_coordinates(cx: &mut TestAppContext) {
5145            let markdown = format!(
5146                "{}\n\nlast",
5147                "alpha beta gamma delta epsilon zeta ".repeat(30)
5148            );
5149            let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
5150            root.update(cx, |root, cx| {
5151                root.width = px(180.);
5152                cx.notify();
5153            });
5154            cx.update(|window, cx| window.draw(cx).clear(cx));
5155            let state = root.read_with(cx, |root, _| root.state.clone());
5156            let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5157            let first = rows[0];
5158            let (start, end) = state.read_with(cx, |state, _| {
5159                (
5160                    state.selection_adapter.first_text_position(0),
5161                    state.selection_adapter.first_text_position("alpha".len()),
5162                )
5163            });
5164            cx.update(|window, cx| {
5165                press(start, window, cx);
5166                extend(end, window, cx);
5167            });
5168            cx.update(|window, cx| window.draw(cx).clear(cx));
5169            cx.update(|window, cx| {
5170                state.read(cx).list_state.scroll_by(first.size.height);
5171                // The logical offset changed, registration and native pixels
5172                // have not. This must not select the next wrapped row.
5173                assert_copy("alpha\n", window, cx);
5174            });
5175        }
5176
5177        #[gpui::test]
5178        fn offscreen_remeasurement_is_not_a_copy_projection(cx: &mut TestAppContext) {
5179            let markdown = (0..180)
5180                .map(|ix| format!("row {ix:03} café 中文"))
5181                .collect::<Vec<_>>()
5182                .join("\n\n");
5183            let (root, cx) = document(&markdown, SelectionFormat::Plain, true, cx);
5184            let state = root.read_with(cx, |root, _| root.state.clone());
5185            scroll_to(&state, 90, cx);
5186            root.update(cx, |root, cx| {
5187                root.width = px(260.);
5188                cx.notify();
5189            });
5190            cx.update(|window, cx| window.draw(cx).clear(cx));
5191            scroll_to(&state, 90, cx);
5192            // measure_all has remeasured earlier, unpainted paragraphs at the
5193            // new width. Only this completed paint supplies Copy geometry.
5194            let (start, end, _) = endpoints(&state, cx);
5195            cx.update(|window, cx| {
5196                press(start, window, cx);
5197                extend(end, window, cx);
5198                assert_copy("row 090 café 中文\n", window, cx);
5199            });
5200        }
5201
5202        #[gpui::test]
5203        fn virtualized_flow_retains_its_source_owned_partial_anchor(cx: &mut TestAppContext) {
5204            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5205                let tail = (1..180)
5206                    .map(|ix| format!("row {ix:03} café 中文"))
5207                    .collect::<Vec<_>>();
5208                let markdown = format!("PREFIX `code` suffix\n\n{}", tail.join("\n\n"));
5209                let expected = if format == SelectionFormat::Plain {
5210                    format!("code suffix\n{}\n", tail.join("\n"))
5211                } else {
5212                    format!("`code` suffix\n\n{}", tail.join("\n\n"))
5213                };
5214                let (root, cx) = document(&markdown, format, true, cx);
5215                let state = root.read_with(cx, |root, _| root.state.clone());
5216                let rows = state.read_with(cx, |state, _| state.selection_adapter.text_bounds());
5217                let code = rows[1];
5218                let suffix = rows[2];
5219                assert!(code.left() < suffix.left());
5220                cx.update(|window, cx| {
5221                    press(point(code.left() + px(0.1), code.center().y), window, cx);
5222                    extend(
5223                        point(suffix.right() - px(0.1), suffix.center().y),
5224                        window,
5225                        cx,
5226                    );
5227                });
5228                cx.update(|window, cx| window.draw(cx).clear(cx));
5229                scroll_to(&state, 179, cx);
5230                // Two completed frames let GPUI retire temporary flow fragments.
5231                cx.update(|window, cx| window.draw(cx).clear(cx));
5232                let (_, _, end) = endpoints(&state, cx);
5233                cx.update(|window, cx| {
5234                    extend(end, window, cx);
5235                    assert_copy(&expected, window, cx);
5236                });
5237            }
5238        }
5239
5240        #[gpui::test]
5241        fn a_new_range_copies_before_its_first_selection_paint(cx: &mut TestAppContext) {
5242            let (state, cx) = setup(SelectionFormat::Plain, cx);
5243            let (start, _, end) = endpoints(&state, cx);
5244            cx.update(|window, cx| {
5245                press(start, window, cx);
5246                extend(end, window, cx);
5247                assert_copy(PLAIN, window, cx);
5248            });
5249        }
5250
5251        #[gpui::test]
5252        fn an_established_range_extends_and_retracts_without_paint(cx: &mut TestAppContext) {
5253            let (state, cx) = setup(SelectionFormat::Plain, cx);
5254            let (start, first_end, end) = endpoints(&state, cx);
5255            cx.update(|window, cx| {
5256                press(start, window, cx);
5257                extend(first_end, window, cx);
5258            });
5259            cx.update(|window, cx| window.draw(cx).clear(cx));
5260            cx.update(|window, cx| {
5261                assert_copy("中文 café\n", window, cx);
5262                extend(end, window, cx);
5263                assert_copy(PLAIN, window, cx);
5264                extend(first_end, window, cx);
5265                assert_copy("中文 café\n", window, cx);
5266            });
5267        }
5268
5269        #[gpui::test]
5270        fn source_copy_projects_the_current_range_without_paint(cx: &mut TestAppContext) {
5271            let (state, cx) = setup(SelectionFormat::Source, cx);
5272            let (start, first_end, end) = endpoints(&state, cx);
5273            cx.update(|window, cx| {
5274                press(start, window, cx);
5275                extend(first_end, window, cx);
5276                assert_copy("中文 **café**", window, cx);
5277                extend(end, window, cx);
5278                assert_copy(MARKDOWN, window, cx);
5279                extend(first_end, window, cx);
5280                assert_eq!(TextSelection::selected_text(window, cx), "中文 **café**");
5281            });
5282        }
5283
5284        #[gpui::test]
5285        fn a_blank_gesture_does_not_reuse_the_previous_range(cx: &mut TestAppContext) {
5286            let (state, cx) = setup(SelectionFormat::Plain, cx);
5287            let (start, first_end, end) = endpoints(&state, cx);
5288            cx.update(|window, cx| {
5289                press(start, window, cx);
5290                extend(end, window, cx);
5291                assert_eq!(TextSelection::selected_text(window, cx), PLAIN);
5292                release(end, window, cx);
5293                press(first_end + point(px(20.), px(0.)), window, cx);
5294                extend(first_end + point(px(60.), px(0.)), window, cx);
5295                assert_eq!(TextSelection::selected_text(window, cx), "");
5296            });
5297        }
5298
5299        #[gpui::test]
5300        fn replacing_source_cannot_reproject_old_content(cx: &mut TestAppContext) {
5301            for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5302                for replacement in ["replacement".to_string(), "replacement ".repeat(500)] {
5303                    let (state, cx) = setup(format, cx);
5304                    let (start, _, end) = endpoints(&state, cx);
5305                    cx.update(|window, cx| {
5306                        press(start, window, cx);
5307                        extend(end, window, cx);
5308                        assert_eq!(
5309                            TextSelection::selected_text(window, cx),
5310                            if format == SelectionFormat::Plain {
5311                                PLAIN
5312                            } else {
5313                                MARKDOWN
5314                            }
5315                        );
5316                        // Large replacements leave the previous parsed document
5317                        // in place while parsing; neither size may reuse it.
5318                        state.update(cx, |state, cx| state.set_text(&replacement, cx));
5319                        assert_eq!(TextSelection::selected_text(window, cx), "");
5320                    });
5321                }
5322            }
5323        }
5324    }
5325
5326    // Regression: markdown `TextView` items inside an outer `gpui::list` with
5327    // `measure_all` must keep a stable total content height while scrolling.
5328    // Before synchronous full-replace parsing, off-screen markdown views were
5329    // first measured with empty content and the scrollbar thumb jittered as the
5330    // total height grew during scrolling.
5331    #[gpui::test]
5332    fn outer_list_content_total_stable_while_scrolling(cx: &mut TestAppContext) {
5333        use gpui::{ListAlignment, ListState, list};
5334
5335        const ITEMS: &[&str] = &[
5336            "# Heading\n\nA paragraph long enough to wrap across several lines and produce a non-trivial height.",
5337            "Short.",
5338            "Paragraph A\n\nParagraph B\n\nParagraph C with more words to increase the height.",
5339            "## Subheading\n\n- One\n- Two\n- Three\n\nClosing paragraph.",
5340            "Only one line.",
5341            "**Bold**: medium length text with `code` mixed with regular words.",
5342            "1. First\n2. Second\n3. Third\n\nA short closing paragraph.",
5343            "A long message with enough words to wrap across multiple lines, create a taller item, and verify that off-screen measurement matches visible measurement.",
5344        ];
5345        let n = 40usize;
5346
5347        struct ListRoot {
5348            state: ListState,
5349        }
5350        impl Render for ListRoot {
5351            fn render(&mut self, _w: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5352                div().w(px(360.)).h(px(500.)).child(
5353                    list(self.state.clone(), |ix, _w, _cx| {
5354                        div()
5355                            .w_full()
5356                            .child(TextView::markdown(
5357                                ("md", ix as u64),
5358                                ITEMS[ix % ITEMS.len()],
5359                            ))
5360                            .into_any_element()
5361                    })
5362                    .size_full(),
5363                )
5364            }
5365        }
5366
5367        cx.update(crate::init);
5368        let state = ListState::new(n, ListAlignment::Top, px(2048.)).measure_all();
5369        let probe = state.clone();
5370        let (_view, cx) = cx.add_window_view(|_w, _cx| ListRoot { state });
5371        let cx: &mut VisualTestContext = cx;
5372
5373        cx.run_until_parked();
5374        cx.update(|w, cx| {
5375            let _ = w.draw(cx);
5376        });
5377        cx.run_until_parked();
5378        cx.update(|w, cx| {
5379            let _ = w.draw(cx);
5380        });
5381
5382        let total = |p: &ListState| {
5383            f32::from(p.max_offset_for_scrollbar().y + p.viewport_bounds().size.height)
5384        };
5385        let mut totals = vec![total(&probe)];
5386        for _ in 0..20 {
5387            probe.scroll_by(px(150.));
5388            cx.update(|w, cx| {
5389                let _ = w.draw(cx);
5390            });
5391            cx.run_until_parked();
5392            totals.push(total(&probe));
5393        }
5394        let min = totals.iter().cloned().fold(f32::INFINITY, f32::min);
5395        let max = totals.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
5396        println!(
5397            "OUTER_LIST_PROBE min={min:.1} max={max:.1} delta={:.1}",
5398            max - min
5399        );
5400        assert!(
5401            (max - min) < 2.0,
5402            "list content total jittered while scrolling: min={min} max={max} totals={totals:?}"
5403        );
5404    }
5405}