Skip to main content

nsh_core/
text.rs

1use std::{
2    any::Any,
3    fmt,
4    hash::{Hash, Hasher},
5    ops::Range,
6    sync::Arc,
7};
8
9use rustc_hash::FxHashMap;
10
11use crate::{
12    geometry::{Bounds, Point, Points, Size, point, px, size},
13    ops::{EventMask, NodeId},
14    style::{
15        Color, DecorationStyle, EllipsizeMode, FontFamily, FontVariant, TextAlign, TextDecoration,
16        TextShadow, TextStyle, TextTransform, VerticalAlign,
17    },
18};
19
20/// Fully resolved character style of a text run.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct ResolvedTextStyle {
23    /// Foreground color.
24    pub color: Color,
25    /// Font size.
26    pub font_size: Points,
27    /// Font weight, `100..=900`.
28    pub font_weight: u16,
29    /// Line height; zero means the font's natural line height.
30    pub line_height: Points,
31    /// Font family; `None` is the system font.
32    pub font_family: Option<FontFamily>,
33    /// Italic.
34    pub italic: bool,
35    /// Extra space between characters.
36    pub letter_spacing: Points,
37    /// A line height set as a multiple of the font size (0: none), kept
38    /// so nested text with another size gets its own line height.
39    pub line_height_multiple: f32,
40    /// Underline / strikethrough.
41    pub decoration: TextDecoration,
42    /// Color of the decoration lines; `None` uses `color`.
43    pub decoration_color: Option<Color>,
44    /// How the decoration lines are drawn.
45    pub decoration_style: DecorationStyle,
46    /// Thickness of the decoration lines; `None` is the font's.
47    pub decoration_thickness: Option<Points>,
48    /// Distance of the underline below the baseline; `None` is the font's.
49    pub underline_offset: Option<Points>,
50    /// Case transform (applied by the core when building the text).
51    pub transform: TextTransform,
52    /// OpenType features (`fontVariant`).
53    pub font_variant: FontVariant,
54    /// The background of the nested text this run is in (drawing only).
55    pub background: Option<TextBackground>,
56    /// Hidden but laid out (`visibility: "hidden"` on the nested text this
57    /// run is in, or on one around it): its characters keep their place in
58    /// the lines, are not drawn (the core makes the run transparent, with
59    /// no background) and are left out of copies and of what screen readers
60    /// read ([`AttributedText::copied_text`], [`AttributedText::visible_text`]).
61    pub hidden: bool,
62}
63
64/// The background of a nested `<Text>` (`backgroundColor` and
65/// `borderRadius` on a span): drawing only, behind its characters and
66/// those of the spans inside it, on each line it reaches as the font's
67/// ascent to descent around the baseline (as CSS paints inline boxes),
68/// every line's box rounded alike (`box-decoration-break: clone`).
69#[derive(Debug, Clone, Copy, PartialEq)]
70pub struct TextBackground {
71    /// Fill color (never fully transparent).
72    pub color: Color,
73    /// Corner radius.
74    pub radius: Points,
75    /// The span that set it, so neighboring spans that look the same still
76    /// get a box each.
77    pub node: NodeId,
78    /// Room above the font's ascent (the span's top padding): drawing only,
79    /// as a CSS inline box's vertical padding, the line keeps its height.
80    pub top: Points,
81    /// Room below the font's descent (the span's bottom padding).
82    pub bottom: Points,
83}
84
85/// A piece of a laid out line, in visual order, for
86/// [`BackgroundBox::join`]: a cluster, glyph or run.
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub struct LinePiece {
89    /// Left edge.
90    pub x: Points,
91    /// Advance.
92    pub width: Points,
93    /// The background of its characters
94    /// ([`AttributedText::background_at`]).
95    pub background: Option<TextBackground>,
96    /// Its font's ascent above the baseline (0 for an attachment).
97    pub ascent: Points,
98    /// Its font's descent below the baseline.
99    pub descent: Points,
100}
101
102/// One box of a span's background on one line (see
103/// [`BackgroundBox::join`]).
104#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct BackgroundBox {
106    /// Left edge, in the coordinates of the pieces.
107    pub x: Points,
108    /// Width.
109    pub width: Points,
110    /// Top, above the baseline: the tallest ascent of its pieces.
111    pub ascent: Points,
112    /// Bottom, below the baseline.
113    pub descent: Points,
114    /// What fills it.
115    pub background: TextBackground,
116}
117
118impl BackgroundBox {
119    /// Calls `f` with the boxes of span backgrounds on one line, given its
120    /// `pieces` in visual order: neighboring pieces of one background join
121    /// into one box, cut to `(left, right)` (whitespace hanging past the
122    /// line's end is not painted).
123    pub fn join(
124        pieces: impl IntoIterator<Item = LinePiece>,
125        (left, right): (Points, Points),
126        mut f: impl FnMut(BackgroundBox),
127    ) {
128        let mut current: Option<BackgroundBox> = None;
129        let mut emit = |b: Option<BackgroundBox>| {
130            if let Some(mut b) = b {
131                b.ascent += b.background.top;
132                b.descent += b.background.bottom;
133                let x1 = (b.x + b.width).min(right);
134                b.x = b.x.max(left);
135                b.width = x1 - b.x;
136                if b.width > Points::ZERO && b.ascent + b.descent > Points::ZERO {
137                    f(b);
138                }
139            }
140        };
141        for p in pieces {
142            let Some(background) = p.background else {
143                emit(current.take());
144                continue;
145            };
146            match &mut current {
147                Some(b) if b.background == background => {
148                    b.width = (p.x + p.width).max(b.x + b.width) - b.x;
149                    b.ascent = b.ascent.max(p.ascent);
150                    b.descent = b.descent.max(p.descent);
151                }
152                _ => {
153                    emit(current.take());
154                    current = Some(BackgroundBox {
155                        x: p.x,
156                        width: p.width,
157                        ascent: p.ascent,
158                        descent: p.descent,
159                        background,
160                    });
161                }
162            }
163        }
164        emit(current);
165    }
166
167    /// The radius of its corners: the background's, at most half its
168    /// width or height.
169    pub fn radius(&self) -> Points {
170        self.background
171            .radius
172            .min(self.width / 2.0)
173            .min((self.ascent + self.descent) / 2.0)
174            .max(Points::ZERO)
175    }
176}
177
178impl Default for ResolvedTextStyle {
179    /// React Native defaults.
180    fn default() -> Self {
181        Self {
182            color: Color::BLACK,
183            font_size: px(14.0),
184            font_weight: 400,
185            line_height: Points::ZERO,
186            font_family: None,
187            italic: false,
188            letter_spacing: Points::ZERO,
189            decoration: TextDecoration {
190                underline: false,
191                line_through: false,
192            },
193            decoration_color: None,
194            decoration_style: DecorationStyle::Solid,
195            decoration_thickness: None,
196            underline_offset: None,
197            line_height_multiple: 0.0,
198            transform: TextTransform::None,
199            font_variant: FontVariant(0),
200            background: None,
201            hidden: false,
202        }
203    }
204}
205
206impl ResolvedTextStyle {
207    /// Applies the properties set on a node on top of the inherited style.
208    #[inline]
209    pub(crate) fn inherit(self, style: &TextStyle) -> Self {
210        // Ems / percentages are of the inherited font size, like CSS.
211        let font_size = match style.font_size_em {
212            Some(em) => px(em * self.font_size.0),
213            None => style.font_size.unwrap_or(self.font_size),
214        };
215        // A multiple follows each nested font size (unitless CSS
216        // line-height); points stay points.
217        let (line_height, line_height_multiple) = match (
218            style.line_height_multiple,
219            style.line_height,
220            style.line_height_em,
221        ) {
222            (_, _, Some(em)) => (em * font_size, 0.0),
223            (Some(m), _, _) => (m * font_size, m),
224            (None, Some(points), _) => (points, 0.0),
225            (None, None, _) if self.line_height_multiple > 0.0 => (
226                self.line_height_multiple * font_size,
227                self.line_height_multiple,
228            ),
229            (None, None, _) => (self.line_height, 0.0),
230        };
231        Self {
232            color: style.color.unwrap_or(self.color),
233            font_size,
234            font_weight: style.font_weight.unwrap_or(self.font_weight),
235            line_height,
236            line_height_multiple,
237            font_family: style.font_family.or(self.font_family),
238            italic: style.italic.unwrap_or(self.italic),
239            // Ems are of the node's own font size, then inherited as points.
240            letter_spacing: match style.letter_spacing_em {
241                Some(em) => em * font_size,
242                None => style.letter_spacing.unwrap_or(self.letter_spacing),
243            },
244            decoration: style.decoration.unwrap_or(self.decoration),
245            decoration_color: style.decoration_color.or(self.decoration_color),
246            decoration_style: style.decoration_style.unwrap_or(self.decoration_style),
247            decoration_thickness: style.decoration_thickness.or(self.decoration_thickness),
248            underline_offset: style.underline_offset.or(self.underline_offset),
249            transform: style.transform.unwrap_or(self.transform),
250            font_variant: style.font_variant.unwrap_or(self.font_variant),
251            background: self.background,
252            hidden: self.hidden,
253        }
254    }
255
256    /// The style hidden ([`Self::hidden`]): nothing of it is drawn, glyphs,
257    /// decoration lines and background alike, and its metrics stay.
258    #[must_use]
259    pub(crate) fn hide(self) -> Self {
260        Self {
261            color: Color::TRANSPARENT,
262            decoration_color: None,
263            background: None,
264            hidden: true,
265            ..self
266        }
267    }
268
269    /// The line height [`ApproxTextEngine`] and offscreen estimates give
270    /// this style: its explicit `line_height`, `line_height_multiple` of
271    /// `font_size` (clamped to at least 1 pt), or `1.2 × font_size`.
272    #[doc(hidden)]
273    #[inline]
274    pub fn approx_line_height(&self) -> Points {
275        let font = self.font_size.max(px(1.0));
276        if self.line_height > Points::ZERO {
277            self.line_height
278        } else if self.line_height_multiple > 0.0 {
279            font * self.line_height_multiple
280        } else {
281            font * 1.2
282        }
283    }
284
285    /// True if both styles produce the same glyph metrics (colors and
286    /// decorations ignored).
287    #[inline]
288    fn layout_eq(&self, other: &Self) -> bool {
289        self.font_size == other.font_size
290            && self.font_weight == other.font_weight
291            && self.line_height == other.line_height
292            && self.font_family == other.font_family
293            && self.italic == other.italic
294            && self.letter_spacing == other.letter_spacing
295            && self.font_variant == other.font_variant
296    }
297}
298
299/// Whether two span lists over one string style every character alike
300/// but for the colors and what is hidden ([`AttributedText::same_but_colors`]).
301fn spans_same_but_colors(a: &[TextSpan], b: &[TextSpan]) -> bool {
302    let colorless = |s: &ResolvedTextStyle| ResolvedTextStyle {
303        color: Color::TRANSPARENT,
304        decoration_color: None,
305        background: s.background.map(|b| TextBackground {
306            color: Color::TRANSPARENT,
307            ..b
308        }),
309        // Hidden characters keep their place in the lines: whether a run is
310        // drawn is decided when drawing, as its colors are.
311        hidden: false,
312        ..*s
313    };
314    // Both cover the string end to end: walk the pieces where they overlap.
315    let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
316    loop {
317        match (a.peek(), b.peek()) {
318            (None, None) => return true,
319            (Some(x), Some(y)) => {
320                let overlap = x.start < y.end && y.start < x.end;
321                if !overlap || colorless(&x.style) != colorless(&y.style) {
322                    return false;
323                }
324                match x.end.cmp(&y.end) {
325                    std::cmp::Ordering::Less => {
326                        a.next();
327                    }
328                    std::cmp::Ordering::Greater => {
329                        b.next();
330                    }
331                    std::cmp::Ordering::Equal => {
332                        a.next();
333                        b.next();
334                    }
335                }
336            }
337            _ => return false,
338        }
339    }
340}
341
342/// A run of characters with one style.
343///
344/// Offsets are in UTF-16 code units, which is what both Apple
345/// (`NSAttributedString`) and Android (`Spannable`) text APIs index by.
346#[derive(Debug, Clone, Copy, PartialEq)]
347pub struct TextSpan {
348    /// Start offset (UTF-16 units, inclusive).
349    pub start: u32,
350    /// End offset (UTF-16 units, exclusive).
351    pub end: u32,
352    /// Style of the run.
353    pub style: ResolvedTextStyle,
354}
355
356/// The merged content of a `<text>` block: its own text plus all nested
357/// spans and raw text nodes, flattened into one string with style runs.
358#[derive(Debug, Clone, PartialEq, Default)]
359pub struct AttributedText {
360    /// The full string.
361    pub text: String,
362    /// Non-overlapping, sorted style runs covering `text`.
363    pub spans: Vec<TextSpan>,
364    /// The root paragraph's strut when the core mounted the text (`None`
365    /// for a directly constructed text, whose engines keep their historic
366    /// first-span fallback). A nested span's smaller resolved line height
367    /// never lowers the paragraph below this strut, while a taller inline
368    /// box can still grow its own line.
369    #[doc(hidden)]
370    pub paragraph_strut: Option<ResolvedTextStyle>,
371    /// Paragraph alignment.
372    pub align: TextAlign,
373    /// Maximum number of lines; 0 means no limit (`numberOfLines`).
374    pub max_lines: u32,
375    /// How text beyond `max_lines` is cut.
376    pub ellipsize: EllipsizeMode,
377    /// Lines never wrap (`whitespace-nowrap`): measured at their natural
378    /// width, overflowing the box.
379    pub no_wrap: bool,
380    /// Shadow behind the whole block (drawing only, not layout).
381    pub shadow: Option<TextShadow>,
382    /// Nested `<text>` spans that take presses (they may nest).
383    pub links: Vec<TextLink>,
384    /// Where links of [`links`](Self::links) go: the `href` of their span
385    /// (`nsh-base`'s `TextView` gives its links their URL), by the link's
386    /// index there. It changes nothing drawn or laid out; a platform that
387    /// makes links hyperlinks takes it (the web draws a link's characters
388    /// as an `<a href>`). Hidden: only the web reads it so far, so it is
389    /// not yet a stable part of the core's API.
390    #[doc(hidden)]
391    pub link_hrefs: Vec<LinkHref>,
392    /// Nested `<Text>` spans with a `testID` (they may nest). Platforms
393    /// draw nothing from them. Tests name a span by its id.
394    pub test_ids: Vec<SpanTestId>,
395    /// What attachments give in place of their placeholder when the text
396    /// is copied (`copyText` of a view inside the text), in text order.
397    /// Platforms draw nothing from them: they are what
398    /// [`AttributedText::copied_text`] puts where the attachment is.
399    pub copy_texts: Vec<AttachmentCopyText>,
400    /// `writingDirection`: right to left (`Some(true)`), left to right, or
401    /// from the content (`None`).
402    pub writing_direction: Option<bool>,
403    /// The block is laid out right to left: `auto` alignment is the right
404    /// side.
405    pub rtl: bool,
406    /// A long press copies the text (`userSelect: "text"` or `select-text`;
407    /// drawing only): `Some(false)` when set off, `None` when not set, which
408    /// is not selectable except where text is by default (desktop
409    /// browsers). [`is_selectable`](Self::is_selectable) is whether it is asked for.
410    pub selectable: Option<bool>,
411    /// The highlight of the selection of selectable text (`selectionColor`);
412    /// the platform's tint when `None`.
413    pub selection_color: Option<Color>,
414    /// Inline views and images, in text order: each is an object
415    /// replacement character (U+FFFC) the engine gives the attachment's
416    /// size. Their optional alignment is passed separately to
417    /// `TextEngine::prepare_aligned`; `prepare` places them on the baseline.
418    pub attachments: Vec<TextAttachment>,
419}
420
421/// A view or image inside a text block (see
422/// [`AttributedText::attachments`]).
423///
424/// Optional placement is held by [`AttachmentAlignments`], leaving this
425/// struct's three-field construction compatible with existing engines.
426/// Every engine places it with the same rule: its top
427/// [`ascent`](Self::ascent) above the baseline, the line reserving its
428/// [`extent`](Self::extent) (so a line grows where the attachment reaches
429/// past the font around it). Only the font's metrics are the platform's.
430#[derive(Debug, Clone, Copy, PartialEq)]
431pub struct TextAttachment {
432    /// Its placeholder character (UTF-16 offset).
433    pub index: u32,
434    /// Width.
435    pub width: Points,
436    /// Height.
437    pub height: Points,
438}
439
440/// The vertical metrics of the font around an attachment (the style of
441/// its placeholder), which [`TextAttachment::ascent`] places it against.
442#[derive(Debug, Clone, Copy, PartialEq, Default)]
443#[non_exhaustive]
444pub struct FontExtent {
445    /// Above the baseline (positive).
446    pub ascent: Points,
447    /// Below the baseline (positive).
448    pub descent: Points,
449    /// Height of lowercase letters.
450    pub x_height: Points,
451}
452
453impl FontExtent {
454    /// A font's ascent, descent and x height.
455    pub fn new(ascent: Points, descent: Points, x_height: Points) -> Self {
456        Self {
457            ascent,
458            descent,
459            x_height,
460        }
461    }
462}
463
464impl TextAttachment {
465    /// The distance of its top above the baseline (negative: below it),
466    /// in a line of `font`: CSS `vertical-align` for a replaced inline
467    /// box. `baseline` needs no metrics (the height, whatever `font` is).
468    pub fn ascent(&self, font: FontExtent, align: VerticalAlign) -> Points {
469        let h = self.height;
470        match align {
471            VerticalAlign::Baseline => h,
472            VerticalAlign::TextTop => font.ascent,
473            VerticalAlign::TextBottom => h - font.descent,
474            VerticalAlign::Middle => (h + font.x_height) / 2.0,
475        }
476    }
477
478    /// What its line reserves for it above and below the baseline (each
479    /// at least 0): with the font's own, the line's extent, so the line
480    /// grows where the attachment reaches past the font. Engines give the
481    /// placeholder these metrics (a run delegate's ascent and descent, a
482    /// replacement span's font metrics) and draw its top
483    /// [`ascent`](Self::ascent) above the baseline.
484    pub fn extent(&self, font: FontExtent, align: VerticalAlign) -> (Points, Points) {
485        let ascent = self.ascent(font, align);
486        (
487            ascent.max(Points::ZERO),
488            (self.height - ascent).max(Points::ZERO),
489        )
490    }
491}
492
493/// Optional alignment of inline attachments, keyed by their UTF-16 offsets.
494/// Kept separately so existing `TextAttachment` and `AttributedText` literals
495/// and custom text engines remain source compatible.
496#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
497#[non_exhaustive]
498pub struct AttachmentAlignments {
499    values: Vec<(u32, VerticalAlign)>,
500    /// How far below its top an attachment's own baseline is, where it
501    /// has one (the first baseline of the text in it): the bits of the points, so the table
502    /// compares and hashes.
503    baselines: Vec<(u32, u32)>,
504}
505
506impl AttachmentAlignments {
507    /// The alignment at `index`; unspecified attachments stand on the baseline.
508    pub fn get(&self, index: u32) -> VerticalAlign {
509        self.values
510            .binary_search_by_key(&index, |v| v.0)
511            .map_or(VerticalAlign::Baseline, |i| self.values[i].1)
512    }
513
514    /// Sets an attachment's alignment. Baseline needs no stored entry.
515    pub fn set(&mut self, index: u32, align: VerticalAlign) {
516        match self.values.binary_search_by_key(&index, |v| v.0) {
517            Ok(i) if align == VerticalAlign::Baseline => {
518                self.values.remove(i);
519            }
520            Ok(i) => self.values[i].1 = align,
521            Err(i) if align != VerticalAlign::Baseline => self.values.insert(i, (index, align)),
522            Err(_) => {}
523        }
524    }
525
526    /// How far below its top the attachment at `index` has its own
527    /// baseline (the first line of the text inside it), if it has one:
528    /// [`VerticalAlign::Baseline`] puts that on the line's baseline, as
529    /// CSS aligns an `inline-flex` box, where an attachment without one
530    /// stands on its bottom edge.
531    pub fn baseline(&self, index: u32) -> Option<Points> {
532        self.baselines
533            .binary_search_by_key(&index, |v| v.0)
534            .ok()
535            .map(|i| Points(f32::from_bits(self.baselines[i].1)))
536    }
537
538    /// Sets or clears the attachment's own baseline
539    /// ([`Self::baseline`]).
540    pub fn set_baseline(&mut self, index: u32, baseline: Option<Points>) {
541        match (
542            self.baselines.binary_search_by_key(&index, |v| v.0),
543            baseline,
544        ) {
545            (Ok(i), Some(b)) => self.baselines[i].1 = b.0.to_bits(),
546            (Ok(i), None) => {
547                self.baselines.remove(i);
548            }
549            (Err(i), Some(b)) => self.baselines.insert(i, (index, b.0.to_bits())),
550            (Err(_), None) => {}
551        }
552    }
553
554    /// The distance of attachment `a`'s top above the baseline in a line
555    /// of `font` ([`TextAttachment::ascent`]), by its alignment here: on
556    /// the baseline, an attachment with a baseline of its own
557    /// ([`Self::baseline`]) puts that one there. What every engine places
558    /// an attachment by.
559    pub fn ascent(&self, a: &TextAttachment, font: FontExtent) -> Points {
560        match (self.get(a.index), self.baseline(a.index)) {
561            (VerticalAlign::Baseline, Some(baseline)) => baseline.max(Points::ZERO).min(a.height),
562            (align, _) => a.ascent(font, align),
563        }
564    }
565
566    /// What attachment `a`'s line reserves for it above and below the
567    /// baseline ([`TextAttachment::extent`]), by its alignment here.
568    pub fn extent(&self, a: &TextAttachment, font: FontExtent) -> (Points, Points) {
569        let ascent = self.ascent(a, font);
570        (
571            ascent.max(Points::ZERO),
572            (a.height - ascent).max(Points::ZERO),
573        )
574    }
575
576    /// Appends an attachment and records its alignment.
577    pub fn push(
578        &mut self,
579        text: &mut AttributedText,
580        size: Size<Points>,
581        align: VerticalAlign,
582        style: ResolvedTextStyle,
583    ) {
584        self.set(text.len_utf16(), align);
585        text.push_attachment(size, style);
586    }
587
588    /// Whether all attachments use the default baseline alignment.
589    pub fn is_empty(&self) -> bool {
590        self.values.is_empty() && self.baselines.is_empty()
591    }
592
593    /// The text's layout hash including attachment alignment.
594    pub fn layout_hash(&self, text: &AttributedText) -> u64 {
595        if self.is_empty() {
596            return text.layout_hash();
597        }
598        use std::hash::{Hash, Hasher};
599        let mut h = std::collections::hash_map::DefaultHasher::new();
600        text.layout_hash().hash(&mut h);
601        self.hash(&mut h);
602        h.finish()
603    }
604}
605
606/// Whether the grapheme cluster `c` is drawn as a color emoji: a character
607/// of emoji presentation or one asked for with U+FE0F, unless U+FE0E asks
608/// for text.
609fn is_emoji_presentation(c: &str) -> bool {
610    use unicode_properties::{EmojiStatus, UnicodeEmoji};
611    !c.contains('\u{FE0E}')
612        && c.chars().any(|ch| {
613            ch == '\u{FE0F}'
614                || matches!(
615                    ch.emoji_status(),
616                    EmojiStatus::EmojiPresentation
617                        | EmojiStatus::EmojiPresentationAndModifierBase
618                        | EmojiStatus::EmojiPresentationAndEmojiComponent
619                        | EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
620                )
621        })
622}
623
624/// The length of `s` in UTF-16 units.
625fn utf16_len(s: &str) -> u32 {
626    s.chars().map(|c| c.len_utf16() as u32).sum()
627}
628
629/// Appends `s` to `out` with the characters HTML gives a meaning (`&`, `<`,
630/// `>`, `"`) escaped: text or an attribute's value of a copy's `text/html`.
631pub(crate) fn escape_html(out: &mut String, s: &str) {
632    for c in s.chars() {
633        match c {
634            '&' => out.push_str("&amp;"),
635            '<' => out.push_str("&lt;"),
636            '>' => out.push_str("&gt;"),
637            '"' => out.push_str("&quot;"),
638            c => out.push(c),
639        }
640    }
641}
642
643/// The byte offset in `s` of the UTF-16 offset `to` and the UTF-16 offset
644/// it is at, counting on from byte `byte`, which is at UTF-16 offset `at`:
645/// the end of `s` past it, the start of a character whose surrogate pair
646/// `to` splits.
647fn seek(s: &str, mut byte: usize, mut at: u32, to: u32) -> (usize, u32) {
648    for c in s[byte..].chars() {
649        let next = at + c.len_utf16() as u32;
650        if next > to {
651            break;
652        }
653        (at, byte) = (next, byte + c.len_utf8());
654    }
655    (byte, at)
656}
657
658/// The character standing for an attachment.
659pub const ATTACHMENT_CHAR: char = '\u{FFFC}';
660
661/// A nested `<text>` span with press listeners: presses on its characters
662/// go to it rather than to the block. It is a stop of the keyboard focus
663/// of its own ([`Self::focus_stop`]): Tab reaches it after its text view,
664/// in text order, the platform reports `FOCUSED` (`focus:`) and `Focus` /
665/// `Blur` for the span's node and presses it on Return, as a view that
666/// takes presses. A span with a hint watching it and no press listeners (a
667/// `RichEditor`'s link mark) is one too, for the pointer only: its events
668/// are `MouseEnter` / `MouseLeave`, it is no stop of Tab, and presses on
669/// its characters go to the views around, as the platforms route only
670/// links whose events take presses.
671#[derive(Debug, Clone, Copy, PartialEq)]
672pub struct TextLink {
673    /// Start offset (UTF-16 units, inclusive).
674    pub start: u32,
675    /// End offset (UTF-16 units, exclusive).
676    pub end: u32,
677    /// The span's node.
678    pub node: NodeId,
679    /// Its listeners.
680    pub events: EventMask,
681    /// A stop of Tab (`ViewProps::focus_stop` of the span: unless
682    /// `focusable={false}` or disabled).
683    pub focus_stop: bool,
684}
685
686/// A nested `<Text>` span with a `testID` ([`AttributedText::test_ids`]).
687#[derive(Debug, Clone, PartialEq, Default)]
688#[non_exhaustive]
689pub struct SpanTestId {
690    /// Start offset (UTF-16 units, inclusive).
691    pub start: u32,
692    /// End offset (UTF-16 units, exclusive).
693    pub end: u32,
694    /// Its `testID`.
695    pub test_id: Arc<str>,
696}
697
698/// Where a link of a text goes (`AttributedText::link_hrefs`). Hidden, as
699/// that field is.
700#[doc(hidden)]
701#[derive(Debug, Clone, PartialEq, Default)]
702#[non_exhaustive]
703pub struct LinkHref {
704    /// The link's index in [`AttributedText::links`].
705    pub link: u32,
706    /// Its span's `href`: a URL or a path of the app's, as a `Link`'s.
707    pub href: Arc<str>,
708}
709
710impl LinkHref {
711    /// Link `link` of the text goes to `href`.
712    pub fn new(link: u32, href: impl Into<Arc<str>>) -> Self {
713        Self {
714            link,
715            href: href.into(),
716        }
717    }
718}
719
720/// What an attachment of a text gives when the text is copied
721/// ([`AttributedText::copy_texts`]): a formula's source, an emoji image's
722/// character.
723#[derive(Debug, Clone, PartialEq, Default)]
724#[non_exhaustive]
725pub struct AttachmentCopyText {
726    /// The attachment's placeholder character (UTF-16 offset,
727    /// [`TextAttachment::index`]).
728    pub index: u32,
729    /// What a copy gives in its place.
730    pub text: Arc<str>,
731}
732
733impl AttachmentCopyText {
734    /// `text` in place of the attachment at UTF-16 offset `index`.
735    pub fn new(index: u32, text: impl Into<Arc<str>>) -> Self {
736        Self {
737            index,
738            text: text.into(),
739        }
740    }
741}
742
743impl AttributedText {
744    /// Whether the text was made selectable (`userSelect: "text"`, `select-text`).
745    pub fn is_selectable(&self) -> bool {
746        self.selectable == Some(true)
747    }
748
749    /// Whether a span has a background ([`TextBackground`]).
750    pub fn has_backgrounds(&self) -> bool {
751        self.spans.iter().any(|s| s.style.background.is_some())
752    }
753
754    /// The explicit root strut, or the first span's style for a directly
755    /// constructed text without one (the platform engines' historic input).
756    #[doc(hidden)]
757    pub fn paragraph_strut_or_first(&self) -> ResolvedTextStyle {
758        self.paragraph_strut.unwrap_or_else(|| {
759            self.spans
760                .first()
761                .map_or_else(ResolvedTextStyle::default, |s| s.style)
762        })
763    }
764
765    /// Whether the root struts reserve the same line box. The reused style
766    /// is plumbing for a zero-width inline box: colors, decorations,
767    /// transforms and letter spacing change nothing of it.
768    #[inline]
769    fn paragraph_strut_layout_eq(&self, other: &Self) -> bool {
770        let (a, b) = (
771            self.paragraph_strut_or_first(),
772            other.paragraph_strut_or_first(),
773        );
774        a.font_size == b.font_size
775            && a.font_weight == b.font_weight
776            && a.line_height == b.line_height
777            && a.font_family == b.font_family
778            && a.italic == b.italic
779            && a.font_variant == b.font_variant
780    }
781
782    /// The largest clamped font size across spans (`14 pt` when empty) and
783    /// the tallest [`ResolvedTextStyle::approx_line_height`] across spans,
784    /// shared by [`ApproxTextEngine`] and offscreen text estimates.
785    pub(crate) fn approx_metrics(&self) -> (Points, Points) {
786        if self.spans.is_empty() {
787            let font = px(14.0);
788            return (font, font * 1.2);
789        }
790        self.spans.iter().fold(
791            (Points::ZERO, self.paragraph_strut_or_first().line_height),
792            |(font, line), span| {
793                let s = &span.style;
794                (
795                    font.max(s.font_size.max(px(1.0))),
796                    line.max(s.approx_line_height()),
797                )
798            },
799        )
800    }
801
802    /// The color every character is drawn in, decoration lines included,
803    /// if there is one (`None` for several, or no text): what a transition
804    /// of the text's color animates ([`crate::transition::recolor`]).
805    pub fn uniform_color(&self) -> Option<Color> {
806        let color = self.spans.first()?.style.color;
807        self.spans
808            .iter()
809            .all(|s| {
810                // A transition would draw a hidden run in its color.
811                !s.style.hidden
812                    && s.style.color == color
813                    && (s.style.decoration.is_none()
814                        || s.style.decoration_color.is_none_or(|c| c == color))
815            })
816            .then_some(color)
817    }
818
819    /// Whether a run is hidden ([`ResolvedTextStyle::hidden`]).
820    pub fn has_hidden(&self) -> bool {
821        self.spans.iter().any(|s| s.style.hidden)
822    }
823
824    /// The text a screen reader reads: all of it but its hidden runs
825    /// ([`ResolvedTextStyle::hidden`]); borrowed when none is.
826    ///
827    /// Empty attachments (no height: a span's padding) are no content and
828    /// are left out too.
829    pub fn visible_text(&self) -> std::borrow::Cow<'_, str> {
830        let spacers = self.attachments.iter().any(|a| a.height <= Points::ZERO);
831        if !self.has_hidden() && !spacers {
832            return std::borrow::Cow::Borrowed(&self.text);
833        }
834        let mut out = String::with_capacity(self.text.len());
835        self.each_shown(0..self.len_utf16(), |s, _| out.push_str(s));
836        if spacers {
837            // Offsets in `out` shift where hidden runs were dropped: find the
838            // empty attachments by counting placeholders instead.
839            let shown: Vec<bool> = self
840                .attachments
841                .iter()
842                .filter(|a| !self.hidden_at(a.index))
843                .map(|a| a.height > Points::ZERO)
844                .collect();
845            let mut nth = 0;
846            out.retain(|c| {
847                if c != ATTACHMENT_CHAR {
848                    return true;
849                }
850                nth += 1;
851                shown.get(nth - 1).copied().unwrap_or(true)
852            });
853        }
854        std::borrow::Cow::Owned(out)
855    }
856
857    /// The characters of the UTF-16 range `range` as a copy gives them:
858    /// an attachment as its copy text ([`Self::copy_texts`]), or nothing
859    /// without one (its placeholder, [`ATTACHMENT_CHAR`], is left out), and
860    /// without hidden runs ([`ResolvedTextStyle::hidden`]). The range is
861    /// clamped to the text; offsets inside a surrogate pair round down.
862    pub fn copied_text(&self, range: Range<u32>) -> String {
863        if self.copy_texts.is_empty() {
864            return self.text_without_attachments(range);
865        }
866        let mut out = String::new();
867        let mut copies = self.copy_texts.iter().peekable();
868        self.each_shown(range, |s, mut at| {
869            for c in s.chars() {
870                if c == ATTACHMENT_CHAR {
871                    while copies.next_if(|t| t.index < at).is_some() {}
872                    if let Some(copy) = copies.next_if(|t| t.index == at) {
873                        out.push_str(&copy.text);
874                    }
875                } else {
876                    out.push(c);
877                }
878                at += c.len_utf16() as u32;
879            }
880        });
881        out
882    }
883
884    /// The characters of the UTF-16 range `range` as an HTML fragment, for
885    /// the `text/html` flavor of a copy: the characters
886    /// [`Self::copied_text`] gives, escaped, with bold runs (weight 600 or
887    /// more) in `<b>`, italic ones in `<i>`, links with an `href`
888    /// ([`Self::link_hrefs`]) in `<a href>` and line breaks as `<br>`.
889    /// The second value is whether any run was bold, italic or a link:
890    /// without one the fragment is the plain text, escaped. Hidden, as
891    /// `link_hrefs` is: only the platforms' copy reads it.
892    #[doc(hidden)]
893    pub fn copied_html(&self, range: Range<u32>) -> (String, bool) {
894        #[derive(Clone, Copy, PartialEq)]
895        struct Format<'a> {
896            href: Option<&'a str>,
897            bold: bool,
898            italic: bool,
899        }
900        fn close(out: &mut String, f: Format<'_>) {
901            if f.italic {
902                out.push_str("</i>");
903            }
904            if f.bold {
905                out.push_str("</b>");
906            }
907            if f.href.is_some() {
908                out.push_str("</a>");
909            }
910        }
911        fn open(out: &mut String, f: Format<'_>) {
912            if let Some(href) = f.href {
913                out.push_str("<a href=\"");
914                escape_html(out, href);
915                out.push_str("\">");
916            }
917            if f.bold {
918                out.push_str("<b>");
919            }
920            if f.italic {
921                out.push_str("<i>");
922            }
923        }
924        let plain = Format {
925            href: None,
926            bold: false,
927            italic: false,
928        };
929        let mut out = String::new();
930        let mut formatted = false;
931        let mut current = plain;
932        let mut copies = self.copy_texts.iter().peekable();
933        let mut piece = String::new();
934        self.each_shown(range, |s, mut at| {
935            for c in s.chars() {
936                let format = match self.span_at(at) {
937                    Some(span) => Format {
938                        href: self
939                            .links
940                            .iter()
941                            .enumerate()
942                            .filter(|(_, l)| at >= l.start && at < l.end)
943                            .filter_map(|(n, l)| Some((l.end - l.start, self.link_href(n)?)))
944                            .min_by_key(|&(len, _)| len)
945                            .map(|(_, href)| href),
946                        bold: span.style.font_weight >= 600,
947                        italic: span.style.italic,
948                    },
949                    None => plain,
950                };
951                piece.clear();
952                if c == ATTACHMENT_CHAR {
953                    while copies.next_if(|t| t.index < at).is_some() {}
954                    if let Some(copy) = copies.next_if(|t| t.index == at) {
955                        piece.push_str(&copy.text);
956                    }
957                } else {
958                    piece.push(c);
959                }
960                at += c.len_utf16() as u32;
961                if piece.is_empty() {
962                    continue;
963                }
964                if format != current {
965                    close(&mut out, current);
966                    open(&mut out, format);
967                    current = format;
968                    formatted |= format != plain;
969                }
970                for line in piece.split_inclusive('\n') {
971                    match line.strip_suffix('\n') {
972                        Some(line) => {
973                            escape_html(&mut out, line);
974                            out.push_str("<br>");
975                        }
976                        None => escape_html(&mut out, line),
977                    }
978                }
979            }
980        });
981        close(&mut out, current);
982        (out, formatted)
983    }
984
985    /// The characters of the UTF-16 range `range` without attachments'
986    /// placeholders ([`ATTACHMENT_CHAR`], whatever they copy as) and
987    /// hidden runs: the text's own characters, as accessibility reads them
988    /// beside the inline views it reads on their own. Clamped as
989    /// [`Self::copied_text`].
990    pub fn text_without_attachments(&self, range: Range<u32>) -> String {
991        let mut out = String::new();
992        self.each_shown(range, |s, _| {
993            out.extend(s.chars().filter(|&c| c != ATTACHMENT_CHAR));
994        });
995        out
996    }
997
998    /// Calls `f` with each piece of `range` (UTF-16 units) that no hidden
999    /// run covers, in order, and the offset it starts at. Characters past
1000    /// the runs (a text built without them) count as shown.
1001    fn each_shown(&self, range: Range<u32>, mut f: impl FnMut(&str, u32)) {
1002        let end = range.end.min(self.len_utf16().max(utf16_len(&self.text)));
1003        let (mut byte, mut at) = seek(&self.text, 0, 0, range.start.min(end));
1004        // The first span ending after `at`.
1005        let mut spans = self.spans[self.spans.partition_point(|s| s.end <= at)..].iter();
1006        while at < end {
1007            let (to, hidden) = match spans.next() {
1008                Some(s) => (s.end.min(end), s.style.hidden),
1009                None => (end, false),
1010            };
1011            let (next, reached) = seek(&self.text, byte, at, to);
1012            if !hidden {
1013                f(&self.text[byte..next], at);
1014            }
1015            if reached == at {
1016                break;
1017            }
1018            (byte, at) = (next, reached);
1019        }
1020    }
1021
1022    /// The span containing the UTF-16 offset `index` (the last one past the
1023    /// end).
1024    pub fn span_at(&self, index: u32) -> Option<&TextSpan> {
1025        let i = self.spans.partition_point(|s| s.end <= index);
1026        self.spans.get(i.min(self.spans.len().saturating_sub(1)))
1027    }
1028
1029    /// The pieces of the UTF-16 range `range` that no hidden run covers
1030    /// ([`ResolvedTextStyle::hidden`]), in order: where a selection's
1031    /// highlight is drawn. The whole range when no run is hidden.
1032    pub fn visible_ranges(&self, range: Range<u32>) -> Vec<Range<u32>> {
1033        if !self.has_hidden() {
1034            return vec![range];
1035        }
1036        let mut out: Vec<Range<u32>> = Vec::new();
1037        let mut at = range.start;
1038        let first = self.spans.partition_point(|s| s.end <= at);
1039        for s in &self.spans[first..] {
1040            if at >= range.end {
1041                break;
1042            }
1043            let to = s.end.min(range.end);
1044            if !s.style.hidden && to > at {
1045                match out.last_mut() {
1046                    Some(last) if last.end == at => last.end = to,
1047                    _ => out.push(at..to),
1048                }
1049            }
1050            at = at.max(to);
1051        }
1052        // Characters past the runs count as shown.
1053        if at < range.end {
1054            match out.last_mut() {
1055                Some(last) if last.end == at => last.end = range.end,
1056                _ => out.push(at..range.end),
1057            }
1058        }
1059        out
1060    }
1061
1062    /// Whether the character at the UTF-16 offset `index` is in a hidden
1063    /// run ([`ResolvedTextStyle::hidden`]): nothing of it is drawn.
1064    pub fn hidden_at(&self, index: u32) -> bool {
1065        self.span_at(index).is_some_and(|s| s.style.hidden)
1066    }
1067
1068    /// The background of the character at the UTF-16 offset `index`.
1069    pub fn background_at(&self, index: u32) -> Option<TextBackground> {
1070        self.span_at(index)?.style.background
1071    }
1072
1073    /// Length of the text so far, in UTF-16 units.
1074    pub fn len_utf16(&self) -> u32 {
1075        self.spans.last().map_or(0, |s| s.end)
1076    }
1077
1078    /// The innermost link containing the UTF-16 offset `index`.
1079    pub fn link_at(&self, index: u32) -> Option<&TextLink> {
1080        self.links
1081            .iter()
1082            .filter(|l| index >= l.start && index < l.end)
1083            .min_by_key(|l| l.end - l.start)
1084    }
1085
1086    /// Where link `link` (its index in [`Self::links`]) goes, when its
1087    /// span has an `href` (`link_hrefs`). Hidden, as that field is.
1088    #[doc(hidden)]
1089    pub fn link_href(&self, link: usize) -> Option<&str> {
1090        self.link_hrefs
1091            .iter()
1092            .find(|h| h.link as usize == link)
1093            .map(|h| &*h.href)
1094    }
1095
1096    /// Appends an attachment of `size` on the baseline.
1097    pub fn push_attachment(&mut self, size: Size<Points>, style: ResolvedTextStyle) {
1098        let index = self.len_utf16();
1099        self.push(ATTACHMENT_CHAR.encode_utf8(&mut [0; 3]), style);
1100        self.attachments.push(TextAttachment {
1101            index,
1102            width: size.width,
1103            height: size.height,
1104        });
1105    }
1106
1107    /// Appends `s` with `style`, merging with the previous run when the
1108    /// style is identical. Italic text keeps its color emoji upright, in
1109    /// runs of their own.
1110    pub fn push(&mut self, s: &str, style: ResolvedTextStyle) {
1111        if s.is_empty() {
1112            return;
1113        }
1114        let s = &*style.transform.apply(s);
1115        if !style.italic || s.is_ascii() {
1116            self.push_run(s, style);
1117            return;
1118        }
1119        // Emoji fonts have no italic face: Chrome and Android slant them,
1120        // WebKit and CoreText keep them upright, as every platform does here.
1121        let upright = ResolvedTextStyle {
1122            italic: false,
1123            ..style
1124        };
1125        let (mut run, mut at) = (0, 0);
1126        while at < s.len() {
1127            let end = crate::text_edit::next_cluster(s, at);
1128            if is_emoji_presentation(&s[at..end]) {
1129                self.push_run(&s[run..at], style);
1130                self.push_run(&s[at..end], upright);
1131                run = end;
1132            }
1133            at = end;
1134        }
1135        self.push_run(&s[run..], style);
1136    }
1137
1138    fn push_run(&mut self, s: &str, style: ResolvedTextStyle) {
1139        if s.is_empty() {
1140            return;
1141        }
1142        let len = s.encode_utf16().count() as u32;
1143        self.text.push_str(s);
1144        match self.spans.last_mut() {
1145            Some(last) if last.style == style => last.end += len,
1146            last => {
1147                let start = last.map_or(0, |l| l.end);
1148                self.spans.push(TextSpan {
1149                    start,
1150                    end: start + len,
1151                    style,
1152                });
1153            }
1154        }
1155    }
1156
1157    /// Whether the two texts differ at most in their spans' colors (text,
1158    /// decoration and background), which of them are hidden
1159    /// ([`ResolvedTextStyle::hidden`]) and metadata (test ids, copy texts,
1160    /// links' hrefs): the same characters in the same styles but for those,
1161    /// wherever the spans begin and end (neighbors that take the same color
1162    /// merge into one span).
1163    pub(crate) fn same_but_colors(&self, other: &Self) -> bool {
1164        // Enumerating the fields makes additions revisit this comparison.
1165        let Self {
1166            text,
1167            spans,
1168            paragraph_strut: _,
1169            align,
1170            max_lines,
1171            ellipsize,
1172            no_wrap,
1173            shadow,
1174            links,
1175            writing_direction,
1176            rtl,
1177            selectable,
1178            selection_color,
1179            attachments,
1180            test_ids: _,
1181            copy_texts: _,
1182            link_hrefs: _,
1183        } = self;
1184        text == &other.text
1185            && self.paragraph_strut_layout_eq(other)
1186            && align == &other.align
1187            && max_lines == &other.max_lines
1188            && ellipsize == &other.ellipsize
1189            && no_wrap == &other.no_wrap
1190            && shadow == &other.shadow
1191            && links == &other.links
1192            && writing_direction == &other.writing_direction
1193            && rtl == &other.rtl
1194            && selectable == &other.selectable
1195            && selection_color == &other.selection_color
1196            && attachments == &other.attachments
1197            && spans_same_but_colors(spans, &other.spans)
1198    }
1199
1200    /// The characters (UTF-16 offsets; ascending, apart) drawn otherwise in
1201    /// `other`, when the two texts differ at most in colors, hidden runs
1202    /// and test metadata, as the core's colors-only path allows; `None`
1203    /// when they differ in anything else. A platform that draws colors from
1204    /// the text and keeps the layout redraws only where these lie.
1205    pub fn recolored_ranges(&self, other: &Self) -> Option<Vec<std::ops::Range<u32>>> {
1206        if !self.same_but_colors(other) {
1207            return None;
1208        }
1209        let mut out: Vec<std::ops::Range<u32>> = Vec::new();
1210        // Both cover the string end to end (`same_but_colors`): walk the
1211        // pieces where they overlap.
1212        let (mut a, mut b) = (self.spans.iter().peekable(), other.spans.iter().peekable());
1213        while let (Some(x), Some(y)) = (a.peek(), b.peek()) {
1214            let (start, end) = (x.start.max(y.start), x.end.min(y.end));
1215            if start < end && x.style != y.style {
1216                match out.last_mut() {
1217                    Some(last) if last.end >= start => last.end = last.end.max(end),
1218                    _ => out.push(start..end),
1219                }
1220            }
1221            match x.end.cmp(&y.end) {
1222                std::cmp::Ordering::Less => {
1223                    a.next();
1224                }
1225                std::cmp::Ordering::Greater => {
1226                    b.next();
1227                }
1228                std::cmp::Ordering::Equal => {
1229                    a.next();
1230                    b.next();
1231                }
1232            }
1233        }
1234        Some(out)
1235    }
1236
1237    /// Whether the two texts have the same metadata: what
1238    /// [`Self::rendering_eq`] leaves out (test ids, copy texts, links'
1239    /// hrefs).
1240    pub(crate) fn metadata_eq(&self, other: &Self) -> bool {
1241        self.test_ids == other.test_ids
1242            && self.copy_texts == other.copy_texts
1243            && self.link_hrefs == other.link_hrefs
1244    }
1245
1246    /// Takes `other`'s metadata ([`Self::metadata_eq`]), keeping what is
1247    /// drawn: a fitted text's scaled spans mounted again with new metadata.
1248    pub(crate) fn set_metadata(&mut self, other: &Self) {
1249        self.test_ids = other.test_ids.clone();
1250        self.copy_texts = other.copy_texts.clone();
1251        self.link_hrefs = other.link_hrefs.clone();
1252    }
1253
1254    /// Equality of the content the platform draws, excluding metadata (test
1255    /// ids, copy texts, links' hrefs).
1256    pub(crate) fn rendering_eq(&self, other: &Self) -> bool {
1257        // Enumerating the fields makes additions revisit this comparison.
1258        let Self {
1259            text,
1260            spans,
1261            paragraph_strut: _,
1262            align,
1263            max_lines,
1264            ellipsize,
1265            no_wrap,
1266            shadow,
1267            links,
1268            writing_direction,
1269            rtl,
1270            selectable,
1271            selection_color,
1272            attachments,
1273            // Metadata: `metadata_eq` and `set_metadata` take these.
1274            test_ids: _,
1275            copy_texts: _,
1276            link_hrefs: _,
1277        } = self;
1278        text == &other.text
1279            && spans == &other.spans
1280            && self.paragraph_strut_layout_eq(other)
1281            && align == &other.align
1282            && max_lines == &other.max_lines
1283            && ellipsize == &other.ellipsize
1284            && no_wrap == &other.no_wrap
1285            && shadow == &other.shadow
1286            && links == &other.links
1287            && writing_direction == &other.writing_direction
1288            && rtl == &other.rtl
1289            && selectable == &other.selectable
1290            && selection_color == &other.selection_color
1291            && attachments == &other.attachments
1292    }
1293
1294    /// True if both texts lay out identically: same characters, runs,
1295    /// metrics and alignment. Decorative attributes (colors) are ignored.
1296    pub fn layout_eq(&self, other: &Self) -> bool {
1297        self.align == other.align
1298            && self.paragraph_strut_layout_eq(other)
1299            && self.writing_direction == other.writing_direction
1300            && self.rtl == other.rtl
1301            && self.max_lines == other.max_lines
1302            && self.ellipsize == other.ellipsize
1303            && self.no_wrap == other.no_wrap
1304            && self.text == other.text
1305            && self.attachments == other.attachments
1306            && self.spans.len() == other.spans.len()
1307            && self
1308                .spans
1309                .iter()
1310                .zip(&other.spans)
1311                .all(|(a, b)| a.start == b.start && a.end == b.end && a.style.layout_eq(&b.style))
1312    }
1313
1314    /// A 64-bit hash of everything [`AttributedText::layout_eq`] compares.
1315    /// SipHash (not Fx): it keys a cache without a full equality check.
1316    pub fn layout_hash(&self) -> u64 {
1317        let mut h = std::hash::DefaultHasher::new();
1318        self.text.hash(&mut h);
1319        let strut = self.paragraph_strut_or_first();
1320        strut.line_height.0.to_bits().hash(&mut h);
1321        (
1322            strut.font_size.0.to_bits(),
1323            strut.font_weight,
1324            strut.font_family,
1325            strut.italic,
1326            strut.font_variant,
1327        )
1328            .hash(&mut h);
1329        (self.align as u8, self.writing_direction, self.rtl).hash(&mut h);
1330        (self.max_lines, self.ellipsize, self.no_wrap).hash(&mut h);
1331        for s in &self.spans {
1332            (s.start, s.end, s.style.font_weight).hash(&mut h);
1333            (s.style.font_family, s.style.italic, s.style.font_variant).hash(&mut h);
1334            s.style.font_size.0.to_bits().hash(&mut h);
1335            s.style.line_height.0.to_bits().hash(&mut h);
1336            s.style.letter_spacing.0.to_bits().hash(&mut h);
1337        }
1338        for a in &self.attachments {
1339            (a.index, a.width.0.to_bits(), a.height.0.to_bits()).hash(&mut h);
1340        }
1341        h.finish()
1342    }
1343}
1344
1345/// An immutable, fully laid out text produced by a [`TextEngine`] on the
1346/// engine thread and drawn as-is by the platform on the UI thread, so text
1347/// is typeset exactly once.
1348#[derive(Clone)]
1349pub struct TextLayout(pub Arc<dyn Any + Send + Sync>);
1350
1351impl TextLayout {
1352    /// Returns the platform layout object.
1353    pub fn downcast<T: Any>(&self) -> Option<&T> {
1354        self.0.downcast_ref()
1355    }
1356}
1357
1358impl fmt::Debug for TextLayout {
1359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1360        f.write_str("TextLayout")
1361    }
1362}
1363
1364/// What a text block asks of its engine besides its characters, runs and
1365/// attachments: CSS's `text-indent`, and whatever a later release adds.
1366///
1367/// Passed to [`TextEngine::prepare_with`]; an engine that does not opt into
1368/// that method lays the text out without them, as it did before.
1369#[derive(Debug, Clone, Copy, PartialEq, Default)]
1370#[non_exhaustive]
1371pub struct TextOptions {
1372    /// `textIndent`: how far the first line of each paragraph starts in
1373    /// from the leading edge, in points. `None` is no indent.
1374    ///
1375    /// CSS's `text-indent` also takes a negative value, which hangs the
1376    /// first line into the margin; the engines here cannot do that the
1377    /// same way on every platform (DirectWrite has no width to hang into,
1378    /// Pango indents the lines after the first instead, a terminal has no
1379    /// margin), so a value that is not positive is no indent, as
1380    /// [`Self::indent`] keeps it.
1381    pub indent: Option<Points>,
1382}
1383
1384impl TextOptions {
1385    /// Sets [`Self::indent`], dropping a value that is not positive (or
1386    /// not finite): it would hang the first line, which no engine does the
1387    /// same way on every platform.
1388    #[must_use]
1389    pub fn indent(mut self, indent: impl Into<Option<Points>>) -> Self {
1390        self.indent = indent
1391            .into()
1392            .filter(|indent| indent.0.is_finite() && indent.0 > 0.0);
1393        self
1394    }
1395}
1396
1397/// The platform text engine (CoreText, Android `StaticLayout`, ...).
1398///
1399/// All methods run on the engine thread, so implementations must not touch
1400/// UI-thread-only objects. The split mirrors how native text stacks work:
1401/// typesetting state is prepared once per content, measured at any number
1402/// of widths during layout, and finally laid out once at the final size.
1403pub trait TextEngine {
1404    /// Typesetting state for one content, reused across measurements
1405    /// (e.g. a `CTFramesetter`).
1406    type Prepared;
1407
1408    /// Prepares `text` for measuring and layout.
1409    fn prepare(&self, text: &AttributedText) -> Self::Prepared;
1410
1411    /// Prepares text with optional inline alignment. Existing engines retain
1412    /// baseline placement until they opt into this extension.
1413    fn prepare_aligned(
1414        &self,
1415        text: &AttributedText,
1416        alignments: &AttachmentAlignments,
1417    ) -> Self::Prepared {
1418        let _ = alignments;
1419        self.prepare(text)
1420    }
1421
1422    /// Prepares text with the block's [`TextOptions`]. Existing engines keep
1423    /// their layout until they opt into this extension.
1424    fn prepare_with(
1425        &self,
1426        text: &AttributedText,
1427        alignments: &AttachmentAlignments,
1428        options: &TextOptions,
1429    ) -> Self::Prepared {
1430        let _ = options;
1431        self.prepare_aligned(text, alignments)
1432    }
1433
1434    /// Size of the prepared text with an optional maximum width.
1435    fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points>;
1436
1437    /// How far below the text's top its first line's baseline is, laid out
1438    /// `width` wide: a flex container aligning by baseline
1439    /// (`align-items: baseline`) lines its items up by it, as CSS does. An
1440    /// engine that does not know gives `None`, and the text is aligned by
1441    /// its bottom edge, Taffy's fallback for a box without a baseline.
1442    fn first_baseline(&self, prepared: &Self::Prepared, width: Points) -> Option<Points> {
1443        let _ = (prepared, width);
1444        None
1445    }
1446
1447    /// Whether a single-line input's intrinsic height depends only on its
1448    /// text style, including when a glyph comes from a fallback font.
1449    fn uniform_input_line_height(&self) -> bool {
1450        false
1451    }
1452
1453    /// Whether each line takes all that fits and [`TextEngine::measure`]'s
1454    /// width is the widest line's: a maximum width between that width and
1455    /// the one measured then breaks the lines at the same places, so the
1456    /// core knows the size without typesetting. A window's resize changes
1457    /// the width of every text of a page on every size.
1458    fn breaks_lines_greedily(&self) -> bool {
1459        false
1460    }
1461
1462    /// Whether the platform draws a text's colors from the
1463    /// [`AttributedText`] mounted with its layout, not from the
1464    /// typesetting state: the spans' text, decoration and background
1465    /// colors and which spans are hidden ([`ResolvedTextStyle::hidden`]),
1466    /// looked up by character when drawing. The prepared state and
1467    /// layouts then hold for any text that differs from theirs only in
1468    /// those (wherever its spans begin and end), so a change of colors or
1469    /// of what is hidden alone keeps them: no new typesetting, measurement
1470    /// or layout, only the new text mounted with the layout already drawn.
1471    fn draws_colors_from_text(&self) -> bool {
1472        false
1473    }
1474
1475    /// The final layout in a box of exactly `size`, for drawing.
1476    fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout;
1477
1478    /// The lines of a final layout (`onTextLayout`); `text` is left empty
1479    /// (the core fills it in).
1480    fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1481        let _ = layout;
1482        Vec::new()
1483    }
1484
1485    /// Where a final layout put the text's attachments, in order: the
1486    /// top left of each placeholder in the content box (y down), or `None`
1487    /// when it was cut off (lines past the limit, an ellipsis).
1488    fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
1489        let _ = layout;
1490        Vec::new()
1491    }
1492
1493    /// The caret position nearest `point` (content box, y down) in a final
1494    /// layout: on the line at that height (the first line above the text,
1495    /// the last below it), at the character edge nearest its x. A point
1496    /// past the end of a wrapped line gives the line's end with
1497    /// [`Affinity::Upstream`], so the caret stays on that line.
1498    ///
1499    /// The default estimates it from [`TextEngine::lines`], each line's
1500    /// characters spread evenly over its width; engines that know where
1501    /// their glyphs are override it.
1502    fn hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
1503        estimate::hit_test(&self.lines(layout), point)
1504    }
1505
1506    /// The caret at `position` in a final layout: a box of no width as high
1507    /// as its line (content box, y down), at the edge of the characters
1508    /// `position` stands between; `None` when the layout has no lines.
1509    ///
1510    /// The default estimates it from [`TextEngine::lines`], as
1511    /// [`TextEngine::hit_test`] does.
1512    fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
1513        estimate::caret_rect(&self.lines(layout), position)
1514    }
1515
1516    /// Appends to `out` the boxes (content box, y down) that cover the
1517    /// characters of `range` (UTF-16 offsets), line high: per line, one box
1518    /// per stretch of adjacent characters (several where bidirectional text
1519    /// splits the range), and through the line's end where the range goes
1520    /// on past it. `out` is the caller's, so a selection drawn every frame
1521    /// reuses one buffer.
1522    ///
1523    /// The default estimates them from [`TextEngine::lines`], as
1524    /// [`TextEngine::hit_test`] does.
1525    fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1526        estimate::range_rects(&self.lines(layout), range, out);
1527    }
1528
1529    /// Makes the font in `data` (TrueType / OpenType) available by its
1530    /// family name. Fonts are registered before the text using them is
1531    /// measured.
1532    fn register_font(&self, data: &[u8]) -> Result<(), String> {
1533        let _ = data;
1534        Err("this text engine does not support custom fonts".to_owned())
1535    }
1536}
1537
1538/// A shared engine, e.g. one the core lays text out with and canvas
1539/// `measureText` measures with.
1540impl<T: TextEngine> TextEngine for std::rc::Rc<T> {
1541    type Prepared = T::Prepared;
1542
1543    fn prepare(&self, text: &AttributedText) -> Self::Prepared {
1544        (**self).prepare(text)
1545    }
1546
1547    fn prepare_aligned(
1548        &self,
1549        text: &AttributedText,
1550        alignments: &AttachmentAlignments,
1551    ) -> Self::Prepared {
1552        (**self).prepare_aligned(text, alignments)
1553    }
1554
1555    fn prepare_with(
1556        &self,
1557        text: &AttributedText,
1558        alignments: &AttachmentAlignments,
1559        options: &TextOptions,
1560    ) -> Self::Prepared {
1561        (**self).prepare_with(text, alignments, options)
1562    }
1563
1564    fn breaks_lines_greedily(&self) -> bool {
1565        (**self).breaks_lines_greedily()
1566    }
1567
1568    fn draws_colors_from_text(&self) -> bool {
1569        (**self).draws_colors_from_text()
1570    }
1571
1572    fn uniform_input_line_height(&self) -> bool {
1573        (**self).uniform_input_line_height()
1574    }
1575
1576    fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points> {
1577        (**self).measure(prepared, max_width)
1578    }
1579
1580    fn first_baseline(&self, prepared: &Self::Prepared, width: Points) -> Option<Points> {
1581        (**self).first_baseline(prepared, width)
1582    }
1583
1584    fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout {
1585        (**self).layout(prepared, size)
1586    }
1587
1588    fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1589        (**self).lines(layout)
1590    }
1591
1592    fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
1593        (**self).attachments(layout)
1594    }
1595
1596    fn hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
1597        (**self).hit_test(layout, point)
1598    }
1599
1600    fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
1601        (**self).caret_rect(layout, position)
1602    }
1603
1604    fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1605        (**self).range_rects(layout, range, out);
1606    }
1607
1608    fn register_font(&self, data: &[u8]) -> Result<(), String> {
1609        (**self).register_font(data)
1610    }
1611}
1612
1613/// One line of laid-out text (`onTextLayout`), in the content box (y
1614/// down, points).
1615#[derive(Debug, Clone, PartialEq, Default)]
1616pub struct TextLine {
1617    /// Its characters.
1618    pub text: String,
1619    /// Start offset in the text (UTF-16 units, inclusive).
1620    pub start: u32,
1621    /// End offset (UTF-16 units, exclusive).
1622    pub end: u32,
1623    /// Left edge.
1624    pub x: Points,
1625    /// Top edge.
1626    pub y: Points,
1627    /// Typographic width.
1628    pub width: Points,
1629    /// Height (ascender + descender + leading).
1630    pub height: Points,
1631    /// Above the baseline.
1632    pub ascender: Points,
1633    /// Below the baseline.
1634    pub descender: Points,
1635    /// Height of capitals.
1636    pub cap_height: Points,
1637    /// Height of lowercase letters.
1638    pub x_height: Points,
1639}
1640
1641/// Which side a caret offset is on where one offset is two places on
1642/// screen: the end of a wrapped line and the start of the next.
1643#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1644pub enum Affinity {
1645    /// With the character before the offset: at the end of the earlier
1646    /// line.
1647    Upstream,
1648    /// With the character after the offset: at the start of the later
1649    /// line.
1650    #[default]
1651    Downstream,
1652}
1653
1654/// A caret position in a text: a UTF-16 offset and the side it is on.
1655#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1656#[non_exhaustive]
1657pub struct TextPosition {
1658    /// The offset (UTF-16 units).
1659    pub offset: u32,
1660    /// Which line it is on where it ends one and starts the next.
1661    pub affinity: Affinity,
1662}
1663
1664impl TextPosition {
1665    /// The position at `offset` on the side `affinity` says.
1666    pub const fn new(offset: u32, affinity: Affinity) -> Self {
1667        Self { offset, affinity }
1668    }
1669
1670    /// The index of the line of `lines` (a final layout's, in order) the
1671    /// caret at this position is on: the line holding the offset, the
1672    /// earlier of two for [`Affinity::Upstream`] at a line's end; past every
1673    /// line (the text's end, an empty last line), the last line starting at
1674    /// or before it. `None` when there are no lines.
1675    pub fn line(self, lines: &[TextLine]) -> Option<usize> {
1676        self.line_in(lines.iter().map(|l| l.start..l.end))
1677    }
1678
1679    /// [`TextPosition::line`] over the UTF-16 ranges of the lines, for
1680    /// engines that keep their lines in a type of their own.
1681    pub fn line_in<I>(self, ranges: I) -> Option<usize>
1682    where
1683        I: IntoIterator<Item = Range<u32>>,
1684        I::IntoIter: Clone,
1685    {
1686        let ranges = ranges.into_iter();
1687        let o = self.offset;
1688        let holds = |r: &Range<u32>| match self.affinity {
1689            Affinity::Upstream => r.start < o && o <= r.end,
1690            Affinity::Downstream => r.start <= o && o < r.end,
1691        };
1692        ranges
1693            .clone()
1694            .position(|r| holds(&r))
1695            .or_else(|| {
1696                let starts = ranges.clone().enumerate();
1697                starts.filter(|(_, r)| r.start <= o).last().map(|(i, _)| i)
1698            })
1699            .or_else(|| ranges.clone().next().map(|_| 0))
1700    }
1701}
1702
1703/// The hit testing of engines that only report their lines: each line's
1704/// characters spread evenly over its width, left to right.
1705mod estimate {
1706    use super::*;
1707
1708    /// The line a point at height `y` lands on: the one at that height, the
1709    /// first above the text, the last below it.
1710    pub(super) fn line_at(lines: &[TextLine], y: Points) -> Option<&TextLine> {
1711        lines.iter().find(|l| y < l.y + l.height).or(lines.last())
1712    }
1713
1714    /// The x of offset `o` (clamped to the line).
1715    fn x_of(l: &TextLine, o: u32) -> Points {
1716        let count = l.end.saturating_sub(l.start);
1717        if count == 0 {
1718            return l.x;
1719        }
1720        let done = o.clamp(l.start, l.end) - l.start;
1721        l.x + l.width * (done as f32 / count as f32)
1722    }
1723
1724    pub(super) fn hit_test(lines: &[TextLine], p: Point<Points>) -> TextPosition {
1725        let Some(l) = line_at(lines, p.y) else {
1726            return TextPosition::default();
1727        };
1728        let count = l.end.saturating_sub(l.start);
1729        let fraction = if l.width > Points::ZERO {
1730            ((p.x - l.x) / l.width).clamp(0.0, 1.0)
1731        } else {
1732            0.0
1733        };
1734        // At most `count`: the cast cannot truncate.
1735        let offset = l.start + (fraction * count as f32).round() as u32;
1736        let affinity = if offset == l.end && count > 0 {
1737            Affinity::Upstream
1738        } else {
1739            Affinity::Downstream
1740        };
1741        TextPosition::new(offset, affinity)
1742    }
1743
1744    pub(super) fn caret_rect(lines: &[TextLine], position: TextPosition) -> Option<Bounds<Points>> {
1745        let l = lines.get(position.line(lines)?)?;
1746        Some(Bounds::new(
1747            point(x_of(l, position.offset), l.y),
1748            size(Points::ZERO, l.height),
1749        ))
1750    }
1751
1752    pub(super) fn range_rects(lines: &[TextLine], r: Range<u32>, out: &mut Vec<Bounds<Points>>) {
1753        if r.start >= r.end {
1754            return;
1755        }
1756        for l in lines.iter().filter(|l| l.start < r.end && r.start < l.end) {
1757            let x1 = x_of(l, r.start);
1758            let x2 = if r.end > l.end {
1759                l.x + l.width
1760            } else {
1761                x_of(l, r.end)
1762            };
1763            out.push(Bounds::new(point(x1, l.y), size(x2 - x1, l.height)));
1764        }
1765    }
1766}
1767
1768/// Prepared typesetting state for [`ApproxTextEngine`].
1769#[doc(hidden)]
1770#[derive(Debug, Clone)]
1771#[non_exhaustive]
1772pub struct ApproxPrepared {
1773    chars: usize,
1774    font: Points,
1775    /// The root strut's font for the baseline when a fixed paragraph line
1776    /// height is set (otherwise `font`, preserving the natural model).
1777    strut_font: Points,
1778    line: Points,
1779    max_lines: u32,
1780    /// `textIndent`: how far each paragraph's first line starts in, in
1781    /// points (0 by default).
1782    indent: Points,
1783    attachments: Vec<TextAttachment>,
1784    astral: Vec<u32>,
1785    breaks: Vec<usize>,
1786}
1787
1788impl ApproxPrepared {
1789    /// Characters this preparation covers.
1790    #[doc(hidden)]
1791    pub fn chars(&self) -> usize {
1792        self.chars
1793    }
1794}
1795
1796impl Default for ApproxPrepared {
1797    fn default() -> Self {
1798        let font = px(14.0);
1799        Self {
1800            chars: 0,
1801            font,
1802            strut_font: font,
1803            line: font * 1.2,
1804            max_lines: 0,
1805            indent: Points::ZERO,
1806            attachments: Vec::new(),
1807            astral: Vec::new(),
1808            breaks: Vec::new(),
1809        }
1810    }
1811}
1812
1813/// A deterministic, platform-free [`TextEngine`] for headless runs and
1814/// tests: every character is `0.55 × font size` wide (in the largest span's
1815/// font) and lines are as tall as the spans' `lineHeight` (or `1.2 × font size`
1816/// by default); a text with line breaks measures as wide as its widest line and
1817/// as tall as its lines (each wrapped on its own), their baseline placed with
1818/// half-leading around the natural `1.2 × font size` ascent (its descent 0 when
1819/// unspaced, its x height `0.5 × font size`), where attachments are placed by
1820/// [`TextAttachment::ascent`] on the line their character wraps to (its lines,
1821/// carets and hits are those of one line). A `textIndent` starts each
1822/// paragraph's first line that far in and narrows it by as much.
1823#[derive(Debug, Default, Clone, Copy)]
1824pub struct ApproxTextEngine;
1825
1826impl TextEngine for ApproxTextEngine {
1827    type Prepared = ApproxPrepared;
1828
1829    fn prepare(&self, text: &AttributedText) -> Self::Prepared {
1830        self.prepare_aligned(text, &AttachmentAlignments::default())
1831    }
1832
1833    fn prepare_aligned(
1834        &self,
1835        text: &AttributedText,
1836        alignments: &AttachmentAlignments,
1837    ) -> Self::Prepared {
1838        let (font, line) = text.approx_metrics();
1839        // Empty (no allocation) for text in the Basic Multilingual Plane.
1840        let astral = text
1841            .text
1842            .chars()
1843            .enumerate()
1844            .filter(|(_, c)| c.len_utf16() == 2)
1845            .filter_map(|(i, _)| u32::try_from(i).ok())
1846            .collect();
1847        // Empty (no allocation) for a text of one line.
1848        let breaks = match text.text.contains('\n') {
1849            true => text.text.split('\n').map(|l| l.chars().count()).collect(),
1850            false => Vec::new(),
1851        };
1852        let metrics = FontExtent::new(font * 1.2, Points::ZERO, font * 0.5);
1853        ApproxPrepared {
1854            chars: text.text.chars().count(),
1855            font,
1856            strut_font: match text.paragraph_strut {
1857                Some(strut) if strut.line_height.0 > 0.0 => strut.font_size,
1858                // A directly constructed text has no root strut: keep the
1859                // historic estimate based on its largest span font.
1860                _ => font,
1861            },
1862            line,
1863            max_lines: text.max_lines,
1864            indent: Points::ZERO,
1865            attachments: text
1866                .attachments
1867                .iter()
1868                .map(|a| TextAttachment {
1869                    height: alignments.ascent(a, metrics),
1870                    ..*a
1871                })
1872                .collect(),
1873            astral,
1874            breaks,
1875        }
1876    }
1877
1878    fn prepare_with(
1879        &self,
1880        text: &AttributedText,
1881        alignments: &AttachmentAlignments,
1882        options: &TextOptions,
1883    ) -> Self::Prepared {
1884        let mut prepared = self.prepare_aligned(text, alignments);
1885        // `TextOptions` keeps an indent that is not positive out.
1886        prepared.indent = options.indent.unwrap_or(Points::ZERO);
1887        prepared
1888    }
1889
1890    /// The first line's baseline from the top of the box (natural ascent plus
1891    /// half-leading).
1892    fn first_baseline(&self, prepared: &Self::Prepared, _: Points) -> Option<Points> {
1893        let natural = prepared.strut_font * 1.2;
1894        Some(natural + (prepared.line - natural) * 0.5)
1895    }
1896
1897    fn measure(&self, prepared: &Self::Prepared, max_width: Option<Points>) -> Size<Points> {
1898        // The order of the products is kept: it decides the last bit.
1899        let wrap = |chars: usize| {
1900            let width = Points(chars as f32 * prepared.font.0 * 0.55);
1901            match max_width {
1902                // No indent: the historic product order decides the last
1903                // bit, and with it how many lines a width gives.
1904                Some(max) if max > Points::ZERO && prepared.indent == Points::ZERO => {
1905                    match width > max {
1906                        true => (max, (width / max).ceil()),
1907                        false => (width, 1.0),
1908                    }
1909                }
1910                Some(max) if max > Points::ZERO => {
1911                    // A paragraph's first line starts `indent` in, so it
1912                    // holds `indent` less and is `indent` wider as a box.
1913                    let first = (max - prepared.indent).max(Points::ZERO);
1914                    if width <= first {
1915                        (width + prepared.indent, 1.0)
1916                    } else {
1917                        (
1918                            first + prepared.indent,
1919                            1.0 + ((width - first) / max).ceil(),
1920                        )
1921                    }
1922                }
1923                _ => (width + prepared.indent, 1.0),
1924            }
1925        };
1926        let (width, mut lines) = match prepared.breaks.is_empty() {
1927            true => wrap(prepared.chars),
1928            false => prepared
1929                .breaks
1930                .iter()
1931                .fold((Points::ZERO, 0.0), |(w, n), &c| {
1932                    let (lw, ln) = wrap(c);
1933                    (w.max(lw), n + ln)
1934                }),
1935        };
1936        if prepared.max_lines > 0 {
1937            lines = lines.min(prepared.max_lines as f32);
1938        }
1939        size(width, prepared.line * lines)
1940    }
1941
1942    fn layout(&self, prepared: &Self::Prepared, size: Size<Points>) -> TextLayout {
1943        // Each character as wide as the others, reported as one line.
1944        let line = prepared.line;
1945        let font = prepared.font;
1946        let natural = prepared.strut_font * 1.2;
1947        let baseline = natural + (line - natural) * 0.5;
1948        let advance = font * 0.55;
1949        let units = prepared.chars.saturating_add(prepared.astral.len());
1950        let mut layout = ApproxLayout {
1951            attachments: Vec::new(),
1952            attachment_widths: Vec::new(),
1953            line: TextLine {
1954                end: u32::try_from(units).unwrap_or(u32::MAX),
1955                width: size.width,
1956                height: line,
1957                ascender: baseline,
1958                descender: (line - baseline).max(Points::ZERO),
1959                x_height: font * 0.5,
1960                ..TextLine::default()
1961            },
1962            advance,
1963            chars: u32::try_from(prepared.chars).unwrap_or(u32::MAX),
1964            astral: prepared.astral.clone(),
1965        };
1966        layout.attachment_widths = prepared
1967            .attachments
1968            .iter()
1969            .map(|a| (layout.char_at(a.index), a.width))
1970            .collect();
1971        layout.attachment_widths.sort_unstable_by_key(|&(k, _)| k);
1972        // An attachment sits on the line its character wraps to, as
1973        // `measure` wraps the text in a box this wide.
1974        layout.attachments = prepared
1975            .attachments
1976            .iter()
1977            .map(|a| {
1978                let (row, x) = approx_place(
1979                    layout.char_at(a.index) as usize,
1980                    prepared.chars,
1981                    font,
1982                    &prepared.breaks,
1983                    size.width,
1984                );
1985                if prepared.max_lines > 0 && row >= prepared.max_lines as f32 {
1986                    return None;
1987                }
1988                Some(point(
1989                    x,
1990                    line * row + (baseline - a.height).max(Points::ZERO),
1991                ))
1992            })
1993            .collect();
1994        TextLayout(Arc::new(layout))
1995    }
1996
1997    fn lines(&self, layout: &TextLayout) -> Vec<TextLine> {
1998        layout
1999            .downcast::<ApproxLayout>()
2000            .map_or_else(Vec::new, |l| vec![l.line.clone()])
2001    }
2002
2003    fn attachments(&self, layout: &TextLayout) -> Vec<Option<Point<Points>>> {
2004        layout
2005            .downcast::<ApproxLayout>()
2006            .map_or_else(Vec::new, |l| l.attachments.clone())
2007    }
2008
2009    fn hit_test(&self, layout: &TextLayout, p: Point<Points>) -> TextPosition {
2010        let Some(l) = layout.downcast::<ApproxLayout>() else {
2011            return TextPosition::default();
2012        };
2013        TextPosition::new(l.unit_of(l.hit_x(p.x)), Affinity::Downstream)
2014    }
2015
2016    fn caret_rect(&self, layout: &TextLayout, position: TextPosition) -> Option<Bounds<Points>> {
2017        let l = layout.downcast::<ApproxLayout>()?;
2018        Some(Bounds::new(
2019            point(l.x_of(position.offset), l.line.y),
2020            size(Points::ZERO, l.line.height),
2021        ))
2022    }
2023
2024    fn range_rects(&self, layout: &TextLayout, range: Range<u32>, out: &mut Vec<Bounds<Points>>) {
2025        let Some(l) = layout.downcast::<ApproxLayout>() else {
2026            return;
2027        };
2028        if range.start >= range.end || range.start >= l.line.end {
2029            return;
2030        }
2031        let (x1, x2) = (l.x_of(range.start), l.x_of(range.end));
2032        out.push(Bounds::new(
2033            point(x1, l.line.y),
2034            size(x2 - x1, l.line.height),
2035        ));
2036    }
2037
2038    fn register_font(&self, _: &[u8]) -> Result<(), String> {
2039        Ok(())
2040    }
2041}
2042
2043/// Where [`ApproxTextEngine`] puts character `k` of a text of `chars`
2044/// characters in a box `width` wide (`breaks`: each line's character count
2045/// when the text has line breaks): its line, counted from 0, and its x. A
2046/// line wraps as `measure` wraps it: at the box's width, the characters
2047/// running on.
2048fn approx_place(
2049    k: usize,
2050    chars: usize,
2051    font: Points,
2052    breaks: &[usize],
2053    width: Points,
2054) -> (f32, Points) {
2055    let whole = [chars];
2056    let lines: &[usize] = if breaks.is_empty() { &whole } else { breaks };
2057    // The order of the products is `measure`'s: it decides the last bit.
2058    let wraps = |chars: usize| {
2059        let w = Points(chars as f32 * font.0 * 0.55);
2060        match w > width && width > Points::ZERO {
2061            true => (w / width).ceil(),
2062            false => 1.0,
2063        }
2064    };
2065    let (mut row, mut start) = (0.0, 0);
2066    for (i, &n) in lines.iter().enumerate() {
2067        if k <= start + n || i + 1 == lines.len() {
2068            let x = Points(k.saturating_sub(start) as f32 * font.0 * 0.55);
2069            let n_wraps = wraps(n);
2070            if n_wraps <= 1.0 {
2071                return (row, x);
2072            }
2073            let wrapped = (x / width).floor().min(n_wraps - 1.0);
2074            return (row + wrapped, x - width * wrapped);
2075        }
2076        row += wraps(n);
2077        start += n + 1;
2078    }
2079    (row, Points::ZERO)
2080}
2081
2082/// [`ApproxTextEngine`]'s final layout: reported as one line.
2083struct ApproxLayout {
2084    attachments: Vec<Option<Point<Points>>>,
2085    /// `(char_index, width)` of each attachment, sorted by `char_index`.
2086    attachment_widths: Vec<(u32, Points)>,
2087    line: TextLine,
2088    /// The width of every character.
2089    advance: Points,
2090    chars: u32,
2091    /// The indices of the characters two UTF-16 units long, in order.
2092    astral: Vec<u32>,
2093}
2094
2095impl ApproxLayout {
2096    /// The UTF-16 offset of character `k`.
2097    fn unit_of(&self, k: u32) -> u32 {
2098        let before = self.astral.partition_point(|&i| i < k);
2099        k.saturating_add(u32::try_from(before).unwrap_or(u32::MAX))
2100    }
2101
2102    /// The character at UTF-16 offset `o`: the one it starts, or the one
2103    /// it is inside (between the two units of a surrogate pair).
2104    fn char_at(&self, o: u32) -> u32 {
2105        let mut k = o;
2106        for (j, &i) in self.astral.iter().enumerate() {
2107            let start = i.saturating_add(u32::try_from(j).unwrap_or(u32::MAX));
2108            if start >= o {
2109                break;
2110            }
2111            k = if start.saturating_add(1) == o {
2112                i
2113            } else {
2114                k.saturating_sub(1)
2115            };
2116        }
2117        k.min(self.chars)
2118    }
2119
2120    /// The x of the caret at UTF-16 offset `o`.
2121    fn x_of(&self, o: u32) -> Points {
2122        let k = self.char_at(o);
2123        let mut x = self.advance * k as f32;
2124        for &(at, width) in &self.attachment_widths {
2125            if at >= k {
2126                break;
2127            }
2128            x += width - self.advance;
2129        }
2130        x
2131    }
2132
2133    /// The character boundary nearest horizontal position `x`.
2134    fn hit_x(&self, x: Points) -> u32 {
2135        if x <= Points::ZERO {
2136            return 0;
2137        }
2138        if self.attachment_widths.is_empty() {
2139            return if self.advance > Points::ZERO {
2140                // Clamped to `0..=chars` first: the cast cannot truncate.
2141                (x / self.advance).round().clamp(0.0, self.chars as f32) as u32
2142            } else {
2143                0
2144            };
2145        }
2146        let mut seg_start = 0u32;
2147        let mut cur_x = Points::ZERO;
2148        for &(at, width) in &self.attachment_widths {
2149            let at = at.min(self.chars);
2150            if at > seg_start {
2151                let n = at - seg_start;
2152                let run_end = cur_x + self.advance * n as f32;
2153                if x < run_end {
2154                    let step = if self.advance > Points::ZERO {
2155                        ((x - cur_x) / self.advance).round().clamp(0.0, n as f32) as u32
2156                    } else {
2157                        0
2158                    };
2159                    return seg_start + step;
2160                }
2161                cur_x = run_end;
2162            }
2163            let att_end = cur_x + width;
2164            if x < att_end {
2165                return if x < cur_x + width * 0.5 {
2166                    at
2167                } else {
2168                    (at + 1).min(self.chars)
2169                };
2170            }
2171            cur_x = att_end;
2172            seg_start = (at + 1).min(self.chars);
2173        }
2174        if seg_start < self.chars {
2175            let n = self.chars - seg_start;
2176            let step = if self.advance > Points::ZERO {
2177                ((x - cur_x) / self.advance).round().clamp(0.0, n as f32) as u32
2178            } else {
2179                0
2180            };
2181            return seg_start + step;
2182        }
2183        self.chars
2184    }
2185}
2186
2187/// Content-addressed text measurements shared by all nodes of a surface,
2188/// so identical texts (list rows, recycled cells) are measured once.
2189///
2190/// Approximate LRU with two generations: lookups hit the current one or
2191/// promote from the previous one; when the current generation is full it
2192/// becomes the previous one. O(1), and never more than `2 * GENERATION`
2193/// entries.
2194///
2195/// It also holds the surface's pixel ratio: measurements are rounded up to
2196/// its device pixels ([`MeasureCache::pixel_ratio`]), so they are only
2197/// valid for one ratio and go when it changes. On a grid surface (a
2198/// terminal) they are rounded up to its whole Cells instead
2199/// ([`MeasureCache::set_cell`]).
2200pub(crate) struct MeasureCache {
2201    current: FxHashMap<(u64, u32), Size<Points>>,
2202    previous: FxHashMap<(u64, u32), Size<Points>>,
2203    pixel_ratio: f32,
2204    cell: Option<Size<Points>>,
2205    /// The commit of a burst of resizes under way (`Core::set_resizing`):
2206    /// text it did not find near the screen is not measured.
2207    pub(crate) resizing: Option<u32>,
2208}
2209
2210impl Default for MeasureCache {
2211    fn default() -> Self {
2212        Self {
2213            current: FxHashMap::default(),
2214            previous: FxHashMap::default(),
2215            pixel_ratio: 1.0,
2216            cell: None,
2217            resizing: None,
2218        }
2219    }
2220}
2221
2222impl MeasureCache {
2223    const GENERATION: usize = 512;
2224
2225    /// The device pixels per point the measurements are rounded to.
2226    pub(crate) fn pixel_ratio(&self) -> f32 {
2227        self.pixel_ratio
2228    }
2229
2230    /// Measures for `ratio` from now on; returns whether it changed (the
2231    /// measurements cached for the previous ratio are dropped).
2232    pub(crate) fn set_pixel_ratio(&mut self, ratio: f32) -> bool {
2233        let ratio = if ratio.is_finite() && ratio > 0.0 {
2234            ratio
2235        } else {
2236            1.0
2237        };
2238        if ratio == self.pixel_ratio {
2239            return false;
2240        }
2241        self.pixel_ratio = ratio;
2242        self.clear();
2243        true
2244    }
2245
2246    /// Measures on a grid of `cell` (a terminal's Cells) from now on, or to
2247    /// device pixels with `None`; returns whether it changed (the
2248    /// measurements cached before are dropped).
2249    pub(crate) fn set_cell(&mut self, cell: Option<Size<Points>>) -> bool {
2250        if cell == self.cell {
2251            return false;
2252        }
2253        self.cell = cell;
2254        self.clear();
2255        true
2256    }
2257
2258    /// `size` rounded up to whole Cells on a grid surface: a text is never
2259    /// shorter or narrower than the Cells it takes, so the frames rounded
2260    /// to Cells never cut its last line or glyph. `None` off a grid.
2261    pub(crate) fn on_cells(&self, size: Size<Points>) -> Option<Size<Points>> {
2262        let cell = self.cell?;
2263        let up = |v: Points, c: Points| Points(((v.0 / c.0) - 1.0e-3).ceil().max(0.0) * c.0);
2264        Some(Size::new(
2265            up(size.width, cell.width),
2266            up(size.height, cell.height),
2267        ))
2268    }
2269
2270    /// Drops every measurement (the fonts changed), keeping the ratio.
2271    pub(crate) fn clear(&mut self) {
2272        self.current.clear();
2273        self.previous.clear();
2274    }
2275
2276    #[inline]
2277    fn key(layout_hash: u64, max_width: Option<Points>) -> (u64, u32) {
2278        // NaN never comes from taffy, so it can stand for "unconstrained".
2279        (layout_hash, max_width.map_or(f32::NAN, |w| w.0).to_bits())
2280    }
2281
2282    pub(crate) fn get(
2283        &mut self,
2284        layout_hash: u64,
2285        max_width: Option<Points>,
2286    ) -> Option<Size<Points>> {
2287        let key = Self::key(layout_hash, max_width);
2288        if let Some(&size) = self.current.get(&key) {
2289            return Some(size);
2290        }
2291        let size = self.previous.remove(&key)?;
2292        self.insert_key(key, size);
2293        Some(size)
2294    }
2295
2296    pub(crate) fn insert(
2297        &mut self,
2298        layout_hash: u64,
2299        max_width: Option<Points>,
2300        size: Size<Points>,
2301    ) {
2302        self.insert_key(Self::key(layout_hash, max_width), size);
2303    }
2304
2305    fn insert_key(&mut self, key: (u64, u32), size: Size<Points>) {
2306        if self.current.len() >= Self::GENERATION {
2307            self.previous = std::mem::take(&mut self.current);
2308            self.current.reserve(Self::GENERATION);
2309        }
2310        self.current.insert(key, size);
2311    }
2312
2313    #[cfg(test)]
2314    fn len(&self) -> usize {
2315        self.current.len() + self.previous.len()
2316    }
2317}
2318
2319/// The most a WOFF file's tables may declare they hold: what `wuff` lets a
2320/// WOFF2 file hold, which it checks itself before it decompresses.
2321const MAX_WOFF_TABLES: u64 = 128 * 1024 * 1024;
2322
2323/// The TrueType or OpenType data of a font file, which the text engines
2324/// register: `data` itself, or what a WOFF or WOFF2 file holds,
2325/// decompressed (WOFF2's transformed glyph tables rebuilt).
2326pub fn font_data(data: &[u8]) -> Result<std::borrow::Cow<'_, [u8]>, String> {
2327    let unwrapped = match data.get(..4) {
2328        Some(b"wOFF") => {
2329            // `wuff` reserves the size each table declares before inflating
2330            // it, so a few bytes could otherwise ask for gigabytes; and it
2331            // copies a table that is not smaller compressed at its compressed
2332            // size, so tables sharing one block of data could copy it past
2333            // what their sizes add up to.
2334            if let Some(size) = woff_tables_size(data)?.filter(|&size| size > MAX_WOFF_TABLES) {
2335                return Err(format!(
2336                    "the WOFF font's tables declare {size} bytes, more than a font may hold \
2337                     ({MAX_WOFF_TABLES})"
2338                ));
2339            }
2340            wuff::decompress_woff1(data)
2341        }
2342        Some(b"wOF2") => wuff::decompress_woff2(data),
2343        _ => return Ok(std::borrow::Cow::Borrowed(data)),
2344    };
2345    unwrapped
2346        .map(std::borrow::Cow::Owned)
2347        .map_err(|e| format!("the WOFF font does not decompress: {e:?}"))
2348}
2349
2350/// Keeps a font file a host registers, once: `false` when `fonts` holds the
2351/// same bytes already, so registering a file again changes nothing.
2352pub fn keep_font(fonts: &mut Vec<Vec<u8>>, data: &[u8]) -> bool {
2353    if fonts.iter().any(|font| font == data) {
2354        return false;
2355    }
2356    fonts.push(data.to_vec());
2357    true
2358}
2359
2360/// The sizes a WOFF file's table directory declares, summed (`None` for a
2361/// directory cut short, which `wuff` rejects): after the 44-byte header,
2362/// 20 bytes a table, its `compLength` at 8 and `origLength` at 12. A table
2363/// larger compressed than it is, which the format does not allow, is an
2364/// error.
2365fn woff_tables_size(data: &[u8]) -> Result<Option<u64>, String> {
2366    let field = |at: usize| Some(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?));
2367    let Some(tables) = data.get(12..14) else {
2368        return Ok(None);
2369    };
2370    let mut size = 0;
2371    for table in 0..usize::from(u16::from_be_bytes([tables[0], tables[1]])) {
2372        let at = 44 + table * 20;
2373        let (Some(compressed), Some(length)) = (field(at + 8), field(at + 12)) else {
2374            return Ok(None);
2375        };
2376        if compressed > length {
2377            return Err(format!(
2378                "the WOFF font's table {table} is larger compressed ({compressed} bytes) than it is \
2379                 ({length})"
2380            ));
2381        }
2382        size += u64::from(length);
2383    }
2384    Ok(Some(size))
2385}
2386
2387/// The family name a font registers under, which `fontFamily` names: its
2388/// typographic family (name 16) when it has one, else its family (name
2389/// 1). A WOFF or WOFF2 font's is the one of the font it holds.
2390pub fn font_family(data: &[u8]) -> Result<String, String> {
2391    let data = font_data(data)?;
2392    let font = parse_font(&data).map_err(|e| format!("not a font: {e}"))?;
2393    font_name(&font, skrifa::raw::types::NameId::TYPOGRAPHIC_FAMILY_NAME)
2394        .or_else(|| font_name(&font, skrifa::raw::types::NameId::FAMILY_NAME))
2395        .ok_or_else(|| "the font has no family name".to_owned())
2396}
2397
2398/// `data`'s first font, if it has the tables every font does.
2399fn parse_font(data: &[u8]) -> Result<skrifa::FontRef<'_>, String> {
2400    use skrifa::raw::TableProvider as _;
2401    let font = skrifa::FontRef::from_index(data, 0).map_err(|e| e.to_string())?;
2402    font.head().map_err(|e| e.to_string())?;
2403    Ok(font)
2404}
2405
2406/// A font's first name `id` in a Unicode encoding (the Unicode platform, or
2407/// Windows' symbol or BMP encoding), the ones a family name is read from.
2408fn font_name(font: &skrifa::FontRef<'_>, id: skrifa::raw::types::NameId) -> Option<String> {
2409    use skrifa::raw::TableProvider as _;
2410    let name = font.name().ok()?;
2411    name.name_record()
2412        .iter()
2413        .filter(|r| {
2414            r.name_id() == id && matches!((r.platform_id(), r.encoding_id()), (0, _) | (3, 0 | 1))
2415        })
2416        .find_map(|r| r.string(name.string_data()).ok())
2417        .map(|s| s.chars().collect())
2418}
2419
2420#[cfg(test)]
2421mod tests {
2422    use super::*;
2423
2424    #[test]
2425    fn push_merges_and_counts_utf16() {
2426        let mut t = AttributedText::default();
2427        let a = ResolvedTextStyle::default();
2428        let b = ResolvedTextStyle {
2429            font_weight: 700,
2430            ..a
2431        };
2432        t.push("ab", a);
2433        t.push("", b);
2434        t.push("😀", a);
2435        t.push("c", b);
2436        assert_eq!(t.text, "ab😀c");
2437        assert_eq!(t.spans.len(), 2);
2438        assert_eq!((t.spans[0].start, t.spans[0].end), (0, 4));
2439        assert_eq!((t.spans[1].start, t.spans[1].end), (4, 5));
2440    }
2441
2442    #[test]
2443    fn a_direct_text_falls_back_to_its_first_span_until_the_root_strut_is_set() {
2444        let small = ResolvedTextStyle {
2445            font_size: px(12.6),
2446            line_height: px(20.475),
2447            ..Default::default()
2448        };
2449        let root = ResolvedTextStyle {
2450            font_size: px(14.0),
2451            line_height: px(22.75),
2452            ..Default::default()
2453        };
2454        let mut text = AttributedText::default();
2455        text.push("`code`", small);
2456        text.push(" body", root);
2457
2458        let fallback = text.paragraph_strut_or_first();
2459        assert_eq!(fallback.font_size, small.font_size);
2460        assert_eq!(fallback.line_height, small.line_height);
2461
2462        text.paragraph_strut = Some(root);
2463        let explicit = text.paragraph_strut_or_first();
2464        assert_eq!(explicit.font_size, root.font_size);
2465        assert_eq!(explicit.line_height, root.line_height);
2466
2467        // An explicit zero is meaningful too: the core can say the root has
2468        // no fixed line height even when the first span has one.
2469        text.paragraph_strut = Some(ResolvedTextStyle {
2470            line_height: Points::ZERO,
2471            ..root
2472        });
2473        assert_eq!(text.paragraph_strut_or_first().line_height, Points::ZERO);
2474    }
2475
2476    #[test]
2477    fn only_the_root_struts_layout_metrics_compare() {
2478        let root = ResolvedTextStyle {
2479            color: Color(0xff00_00ff),
2480            font_size: px(14.0),
2481            line_height: px(22.75),
2482            letter_spacing: px(2.0),
2483            decoration: TextDecoration {
2484                underline: true,
2485                line_through: false,
2486            },
2487            ..Default::default()
2488        };
2489        let mut a = AttributedText::default();
2490        a.push("hello", root);
2491        a.paragraph_strut = Some(root);
2492        let mut b = a.clone();
2493        b.paragraph_strut = Some(ResolvedTextStyle {
2494            color: Color(0x0000_ffff),
2495            letter_spacing: Points::ZERO,
2496            decoration: TextDecoration::default(),
2497            transform: TextTransform::Uppercase,
2498            hidden: true,
2499            ..root
2500        });
2501
2502        assert!(a.layout_eq(&b));
2503        assert_eq!(a.layout_hash(), b.layout_hash());
2504        assert!(a.rendering_eq(&b));
2505        assert!(a.same_but_colors(&b));
2506
2507        let mut c = b.clone();
2508        c.paragraph_strut.as_mut().unwrap().font_weight = 700;
2509        assert!(!a.layout_eq(&c));
2510        assert_ne!(a.layout_hash(), c.layout_hash());
2511        assert!(!a.rendering_eq(&c));
2512        assert!(!a.same_but_colors(&c));
2513    }
2514
2515    #[test]
2516    fn italic_text_keeps_color_emoji_upright() {
2517        let italic = ResolvedTextStyle {
2518            italic: true,
2519            ..Default::default()
2520        };
2521        let runs = |s: &str| {
2522            let mut t = AttributedText::default();
2523            t.push(s, italic);
2524            let units: Vec<u16> = t.text.encode_utf16().collect();
2525            t.spans
2526                .iter()
2527                .map(|s| {
2528                    let text = String::from_utf16(&units[s.start as usize..s.end as usize]);
2529                    (text.unwrap(), s.style.italic)
2530                })
2531                .collect::<Vec<_>>()
2532        };
2533        let run = |s: &str, italic: bool| (s.to_owned(), italic);
2534        assert_eq!(
2535            runs("斜体 abc 😀😀 end"),
2536            [
2537                run("斜体 abc ", true),
2538                run("😀😀", false),
2539                run(" end", true)
2540            ]
2541        );
2542        // Sequences stay whole: ZWJ, skin tone, flag, keycap, U+FE0F.
2543        assert_eq!(runs("👩‍💻👍🏽🇨🇳#️⃣❤️"), [run("👩‍💻👍🏽🇨🇳#️⃣❤️", false)]);
2544        // Text presentation by default, or asked for with U+FE0E.
2545        assert_eq!(runs("© ❤ ☺ 😀\u{FE0E}"), [run("© ❤ ☺ 😀\u{FE0E}", true)]);
2546
2547        // Upright text is one run, and pushes merge across the emoji.
2548        let mut t = AttributedText::default();
2549        t.push("a😀", ResolvedTextStyle::default());
2550        assert_eq!(t.spans.len(), 1);
2551        t.push("😀", italic);
2552        t.push("b", italic);
2553        assert_eq!(t.spans.len(), 2);
2554        assert_eq!((t.spans[0].end, t.spans[1].start), (5, 5));
2555    }
2556
2557    #[test]
2558    fn color_does_not_affect_layout_identity() {
2559        let mut a = AttributedText::default();
2560        a.push("hello", ResolvedTextStyle::default());
2561        let mut b = AttributedText::default();
2562        b.push(
2563            "hello",
2564            ResolvedTextStyle {
2565                color: Color(0xff00_00ff),
2566                ..Default::default()
2567            },
2568        );
2569        assert_ne!(a, b);
2570        assert!(a.layout_eq(&b));
2571        assert_eq!(a.layout_hash(), b.layout_hash());
2572        let mut c = b.clone();
2573        c.spans[0].style.font_size = px(15.0);
2574        assert!(!a.layout_eq(&c));
2575        assert_ne!(a.layout_hash(), c.layout_hash());
2576    }
2577
2578    #[test]
2579    fn measure_cache_is_bounded_and_promotes() {
2580        let mut cache = MeasureCache::default();
2581        cache.insert(1, Some(px(100.0)), size(px(1.0), px(1.0)));
2582        for i in 0..10_000u64 {
2583            cache.insert(1000 + i, None, Size::default());
2584            // Keep entry 1 hot: every lookup promotes it.
2585            assert!(cache.get(1, Some(px(100.0))).is_some());
2586            assert!(cache.len() <= 2 * MeasureCache::GENERATION);
2587        }
2588        assert!(cache.get(1, Some(px(99.0))).is_none());
2589        assert!(cache.get(1000, None).is_none(), "cold entries are evicted");
2590    }
2591
2592    /// An attachment with a baseline of its own stands on the line's by it
2593    /// (the first baseline of the text in it), and the line reserves what reaches past each
2594    /// side; the other alignments place its box, whatever is in it.
2595    #[test]
2596    fn an_attachments_own_baseline_stands_on_the_lines() {
2597        let font = FontExtent::new(px(10.0), px(3.0), px(5.0));
2598        let a = TextAttachment {
2599            index: 4,
2600            width: px(30.0),
2601            height: px(20.0),
2602        };
2603        let mut alignments = AttachmentAlignments::default();
2604        assert_eq!(alignments.ascent(&a, font), px(20.0));
2605        alignments.set_baseline(4, Some(px(14.0)));
2606        assert!(!alignments.is_empty());
2607        assert_eq!(alignments.baseline(4), Some(px(14.0)));
2608        assert_eq!(alignments.baseline(5), None);
2609        assert_eq!(alignments.ascent(&a, font), px(14.0));
2610        assert_eq!(alignments.extent(&a, font), (px(14.0), px(6.0)));
2611        // Never past its own box.
2612        alignments.set_baseline(4, Some(px(25.0)));
2613        assert_eq!(alignments.extent(&a, font), (px(20.0), px(0.0)));
2614        alignments.set_baseline(4, Some(px(14.0)));
2615        alignments.set(4, VerticalAlign::TextTop);
2616        assert_eq!(alignments.ascent(&a, font), px(10.0));
2617        alignments.set(4, VerticalAlign::Baseline);
2618        alignments.set_baseline(4, None);
2619        assert!(alignments.is_empty());
2620        // A text's layout is another with it.
2621        let text = AttributedText::default();
2622        let plain = alignments.layout_hash(&text);
2623        alignments.set_baseline(4, Some(px(14.0)));
2624        assert_ne!(alignments.layout_hash(&text), plain);
2625    }
2626
2627    #[test]
2628    fn attachments_sit_in_their_line_by_vertical_align() {
2629        // A font 10 above and 3 below the baseline, x height 5; a 20 pt
2630        // tall attachment.
2631        let font = FontExtent::new(px(10.0), px(3.0), px(5.0));
2632        let at = || TextAttachment {
2633            index: 0,
2634            width: px(8.0),
2635            height: px(20.0),
2636        };
2637        let place = |align| {
2638            let a = at();
2639            (a.ascent(font, align), a.extent(font, align))
2640        };
2641        // Bottom on the baseline: all of it above.
2642        assert_eq!(
2643            place(VerticalAlign::Baseline),
2644            (px(20.0), (px(20.0), px(0.0)))
2645        );
2646        // Top at the font's top: 10 above, 10 below (the line grows down).
2647        assert_eq!(
2648            place(VerticalAlign::TextTop),
2649            (px(10.0), (px(10.0), px(10.0)))
2650        );
2651        // Bottom at the font's bottom (Android's `ImageSpan` default).
2652        assert_eq!(
2653            place(VerticalAlign::TextBottom),
2654            (px(17.0), (px(17.0), px(3.0)))
2655        );
2656        // Middle 2.5 above the baseline.
2657        assert_eq!(
2658            place(VerticalAlign::Middle),
2659            (px(12.5), (px(12.5), px(7.5)))
2660        );
2661        // Smaller than the font: what it does not reach reserves nothing.
2662        let small = TextAttachment {
2663            height: px(4.0),
2664            ..at()
2665        };
2666        assert_eq!(small.ascent(font, VerticalAlign::TextTop), px(10.0));
2667        assert_eq!(
2668            small.extent(font, VerticalAlign::TextTop),
2669            (px(10.0), px(0.0))
2670        );
2671        let small = TextAttachment {
2672            height: px(2.0),
2673            ..at()
2674        };
2675        assert_eq!(small.ascent(font, VerticalAlign::TextBottom), px(-1.0));
2676        assert_eq!(
2677            small.extent(font, VerticalAlign::TextBottom),
2678            (px(0.0), px(3.0))
2679        );
2680    }
2681
2682    /// The headless engine's first baseline is the bottom of its first
2683    /// line, where it draws it, at any width.
2684    #[test]
2685    fn approx_engine_has_its_first_baseline_at_its_first_lines_bottom() {
2686        let engine = ApproxTextEngine;
2687        let mut t = AttributedText::default();
2688        t.push(
2689            "a long line\nand another",
2690            ResolvedTextStyle {
2691                font_size: px(10.0),
2692                ..ResolvedTextStyle::default()
2693            },
2694        );
2695        let prepared = engine.prepare(&t);
2696        let layout = engine.layout(&prepared, engine.measure(&prepared, None));
2697        let line = engine.lines(&layout).remove(0);
2698        for width in [px(20.0), px(1000.0)] {
2699            assert_eq!(
2700                engine.first_baseline(&prepared, width),
2701                Some(line.y + line.ascender)
2702            );
2703        }
2704        assert_eq!(engine.first_baseline(&prepared, px(20.0)), Some(px(12.0)));
2705    }
2706
2707    #[test]
2708    fn approx_engine_honors_line_height_and_multiple() {
2709        let engine = ApproxTextEngine;
2710        let mut explicit = AttributedText::default();
2711        explicit.push(
2712            "ab\ncd",
2713            ResolvedTextStyle {
2714                font_size: px(10.0),
2715                line_height: px(24.0),
2716                ..ResolvedTextStyle::default()
2717            },
2718        );
2719        let prepared = engine.prepare(&explicit);
2720        let measured = engine.measure(&prepared, None);
2721        assert_eq!(measured, size(px(11.0), px(48.0)));
2722        let laid = engine.layout(&prepared, measured);
2723        let line = engine.lines(&laid).remove(0);
2724        // Natural ascent = 12, line = 24, half-leading = 6 => ascender 18, descender 6.
2725        assert_eq!(line.height, px(24.0));
2726        assert_eq!(line.ascender, px(18.0));
2727        assert_eq!(line.descender, px(6.0));
2728        assert_eq!(engine.first_baseline(&prepared, px(50.0)), Some(px(18.0)));
2729        assert_eq!(
2730            engine.first_baseline(&prepared, px(50.0)),
2731            Some(line.y + line.ascender)
2732        );
2733
2734        let mut multiple = AttributedText::default();
2735        multiple.push(
2736            "ab",
2737            ResolvedTextStyle {
2738                font_size: px(10.0),
2739                line_height_multiple: 2.0,
2740                ..ResolvedTextStyle::default()
2741            },
2742        );
2743        let mp = engine.prepare(&multiple);
2744        assert_eq!(engine.measure(&mp, None), size(px(11.0), px(20.0)));
2745
2746        // Mixed spans take the tallest resolved line height.
2747        let mut mixed = AttributedText::default();
2748        mixed.push(
2749            "a",
2750            ResolvedTextStyle {
2751                font_size: px(10.0),
2752                line_height: px(16.0),
2753                ..ResolvedTextStyle::default()
2754            },
2755        );
2756        mixed.push(
2757            "b",
2758            ResolvedTextStyle {
2759                font_size: px(12.0),
2760                line_height: px(30.0),
2761                ..ResolvedTextStyle::default()
2762            },
2763        );
2764        let mp_mixed = engine.prepare(&mixed);
2765        assert_eq!(engine.measure(&mp_mixed, None).height, px(30.0));
2766
2767        // Unspaced mixed font sizes resolve both advance and natural ascent
2768        // from the largest span, matching offscreen estimates.
2769        let mut mixed_fonts = AttributedText::default();
2770        mixed_fonts.push(
2771            "a",
2772            ResolvedTextStyle {
2773                font_size: px(10.0),
2774                ..ResolvedTextStyle::default()
2775            },
2776        );
2777        mixed_fonts.push(
2778            "b",
2779            ResolvedTextStyle {
2780                font_size: px(20.0),
2781                ..ResolvedTextStyle::default()
2782            },
2783        );
2784        let mp_fonts = engine.prepare(&mixed_fonts);
2785        assert_eq!(engine.measure(&mp_fonts, None), size(px(22.0), px(24.0)));
2786        assert_eq!(engine.first_baseline(&mp_fonts, px(50.0)), Some(px(24.0)));
2787
2788        // Default prepared state matches an empty `AttributedText`, and zero
2789        // font sizes clamp to at least 1 pt.
2790        assert_eq!(
2791            engine.measure(&ApproxPrepared::default(), None),
2792            engine.measure(&engine.prepare(&AttributedText::default()), None)
2793        );
2794        assert_eq!(
2795            ResolvedTextStyle {
2796                font_size: Points::ZERO,
2797                ..ResolvedTextStyle::default()
2798            }
2799            .approx_line_height(),
2800            px(1.2)
2801        );
2802    }
2803
2804    #[test]
2805    fn approx_engine_places_aligned_attachments() {
2806        let engine = ApproxTextEngine;
2807        let style = ResolvedTextStyle {
2808            font_size: px(10.0),
2809            ..ResolvedTextStyle::default()
2810        };
2811        let y = |align| {
2812            let mut t = AttributedText::default();
2813            t.push("ab", style);
2814            let mut alignments = AttachmentAlignments::default();
2815            alignments.push(&mut t, size(px(8.0), px(6.0)), align, style);
2816            let prepared = engine.prepare_aligned(&t, &alignments);
2817            let layout = engine.layout(&prepared, size(px(100.0), px(12.0)));
2818            engine.attachments(&layout)[0].map(|p| (p.x, p.y))
2819        };
2820        // A 12 pt line with its baseline at the bottom, x height 5.
2821        assert_eq!(y(VerticalAlign::Baseline), Some((px(11.0), px(6.0))));
2822        assert_eq!(y(VerticalAlign::TextTop), Some((px(11.0), px(0.0))));
2823        assert_eq!(y(VerticalAlign::TextBottom), Some((px(11.0), px(6.0))));
2824        assert_eq!(y(VerticalAlign::Middle), Some((px(11.0), px(6.5))));
2825    }
2826
2827    #[test]
2828    fn approx_engine_places_attachments_on_the_lines_they_wrap_to() {
2829        let engine = ApproxTextEngine;
2830        let style = ResolvedTextStyle {
2831            font_size: px(10.0),
2832            ..ResolvedTextStyle::default()
2833        };
2834        // Characters 5.5 wide, lines 12 tall; an 8×6 attachment sits 6
2835        // below its line's top.
2836        let place = |text: &str, width: f32, max_lines: u32| {
2837            let mut t = AttributedText::default();
2838            t.push(text, style);
2839            t.push_attachment(size(px(8.0), px(6.0)), style);
2840            t.push("z", style);
2841            t.max_lines = max_lines;
2842            let prepared = engine.prepare(&t);
2843            let measured = engine.measure(&prepared, Some(px(width)));
2844            let layout = engine.layout(&prepared, size(px(width), measured.height));
2845            engine.attachments(&layout)[0].map(|p| (p.x, p.y))
2846        };
2847        // On one line where it fits.
2848        assert_eq!(place("abcd", 100.0, 0), Some((px(22.0), px(6.0))));
2849        // Ten characters before it in a box of 22: 55 points of text run
2850        // on to a third line, 11 in.
2851        assert_eq!(place("abcdefghij", 22.0, 0), Some((px(11.0), px(30.0))));
2852        // After a line break, on the line after the wrapped first one.
2853        assert_eq!(place("abcdefghij\nab", 22.0, 0), Some((px(11.0), px(42.0))));
2854        // On a line past the limit: cut off.
2855        assert_eq!(place("abcdefghij", 22.0, 2), None);
2856        // A character two UTF-16 units long counts once.
2857        assert_eq!(place("a😀b", 100.0, 0), Some((px(16.5), px(6.0))));
2858    }
2859
2860    fn line(start: u32, end: u32, y: f32) -> TextLine {
2861        TextLine {
2862            start,
2863            end,
2864            x: px(0.0),
2865            y: px(y),
2866            width: px((end - start) as f32 * 10.0),
2867            height: px(20.0),
2868            ..TextLine::default()
2869        }
2870    }
2871
2872    #[test]
2873    fn caret_positions_take_their_line_by_affinity() {
2874        // "abcd" wrapped after its 4th character, then a hard break and an
2875        // empty last line.
2876        let lines = [line(0, 4, 0.0), line(4, 9, 20.0), line(9, 9, 40.0)];
2877        let at = |o, a| TextPosition::new(o, a).line(&lines);
2878        assert_eq!(at(4, Affinity::Upstream), Some(0));
2879        assert_eq!(at(4, Affinity::Downstream), Some(1));
2880        assert_eq!(at(0, Affinity::Upstream), Some(0));
2881        assert_eq!(at(9, Affinity::Upstream), Some(1));
2882        assert_eq!(at(9, Affinity::Downstream), Some(2));
2883        assert_eq!(at(50, Affinity::Downstream), Some(2));
2884        assert_eq!(TextPosition::default().line(&[]), None);
2885    }
2886
2887    /// An engine that only reports its lines (the defaults' hit testing).
2888    struct LinesOnly(Vec<TextLine>);
2889
2890    impl TextEngine for LinesOnly {
2891        type Prepared = ();
2892
2893        fn prepare(&self, _: &AttributedText) {}
2894
2895        fn measure(&self, (): &(), _: Option<Points>) -> Size<Points> {
2896            Size::default()
2897        }
2898
2899        fn layout(&self, (): &(), _: Size<Points>) -> TextLayout {
2900            TextLayout(Arc::new(()))
2901        }
2902
2903        fn lines(&self, _: &TextLayout) -> Vec<TextLine> {
2904            self.0.clone()
2905        }
2906    }
2907
2908    #[test]
2909    fn line_only_engines_estimate_hits_carets_and_ranges() {
2910        let engine = LinesOnly(vec![line(0, 4, 0.0), line(4, 8, 20.0)]);
2911        let layout = engine.layout(&(), Size::default());
2912        // Past the end of the wrapped first line: its end, on that line.
2913        let end = engine.hit_test(&layout, point(px(70.0), px(5.0)));
2914        assert_eq!(end, TextPosition::new(4, Affinity::Upstream));
2915        assert_eq!(
2916            engine.caret_rect(&layout, end),
2917            Some(Bounds::new(
2918                point(px(40.0), px(0.0)),
2919                size(px(0.0), px(20.0))
2920            ))
2921        );
2922        assert_eq!(
2923            engine.caret_rect(&layout, TextPosition::new(4, Affinity::Downstream)),
2924            Some(Bounds::new(
2925                point(px(0.0), px(20.0)),
2926                size(px(0.0), px(20.0))
2927            ))
2928        );
2929        // Below the text: the last line, the nearest character edge.
2930        let below = engine.hit_test(&layout, point(px(16.0), px(90.0)));
2931        assert_eq!(below, TextPosition::new(6, Affinity::Downstream));
2932        let mut rects = Vec::new();
2933        engine.range_rects(&layout, 2..6, &mut rects);
2934        assert_eq!(
2935            rects,
2936            [
2937                Bounds::new(point(px(20.0), px(0.0)), size(px(20.0), px(20.0))),
2938                Bounds::new(point(px(0.0), px(20.0)), size(px(20.0), px(20.0))),
2939            ]
2940        );
2941        rects.clear();
2942        engine.range_rects(&layout, 3..3, &mut rects);
2943        assert!(rects.is_empty());
2944    }
2945
2946    #[test]
2947    fn approx_engine_hit_tests_whole_characters() {
2948        let engine = ApproxTextEngine;
2949        let mut t = AttributedText::default();
2950        // Characters 5.5 wide; the emoji is two UTF-16 units (1..3).
2951        t.push(
2952            "a😀b",
2953            ResolvedTextStyle {
2954                font_size: px(10.0),
2955                ..ResolvedTextStyle::default()
2956            },
2957        );
2958        let layout = engine.layout(&engine.prepare(&t), size(px(100.0), px(12.0)));
2959        assert_eq!(engine.lines(&layout)[0].end, 4);
2960        let hit = |x| engine.hit_test(&layout, point(px(x), px(6.0))).offset;
2961        assert_eq!([hit(-3.0), hit(5.0), hit(11.5), hit(99.0)], [0, 1, 3, 4]);
2962        let caret_x = |o| {
2963            engine
2964                .caret_rect(&layout, TextPosition::new(o, Affinity::Downstream))
2965                .map(|b| b.origin.x)
2966        };
2967        // Inside the surrogate pair: at the emoji's start.
2968        assert_eq!(caret_x(2), Some(px(5.5)));
2969        assert_eq!(caret_x(3), Some(px(11.0)));
2970        assert_eq!(caret_x(9), Some(px(16.5)));
2971        let mut rects = Vec::new();
2972        engine.range_rects(&layout, 1..3, &mut rects);
2973        assert_eq!(
2974            rects,
2975            [Bounds::new(
2976                point(px(5.5), px(0.0)),
2977                size(px(5.5), px(12.0))
2978            )]
2979        );
2980    }
2981
2982    #[test]
2983    fn woff_and_woff2_fonts_decompress_to_the_font_they_hold() {
2984        let ttf: &[u8] =
2985            include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.ttf");
2986        let face = |data: &[u8]| {
2987            use skrifa::{MetadataProvider as _, raw::TableProvider as _};
2988            let font = parse_font(data).expect("a font");
2989            let family = font_name(&font, skrifa::raw::types::NameId::FAMILY_NAME);
2990            (
2991                family,
2992                font.maxp().expect("maxp").num_glyphs(),
2993                font.charmap().map('P'),
2994            )
2995        };
2996        let original = face(ttf);
2997        assert_eq!(original.0.as_deref(), Some("Pacifico"));
2998        // TrueType comes back as it is.
2999        assert!(matches!(font_data(ttf), Ok(std::borrow::Cow::Borrowed(_))));
3000        for wrapped in [
3001            &include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff")[..],
3002            &include_bytes!("../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff2")[..],
3003        ] {
3004            let data = font_data(wrapped).expect("decompressed");
3005            assert_eq!(face(&data), original);
3006        }
3007        assert!(font_data(b"wOF2 and nothing else").is_err());
3008        assert_eq!(font_family(ttf).as_deref(), Ok("Pacifico"));
3009        assert_eq!(
3010            font_family(include_bytes!(
3011                "../../../tests/compat/cases/layout/fonts/Pacifico-Regular.woff2"
3012            ))
3013            .as_deref(),
3014            Ok("Pacifico")
3015        );
3016        assert!(font_family(b"not a font").is_err());
3017    }
3018
3019    #[test]
3020    fn keep_font_keeps_each_file_once() {
3021        let mut fonts = Vec::new();
3022        assert!(keep_font(&mut fonts, b"a"));
3023        assert!(!keep_font(&mut fonts, b"a"));
3024        assert!(keep_font(&mut fonts, b"b"));
3025        assert_eq!(fonts, [b"a".to_vec(), b"b".to_vec()]);
3026    }
3027
3028    /// A WOFF file of 68 bytes whose one table declares `length` bytes.
3029    fn forged_woff(length: u32) -> Vec<u8> {
3030        let mut data = Vec::new();
3031        data.extend(b"wOFF\0\x01\0\0");
3032        data.extend(68u32.to_be_bytes()); // length
3033        data.extend(1u16.to_be_bytes()); // numTables
3034        data.extend([0; 2]); // reserved
3035        data.extend(length.saturating_add(28).to_be_bytes()); // totalSfntSize
3036        data.extend([0; 24]); // versions, metadata, private data
3037        data.extend(b"glyf");
3038        data.extend(64u32.to_be_bytes()); // offset
3039        data.extend(4u32.to_be_bytes()); // compLength
3040        data.extend(length.to_be_bytes()); // origLength
3041        data.extend([0; 4]); // origChecksum
3042        data.extend([0x78, 0x9c, 0x03, 0x00]); // zlib
3043        data
3044    }
3045
3046    #[test]
3047    fn a_woff_font_declaring_more_than_a_font_holds_is_refused_before_it_decompresses() {
3048        let forged = forged_woff(u32::MAX);
3049        let error = font_data(&forged).expect_err("refused");
3050        assert!(error.contains("declare"), "{error}");
3051        // A size a font may have goes on to `wuff`, which finds the table
3052        // does not hold it.
3053        let error = font_data(&forged_woff(1024)).expect_err("refused");
3054        assert!(error.contains("does not decompress"), "{error}");
3055        // So does a directory cut short, for `wuff` to report.
3056        assert!(matches!(woff_tables_size(&forged[..56]), Ok(None)));
3057        assert!(font_data(&forged[..56]).is_err());
3058    }
3059
3060    #[test]
3061    fn a_woff_font_whose_tables_share_data_larger_than_they_are_is_refused() {
3062        // Two tables of 4 bytes, each taking the same 8 bytes as stored as
3063        // they are: `wuff` would copy those 8 bytes for each, however many
3064        // tables there were.
3065        let mut forged = Vec::new();
3066        forged.extend(b"wOFF\0\x01\0\0");
3067        forged.extend(92u32.to_be_bytes()); // length
3068        forged.extend(2u16.to_be_bytes()); // numTables
3069        forged.extend([0; 2]); // reserved
3070        forged.extend(44u32.to_be_bytes()); // totalSfntSize
3071        forged.extend([0; 24]); // versions, metadata, private data
3072        for tag in [b"cmap", b"glyf"] {
3073            forged.extend(tag);
3074            forged.extend(84u32.to_be_bytes()); // offset, the same block
3075            forged.extend(8u32.to_be_bytes()); // compLength
3076            forged.extend(4u32.to_be_bytes()); // origLength
3077            forged.extend([0; 4]); // origChecksum
3078        }
3079        forged.extend([0; 8]);
3080        assert_eq!(forged.len(), 92);
3081        let error = font_data(&forged).expect_err("refused");
3082        assert!(error.contains("larger compressed"), "{error}");
3083    }
3084
3085    #[test]
3086    fn a_woff2_font_declaring_more_than_its_size_allows_is_refused() {
3087        // One `cmap` table declaring 4 GiB from a brotli stream of 4 bytes
3088        // (`wuff` holds what a WOFF2 file decompresses to at most 100 times
3089        // the file's size, and 128 MiB).
3090        let mut forged = Vec::new();
3091        forged.extend(b"wOF2\0\x01\0\0");
3092        forged.extend(60u32.to_be_bytes()); // length
3093        forged.extend(1u16.to_be_bytes()); // numTables
3094        forged.extend([0; 2]); // reserved
3095        forged.extend(u32::MAX.to_be_bytes()); // totalSfntSize
3096        forged.extend(4u32.to_be_bytes()); // totalCompressedSize
3097        forged.extend([0; 24]); // versions, metadata, private data
3098        forged.push(0); // cmap, untransformed
3099        forged.extend([0x8f, 0xff, 0xff, 0xff, 0x7f]); // origLength, UIntBase128
3100        forged.extend([0; 6]); // the stream, padded to 4 bytes
3101        assert_eq!(forged.len(), 60);
3102        assert!(font_data(&forged).is_err());
3103    }
3104
3105    #[test]
3106    fn em_font_size_is_of_the_inherited_size() {
3107        let parent = ResolvedTextStyle {
3108            font_size: px(16.0),
3109            ..ResolvedTextStyle::default()
3110        };
3111        let span = TextStyle {
3112            font_size_em: Some(0.875),
3113            letter_spacing_em: Some(0.1),
3114            ..TextStyle::default()
3115        };
3116        let r = parent.inherit(&span);
3117        assert_eq!(r.font_size, px(14.0));
3118        // Other ems follow the resolved size.
3119        assert!((r.letter_spacing.0 - 1.4).abs() < 1e-4);
3120    }
3121}
3122
3123/// The engine calls a [`TextGeometry`] needs, object-safe.
3124pub(crate) trait GeometryEngine {
3125    fn geometry_lines(&self, layout: &TextLayout) -> Vec<TextLine>;
3126    fn geometry_hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition;
3127    fn geometry_caret_rect(
3128        &self,
3129        layout: &TextLayout,
3130        position: TextPosition,
3131    ) -> Option<Bounds<Points>>;
3132    fn geometry_range_rects(
3133        &self,
3134        layout: &TextLayout,
3135        range: Range<u32>,
3136        out: &mut Vec<Bounds<Points>>,
3137    );
3138}
3139
3140impl<M: TextEngine> GeometryEngine for M {
3141    fn geometry_lines(&self, layout: &TextLayout) -> Vec<TextLine> {
3142        self.lines(layout)
3143    }
3144    fn geometry_hit_test(&self, layout: &TextLayout, point: Point<Points>) -> TextPosition {
3145        self.hit_test(layout, point)
3146    }
3147    fn geometry_caret_rect(
3148        &self,
3149        layout: &TextLayout,
3150        position: TextPosition,
3151    ) -> Option<Bounds<Points>> {
3152        self.caret_rect(layout, position)
3153    }
3154    fn geometry_range_rects(
3155        &self,
3156        layout: &TextLayout,
3157        range: Range<u32>,
3158        out: &mut Vec<Bounds<Points>>,
3159    ) {
3160        self.range_rects(layout, range, out);
3161    }
3162}
3163
3164/// A text block's final layout as the platform engine made it
3165/// ([`crate::Text::on_text_layout`]), to ask where its characters are:
3166/// the engine's own answers, not an estimate from the lines.
3167///
3168/// Offsets are UTF-16 units in the block's own text: the empty
3169/// placeholders the core adds for a span's padding are not counted, so
3170/// they match the text the app gave. Boxes are in the content box (y
3171/// down, points). Rust-only: it holds the engine and lives on the engine
3172/// thread.
3173#[derive(Clone)]
3174pub struct TextGeometry {
3175    engine: std::rc::Rc<dyn GeometryEngine>,
3176    layout: TextLayout,
3177    text: Arc<AttributedText>,
3178    /// The laid-out text's offsets of the padding placeholders, in order.
3179    spacers: Arc<[u32]>,
3180}
3181
3182impl TextGeometry {
3183    pub(crate) fn new(
3184        engine: std::rc::Rc<dyn GeometryEngine>,
3185        layout: TextLayout,
3186        text: Arc<AttributedText>,
3187        spacers: &[u32],
3188    ) -> Self {
3189        let mut spacers = spacers.to_vec();
3190        spacers.sort_unstable();
3191        spacers.dedup();
3192        Self {
3193            engine,
3194            layout,
3195            text,
3196            spacers: spacers.into(),
3197        }
3198    }
3199
3200    /// The offset in the app's text of laid-out offset `t`.
3201    fn to_source(&self, t: u32) -> u32 {
3202        t - self.spacers.partition_point(|&s| s < t) as u32
3203    }
3204
3205    /// The laid-out offset of offset `s` in the app's text: past the
3206    /// placeholders before it, and past those at it unless `upstream`
3207    /// (the caret stays with the character before).
3208    fn to_laid(&self, s: u32, upstream: bool) -> u32 {
3209        let mut t = s;
3210        for &at in self.spacers.iter() {
3211            if at < t || (at == t && !upstream) {
3212                t += 1;
3213            } else {
3214                break;
3215            }
3216        }
3217        t
3218    }
3219
3220    /// Its lines, in order, with their characters.
3221    pub fn lines(&self) -> Vec<TextLine> {
3222        let units: Vec<u16> = self.text.text.encode_utf16().collect();
3223        let mut lines = self.engine.geometry_lines(&self.layout);
3224        for line in &mut lines {
3225            let (start, end) = (line.start as usize, (line.end as usize).min(units.len()));
3226            if start < end {
3227                let mut text = String::from_utf16_lossy(&units[start..end]);
3228                if self
3229                    .spacers
3230                    .iter()
3231                    .any(|&s| s >= line.start && s < line.end)
3232                {
3233                    // Placeholders are one unit each: drop those at spacer
3234                    // offsets.
3235                    let mut k = line.start;
3236                    text = text
3237                        .chars()
3238                        .filter(|c| {
3239                            let at = k;
3240                            k += c.len_utf16() as u32;
3241                            !(*c == ATTACHMENT_CHAR && self.spacers.binary_search(&at).is_ok())
3242                        })
3243                        .collect();
3244                }
3245                line.text = text;
3246            }
3247            line.start = self.to_source(line.start);
3248            line.end = self.to_source(line.end);
3249        }
3250        lines
3251    }
3252
3253    /// The caret position nearest `point` (content box).
3254    pub fn hit_test(&self, point: Point<Points>) -> TextPosition {
3255        let p = self.engine.geometry_hit_test(&self.layout, point);
3256        TextPosition::new(self.to_source(p.offset), p.affinity)
3257    }
3258
3259    /// The caret at `position`: a box of no width as high as its line.
3260    pub fn caret_rect(&self, position: TextPosition) -> Option<Bounds<Points>> {
3261        let upstream = position.affinity == Affinity::Upstream;
3262        let t = self.to_laid(position.offset, upstream);
3263        self.engine
3264            .geometry_caret_rect(&self.layout, TextPosition::new(t, position.affinity))
3265    }
3266
3267    /// The boxes that cover the characters of `range`, line high.
3268    pub fn range_rects(&self, range: Range<u32>) -> Vec<Bounds<Points>> {
3269        let mut out = Vec::new();
3270        if range.start < range.end {
3271            let r = self.to_laid(range.start, false)..self.to_laid(range.end, true);
3272            self.engine.geometry_range_rects(&self.layout, r, &mut out);
3273        }
3274        out
3275    }
3276}
3277
3278thread_local! {
3279    static GEOMETRY: std::cell::RefCell<Option<TextGeometry>> =
3280        const { std::cell::RefCell::new(None) };
3281}
3282
3283/// The geometry of the text block whose `TextLayout` event is being
3284/// dispatched, for [`crate::Text::on_text_layout`]: the event's payload
3285/// crosses threads, the engine does not.
3286pub(crate) struct GeometryScope(Option<TextGeometry>);
3287
3288impl GeometryScope {
3289    pub(crate) fn enter(geometry: TextGeometry) -> Self {
3290        Self(GEOMETRY.with(|g| g.replace(Some(geometry))))
3291    }
3292
3293    /// The geometry of the event being dispatched, if any.
3294    pub(crate) fn current() -> Option<TextGeometry> {
3295        GEOMETRY.with(|g| g.borrow().clone())
3296    }
3297}
3298
3299impl Drop for GeometryScope {
3300    fn drop(&mut self) {
3301        let previous = self.0.take();
3302        GEOMETRY.with(|g| *g.borrow_mut() = previous);
3303    }
3304}
3305
3306impl fmt::Debug for TextGeometry {
3307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3308        f.debug_struct("TextGeometry")
3309            .field("spacers", &self.spacers)
3310            .finish_non_exhaustive()
3311    }
3312}
3313
3314#[cfg(test)]
3315mod geometry_tests {
3316    use super::*;
3317
3318    /// "a[pad]bc[pad]d": a padded span's placeholders, as the core adds them.
3319    fn padded() -> Arc<AttributedText> {
3320        let mut text = AttributedText {
3321            text: format!("a{ATTACHMENT_CHAR}bc{ATTACHMENT_CHAR}d"),
3322            ..AttributedText::default()
3323        };
3324        for index in [1, 4] {
3325            text.attachments.push(TextAttachment {
3326                index,
3327                width: Points(4.0),
3328                height: Points::ZERO,
3329            });
3330        }
3331        Arc::new(text)
3332    }
3333
3334    fn geometry() -> TextGeometry {
3335        let engine = ApproxTextEngine;
3336        let text = padded();
3337        let prepared = engine.prepare(&text);
3338        let layout = engine.layout(&prepared, size(Points(1000.0), Points(100.0)));
3339        TextGeometry::new(std::rc::Rc::new(ApproxTextEngine), layout, text, &[1, 4])
3340    }
3341
3342    #[test]
3343    fn padding_placeholders_are_not_offsets() {
3344        let g = geometry();
3345        let lines = g.lines();
3346        assert_eq!(lines.len(), 1);
3347        assert_eq!(lines[0].text, "abcd");
3348        assert_eq!((lines[0].start, lines[0].end), (0, 4));
3349        let at = |o| {
3350            g.caret_rect(TextPosition::new(o, Affinity::Downstream))
3351                .unwrap()
3352                .origin
3353                .x
3354        };
3355        let laid = |o: u32| {
3356            ApproxTextEngine
3357                .caret_rect(&g.layout, TextPosition::new(o, Affinity::Downstream))
3358                .unwrap()
3359                .origin
3360                .x
3361        };
3362        // "b" is after the first placeholder, "d" after both.
3363        assert_eq!(at(1), laid(2));
3364        assert_eq!(at(3), laid(5));
3365        // And back: a point at "d" is offset 3 of the text.
3366        let p = point(laid(5), Points(1.0));
3367        assert_eq!(g.hit_test(p).offset, 3);
3368        // A range over "bc" covers the laid-out "bc", not the spacers.
3369        let r = g.range_rects(1..3);
3370        assert_eq!(r.len(), 1);
3371        assert_eq!(r[0].origin.x, laid(2));
3372    }
3373
3374    #[test]
3375    fn zero_height_user_attachments_stay_in_source_offsets() {
3376        let engine = ApproxTextEngine;
3377        let mut text = AttributedText {
3378            text: format!("a{ATTACHMENT_CHAR}b"),
3379            ..AttributedText::default()
3380        };
3381        text.attachments.push(TextAttachment {
3382            index: 1,
3383            width: Points(40.0),
3384            height: Points::ZERO,
3385        });
3386        let text = Arc::new(text);
3387        let prepared = engine.prepare(&text);
3388        let layout = engine.layout(&prepared, size(Points(1000.0), Points(100.0)));
3389        // Not a synthetic span-padding spacer, so its offset remains part of the source text.
3390        let g = TextGeometry::new(std::rc::Rc::new(ApproxTextEngine), layout, text, &[]);
3391        let lines = g.lines();
3392        assert_eq!(lines.len(), 1);
3393        assert_eq!((lines[0].start, lines[0].end), (0, 3));
3394        assert_eq!(lines[0].text, format!("a{ATTACHMENT_CHAR}b"));
3395        let r = g.range_rects(1..2);
3396        assert_eq!(r.len(), 1);
3397        assert_eq!(r[0].size.width, Points(40.0));
3398    }
3399
3400    #[test]
3401    fn approx_engine_hit_test_and_range_rects_respect_attachment_widths() {
3402        let engine = ApproxTextEngine;
3403        let style = ResolvedTextStyle {
3404            font_size: px(10.0 / 0.55),
3405            ..ResolvedTextStyle::default()
3406        };
3407        let mut t = AttributedText::default();
3408        t.push("ab", style);
3409        t.push_attachment(size(px(80.0), px(16.0)), style);
3410        t.push("cd", style);
3411        let prepared = engine.prepare(&t);
3412        let layout = engine.layout(&prepared, size(px(300.0), px(20.0)));
3413
3414        let x = |o| {
3415            engine
3416                .caret_rect(&layout, TextPosition::new(o, Affinity::Downstream))
3417                .map(|b| b.origin.x.0.round())
3418        };
3419        assert_eq!(x(0), Some(0.0));
3420        assert_eq!(x(2), Some(20.0));
3421        assert_eq!(x(3), Some(100.0));
3422        assert_eq!(x(5), Some(120.0));
3423
3424        let mut rects = Vec::new();
3425        engine.range_rects(&layout, 2..3, &mut rects);
3426        assert_eq!(rects.len(), 1);
3427        assert_eq!(rects[0].origin.x.0.round(), 20.0);
3428        assert_eq!(rects[0].size.width.0.round(), 80.0);
3429
3430        assert_eq!(engine.hit_test(&layout, point(px(19.0), px(5.0))).offset, 2);
3431        assert_eq!(engine.hit_test(&layout, point(px(50.0), px(5.0))).offset, 2);
3432        assert_eq!(engine.hit_test(&layout, point(px(70.0), px(5.0))).offset, 3);
3433        assert_eq!(
3434            engine.hit_test(&layout, point(px(101.0), px(5.0))).offset,
3435            3
3436        );
3437        assert_eq!(
3438            engine.hit_test(&layout, point(px(118.0), px(5.0))).offset,
3439            5
3440        );
3441    }
3442}