Skip to main content

gpui_base/text/
editor_host.rs

1//! Host API for external editors.
2//!
3//! An editor that lives outside gpui-kit keeps its own document model and
4//! hands gpui-kit a [`BlockNode`] tree, the same tree [`TextView`] renders.
5//! gpui-kit renders it and gives back, per text leaf, the geometry the editor
6//! needs for hit-testing, caret placement and platform input (IME) bounds.
7//!
8//! The boundary is deliberately narrow:
9//!
10//! - **In:** a [`BlockNode`] tree whose text leaves carry a host-chosen `u64`
11//!   key (see [`Paragraph::with_leaf_key`] and [`CodeBlock::with_leaf_key`]),
12//!   a [`RenderContext`], and per-key decoration ranges.
13//! - **Out:** one opaque [`LeafGeometry`] per key from
14//!   [`collect_leaf_geometry`].
15//!
16//! Nothing lower is exposed: no `TextLayout`, no layout internals, no sink
17//! trait, no retained-layout or projection caches.
18//!
19//! The host owns editing semantics, document revisions, accessibility and native
20//! input integration. This module provides horizontal TextView block rendering;
21//! it is not a complete visual-caret navigation or pagination API. Extend the
22//! public boundary additively while keeping rendering internals private.
23//!
24//! [`TextView`]: super::TextView
25
26use std::{cell::RefCell, collections::HashMap, ops::Range, rc::Rc, sync::Arc};
27
28use gpui::{
29    AnyElement, App, Bounds, ClickEvent, ElementId, HighlightStyle, Hsla, ImageSource,
30    InteractiveElement as _, IntoElement as _, ParentElement as _, Pixels, Point, SharedString,
31    SharedUri, TextLayout, Window, WrappedLineLayout, div, point, px,
32};
33use unicode_segmentation::UnicodeSegmentation as _;
34
35use super::{
36    TextViewDefaults, TextViewStyle,
37    document::{NodeRenderOptions, PrevBlock, flow_position},
38    editor_seam::{self, EditorSink},
39    format::markdown,
40    markdown_ext::MarkdownExtensions,
41    node::NodeContext,
42};
43
44pub use super::node::{
45    BlockNode, BlockState, CodeBlock, ColumnumnAlign as ColumnAlign, ImageNode, InlineNode,
46    LinkMark, Paragraph, Span, Table, TextMark,
47};
48
49/// Parses Markdown with the parser [`TextView`](super::TextView) uses,
50/// including the given extensions, into the block tree.
51pub fn parse_markdown(
52    source: &str,
53    extensions: Arc<MarkdownExtensions>,
54) -> Result<Vec<BlockNode>, SharedString> {
55    let mut cx = NodeContext {
56        markdown_extensions: extensions,
57        ..Default::default()
58    };
59    let parsed = markdown::parse(source, &mut cx)?;
60    Ok(Arc::unwrap_or_clone(parsed.blocks))
61}
62
63/// What [`BlockNode::render`] needs besides the node: the text style, code
64/// highlighter and Markdown extensions.
65#[derive(Clone)]
66pub struct RenderContext {
67    node: NodeContext,
68}
69
70impl RenderContext {
71    /// Creates a local rendering context without reading application globals.
72    /// The host supplies body typography through its container or
73    /// `with_body_font_size`.
74    pub fn new(style: TextViewStyle) -> Self {
75        Self {
76            node: NodeContext {
77                style: Arc::new(style),
78                ..Default::default()
79            },
80        }
81    }
82
83    /// Replaces code highlighting for this context only.
84    pub fn with_code_block_highlighter<F>(mut self, highlighter: F) -> Self
85    where
86        F: Fn(&CodeBlock) -> Vec<(Range<usize>, HighlightStyle)> + Send + Sync + 'static,
87    {
88        self.node.code_block_highlighter = Some(Arc::new(highlighter));
89        self
90    }
91
92    /// Resolves document image URIs. The host owns resource access policy.
93    pub fn with_image_source<F>(mut self, resolver: F) -> Self
94    where
95        F: Fn(&SharedUri) -> ImageSource + Send + Sync + 'static,
96    {
97        self.node.image_source = Some(Arc::new(resolver));
98        self
99    }
100
101    /// Handles link activation. Without a handler, links use App::open_url.
102    pub fn on_link_click<F>(mut self, handler: F) -> Self
103    where
104        F: Fn(&SharedString, &ClickEvent, &mut Window, &mut App) + Send + Sync + 'static,
105    {
106        self.node.link_click_handler = Some(Arc::new(handler));
107        self
108    }
109
110    /// Registers a reference-link definition from the host's document.
111    /// Supply definitions for the entire document, including virtualized blocks.
112    pub fn with_link_reference(
113        mut self,
114        identifier: impl Into<SharedString>,
115        link: LinkMark,
116    ) -> Self {
117        self.node.link_refs.insert(identifier.into(), link);
118        self
119    }
120
121    /// The context TextView would start from: the global [`TextViewDefaults`]
122    /// style and code-block highlighter when set, else the theme's style.
123    pub fn from_app(cx: &App) -> Self {
124        let theme = crate::Theme::global(cx);
125        let defaults = cx.try_global::<TextViewDefaults>();
126        let style = defaults
127            .and_then(|defaults| defaults.style().cloned())
128            .unwrap_or_else(|| TextViewStyle::from_theme(&theme));
129        Self {
130            node: NodeContext {
131                style: Arc::new(style),
132                code_block_highlighter: defaults.and_then(|d| d.code_block_highlighter()),
133                ..Default::default()
134            },
135        }
136    }
137
138    /// Replaces the text style.
139    pub fn with_style(mut self, style: TextViewStyle) -> Self {
140        self.node.style = Arc::new(style);
141        self
142    }
143
144    /// Supplies this render's foreground ranges for a keyed paragraph leaf,
145    /// including a heading or table cell. Replaces any ranges for the same key.
146    ///
147    /// Ranges use the leaf's rendered UTF-8 bytes; images and custom inline
148    /// objects occupy one U+FFFC (three bytes), as in [`LeafGeometry`]. Text
149    /// ranges are clipped to each text fragment; non-character boundaries and
150    /// empty or reversed ranges are ignored. An object's foreground changes
151    /// only when a range covers its entire placeholder; images are unchanged.
152    ///
153    /// These colors override mark and link foregrounds; later ranges win
154    /// overlaps. Other mark properties and link activation are preserved.
155    /// Uncovered text inherits its ordinary foreground. Colors belong to this
156    /// rendering context, never the document tree: supply current theme/surface
157    /// colors on each render, or omit the ranges to restore inheritance.
158    pub fn with_foreground_ranges(mut self, key: u64, ranges: Vec<(Range<usize>, Hsla)>) -> Self {
159        let foregrounds = self.node.foregrounds.get_or_insert_with(Default::default);
160        Arc::make_mut(foregrounds).insert(key, ranges);
161        self
162    }
163
164    /// Sets the Markdown extensions that render custom nodes.
165    pub fn with_markdown_extensions(mut self, extensions: Arc<MarkdownExtensions>) -> Self {
166        self.node.markdown_extensions = extensions;
167        self
168    }
169
170    /// Sets the font size body text inherits, which the block gaps and
171    /// heading sizes are relative to.
172    pub fn with_body_font_size(mut self, size: Pixels) -> Self {
173        self.node.body_font_size = size;
174        self
175    }
176
177    /// The text style blocks render with.
178    pub fn style(&self) -> &TextViewStyle {
179        &self.node.style
180    }
181}
182
183/// Where a block stands in the flow it is rendered in, which decides the gaps
184/// around it: the first block takes no gap above, the last none below, and a
185/// heading or rule counts the block before it.
186#[derive(Clone, Copy, Debug)]
187pub struct FlowPosition {
188    is_first: bool,
189    is_last: bool,
190    prev: PrevBlock,
191}
192
193impl FlowPosition {
194    /// The position of `blocks[ix]` among its siblings. Blocks that render
195    /// nothing (definitions, breaks) are skipped when looking for the block
196    /// before it.
197    pub fn at(blocks: &[&BlockNode], ix: usize, is_last: bool) -> Self {
198        let (is_first, prev) = flow_position(blocks, ix);
199        Self {
200            is_first,
201            is_last,
202            prev,
203        }
204    }
205
206    /// Overrides whether the block opens its flow, e.g. for a chunk of a
207    /// long list rendered as a list of its own.
208    pub fn first(mut self, is_first: bool) -> Self {
209        self.is_first = is_first;
210        self
211    }
212
213    /// Overrides whether the block closes its flow.
214    pub fn last(mut self, is_last: bool) -> Self {
215        self.is_last = is_last;
216        self
217    }
218}
219
220impl BlockNode {
221    /// Renders under a stable host-owned identity. Use a domain ID, not a list
222    /// position, when inserting, reordering or virtualizing blocks. Identity
223    /// scopes GPUI element state independently of the leaf keys used for geometry.
224    pub fn render_with_id(
225        &self,
226        id: impl Into<ElementId>,
227        flow: FlowPosition,
228        render_context: &RenderContext,
229        window: &mut Window,
230        cx: &mut App,
231    ) -> AnyElement {
232        div()
233            .id(id)
234            .child(self.render(0, flow, render_context, window, cx))
235            .into_any_element()
236    }
237
238    /// Renders the block as TextView does. `ix` identifies the block among
239    /// its siblings (element ids derive from it).
240    pub fn render(
241        &self,
242        ix: usize,
243        flow: FlowPosition,
244        cx: &RenderContext,
245        window: &mut Window,
246        app: &mut App,
247    ) -> AnyElement {
248        self.render_block(
249            NodeRenderOptions {
250                ix,
251                is_first: flow.is_first,
252                is_last: flow.is_last,
253                prev: flow.prev,
254                ..Default::default()
255            },
256            &cx.node,
257            window,
258            app,
259        )
260    }
261}
262
263/// Runs `f`, which should prepaint rendered blocks, and returns its result
264/// with the geometry every keyed text leaf reported meanwhile.
265///
266/// `decorations` maps a leaf key to byte ranges of that leaf's text (atoms
267/// count as one `U+FFFC` each) to paint behind the text: the host's selection,
268/// find matches, anything. Leaves without a key, or without an entry, paint as
269/// usual. Atom decorations cover the whole atom and paint over its content
270/// so selections remain visible over opaque images. Supply translucent colors
271/// for overlays. Ranges are half-open; empty ranges paint nothing.
272/// Scopes nest, and the previous one is restored even if `f` panics.
273///
274/// Keys must be unique within one collection scope. Nested scopes are isolated:
275/// an outer scope does not collect the inner scope's leaves. Only prepainted
276/// leaves are returned; absence is not evidence that a document leaf was removed.
277/// The host owns document revisions, virtualization, focus, native input and
278/// UTF-16/UTF-8 conversion for platform input APIs.
279pub fn collect_leaf_geometry<R>(
280    decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
281    f: impl FnOnce() -> R,
282) -> (R, HashMap<u64, LeafGeometry>) {
283    let collector = Rc::new(Collector {
284        pieces: RefCell::default(),
285        decorations,
286    });
287    let result = editor_seam::with_sink(collector.clone(), f);
288    let mut pieces = collector.pieces.take();
289    pieces.retain(|_, pieces| !pieces.is_empty());
290    let leaves = pieces
291        .into_iter()
292        .map(|(key, pieces)| (key, LeafGeometry { pieces }))
293        .collect();
294    (result, leaves)
295}
296
297struct Collector {
298    pieces: RefCell<HashMap<u64, Vec<Piece>>>,
299    decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
300}
301
302impl EditorSink for Collector {
303    fn report(&self, key: u64, layout: &TextLayout) {
304        self.pieces
305            .borrow_mut()
306            .insert(key, vec![Piece::Whole(LayoutSnapshot::new(layout))]);
307    }
308
309    fn begin_pieces(&self, key: u64) {
310        self.pieces.borrow_mut().insert(key, Vec::new());
311    }
312
313    fn report_text_piece(&self, key: u64, start: usize, layout: &TextLayout) {
314        self.pieces
315            .borrow_mut()
316            .entry(key)
317            .or_default()
318            .push(Piece::Text {
319                start,
320                layout: LayoutSnapshot::new(layout),
321            });
322    }
323
324    fn report_box_piece(&self, key: u64, range: Range<usize>, bounds: Bounds<Pixels>) {
325        self.pieces
326            .borrow_mut()
327            .entry(key)
328            .or_default()
329            .push(Piece::Atom { range, bounds });
330    }
331
332    fn report_empty_piece(&self, key: u64, start: usize, bounds: Bounds<Pixels>) {
333        self.pieces
334            .borrow_mut()
335            .entry(key)
336            .or_default()
337            .push(Piece::Empty { start, bounds });
338    }
339
340    fn backgrounds(&self, key: u64) -> Vec<(Range<usize>, Hsla)> {
341        self.decorations.get(&key).cloned().unwrap_or_default()
342    }
343}
344
345/// Copy mutable frame state, sharing only immutable shaped lines.
346#[derive(Clone)]
347struct LayoutSnapshot {
348    bounds: Bounds<Pixels>,
349    len: usize,
350    line_height: Pixels,
351    text: SharedString,
352    lines: Vec<Arc<WrappedLineLayout>>,
353}
354
355impl LayoutSnapshot {
356    fn new(layout: &TextLayout) -> Self {
357        Self {
358            bounds: layout.bounds(),
359            len: layout.len(),
360            line_height: layout.line_height(),
361            text: layout.text().into(),
362            lines: layout.line_layouts().into_iter().collect(),
363        }
364    }
365
366    fn bounds(&self) -> Bounds<Pixels> {
367        self.bounds
368    }
369    fn len(&self) -> usize {
370        self.len
371    }
372    fn line_height(&self) -> Pixels {
373        self.line_height
374    }
375    fn text(&self) -> &str {
376        &self.text
377    }
378    fn line_layouts(&self) -> &[Arc<WrappedLineLayout>] {
379        &self.lines
380    }
381
382    fn position_for_index(&self, index: usize) -> Option<Point<Pixels>> {
383        let mut origin = self.bounds.origin;
384        let mut start = 0;
385        for line in &self.lines {
386            if index <= start + line.len() {
387                return line
388                    .position_for_index(index - start, self.line_height)
389                    .map(|p| origin + p);
390            }
391            start += line.len() + 1;
392            origin.y += line.size(self.line_height).height;
393        }
394        None
395    }
396}
397
398/// How a leaf was laid out: one layout for the whole leaf, or (for a mixed
399/// paragraph rendered as a flow) single-line text fragments and atom boxes in
400/// leaf byte order.
401#[derive(Clone)]
402enum Piece {
403    Whole(LayoutSnapshot),
404    Text {
405        start: usize,
406        layout: LayoutSnapshot,
407    },
408    Empty {
409        start: usize,
410        bounds: Bounds<Pixels>,
411    },
412    Atom {
413        range: Range<usize>,
414        bounds: Bounds<Pixels>,
415    },
416}
417
418impl Piece {
419    fn bounds(&self) -> Bounds<Pixels> {
420        match self {
421            Piece::Whole(layout) | Piece::Text { layout, .. } => layout.bounds(),
422            Piece::Atom { bounds, .. } | Piece::Empty { bounds, .. } => *bounds,
423        }
424    }
425
426    fn range(&self) -> Range<usize> {
427        match self {
428            Piece::Whole(layout) => 0..layout.len(),
429            Piece::Text { start, layout } => *start..start + layout.len(),
430            Piece::Atom { range, .. } => range.clone(),
431            Piece::Empty { start, .. } => *start..*start,
432        }
433    }
434}
435
436/// Which side of a soft wrap a caret sits on.
437///
438/// At a soft wrap one byte offset names two caret positions: the end of the
439/// upper visual line and the start of the lower one. Same terms as AppKit's
440/// `NSSelectionAffinity` and Flutter's `TextAffinity`.
441#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
442pub enum CaretAffinity {
443    /// The end of the visual line before the offset.
444    Upstream,
445    /// The start of the visual line after the offset.
446    #[default]
447    Downstream,
448}
449
450/// A caret position: a byte offset plus the side of a soft wrap it is on.
451#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
452pub struct Caret {
453    /// The byte offset into the leaf's text.
454    pub index: usize,
455    /// The visual line the caret is on when `index` is at a soft wrap.
456    pub affinity: CaretAffinity,
457}
458
459impl Caret {
460    /// A caret at `index`, at the start of a line at a soft wrap.
461    pub fn new(index: usize) -> Self {
462        Self {
463            index,
464            affinity: CaretAffinity::Downstream,
465        }
466    }
467
468    /// A caret at `index`, at the end of a line at a soft wrap.
469    pub fn upstream(index: usize) -> Self {
470        Self {
471            index,
472            affinity: CaretAffinity::Upstream,
473        }
474    }
475}
476
477/// Where one keyed text leaf was laid out in the last frame.
478///
479/// Indices are byte offsets into the leaf's text, where each inline atom
480/// (image, custom node) is one `U+FFFC` (3 bytes). Coordinates are window
481/// pixels and are valid for the frame that produced them. It is a value, not a
482/// handle: it owns its bounds and shares immutable shaped lines, never the
483/// renderer's mutable layout state. Later frames do not mutate this snapshot.
484/// The host must replace it after content, width, typography or scrolling changes.
485#[derive(Clone)]
486pub struct LeafGeometry {
487    pieces: Vec<Piece>,
488}
489
490impl LeafGeometry {
491    fn whole(&self) -> Option<&LayoutSnapshot> {
492        match self.pieces.as_slice() {
493            [Piece::Whole(layout)] => Some(layout),
494            _ => None,
495        }
496    }
497
498    /// The bounds of the leaf: the union of its pieces.
499    pub fn bounds(&self) -> Bounds<Pixels> {
500        self.pieces
501            .iter()
502            .map(Piece::bounds)
503            .reduce(|a, b| a.union(&b))
504            .unwrap_or_default()
505    }
506
507    /// The length of the leaf's text in bytes, atoms included.
508    pub fn len(&self) -> usize {
509        self.pieces
510            .iter()
511            .map(|piece| piece.range().end)
512            .max()
513            .unwrap_or(0)
514    }
515
516    /// Whether the leaf's text is empty (it still has a line box).
517    pub fn is_empty(&self) -> bool {
518        self.len() == 0
519    }
520
521    /// The height of a line.
522    pub fn line_height(&self) -> Pixels {
523        self.pieces
524            .iter()
525            .find_map(|piece| match piece {
526                Piece::Whole(layout) | Piece::Text { layout, .. } => Some(layout.line_height()),
527                Piece::Empty { bounds, .. } => Some(bounds.size.height),
528                Piece::Atom { .. } => None,
529            })
530            .unwrap_or_else(|| self.bounds().size.height)
531    }
532
533    /// The height of a caret: the font's ascent plus descent, not the whole
534    /// line box, which includes leading.
535    pub fn caret_height(&self) -> Pixels {
536        let line_height = self.line_height();
537        self.pieces
538            .iter()
539            .find_map(|piece| match piece {
540                Piece::Whole(layout) | Piece::Text { layout, .. } => {
541                    let line = layout.lines.first()?;
542                    let h = line.unwrapped_layout.ascent + line.unwrapped_layout.descent;
543                    (h > Pixels::ZERO).then_some(h)
544                }
545                Piece::Atom { .. } | Piece::Empty { .. } => None,
546            })
547            .unwrap_or(line_height * 0.85)
548            .min(line_height)
549    }
550
551    /// The top of a caret placed at byte `index`, in window coordinates.
552    pub fn position_for_index(&self, index: usize) -> Point<Pixels> {
553        if let Some(layout) = self.whole() {
554            return layout
555                .position_for_index(index.min(layout.len()))
556                .unwrap_or_else(|| self.bounds().origin);
557        }
558        // The piece the index starts, else the one it ends (a caret at a
559        // fragment boundary sits at the start of the next fragment).
560        let piece = self
561            .pieces
562            .iter()
563            .find(|p| p.range().contains(&index))
564            .or_else(|| self.pieces.iter().rev().find(|p| p.range().end == index))
565            .or(self.pieces.last());
566        match piece {
567            Some(piece) => self.position_in_piece(piece, index),
568            None => self.bounds().origin,
569        }
570    }
571
572    /// The byte index of the caret position closest to `at`: glyph halves
573    /// round to the nearer side, unlike `TextLayout::index_for_position`.
574    pub fn index_for_position(&self, at: Point<Pixels>) -> usize {
575        if let Some(layout) = self.whole() {
576            return whole_index_at(layout, at);
577        }
578        let Some(piece) = self.hit_piece(at) else {
579            return 0;
580        };
581        let index = match piece {
582            Piece::Whole(layout) => whole_index_at(layout, at),
583            // Fragments are one line: take the caret position nearest to the
584            // point (`closest_index_for_position` rounds up at an exact
585            // boundary inside scaled code text).
586            // Only grapheme boundaries are candidates: an interior byte of a
587            // multi-byte character maps to the next glyph's x, so it could
588            // tie with (and beat) the real boundary and split the character.
589            Piece::Text { start, layout } => {
590                let text = layout.text();
591                let nearest = text
592                    .grapheme_indices(true)
593                    .map(|(i, _)| i)
594                    .chain(std::iter::once(text.len()))
595                    .filter_map(|i| {
596                        layout
597                            .position_for_index(i)
598                            .map(|p| (i, (p.x - at.x).abs()))
599                    })
600                    .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
601                    .map_or(0, |(i, _)| i);
602                start + nearest
603            }
604            Piece::Empty { start, .. } => *start,
605            Piece::Atom { range, bounds } => {
606                if at.x < bounds.center().x {
607                    range.start
608                } else {
609                    range.end
610                }
611            }
612        };
613        index.min(self.len())
614    }
615
616    /// The caret closest to `at`, keeping the visual line that was hit: at a
617    /// soft wrap the end of the upper line is [`CaretAffinity::Upstream`].
618    /// Pass it to [`Self::position_for_caret`] to round-trip a click.
619    pub fn caret_for_position(&self, at: Point<Pixels>) -> Caret {
620        if let Some(layout) = self.whole() {
621            return whole_caret_at(layout, at);
622        }
623        let index = self.index_for_position(at);
624        // The hit ends a piece (the right end of a line in the flow): stay on
625        // the line that was hit, not the next piece's.
626        let ends_hit_line = self.hit_piece(at).is_some_and(|piece| {
627            let range = piece.range();
628            range.start < range.end && range.end == index
629        });
630        if ends_hit_line {
631            Caret::upstream(index)
632        } else {
633            Caret::new(index)
634        }
635    }
636
637    /// The top of `caret` in window coordinates. Unlike
638    /// [`Self::position_for_index`], a caret at a soft wrap lands on the
639    /// visual line its affinity names.
640    pub fn position_for_caret(&self, caret: Caret) -> Point<Pixels> {
641        let index = caret.index;
642        if let Some(layout) = self.whole() {
643            return whole_position_for_caret(layout, caret).unwrap_or_else(|| self.bounds().origin);
644        }
645        match caret.affinity {
646            CaretAffinity::Downstream => {
647                // A caret at the start of a piece belongs to that piece.
648                let starts = self
649                    .pieces
650                    .iter()
651                    .find(|p| p.range().start == index && p.range().end > index);
652                match starts {
653                    Some(piece) => self.position_in_piece(piece, index),
654                    None => self.position_for_index(index),
655                }
656            }
657            CaretAffinity::Upstream => {
658                let ends = self
659                    .pieces
660                    .iter()
661                    .find(|p| p.range().start < index && p.range().end == index);
662                match ends {
663                    Some(piece) => self.position_in_piece(piece, index),
664                    None => self.position_for_index(index),
665                }
666            }
667        }
668    }
669
670    fn position_in_piece(&self, piece: &Piece, index: usize) -> Point<Pixels> {
671        match piece {
672            Piece::Whole(layout) | Piece::Text { layout, .. } => {
673                let local = index.saturating_sub(piece.range().start).min(layout.len());
674                layout
675                    .position_for_index(local)
676                    .unwrap_or_else(|| layout.bounds().origin)
677            }
678            Piece::Empty { bounds, .. } => bounds.origin,
679            Piece::Atom { range, bounds } => {
680                let x = if index >= range.end {
681                    bounds.right()
682                } else {
683                    bounds.left()
684                };
685                let y = (bounds.bottom() - self.line_height()).max(bounds.top());
686                point(x, y)
687            }
688        }
689    }
690
691    /// The piece under `at`: the visual line under the point (pieces whose
692    /// vertical extent holds it, else the nearest), then the horizontally
693    /// nearest piece.
694    fn hit_piece(&self, at: Point<Pixels>) -> Option<&Piece> {
695        let dy = |p: &Piece| {
696            let b = p.bounds();
697            if at.y < b.top() {
698                b.top() - at.y
699            } else if at.y > b.bottom() {
700                at.y - b.bottom()
701            } else {
702                px(0.)
703            }
704        };
705        let dx = |p: &Piece| {
706            let b = p.bounds();
707            if at.x < b.left() {
708                b.left() - at.x
709            } else if at.x > b.right() {
710                at.x - b.right()
711            } else {
712                px(0.)
713            }
714        };
715        self.pieces.iter().min_by(|a, b| {
716            (dy(a), dx(a))
717                .partial_cmp(&(dy(b), dx(b)))
718                .unwrap_or(std::cmp::Ordering::Equal)
719        })
720    }
721
722    /// The byte range of the inline atom drawn under `at`, if any.
723    pub fn atom_at(&self, at: Point<Pixels>) -> Option<Range<usize>> {
724        self.pieces.iter().find_map(|piece| match piece {
725            Piece::Atom { range, bounds } if bounds.contains(&at) => Some(range.clone()),
726            _ => None,
727        })
728    }
729}
730
731/// The closest index in a whole-leaf layout for a window point.
732fn whole_index_at(layout: &LayoutSnapshot, at: Point<Pixels>) -> usize {
733    let bounds = layout.bounds();
734    let line_height = layout.line_height();
735    let mut top = bounds.top();
736    let mut start = 0;
737    let lines = layout.line_layouts();
738    for (ix, line) in lines.iter().enumerate() {
739        let height = line.size(line_height).height.max(line_height);
740        let is_last = ix + 1 == lines.len();
741        if at.y < top + height || is_last {
742            let local = point(
743                (at.x - bounds.left()).max(px(0.)),
744                (at.y - top).clamp(px(0.), (height - px(1.)).max(px(0.))),
745            );
746            let index = match line.closest_index_for_position(local, line_height) {
747                Ok(ix) | Err(ix) => ix,
748            };
749            return start + index;
750        }
751        top += height;
752        start += line.len() + 1;
753    }
754    0
755}
756
757/// The byte offsets where each soft-wrapped row after the first starts.
758fn wrap_starts(line: &WrappedLineLayout) -> impl Iterator<Item = usize> + '_ {
759    line.wrap_boundaries
760        .iter()
761        .map(|b| line.unwrapped_layout.runs[b.run_ix].glyphs[b.glyph_ix].index)
762}
763
764/// [`whole_index_at`] plus the affinity of the visual row that was hit.
765fn whole_caret_at(layout: &LayoutSnapshot, at: Point<Pixels>) -> Caret {
766    let index = whole_index_at(layout, at);
767    let bounds = layout.bounds();
768    let line_height = layout.line_height();
769    let mut top = bounds.top();
770    let mut start = 0;
771    let lines = layout.line_layouts();
772    for (ix, line) in lines.iter().enumerate() {
773        let height = line.size(line_height).height.max(line_height);
774        if at.y < top + height || ix + 1 == lines.len() {
775            let row = ((at.y - top).max(px(0.)) / line_height) as usize;
776            // The hit row ends where the next row starts: an index there is
777            // the end of the hit row.
778            let row_end = wrap_starts(line).nth(row).map(|i| start + i);
779            return if row_end == Some(index) {
780                Caret::upstream(index)
781            } else {
782                Caret::new(index)
783            };
784        }
785        top += height;
786        start += line.len() + 1;
787    }
788    Caret::new(index)
789}
790
791/// The top of `caret` in a whole-leaf layout, on the row its affinity names.
792fn whole_position_for_caret(layout: &LayoutSnapshot, caret: Caret) -> Option<Point<Pixels>> {
793    let index = caret.index.min(layout.len());
794    let line_height = layout.line_height();
795    let mut origin = layout.bounds().origin;
796    let mut start = 0;
797    for line in layout.line_layouts() {
798        if index <= start + line.len() {
799            let local = index - start;
800            let unwrapped = &line.unwrapped_layout;
801            // Row starts: 0, then each wrap. Pick the last row starting at or
802            // before `local`; upstream steps back off a row that starts there.
803            let mut row = 0;
804            let mut row_start = 0;
805            for (ix, wrap) in wrap_starts(line).enumerate() {
806                if wrap < local || (wrap == local && caret.affinity == CaretAffinity::Downstream) {
807                    row = ix + 1;
808                    row_start = wrap;
809                } else {
810                    break;
811                }
812            }
813            let x = unwrapped.x_for_index(local) - unwrapped.x_for_index(row_start);
814            return Some(origin + point(x, line_height * row as f32));
815        }
816        start += line.len() + 1;
817        origin.y += line.size(line_height).height;
818    }
819    None
820}
821
822#[cfg(test)]
823mod tests {
824    use std::cell::Cell;
825
826    use gpui::{
827        Context, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
828        Render, Styled as _, TestAppContext, VisualTestContext, div, rgb, rgba,
829    };
830
831    use super::*;
832    use crate::text::{InlineElement, MarkdownNode, markdown_ext::TestInlinePlugin};
833
834    type Geometries = Rc<RefCell<HashMap<u64, LeafGeometry>>>;
835
836    /// Stands in for an editor's root element: prepaints its child inside a
837    /// `collect_leaf_geometry` scope and keeps what the leaves reported.
838    struct Probe {
839        child: Option<AnyElement>,
840        decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
841        out: Geometries,
842        /// Replaces `collect_leaf_geometry` with a custom sink.
843        sink: Option<Rc<dyn EditorSink>>,
844    }
845
846    impl Element for Probe {
847        type RequestLayoutState = AnyElement;
848        type PrepaintState = ();
849
850        fn id(&self) -> Option<ElementId> {
851            None
852        }
853
854        fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
855            None
856        }
857
858        fn request_layout(
859            &mut self,
860            _: Option<&GlobalElementId>,
861            _: Option<&InspectorElementId>,
862            window: &mut Window,
863            cx: &mut App,
864        ) -> (LayoutId, AnyElement) {
865            let mut child = self.child.take().unwrap();
866            (child.request_layout(window, cx), child)
867        }
868
869        fn prepaint(
870            &mut self,
871            _: Option<&GlobalElementId>,
872            _: Option<&InspectorElementId>,
873            _: Bounds<Pixels>,
874            child: &mut AnyElement,
875            window: &mut Window,
876            cx: &mut App,
877        ) {
878            if let Some(sink) = self.sink.take() {
879                editor_seam::with_sink(sink, || child.prepaint(window, cx));
880                return;
881            }
882            let decorations = std::mem::take(&mut self.decorations);
883            let (_, geometries) = collect_leaf_geometry(decorations, || child.prepaint(window, cx));
884            *self.out.borrow_mut() = geometries;
885        }
886
887        fn paint(
888            &mut self,
889            _: Option<&GlobalElementId>,
890            _: Option<&InspectorElementId>,
891            _: Bounds<Pixels>,
892            child: &mut AnyElement,
893            _: &mut (),
894            window: &mut Window,
895            cx: &mut App,
896        ) {
897            child.paint(window, cx);
898        }
899    }
900
901    struct Host {
902        blocks: Vec<BlockNode>,
903        extensions: Arc<MarkdownExtensions>,
904        decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
905        out: Geometries,
906        width: Pixels,
907        sink: Option<Rc<dyn EditorSink>>,
908        render_context: Option<RenderContext>,
909    }
910
911    impl Render for Host {
912        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
913            let rcx = self
914                .render_context
915                .clone()
916                .unwrap_or_else(|| RenderContext::from_app(cx))
917                .with_markdown_extensions(self.extensions.clone())
918                .with_body_font_size(px(16.));
919            let refs: Vec<&BlockNode> = self.blocks.iter().collect();
920            let children: Vec<AnyElement> = refs
921                .iter()
922                .enumerate()
923                .map(|(ix, block)| {
924                    let flow = FlowPosition::at(&refs, ix, ix + 1 == refs.len());
925                    block.render(ix, flow, &rcx, window, cx)
926                })
927                .collect();
928            Probe {
929                child: Some(div().w(self.width).children(children).into_any_element()),
930                decorations: self.decorations.clone(),
931                out: self.out.clone(),
932                sink: self.sink.clone(),
933            }
934        }
935    }
936
937    fn draw(
938        cx: &mut TestAppContext,
939        blocks: Vec<BlockNode>,
940        decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
941        extensions: Arc<MarkdownExtensions>,
942        width: Pixels,
943    ) -> HashMap<u64, LeafGeometry> {
944        draw_and_inspect(cx, blocks, decorations, extensions, width, |_| ()).0
945    }
946
947    fn draw_and_inspect<R>(
948        cx: &mut TestAppContext,
949        blocks: Vec<BlockNode>,
950        decorations: HashMap<u64, Vec<(Range<usize>, Hsla)>>,
951        extensions: Arc<MarkdownExtensions>,
952        width: Pixels,
953        inspect: impl FnOnce(&mut Window) -> R,
954    ) -> (HashMap<u64, LeafGeometry>, R) {
955        cx.update(crate::init);
956        let out = Geometries::default();
957        let (_, vcx) = cx.add_window_view({
958            let out = out.clone();
959            move |_, _| Host {
960                blocks,
961                extensions,
962                decorations,
963                out,
964                width,
965                sink: None,
966                render_context: None,
967            }
968        });
969        settle(vcx);
970        let inspected = vcx.update(|window, _| inspect(window));
971        (out.take(), inspected)
972    }
973
974    fn settle(cx: &mut VisualTestContext) {
975        cx.run_until_parked();
976        cx.update(|window, cx| window.draw(cx).clear(cx));
977        cx.run_until_parked();
978    }
979
980    fn plain(text: &str) -> Paragraph {
981        let mut paragraph = Paragraph::default();
982        paragraph.push(InlineNode::new(text.to_string()));
983        paragraph
984    }
985
986    fn atom_plugin() -> Arc<MarkdownExtensions> {
987        Arc::new(
988            MarkdownExtensions::default().plugin(TestInlinePlugin::new("atom").render_with(
989                |_, _, _, _| {
990                    Some(InlineElement::new(div().w(px(24.)).h(px(16.))).with_baseline(px(12.)))
991                },
992            )),
993        )
994    }
995
996    #[gpui::test]
997    fn render_local_foregrounds_keep_reused_leaf_geometry(cx: &mut TestAppContext) {
998        cx.update(crate::init);
999        let out = Geometries::default();
1000        let (host, vcx) = cx.add_window_view({
1001            let out = out.clone();
1002            move |_, cx| {
1003                let mut mixed = plain("a中😀").with_leaf_key(2);
1004                mixed.push(atom());
1005                mixed.push(InlineNode::new("tail"));
1006                Host {
1007                    blocks: vec![
1008                        BlockNode::Paragraph(plain("a中😀").with_leaf_key(1)),
1009                        BlockNode::Paragraph(mixed),
1010                    ],
1011                    extensions: atom_plugin(),
1012                    decorations: HashMap::new(),
1013                    out,
1014                    width: px(300.),
1015                    sink: None,
1016                    render_context: Some(
1017                        RenderContext::from_app(cx)
1018                            .with_foreground_ranges(1, vec![(0..8, gpui::red())])
1019                            .with_foreground_ranges(2, vec![(0..15, gpui::red())]),
1020                    ),
1021                }
1022            }
1023        });
1024        settle(vcx);
1025        let before = out.borrow().clone();
1026        for color in [Some(gpui::blue()), None] {
1027            host.update(vcx, |host, cx| {
1028                let ranges: Vec<_> = color.map(|color| (0..15, color)).into_iter().collect();
1029                host.render_context = Some(
1030                    RenderContext::from_app(cx)
1031                        .with_foreground_ranges(1, vec![(0..15, gpui::red())])
1032                        .with_foreground_ranges(1, ranges.clone())
1033                        .with_foreground_ranges(2, ranges.clone()),
1034                );
1035                assert_eq!(
1036                    host.render_context
1037                        .as_ref()
1038                        .unwrap()
1039                        .node
1040                        .foregrounds
1041                        .as_ref()
1042                        .unwrap()[&1],
1043                    ranges
1044                );
1045                cx.notify();
1046            });
1047            settle(vcx);
1048            let after = out.borrow();
1049            for key in [1, 2] {
1050                assert_eq!(after[&key].bounds(), before[&key].bounds());
1051                assert_eq!(after[&key].len(), before[&key].len());
1052                for at in [0, 1, 4, 8] {
1053                    assert_eq!(
1054                        after[&key].position_for_index(at),
1055                        before[&key].position_for_index(at)
1056                    );
1057                }
1058            }
1059        }
1060    }
1061
1062    fn atom() -> InlineNode {
1063        InlineNode::custom(MarkdownNode::new("atom", ()).text("\u{FFFC}"))
1064    }
1065
1066    #[gpui::test]
1067    fn keyed_leaves_report_geometry_and_unkeyed_leaves_do_not(cx: &mut TestAppContext) {
1068        let blocks = vec![
1069            BlockNode::Heading {
1070                level: 1,
1071                children: plain("Title").with_leaf_key(1),
1072                span: None,
1073            },
1074            BlockNode::Paragraph(plain("first").with_leaf_key(2)),
1075            BlockNode::Paragraph(plain("not an editor leaf")),
1076            BlockNode::CodeBlock(
1077                CodeBlock::new("let x = 1;".into(), Some("rust".into()), None::<Span>)
1078                    .with_leaf_key(3),
1079            ),
1080            BlockNode::Table(Table::new(
1081                vec![
1082                    vec![plain("a").with_leaf_key(4), plain("b").with_leaf_key(5)],
1083                    vec![plain("c").with_leaf_key(6), plain("d").with_leaf_key(7)],
1084                ],
1085                vec![ColumnAlign::None, ColumnAlign::Right],
1086            )),
1087            BlockNode::List {
1088                children: vec![BlockNode::ListItem {
1089                    children: vec![BlockNode::Paragraph(plain("item").with_leaf_key(8))],
1090                    spread: false,
1091                    checked: None,
1092                    task_marker: None,
1093                    span: None,
1094                }],
1095                ordered: false,
1096                start: None,
1097                span: None,
1098            },
1099        ];
1100        let geometries = draw(cx, blocks, HashMap::new(), Default::default(), px(300.));
1101        let mut keys: Vec<u64> = geometries.keys().copied().collect();
1102        keys.sort_unstable();
1103        assert_eq!(keys, (1..=8).collect::<Vec<_>>());
1104        for key in [1, 2, 3, 8] {
1105            assert!(geometries[&key].bounds().size.height > px(0.), "leaf {key}");
1106        }
1107        assert_eq!(geometries[&1].len(), "Title".len());
1108        assert_eq!(geometries[&3].len(), "let x = 1;".len());
1109        // Document order is top to bottom.
1110        let top = |key: u64| geometries[&key].bounds().top();
1111        assert!(top(1) < top(2) && top(2) < top(3) && top(3) < top(4) && top(7) < top(8));
1112        // Cells of one row share a line; the second column sits to the right.
1113        assert_eq!(top(4), top(5));
1114        assert!(geometries[&5].bounds().left() > geometries[&4].bounds().right() - px(1.));
1115    }
1116
1117    #[gpui::test]
1118    fn wrapped_leaf_maps_indices_and_positions(cx: &mut TestAppContext) {
1119        let text = "the quick brown fox jumps over the lazy dog and keeps running far away";
1120        let blocks = vec![BlockNode::Paragraph(plain(text).with_leaf_key(1))];
1121        let geometries = draw(cx, blocks, HashMap::new(), Default::default(), px(120.));
1122        let leaf = &geometries[&1];
1123        assert_eq!(leaf.len(), text.len());
1124        assert!(!leaf.is_empty());
1125        let line = leaf.line_height();
1126        assert!(line > px(0.) && leaf.caret_height() <= line);
1127        let mut last_y = px(-1.);
1128        let mut lines = std::collections::BTreeSet::new();
1129        for index in 0..=text.len() {
1130            let caret = leaf.position_for_index(index);
1131            assert!(caret.y >= last_y, "carets never move up");
1132            last_y = caret.y;
1133            lines.insert((caret.y.as_f32() * 100.) as i64);
1134            // Hit-testing at a caret lands on that caret (at a soft wrap the
1135            // end of a line and the start of the next share a caret index).
1136            let hit = leaf.index_for_position(point(caret.x, caret.y + line / 2.));
1137            assert_eq!(
1138                leaf.position_for_index(hit),
1139                caret,
1140                "index {index} hit {hit}"
1141            );
1142        }
1143        assert!(lines.len() >= 3, "the text wraps onto several lines");
1144        // Far outside the leaf clamps to its ends.
1145        assert_eq!(leaf.index_for_position(point(px(-500.), px(-500.))), 0);
1146        assert_eq!(
1147            leaf.index_for_position(point(px(5000.), px(5000.))),
1148            text.len()
1149        );
1150    }
1151
1152    /// Clicks the left and right edge of every visual line and checks the
1153    /// caret maps back to the clicked line (issue #3832).
1154    fn assert_carets_keep_their_line(leaf: &LeafGeometry) {
1155        let bounds = leaf.bounds();
1156        let line = leaf.line_height();
1157        let rows = (bounds.size.height / line).round() as usize;
1158        assert!(rows >= 3, "the text wraps onto several lines");
1159        let mut wraps = 0;
1160        for row in 0..rows {
1161            let row_top = bounds.top() + line * row as f32;
1162            let y = row_top + line / 2.;
1163            for x in [bounds.left() + px(1.), bounds.right() - px(1.)] {
1164                let caret = leaf.caret_for_position(point(x, y));
1165                assert_eq!(caret.index, leaf.index_for_position(point(x, y)));
1166                let pos = leaf.position_for_caret(caret);
1167                assert!(
1168                    (pos.y - row_top).abs() <= line / 2.,
1169                    "row {row} x {x:?}: {caret:?} at {pos:?}, row top {row_top:?}"
1170                );
1171                if leaf.position_for_index(caret.index).y != pos.y {
1172                    wraps += 1;
1173                }
1174            }
1175        }
1176        assert!(wraps > 0, "some clicks land on a soft wrap");
1177    }
1178
1179    #[gpui::test]
1180    fn wrapped_whole_leaf_carets_keep_their_line(cx: &mut TestAppContext) {
1181        let text = "the quick brown fox jumps over the lazy dog and keeps running far away";
1182        let blocks = vec![BlockNode::Paragraph(plain(text).with_leaf_key(1))];
1183        let geometries = draw(cx, blocks, HashMap::new(), Default::default(), px(120.));
1184        let leaf = &geometries[&1];
1185        assert!(leaf.whole().is_some());
1186        assert_carets_keep_their_line(leaf);
1187        // Away from wraps both affinities agree with `position_for_index`.
1188        for index in [0, 1, text.len()] {
1189            let at = leaf.position_for_index(index);
1190            assert_eq!(leaf.position_for_caret(Caret::new(index)), at);
1191            assert_eq!(leaf.position_for_caret(Caret::upstream(index)), at);
1192        }
1193    }
1194
1195    #[gpui::test]
1196    fn wrapped_mixed_leaf_carets_keep_their_line(cx: &mut TestAppContext) {
1197        let words = "the quick brown fox jumps over the lazy dog and ";
1198        let mut paragraph = Paragraph::default();
1199        paragraph.push(InlineNode::new(words));
1200        paragraph.push(atom());
1201        paragraph.push(InlineNode::new(words));
1202        let blocks = vec![BlockNode::Paragraph(paragraph.with_leaf_key(1))];
1203        let geometries = draw(cx, blocks, HashMap::new(), atom_plugin(), px(120.));
1204        let leaf = &geometries[&1];
1205        assert!(leaf.whole().is_none());
1206        assert_carets_keep_their_line(leaf);
1207    }
1208
1209    #[gpui::test]
1210    fn mixed_text_and_atoms_report_boxes(cx: &mut TestAppContext) {
1211        let mut paragraph = Paragraph::default();
1212        paragraph.push(InlineNode::new("ab"));
1213        paragraph.push(atom());
1214        paragraph.push(InlineNode::new("cd"));
1215        let atom_len = '\u{FFFC}'.len_utf8();
1216        let blocks = vec![BlockNode::Paragraph(paragraph.with_leaf_key(1))];
1217        let geometries = draw(cx, blocks, HashMap::new(), atom_plugin(), px(300.));
1218        let leaf = &geometries[&1];
1219        assert_eq!(leaf.len(), 2 + atom_len + 2);
1220        // The box is hit-testable, and only the box.
1221        let range = 2..2 + atom_len;
1222        let before = leaf.position_for_index(2);
1223        let after = leaf.position_for_index(2 + atom_len);
1224        assert!(after.x > before.x, "the caret moves across the atom");
1225        let inside = point(
1226            (before.x + after.x) / 2.,
1227            before.y + leaf.line_height() / 2.,
1228        );
1229        assert_eq!(leaf.atom_at(inside), Some(range.clone()));
1230        assert_eq!(leaf.atom_at(point(before.x - px(8.), inside.y)), None);
1231        // Clicking either half of the atom puts the caret on its near edge.
1232        let quarter = |t: f32| point(before.x + (after.x - before.x) * t, inside.y);
1233        assert_eq!(leaf.index_for_position(quarter(0.25)), range.start);
1234        assert_eq!(leaf.index_for_position(quarter(0.75)), range.end);
1235        // Text on both sides keeps its own indices.
1236        let end = leaf.position_for_index(leaf.len());
1237        assert_eq!(
1238            leaf.index_for_position(point(end.x + px(40.), inside.y)),
1239            leaf.len()
1240        );
1241        assert_eq!(leaf.index_for_position(point(px(-40.), inside.y)), 0);
1242    }
1243
1244    #[gpui::test]
1245    fn mixed_flow_hits_land_on_grapheme_boundaries(cx: &mut TestAppContext) {
1246        // Accented, CJK and emoji text (a skin-tone sequence is one grapheme
1247        // of two chars) on both sides of atoms, so the leaf is a mixed flow.
1248        let parts = ["éa", "\u{FFFC}", "中文", "\u{FFFC}", "👍🏽x"];
1249        let mut paragraph = Paragraph::default();
1250        for part in parts {
1251            if part == "\u{FFFC}" {
1252                paragraph.push(atom());
1253            } else {
1254                paragraph.push(InlineNode::new(part));
1255            }
1256        }
1257        let text = parts.concat();
1258        let blocks = vec![BlockNode::Paragraph(paragraph.with_leaf_key(1))];
1259        let geometries = draw(cx, blocks, HashMap::new(), atom_plugin(), px(400.));
1260        let leaf = &geometries[&1];
1261        assert_eq!(leaf.len(), text.len());
1262        let boundaries: Vec<usize> = text
1263            .grapheme_indices(true)
1264            .map(|(i, _)| i)
1265            .chain(std::iter::once(text.len()))
1266            .collect();
1267
1268        // Sweep the whole line: every hit is a grapheme boundary that an
1269        // edit can use.
1270        let bounds = leaf.bounds();
1271        let y = bounds.top() + leaf.line_height() / 2.;
1272        let mut x = bounds.left() - px(4.);
1273        while x <= bounds.right() + px(4.) {
1274            let index = leaf.index_for_position(point(x, y));
1275            assert!(
1276                boundaries.contains(&index),
1277                "hit at {x:?} returned {index}, inside a grapheme of {text:?}"
1278            );
1279            let mut edited = text.clone();
1280            edited.insert(index, '|');
1281            x += px(0.5);
1282        }
1283
1284        // The caret x of each boundary hits that boundary, never a byte
1285        // inside the character before it (`é`: offsets 1 and 2 share an x).
1286        for &index in &boundaries {
1287            let at = leaf.position_for_index(index);
1288            assert_eq!(
1289                leaf.index_for_position(point(at.x, y)),
1290                index,
1291                "caret position of {index} in {text:?}"
1292            );
1293        }
1294    }
1295
1296    #[gpui::test]
1297    fn mixed_flow_keeps_empty_lines_and_trailing_breaks(cx: &mut TestAppContext) {
1298        let mut paragraph = Paragraph::default();
1299        paragraph.push(atom());
1300        paragraph.push(InlineNode::new("a\n\n"));
1301        let mut breaks = Paragraph::default();
1302        breaks.push(atom());
1303        breaks.push(InlineNode::new("\n\n"));
1304        let leaves = draw(
1305            cx,
1306            vec![
1307                BlockNode::Paragraph(paragraph.with_leaf_key(1)),
1308                BlockNode::Paragraph(breaks.with_leaf_key(2)),
1309            ],
1310            HashMap::new(),
1311            atom_plugin(),
1312            px(300.),
1313        );
1314        let leaf = &leaves[&1];
1315        assert_eq!(leaf.len(), 6);
1316        let a = leaf.position_for_index(3);
1317        let empty = leaf.position_for_index(5);
1318        let end = leaf.position_for_index(6);
1319        assert!(a.y < empty.y && empty.y < end.y);
1320        for index in [5, 6] {
1321            let caret = leaf.position_for_index(index);
1322            assert_eq!(
1323                leaf.index_for_position(point(
1324                    caret.x + px(20.),
1325                    caret.y + leaf.line_height() / 2.
1326                )),
1327                index
1328            );
1329        }
1330        assert!(leaf.bounds().bottom() >= end.y + leaf.line_height());
1331        let breaks = &leaves[&2];
1332        assert_eq!(breaks.len(), 5);
1333        assert!(breaks.line_height() < breaks.bounds().size.height);
1334        assert!(breaks.position_for_index(5).y > breaks.position_for_index(4).y);
1335    }
1336
1337    #[gpui::test]
1338    fn atom_decorations_are_painted_for_custom_nodes_and_images(cx: &mut TestAppContext) {
1339        let color: Hsla = rgba(0x12345680).into();
1340        let mut custom = Paragraph::default();
1341        custom.push(atom());
1342        let mut image = Paragraph::default();
1343        image.push(InlineNode::image(ImageNode {
1344            url: "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'/>".into(),
1345            width: Some(px(20.).into()), height: Some(px(20.).into()),
1346            ..Default::default()
1347        }));
1348        let blocks = vec![
1349            BlockNode::Paragraph(custom.with_leaf_key(1)),
1350            BlockNode::Paragraph(image.with_leaf_key(2)),
1351        ];
1352        let decorations = HashMap::from([
1353            (1, vec![(0..3, color), (1..1, color)]),
1354            (2, vec![(0..3, color), (3..6, color)]),
1355        ]);
1356        let (_, painted) =
1357            draw_and_inspect(cx, blocks, decorations, atom_plugin(), px(300.), |window| {
1358                let background: gpui::Background = color.into();
1359                window
1360                    .painted_quads()
1361                    .into_iter()
1362                    .filter(|quad| quad.background == background)
1363                    .count()
1364            });
1365        assert_eq!(
1366            painted, 2,
1367            "one overlay per atom; empty and adjacent ranges paint nothing"
1368        );
1369    }
1370
1371    #[gpui::test]
1372    fn rekeying_cloned_leaves_preserves_each_identity(cx: &mut TestAppContext) {
1373        let original = plain("shared source").with_leaf_key(1);
1374        let copy = original.clone().with_leaf_key(2);
1375        let code = CodeBlock::new("let x = 1;".into(), None, None::<Span>).with_leaf_key(3);
1376        let copy_code = code.clone().with_leaf_key(4);
1377        let leaves = draw(
1378            cx,
1379            vec![
1380                BlockNode::Paragraph(original),
1381                BlockNode::Paragraph(copy),
1382                BlockNode::CodeBlock(code),
1383                BlockNode::CodeBlock(copy_code),
1384            ],
1385            HashMap::new(),
1386            Default::default(),
1387            px(300.),
1388        );
1389        assert_eq!(leaves.len(), 4);
1390        assert_eq!(leaves[&1].len(), "shared source".len());
1391        assert_eq!(leaves[&3].len(), "let x = 1;".len());
1392        assert!(leaves[&1].bounds().top() < leaves[&2].bounds().top());
1393        assert!(leaves[&3].bounds().top() < leaves[&4].bounds().top());
1394    }
1395
1396    #[gpui::test]
1397    fn geometry_is_an_immutable_snapshot(cx: &mut TestAppContext) {
1398        cx.update(crate::init);
1399        let out = Geometries::default();
1400        let (host, vcx) = cx.add_window_view({
1401            let out = out.clone();
1402            move |_, _| Host {
1403                blocks: vec![BlockNode::Paragraph(
1404                    plain("a long sentence that wraps when the viewport gets narrower")
1405                        .with_leaf_key(1),
1406                )],
1407                extensions: Default::default(),
1408                decorations: HashMap::new(),
1409                out,
1410                width: px(600.),
1411                sink: None,
1412                render_context: None,
1413            }
1414        });
1415        settle(vcx);
1416        let old = out.borrow()[&1].clone();
1417        let before = old.bounds();
1418        vcx.update(|_, cx| {
1419            host.update(cx, |host, cx| {
1420                host.width = px(80.);
1421                cx.notify();
1422            })
1423        });
1424        settle(vcx);
1425        assert!(out.borrow()[&1].bounds().size.height > before.size.height);
1426        assert_eq!(old.bounds(), before);
1427        assert_eq!(old.position_for_index(0), before.origin);
1428    }
1429
1430    #[gpui::test]
1431    fn empty_keyed_leaf_has_a_line_box_and_empty_unkeyed_leaf_stays_empty(cx: &mut TestAppContext) {
1432        let blocks = vec![
1433            BlockNode::Paragraph(Paragraph::default()),
1434            BlockNode::Paragraph(Paragraph::default().with_leaf_key(9)),
1435        ];
1436        let geometries = draw(cx, blocks, HashMap::new(), Default::default(), px(300.));
1437        assert_eq!(geometries.len(), 1);
1438        let leaf = &geometries[&9];
1439        assert!(leaf.is_empty());
1440        assert!(leaf.bounds().size.height > px(0.));
1441        assert_eq!(leaf.position_for_index(0).x, leaf.bounds().left());
1442        assert_eq!(
1443            leaf.index_for_position(point(px(50.), leaf.bounds().top())),
1444            0
1445        );
1446    }
1447
1448    #[gpui::test]
1449    fn image_only_leaf_reports_its_box(cx: &mut TestAppContext) {
1450        let image = ImageNode {
1451            url: "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'/>".into(),
1452            width: Some(px(20.).into()),
1453            height: Some(px(20.).into()),
1454            ..Default::default()
1455        };
1456        let mut paragraph = Paragraph::default();
1457        paragraph.push(InlineNode::image(image));
1458        let blocks = vec![BlockNode::Paragraph(paragraph.with_leaf_key(1))];
1459        let geometries = draw(cx, blocks, HashMap::new(), Default::default(), px(300.));
1460        let leaf = &geometries[&1];
1461        let atom_len = '\u{FFFC}'.len_utf8();
1462        assert_eq!(leaf.len(), atom_len);
1463        let inside = leaf.bounds().center();
1464        assert_eq!(leaf.atom_at(inside), Some(0..atom_len));
1465    }
1466
1467    /// Records which leaves ask for backgrounds, to prove decorations are
1468    /// requested for keyed leaves only.
1469    #[derive(Default)]
1470    struct Recorder {
1471        asked: RefCell<Vec<u64>>,
1472    }
1473
1474    impl EditorSink for Recorder {
1475        fn report(&self, _: u64, _: &TextLayout) {}
1476        fn begin_pieces(&self, _: u64) {}
1477        fn report_text_piece(&self, _: u64, _: usize, _: &TextLayout) {}
1478        fn report_box_piece(&self, _: u64, _: Range<usize>, _: Bounds<Pixels>) {}
1479        fn report_empty_piece(&self, _: u64, _: usize, _: Bounds<Pixels>) {}
1480        fn backgrounds(&self, key: u64) -> Vec<(Range<usize>, Hsla)> {
1481            self.asked.borrow_mut().push(key);
1482            vec![(0..1, rgb(0xff0000).into())]
1483        }
1484    }
1485
1486    #[gpui::test]
1487    fn decorations_are_requested_per_keyed_leaf(cx: &mut TestAppContext) {
1488        cx.update(crate::init);
1489        let recorder = Rc::new(Recorder::default());
1490        let mut mixed = Paragraph::default();
1491        mixed.push(InlineNode::new("ab"));
1492        mixed.push(atom());
1493        let blocks = vec![
1494            BlockNode::Paragraph(plain("one").with_leaf_key(1)),
1495            BlockNode::Paragraph(plain("unkeyed")),
1496            BlockNode::Paragraph(mixed.with_leaf_key(2)),
1497        ];
1498        let (_, vcx) = cx.add_window_view({
1499            let sink: Rc<dyn EditorSink> = recorder.clone();
1500            move |_, _| Host {
1501                blocks,
1502                extensions: atom_plugin(),
1503                decorations: HashMap::new(),
1504                out: Geometries::default(),
1505                width: px(300.),
1506                sink: Some(sink),
1507                render_context: None,
1508            }
1509        });
1510        settle(vcx);
1511        let asked = recorder.asked.borrow();
1512        assert!(asked.contains(&1) && asked.contains(&2), "{asked:?}");
1513        assert!(asked.iter().all(|key| *key == 1 || *key == 2), "{asked:?}");
1514    }
1515
1516    #[gpui::test]
1517    fn decorated_leaves_still_report_geometry(cx: &mut TestAppContext) {
1518        let blocks = vec![BlockNode::Paragraph(plain("hello world").with_leaf_key(1))];
1519        let decorations = HashMap::from([(
1520            1,
1521            vec![
1522                (0..5, rgba(0x3366ff80).into()),
1523                (6..11, rgb(0xffcc00).into()),
1524            ],
1525        )]);
1526        let plain_geometry = draw(
1527            cx,
1528            blocks.clone(),
1529            HashMap::new(),
1530            Default::default(),
1531            px(300.),
1532        );
1533        let decorated = draw(cx, blocks, decorations, Default::default(), px(300.));
1534        assert_eq!(
1535            decorated[&1].bounds().size,
1536            plain_geometry[&1].bounds().size,
1537            "decorations paint behind the text and never change layout"
1538        );
1539    }
1540
1541    #[test]
1542    fn collect_leaf_geometry_nests_and_restores_on_panic() {
1543        let seen = Cell::new(0);
1544        let (inner_ran, geometries) = collect_leaf_geometry(HashMap::new(), || {
1545            assert!(editor_seam::current().is_some());
1546            let outer = editor_seam::current().unwrap();
1547            collect_leaf_geometry(HashMap::new(), || seen.set(seen.get() + 1));
1548            let after = editor_seam::current().unwrap();
1549            assert!(Rc::ptr_eq(&outer, &after), "the outer scope is restored");
1550            true
1551        });
1552        assert!(inner_ran && geometries.is_empty() && seen.get() == 1);
1553        assert!(editor_seam::current().is_none());
1554
1555        let result = std::panic::catch_unwind(|| {
1556            collect_leaf_geometry(HashMap::new(), || panic!("boom"));
1557        });
1558        assert!(result.is_err());
1559        assert!(editor_seam::current().is_none(), "cleared after a panic");
1560    }
1561
1562    #[test]
1563    fn parse_markdown_reads_what_an_editor_round_trips() {
1564        let source = "```rust title=\"x\"\nfn main() {}\n```\n\n\
1565                      | a | b | c | d |\n|---|:--|:-:|--:|\n| 1 | 2 | 3 | 4 |\n\n\
1566                      [ref]: https://example.com \"Title\"\n";
1567        let blocks = parse_markdown(source, Default::default()).unwrap();
1568        let code = blocks
1569            .iter()
1570            .find_map(|block| match block {
1571                BlockNode::CodeBlock(code) => Some(code),
1572                _ => None,
1573            })
1574            .expect("code block");
1575        assert_eq!(code.lang().as_deref(), Some("rust"));
1576        assert_eq!(code.meta().as_deref(), Some("title=\"x\""));
1577        let table = blocks
1578            .iter()
1579            .find_map(|block| match block {
1580                BlockNode::Table(table) => Some(table),
1581                _ => None,
1582            })
1583            .expect("table");
1584        assert_eq!(
1585            table.column_aligns(),
1586            [
1587                ColumnAlign::None,
1588                ColumnAlign::Left,
1589                ColumnAlign::Center,
1590                ColumnAlign::Right
1591            ]
1592        );
1593        let cells: Vec<Vec<String>> = table
1594            .rows()
1595            .map(|row| {
1596                row.map(|cell| cell.children().iter().map(|c| c.text()).collect())
1597                    .collect()
1598            })
1599            .collect();
1600        assert_eq!(cells, [["a", "b", "c", "d"], ["1", "2", "3", "4"]]);
1601        assert!(blocks.iter().any(|block| matches!(
1602            block,
1603            BlockNode::Definition { identifier, .. } if identifier.as_ref() == "ref"
1604        )));
1605        assert!(
1606            blocks
1607                .iter()
1608                .all(|block| block.span().is_some() || matches!(block, BlockNode::Unknown))
1609        );
1610    }
1611
1612    #[test]
1613    fn parse_markdown_matches_text_view_parse() {
1614        let source = "# Title\n\nSome **bold** and `code` and ==mark==.\n\n- one\n- two\n";
1615        let mut cx = NodeContext::default();
1616        let expected = markdown::parse(source, &mut cx).unwrap();
1617        let blocks = parse_markdown(source, Default::default()).unwrap();
1618        assert_eq!(blocks, *expected.blocks);
1619    }
1620
1621    #[test]
1622    fn table_and_paragraph_builders_read_back() {
1623        let mut paragraph = Paragraph::default();
1624        paragraph.push(InlineNode::new("hi").marks(vec![(0..2, TextMark::default().bold())]));
1625        assert_eq!(paragraph.children()[0].text(), "hi");
1626        assert!(paragraph.children()[0].mark_runs()[0].1.bold);
1627        assert!(paragraph.children()[0].as_image().is_none());
1628        assert!(paragraph.children()[0].as_custom().is_none());
1629        let table = Table::new(vec![vec![paragraph]], vec![ColumnAlign::Center]);
1630        assert_eq!(table.rows().count(), 1);
1631        assert_eq!(table.column_aligns(), [ColumnAlign::Center]);
1632    }
1633}