Skip to main content

waft_painting/
text_painter.rs

1//! Flutter counterpart: `painting/text_painter.dart`.
2//!
3//! `wordBoundaries` sits with `RenderEditable` in rendering, which owns the laid-out
4//! paragraph it reads; `locale` waits. See `PORTING.md`.
5
6use std::cell::OnceCell;
7
8use waft_embedder::{
9    BoxHeightStyle, BoxWidthStyle, Canvas, CanvasText, Color, FontCollection, GlyphInfo,
10    LineMetrics, Offset, Paint, PaintStyle, Paragraph, ParagraphBuilder, ParagraphConstraints,
11    ParagraphStyle, Rect, Size, Stroke, TextAffinity, TextAlign, TextBaseline, TextBox,
12    TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection, clamp_double,
13};
14use waft_foundation::PRECISION_ERROR_TOLERANCE;
15
16use crate::basic_types::RenderComparison;
17use crate::inline_span::{InlineSpanRef, utf16_len};
18use crate::strut_style::StrutStyle;
19use crate::text_scaler::TextScaler;
20use crate::text_style::TextStyle;
21
22/// The default font size if none is specified.
23///
24/// This should be consistent with the default font size in `dart:ui`.
25pub const K_DEFAULT_FONT_SIZE: f64 = 14.0;
26
27/// How overflowing text should be handled.
28///
29/// A [`TextOverflow`] can be passed to `Text` and `RichText` via their `overflow` properties,
30/// but they really work when the text will overflow its container. For example, they require
31/// specifying the `maxLines` property, or wrapping the text in a `SizedBox` with a fixed
32/// height.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum TextOverflow {
35    /// Clip the overflowing text to fix its container.
36    Clip,
37
38    /// Fade the overflowing text to transparent.
39    Fade,
40
41    /// Use an ellipsis to indicate that the text has overflowed.
42    Ellipsis,
43
44    /// Render overflowing text outside of its box.
45    Visible,
46}
47
48/// Holds the [`Size`] and baseline required to represent the dimensions of a placeholder
49/// in text.
50///
51/// Placeholders specify an empty space in the text layout, which is used to later render
52/// arbitrary inline widgets into defined by a `WidgetSpan`.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct PlaceholderDimensions {
55    /// Width and height dimensions of the placeholder.
56    pub size: Size,
57    /// How the placeholder vertically aligns with the text.
58    pub alignment: waft_embedder::PlaceholderAlignment,
59    /// Distance of the [`alignment`](Self::alignment) from the top of the placeholder.
60    pub baseline_offset: Option<f64>,
61    /// The [`TextBaseline`] to align against when using
62    /// `PlaceholderAlignment::Baseline`, `AboveBaseline`, and `BelowBaseline`.
63    pub baseline: Option<TextBaseline>,
64}
65
66impl PlaceholderDimensions {
67    /// A constant representing an empty placeholder.
68    pub const EMPTY: PlaceholderDimensions = PlaceholderDimensions {
69        size: Size::ZERO,
70        alignment: waft_embedder::PlaceholderAlignment::Bottom,
71        baseline_offset: None,
72        baseline: None,
73    };
74
75    /// Constructs a [`PlaceholderDimensions`] object.
76    pub const fn new(
77        size: Size,
78        alignment: waft_embedder::PlaceholderAlignment,
79    ) -> PlaceholderDimensions {
80        PlaceholderDimensions {
81            size,
82            alignment,
83            baseline_offset: None,
84            baseline: None,
85        }
86    }
87}
88
89/// The different ways of measuring the width of one or more lines of text.
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
91pub enum TextWidthBasis {
92    /// Multiline text will take up the full width given by the parent. For single line text,
93    /// only the minimum amount of width needed to contain the text will be used. A common use
94    /// case for this is a standard series of paragraphs.
95    #[default]
96    Parent,
97
98    /// The width will be exactly enough to contain the longest line and no longer. A common
99    /// use case for this is chat bubbles.
100    LongestLine,
101}
102
103/// Whether `code_point` is one of the newline code points the paragraph breaks on.
104fn is_newline(code_point: u32) -> bool {
105    matches!(
106        code_point,
107        0x000A | // Line Feed
108        0x0085 | // New Line
109        0x000B | // Form Feed
110        0x000C | // Vertical Feed
111        0x2028 | // Line Separator
112        0x2029 // Paragraph Separator
113    )
114}
115
116/// A laid-out paragraph and the direction it was laid out in (Dart's `_TextLayout`).
117struct TextLayout {
118    paragraph: Paragraph,
119    writing_direction: TextDirection,
120    end_of_text_caret_metrics: OnceCell<LineCaretMetrics>,
121}
122
123impl TextLayout {
124    fn new(paragraph: Paragraph, writing_direction: TextDirection) -> TextLayout {
125        TextLayout {
126            paragraph,
127            writing_direction,
128            end_of_text_caret_metrics: OnceCell::new(),
129        }
130    }
131
132    fn height(&self) -> f64 {
133        self.paragraph.height()
134    }
135
136    fn min_intrinsic_line_extent(&self) -> f64 {
137        self.paragraph.min_intrinsic_width()
138    }
139
140    fn max_intrinsic_line_extent(&self) -> f64 {
141        self.paragraph.max_intrinsic_width()
142    }
143
144    fn longest_line(&self) -> f64 {
145        self.paragraph.longest_line()
146    }
147
148    fn get_distance_to_baseline(&self, baseline: TextBaseline) -> f64 {
149        match baseline {
150            TextBaseline::Alphabetic => self.paragraph.alphabetic_baseline(),
151            TextBaseline::Ideographic => self.paragraph.ideographic_baseline(),
152        }
153    }
154
155    /// The caret metrics for the end of the text, anchored at the last line's baseline.
156    fn end_of_text_caret_metrics(&self, plain_text: &str) -> LineCaretMetrics {
157        *self
158            .end_of_text_caret_metrics
159            .get_or_init(|| self.compute_end_of_text_caret_anchor_offset(plain_text))
160    }
161
162    fn compute_end_of_text_caret_anchor_offset(&self, raw_string: &str) -> LineCaretMetrics {
163        let last_line_index = self.paragraph.number_of_lines() - 1;
164        debug_assert!(last_line_index >= 0);
165        let line_metrics = self
166            .paragraph
167            .get_line_metrics_at(last_line_index)
168            .expect("the last line exists");
169        let last_code_unit = raw_string.encode_utf16().last().unwrap_or(0);
170        let has_trailing_spaces = match last_code_unit {
171            0x0009 => true,                    // horizontal tab
172            0x00A0 | 0x2007 | 0x202F => false, // no-break, figure, narrow no-break space
173            unit => char::from_u32(u32::from(unit)).is_some_and(is_space_separator),
174        };
175        let baseline = line_metrics.baseline;
176        let last_glyph = self.paragraph.get_glyph_info_at(utf16_len(raw_string) - 1);
177        let (dx, height) = match last_glyph {
178            Some(last_glyph) if has_trailing_spaces => {
179                let glyph_bounds = last_glyph.grapheme_cluster_layout_bounds;
180                debug_assert!(!glyph_bounds.is_empty());
181                let dx = match self.writing_direction {
182                    TextDirection::Ltr => glyph_bounds.right,
183                    TextDirection::Rtl => glyph_bounds.left,
184                };
185                (dx, glyph_bounds.height())
186            }
187            _ => {
188                let dx = match self.writing_direction {
189                    TextDirection::Ltr => line_metrics.left + line_metrics.width,
190                    TextDirection::Rtl => line_metrics.left,
191                };
192                (dx, line_metrics.height)
193            }
194        };
195        LineCaretMetrics {
196            offset: Offset::new(dx, baseline),
197            writing_direction: self.writing_direction,
198            height,
199        }
200    }
201
202    fn content_width_for(
203        &self,
204        min_width: f64,
205        max_width: f64,
206        width_basis: TextWidthBasis,
207    ) -> f64 {
208        match width_basis {
209            TextWidthBasis::LongestLine => clamp_double(self.longest_line(), min_width, max_width),
210            TextWidthBasis::Parent => {
211                clamp_double(self.max_intrinsic_line_extent(), min_width, max_width)
212            }
213        }
214    }
215}
216
217/// Unicode `Space_Separator` (Zs).
218fn is_space_separator(ch: char) -> bool {
219    matches!(
220        ch,
221        '\u{0020}' | '\u{00A0}' | '\u{1680}' | '\u{2000}'
222            ..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
223    )
224}
225
226/// This struct stores the current text layout and the corresponding `text_align` and
227/// `content_width`.
228///
229/// This class also does some cache invalidation.
230struct TextPainterLayoutCacheWithOffset {
231    layout: TextLayout,
232    /// The input width used to lay out the paragraph.
233    layout_max_width: f64,
234    /// The content width the text painter should report in [`TextPainter::width`].
235    /// This is also used to compute the `paint_offset`.
236    content_width: f64,
237    /// The effective text alignment in the [`TextPainter`]'s canvas. The value is within the
238    /// `[0, 1]` interval: 0 for left aligned and 1 for right aligned.
239    text_alignment: f64,
240    cached_inline_placeholder_boxes: Option<Vec<TextBox>>,
241    cached_line_metrics: Option<Vec<LineMetrics>>,
242    /// Used to determine whether the caret metrics cache should be invalidated.
243    previous_caret_position_key: Option<i32>,
244}
245
246impl TextPainterLayoutCacheWithOffset {
247    fn new(
248        layout: TextLayout,
249        text_alignment: f64,
250        layout_max_width: f64,
251        content_width: f64,
252    ) -> TextPainterLayoutCacheWithOffset {
253        debug_assert!((0.0..=1.0).contains(&text_alignment));
254        debug_assert!(!layout_max_width.is_nan());
255        debug_assert!(!content_width.is_nan());
256        TextPainterLayoutCacheWithOffset {
257            layout,
258            layout_max_width,
259            content_width,
260            text_alignment,
261            cached_inline_placeholder_boxes: None,
262            cached_line_metrics: None,
263            previous_caret_position_key: None,
264        }
265    }
266
267    /// The paint offset that should be applied to the paragraph before painting.
268    fn paint_offset(&self) -> Offset {
269        if self.text_alignment == 0.0 {
270            return Offset::ZERO;
271        }
272        if !self.paragraph().width().is_finite() {
273            return Offset::new(f64::INFINITY, 0.0);
274        }
275        let dx = self.text_alignment * (self.content_width - self.paragraph().width());
276        debug_assert!(!dx.is_nan());
277        Offset::new(dx, 0.0)
278    }
279
280    fn paragraph(&self) -> &Paragraph {
281        &self.layout.paragraph
282    }
283
284    // Try to resize the current paragraph to fit the new input width range, without
285    // re-laying out the paragraph.
286    //
287    // Returns true if the resizing was successful.
288    fn resize_to_fit(
289        &mut self,
290        min_width: f64,
291        max_width: f64,
292        width_basis: TextWidthBasis,
293    ) -> bool {
294        debug_assert!(self.layout.max_intrinsic_line_extent().is_finite());
295        debug_assert!(min_width <= max_width);
296        // The assumption here is that if the length of the paragraph is
297        // already the same as the maxWidth, the paragraph's width can't be
298        // adjusted.
299        if max_width == self.content_width && min_width == self.content_width {
300            self.content_width = self
301                .layout
302                .content_width_for(min_width, max_width, width_basis);
303            return true;
304        }
305
306        // Special case:
307        // When the paint offset and the paragraph width are both +∞, it's likely
308        // that the text layout engine skipped layout because there weren't anything
309        // to paint. Override the paragraph width with paragraph max width to
310        // avoid infinite paint offsets.
311        if !self.paint_offset().dx().is_finite()
312            && !self.paragraph().width().is_finite()
313            && min_width.is_finite()
314        {
315            debug_assert!(self.paint_offset().dx() == f64::INFINITY);
316            debug_assert!(self.paragraph().width() == f64::INFINITY);
317            return false;
318        }
319
320        let max_intrinsic_width = self.paragraph().max_intrinsic_width();
321        // Skip line breaking if the input width remains the same, of there will be
322        // no soft breaks.
323        let skip_line_breaking = max_width == self.layout_max_width // Same input max width so relayout is unnecessary.
324            || ((self.paragraph().width() - max_intrinsic_width) > -PRECISION_ERROR_TOLERANCE
325                && (max_width - max_intrinsic_width) > -PRECISION_ERROR_TOLERANCE);
326        if skip_line_breaking {
327            // Adjust width to the same input width.
328            self.content_width = self
329                .layout
330                .content_width_for(min_width, max_width, width_basis);
331            return true;
332        }
333        false
334    }
335
336    // ---- Cached values whose life cycle ends when the paragraph is relaid out ----
337
338    fn inline_placeholder_boxes(&mut self) -> &[TextBox] {
339        self.cached_inline_placeholder_boxes
340            .get_or_insert_with(|| self.layout.paragraph.get_boxes_for_placeholders())
341    }
342
343    fn line_metrics(&mut self) -> &[LineMetrics] {
344        self.cached_line_metrics
345            .get_or_insert_with(|| self.layout.paragraph.compute_line_metrics())
346    }
347}
348
349/// The _CaretMetrics for carets located in a non-empty paragraph. Such carets are anchored
350/// to the trailing edge or the leading edge of a glyph, or a ligature component.
351#[derive(Clone, Copy, Debug, PartialEq)]
352struct LineCaretMetrics {
353    /// The offset from the top left corner of the paragraph to the caret's top start
354    /// location.
355    offset: Offset,
356    /// The writing direction of the glyph the caret is anchored to. This is used to compute
357    /// the caret's rect.
358    writing_direction: TextDirection,
359    /// The full height of the glyph at the caret position.
360    height: f64,
361}
362
363impl LineCaretMetrics {
364    fn shift(&self, offset: Offset) -> LineCaretMetrics {
365        if offset == Offset::ZERO {
366            *self
367        } else {
368            LineCaretMetrics {
369                offset: offset + self.offset,
370                writing_direction: self.writing_direction,
371                height: self.height,
372            }
373        }
374    }
375}
376
377/// An object that paints a `TextSpan` tree into a `Canvas`.
378///
379/// To use a [`TextPainter`], follow these steps:
380///
381/// 1. Create a `TextSpan` tree and pass it to the [`TextPainter`] with
382///    [`set_text`](Self::set_text); set [`set_text_direction`](Self::set_text_direction).
383/// 2. Call [`layout`](Self::layout) to prepare the paragraph.
384/// 3. Call [`paint`](Self::paint) as often as desired to paint the paragraph.
385/// 4. Call [`dispose`](Self::dispose) when the object will no longer be accessed to release
386///    native resources. For [`TextPainter`] objects that are used repeatedly and stored on a
387///    `State` or `RenderObject`, call [`dispose`](Self::dispose) from `State::dispose` or
388///    `RenderObject::dispose` or similar. For those used only ephemerally, it is sufficient
389///    to immediately dispose them after use.
390///
391/// If the width of the area into which the text is being painted changes, return to step 2.
392/// If the text to be painted changes, return to step 1.
393///
394/// Dart's constructor arguments are the setters: `TextPainter::new()` is a painter with
395/// every default. The methods that shape take the [`FontCollection`] to shape against;
396/// `PaintingBinding::fonts` is the app-wide one.
397pub struct TextPainter {
398    text: Option<InlineSpanRef>,
399    text_align: TextAlign,
400    text_direction: Option<TextDirection>,
401    text_scaler: TextScaler,
402    ellipsis: Option<String>,
403    max_lines: Option<i32>,
404    text_width_basis: TextWidthBasis,
405    text_height_behavior: Option<TextHeightBehavior>,
406    strut_style: Option<StrutStyle>,
407    placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
408    layout_cache: Option<TextPainterLayoutCacheWithOffset>,
409    layout_template: Option<Paragraph>,
410    // Whether _layoutCache contains outdated paint information and needs to be
411    // updated before painting.
412    //
413    // ui.Paragraph is entirely immutable, thus text style changes that can affect
414    // layout and those who can't both require the ui.Paragraph object being
415    // recreated. The caller may not call `layout` again after text color change.
416    // See: https://github.com/flutter/flutter/issues/85108
417    rebuild_paragraph_for_paint: bool,
418    cached_plain_text: Option<String>,
419    caret_metrics: Option<LineCaretMetrics>,
420    debug_needs_relayout: bool,
421    /// Paints the layout boxes of each character when true. For debugging.
422    pub debug_paint_text_layout_boxes: bool,
423    disposed: bool,
424}
425
426impl Default for TextPainter {
427    fn default() -> TextPainter {
428        TextPainter::new()
429    }
430}
431
432impl TextPainter {
433    /// Creates a text painter that paints the given text.
434    ///
435    /// The `text` and `text_direction` must be set before [`layout`](Self::layout) is
436    /// called.
437    pub fn new() -> TextPainter {
438        TextPainter {
439            text: None,
440            text_align: TextAlign::Start,
441            text_direction: None,
442            text_scaler: TextScaler::NO_SCALING,
443            ellipsis: None,
444            max_lines: None,
445            text_width_basis: TextWidthBasis::Parent,
446            text_height_behavior: None,
447            strut_style: None,
448            placeholder_dimensions: None,
449            layout_cache: None,
450            layout_template: None,
451            rebuild_paragraph_for_paint: true,
452            cached_plain_text: None,
453            caret_metrics: None,
454            debug_needs_relayout: true,
455            debug_paint_text_layout_boxes: false,
456            disposed: false,
457        }
458    }
459
460    /// Computes the width of a configured [`TextPainter`].
461    ///
462    /// This is a convenience method that creates a text painter with the supplied
463    /// parameters, lays it out with the supplied `min_width` and `max_width`, and returns its
464    /// [`width`](Self::width), disposing the painter. Other settings go through a painter's
465    /// setters. `fonts` is the collection to shape against.
466    pub fn compute_width(
467        fonts: &mut FontCollection,
468        text: InlineSpanRef,
469        text_direction: TextDirection,
470        min_width: f64,
471        max_width: f64,
472    ) -> f64 {
473        let mut painter = TextPainter::new();
474        painter.set_text(Some(text));
475        painter.set_text_direction(Some(text_direction));
476        painter.layout(fonts, min_width, max_width);
477        let width = painter.width();
478        painter.dispose();
479        width
480    }
481
482    /// Computes the max intrinsic width of a configured [`TextPainter`].
483    ///
484    /// This is a convenience method that creates a text painter with the supplied
485    /// parameters, lays it out with the supplied `min_width` and `max_width`, and returns its
486    /// [`max_intrinsic_width`](Self::max_intrinsic_width), disposing the painter.
487    pub fn compute_max_intrinsic_width(
488        fonts: &mut FontCollection,
489        text: InlineSpanRef,
490        text_direction: TextDirection,
491        min_width: f64,
492        max_width: f64,
493    ) -> f64 {
494        let mut painter = TextPainter::new();
495        painter.set_text(Some(text));
496        painter.set_text_direction(Some(text_direction));
497        painter.layout(fonts, min_width, max_width);
498        let width = painter.max_intrinsic_width();
499        painter.dispose();
500        width
501    }
502
503    fn debug_assert_text_layout_is_valid(&self) -> bool {
504        debug_assert!(!self.debug_disposed());
505        assert!(
506            self.layout_cache.is_some(),
507            "Text layout not available: the TextPainter has never been laid out."
508        );
509        true
510    }
511
512    /// Marks this text painter's layout information as dirty and removes cached information.
513    ///
514    /// Uses this method to notify text painter to relayout in the scenario where the layout
515    /// information may change without the text being changed.
516    pub fn mark_needs_layout(&mut self) {
517        if let Some(mut cache) = self.layout_cache.take() {
518            cache.layout.paragraph.dispose();
519        }
520    }
521
522    /// The (potentially styled) text to paint.
523    ///
524    /// After this is set, you must call [`layout`](Self::layout) before the next call to
525    /// [`paint`](Self::paint).
526    pub fn text(&self) -> Option<&InlineSpanRef> {
527        self.text.as_ref()
528    }
529
530    /// Sets [`text`](Self::text).
531    pub fn set_text(&mut self, value: Option<InlineSpanRef>) {
532        debug_assert!(
533            value
534                .as_ref()
535                .is_none_or(|value| value.debug_assert_is_valid())
536        );
537        let same = match (&self.text, &value) {
538            (None, None) => true,
539            (Some(current), Some(value)) => current.eq_span(&**value),
540            _ => false,
541        };
542        if same {
543            return;
544        }
545        let style_changed = self.text.as_ref().and_then(|text| text.style())
546            != value.as_ref().and_then(|value| value.style());
547        if style_changed && let Some(mut template) = self.layout_template.take() {
548            template.dispose();
549        }
550
551        let comparison = match (&self.text, &value) {
552            (_, None) => RenderComparison::Layout,
553            (Some(current), Some(value)) => current.compare_to(&**value),
554            (None, Some(_)) => RenderComparison::Layout,
555        };
556
557        self.text = value;
558        self.cached_plain_text = None;
559
560        if comparison >= RenderComparison::Layout {
561            self.mark_needs_layout();
562        } else if comparison >= RenderComparison::Paint {
563            // Don't invalid the _layoutCache just yet. It still contains valid layout
564            // information.
565            self.rebuild_paragraph_for_paint = true;
566        }
567        // Neither relayout or repaint is needed.
568    }
569
570    /// Returns a plain text version of the text to paint.
571    ///
572    /// This uses `InlineSpan::to_plain_text` to get the full contents of all nodes in the
573    /// tree.
574    pub fn plain_text(&mut self) -> &str {
575        if self.cached_plain_text.is_none() {
576            self.cached_plain_text = Some(
577                self.text
578                    .as_ref()
579                    .map(|text| text.to_plain_text(false, true))
580                    .unwrap_or_default(),
581            );
582        }
583        self.cached_plain_text.as_deref().unwrap_or("")
584    }
585
586    /// How the text should be aligned horizontally.
587    ///
588    /// After this is set, you must call [`layout`](Self::layout) before the next call to
589    /// [`paint`](Self::paint).
590    ///
591    /// The [`text_align`](Self::text_align) property defaults to [`TextAlign::Start`].
592    pub fn text_align(&self) -> TextAlign {
593        self.text_align
594    }
595
596    /// Sets [`text_align`](Self::text_align).
597    pub fn set_text_align(&mut self, value: TextAlign) {
598        if self.text_align == value {
599            return;
600        }
601        self.text_align = value;
602        self.mark_needs_layout();
603    }
604
605    /// The default directionality of the text.
606    ///
607    /// This controls how the [`TextAlign::Start`], [`TextAlign::End`], and
608    /// [`TextAlign::Justify`] values of [`text_align`](Self::text_align) are resolved.
609    ///
610    /// This is also used to disambiguate how to render bidirectional text. For example, if
611    /// the [`text`](Self::text) is an English phrase followed by a Hebrew phrase, in a
612    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
613    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
614    /// will be on the right and the Hebrew phrase on its left.
615    ///
616    /// After this is set, you must call [`layout`](Self::layout) before the next call to
617    /// [`paint`](Self::paint).
618    ///
619    /// This and [`text`](Self::text) must be set before [`layout`](Self::layout) is called.
620    pub fn text_direction(&self) -> Option<TextDirection> {
621        self.text_direction
622    }
623
624    /// Sets [`text_direction`](Self::text_direction).
625    pub fn set_text_direction(&mut self, value: Option<TextDirection>) {
626        if self.text_direction == value {
627            return;
628        }
629        self.text_direction = value;
630        self.mark_needs_layout();
631        // Shouldn't really matter, but for strict correctness...
632        if let Some(mut template) = self.layout_template.take() {
633            template.dispose();
634        }
635    }
636
637    /// The font scaling strategy to use when laying out and rendering the text.
638    ///
639    /// The value usually comes from `MediaQuery.textScalerOf`, which typically reflects the
640    /// user-specified text scaling value in the platform's accessibility settings.
641    ///
642    /// The [`TextStyle::font_size`] of the text will be adjusted by the [`TextScaler`] before
643    /// layout and painting.
644    ///
645    /// After this is set, you must call [`layout`](Self::layout) before the next call to
646    /// [`paint`](Self::paint).
647    pub fn text_scaler(&self) -> &TextScaler {
648        &self.text_scaler
649    }
650
651    /// Sets [`text_scaler`](Self::text_scaler).
652    pub fn set_text_scaler(&mut self, value: TextScaler) {
653        if value == self.text_scaler {
654            return;
655        }
656        self.text_scaler = value;
657        self.mark_needs_layout();
658        if let Some(mut template) = self.layout_template.take() {
659            template.dispose();
660        }
661    }
662
663    /// The string used to ellipsize overflowing text. Setting this to a non-empty string
664    /// will cause this string to be substituted for the remaining text if the text can not
665    /// fit within the specified maximum width.
666    ///
667    /// Specifically, the ellipsis is applied to the last line before the line truncated by
668    /// [`max_lines`](Self::max_lines), if [`max_lines`](Self::max_lines) is non-`None` and
669    /// that line overflows the width constraint, or to the first line that is wider than the
670    /// width constraint, if [`max_lines`](Self::max_lines) is `None`. The width constraint
671    /// is the `max_width` passed to [`layout`](Self::layout).
672    ///
673    /// After this is set, you must call [`layout`](Self::layout) before the next call to
674    /// [`paint`](Self::paint).
675    ///
676    /// The string will be applied at the end of the text, even if the text is longer than
677    /// one line.
678    pub fn ellipsis(&self) -> Option<&str> {
679        self.ellipsis.as_deref()
680    }
681
682    /// Sets [`ellipsis`](Self::ellipsis).
683    pub fn set_ellipsis(&mut self, value: Option<String>) {
684        debug_assert!(value.as_ref().is_none_or(|value| !value.is_empty()));
685        if self.ellipsis == value {
686            return;
687        }
688        self.ellipsis = value;
689        self.mark_needs_layout();
690    }
691
692    /// An optional maximum number of lines for the text to span, wrapping if necessary.
693    ///
694    /// If the text exceeds the given number of lines, it is truncated such that subsequent
695    /// lines are dropped.
696    ///
697    /// After this is set, you must call [`layout`](Self::layout) before the next call to
698    /// [`paint`](Self::paint).
699    pub fn max_lines(&self) -> Option<i32> {
700        self.max_lines
701    }
702
703    /// Sets [`max_lines`](Self::max_lines). The value may be `None`. If it is not `None`,
704    /// then it must be greater than zero.
705    pub fn set_max_lines(&mut self, value: Option<i32>) {
706        debug_assert!(value.is_none_or(|value| value > 0));
707        if self.max_lines == value {
708            return;
709        }
710        self.max_lines = value;
711        self.mark_needs_layout();
712    }
713
714    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
715    /// layout metrics.
716    ///
717    /// Omitting or providing `None` will disable strut.
718    ///
719    /// Omitting or providing `None` for any properties of [`StrutStyle`] will result in
720    /// default values being used. It is highly recommended to at least specify a
721    /// [`StrutStyle::font_size`].
722    pub fn strut_style(&self) -> Option<&StrutStyle> {
723        self.strut_style.as_ref()
724    }
725
726    /// Sets [`strut_style`](Self::strut_style).
727    pub fn set_strut_style(&mut self, value: Option<StrutStyle>) {
728        if self.strut_style == value {
729            return;
730        }
731        self.strut_style = value;
732        self.mark_needs_layout();
733    }
734
735    /// Defines how to measure the width of the rendered text.
736    pub fn text_width_basis(&self) -> TextWidthBasis {
737        self.text_width_basis
738    }
739
740    /// Sets [`text_width_basis`](Self::text_width_basis).
741    pub fn set_text_width_basis(&mut self, value: TextWidthBasis) {
742        if self.text_width_basis == value {
743            return;
744        }
745        if cfg!(debug_assertions) {
746            self.debug_needs_relayout = true;
747        }
748        self.text_width_basis = value;
749    }
750
751    /// Defines how to apply `TextStyle.height` over and under text.
752    pub fn text_height_behavior(&self) -> Option<TextHeightBehavior> {
753        self.text_height_behavior
754    }
755
756    /// Sets [`text_height_behavior`](Self::text_height_behavior).
757    pub fn set_text_height_behavior(&mut self, value: Option<TextHeightBehavior>) {
758        if self.text_height_behavior == value {
759            return;
760        }
761        self.text_height_behavior = value;
762        self.mark_needs_layout();
763    }
764
765    /// An ordered list of [`TextBox`]es that bound the positions of the placeholders in the
766    /// paragraph.
767    ///
768    /// Each box corresponds to a `PlaceholderSpan` in the order they were defined in the
769    /// `InlineSpan` tree.
770    pub fn inline_placeholder_boxes(&mut self) -> Option<Vec<TextBox>> {
771        let layout = self.layout_cache.as_mut()?;
772        let offset = layout.paint_offset();
773        if !offset.dx().is_finite() || !offset.dy().is_finite() {
774            return Some(Vec::new());
775        }
776        let raw_boxes = layout.inline_placeholder_boxes();
777        if offset == Offset::ZERO {
778            return Some(raw_boxes.to_vec());
779        }
780        Some(
781            raw_boxes
782                .iter()
783                .map(|text_box| shift_text_box(*text_box, offset))
784                .collect(),
785        )
786    }
787
788    /// Sets the dimensions of each placeholder in [`text`](Self::text).
789    ///
790    /// The number of [`PlaceholderDimensions`] provided should be the same as the number of
791    /// `PlaceholderSpan`s in text. Passing in an empty or `None` `value` will do nothing.
792    ///
793    /// If [`layout`](Self::layout) is attempted without setting the placeholder dimensions,
794    /// the placeholders will be ignored in the text layout and no valid
795    /// [`inline_placeholder_boxes`](Self::inline_placeholder_boxes) will be returned.
796    pub fn set_placeholder_dimensions(&mut self, value: Option<Vec<PlaceholderDimensions>>) {
797        let Some(value) = value else {
798            return;
799        };
800        if value.is_empty() || Some(&value) == self.placeholder_dimensions.as_ref() {
801            return;
802        }
803        if cfg!(debug_assertions) {
804            let mut placeholder_count = 0;
805            if let Some(text) = &self.text {
806                text.clone().visit_children(&mut |span| {
807                    if span.as_placeholder_span().is_some() {
808                        placeholder_count += 1;
809                    }
810                    value.len() >= placeholder_count
811                });
812            }
813            assert_eq!(placeholder_count, value.len());
814        }
815        self.placeholder_dimensions = Some(value);
816        self.mark_needs_layout();
817    }
818
819    fn create_paragraph_style(&self, text_align_override: Option<TextAlign>) -> ParagraphStyle {
820        debug_assert!(
821            self.text_direction.is_some(),
822            "TextPainter.textDirection must be set to a non-null value before using the TextPainter."
823        );
824        let default_style = TextStyle::new();
825        let base_style = self
826            .text
827            .as_ref()
828            .and_then(|text| text.style())
829            .unwrap_or(&default_style);
830        let mut paragraph_style = base_style
831            .get_paragraph_style()
832            .text_align(text_align_override.unwrap_or(self.text_align))
833            .text_scaler(self.text_scaler.clone());
834        if let Some(text_direction) = self.text_direction {
835            paragraph_style = paragraph_style.text_direction(text_direction);
836        }
837        if let Some(max_lines) = self.max_lines {
838            paragraph_style = paragraph_style.max_lines(max_lines);
839        }
840        if let Some(text_height_behavior) = self.text_height_behavior {
841            paragraph_style = paragraph_style.text_height_behavior(text_height_behavior);
842        }
843        if let Some(ellipsis) = &self.ellipsis {
844            paragraph_style = paragraph_style.ellipsis(ellipsis.clone());
845        }
846        if let Some(strut_style) = &self.strut_style {
847            paragraph_style = paragraph_style.strut_style(strut_style.clone());
848        }
849        paragraph_style.build()
850    }
851
852    fn create_layout_template(&self, fonts: &mut FontCollection) -> Paragraph {
853        // Direction doesn't matter, text is just a space.
854        let mut builder = ParagraphBuilder::new(self.create_paragraph_style(Some(TextAlign::Left)));
855        let text_style = self
856            .text
857            .as_ref()
858            .and_then(|text| text.style())
859            .map(|style| style.get_text_style_with(&self.text_scaler));
860        if let Some(text_style) = text_style {
861            builder.push_style(text_style);
862        }
863        builder.add_text(" ");
864        let mut template = builder.build(fonts);
865        template.layout(ParagraphConstraints::new(f64::INFINITY));
866        template
867    }
868
869    fn get_or_create_layout_template(&mut self, fonts: &mut FontCollection) -> &Paragraph {
870        if self.layout_template.is_none() {
871            self.layout_template = Some(self.create_layout_template(fonts));
872        }
873        self.layout_template.as_ref().expect("just created")
874    }
875
876    /// The height of a space in [`text`](Self::text) in logical pixels.
877    ///
878    /// Not every line of text in [`text`](Self::text) will have this height, but this height
879    /// is "typical" for text in [`text`](Self::text) and useful for sizing other objects
880    /// relative a typical line of text.
881    ///
882    /// Obtaining this value does not require calling [`layout`](Self::layout).
883    ///
884    /// The style of the [`text`](Self::text) property is used to determine the font settings
885    /// that contribute to the [`preferred_line_height`](Self::preferred_line_height). If
886    /// [`text`](Self::text) is `None` or if it specifies no styles, the default `TextStyle`
887    /// values are used (a 10 pixel sans-serif font).
888    pub fn preferred_line_height(&mut self, fonts: &mut FontCollection) -> f64 {
889        self.get_or_create_layout_template(fonts).height()
890    }
891
892    /// The width at which decreasing the width of the text would prevent it from painting
893    /// itself completely within its bounds.
894    ///
895    /// Valid only after [`layout`](Self::layout) has been called.
896    pub fn min_intrinsic_width(&self) -> f64 {
897        debug_assert!(self.debug_assert_text_layout_is_valid());
898        self.layout_cache().layout.min_intrinsic_line_extent()
899    }
900
901    /// The width at which increasing the width of the text no longer decreases the height.
902    ///
903    /// Valid only after [`layout`](Self::layout) has been called.
904    pub fn max_intrinsic_width(&self) -> f64 {
905        debug_assert!(self.debug_assert_text_layout_is_valid());
906        self.layout_cache().layout.max_intrinsic_line_extent()
907    }
908
909    /// The horizontal space required to paint this text.
910    ///
911    /// Valid only after [`layout`](Self::layout) has been called.
912    pub fn width(&self) -> f64 {
913        debug_assert!(self.debug_assert_text_layout_is_valid());
914        debug_assert!(!self.debug_needs_relayout);
915        self.layout_cache().content_width
916    }
917
918    /// The vertical space required to paint this text.
919    ///
920    /// Valid only after [`layout`](Self::layout) has been called.
921    pub fn height(&self) -> f64 {
922        debug_assert!(self.debug_assert_text_layout_is_valid());
923        self.layout_cache().layout.height()
924    }
925
926    /// The amount of space required to paint this text.
927    ///
928    /// Valid only after [`layout`](Self::layout) has been called.
929    pub fn size(&self) -> Size {
930        debug_assert!(self.debug_assert_text_layout_is_valid());
931        debug_assert!(!self.debug_needs_relayout);
932        Size::new(self.width(), self.height())
933    }
934
935    /// Returns the distance from the top of the text to the first baseline of the given
936    /// type.
937    ///
938    /// Valid only after [`layout`](Self::layout) has been called.
939    pub fn compute_distance_to_actual_baseline(&self, baseline: TextBaseline) -> f64 {
940        debug_assert!(self.debug_assert_text_layout_is_valid());
941        self.layout_cache()
942            .layout
943            .get_distance_to_baseline(baseline)
944    }
945
946    /// Whether any text was truncated or ellipsized.
947    ///
948    /// If [`max_lines`](Self::max_lines) is not `None`, this is true if there were more lines
949    /// to draw than the given [`max_lines`](Self::max_lines), and thus at least one line was
950    /// omitted. If [`max_lines`](Self::max_lines) is `None`, this is true if
951    /// [`ellipsis`](Self::ellipsis) is not the empty string and there was a line that
952    /// overflowed the `max_width` argument passed to [`layout`](Self::layout).
953    ///
954    /// Valid only after [`layout`](Self::layout) has been called.
955    pub fn did_exceed_max_lines(&self) -> bool {
956        debug_assert!(self.debug_assert_text_layout_is_valid());
957        self.layout_cache().paragraph().did_exceed_max_lines()
958    }
959
960    fn layout_cache(&self) -> &TextPainterLayoutCacheWithOffset {
961        self.layout_cache
962            .as_ref()
963            .expect("Text layout not available: the TextPainter has never been laid out.")
964    }
965
966    // Creates a ui.Paragraph using the current configurations in this class and
967    // assign it to _paragraph.
968    fn create_paragraph(&mut self, fonts: &mut FontCollection, text: &InlineSpanRef) -> Paragraph {
969        let mut builder = ParagraphBuilder::new(self.create_paragraph_style(None));
970        text.build(
971            &mut builder,
972            &self.text_scaler,
973            self.placeholder_dimensions.as_deref(),
974        );
975        self.rebuild_paragraph_for_paint = false;
976        builder.build(fonts)
977    }
978
979    /// Computes the visual position of the glyphs for painting the text.
980    ///
981    /// The text will layout with a width that's as close to its max intrinsic width (or its
982    /// longest line, if [`text_width_basis`](Self::text_width_basis) is set to
983    /// [`TextWidthBasis::Parent`]) as possible while still being greater than or equal to
984    /// `min_width` and less than or equal to `max_width`.
985    ///
986    /// The [`text`](Self::text) and [`text_direction`](Self::text_direction) properties
987    /// must be non-`None` before this is called. `fonts` is the collection to shape against.
988    pub fn layout(&mut self, fonts: &mut FontCollection, min_width: f64, max_width: f64) {
989        debug_assert!(!max_width.is_nan());
990        debug_assert!(!min_width.is_nan());
991        if cfg!(debug_assertions) {
992            self.debug_needs_relayout = false;
993        }
994
995        if let Some(cached_layout) = self.layout_cache.as_mut()
996            && cached_layout.resize_to_fit(min_width, max_width, self.text_width_basis)
997        {
998            return;
999        }
1000
1001        let text = self.text.clone().expect(
1002            "TextPainter.text must be set to a non-null value before using the TextPainter.",
1003        );
1004        let text_direction = self.text_direction.expect(
1005            "TextPainter.textDirection must be set to a non-null value before using the TextPainter.",
1006        );
1007
1008        // Determines the actual max width, and whether the max width needs to be adjusted.
1009        let paint_offset_alignment = compute_paint_offset_fraction(self.text_align, text_direction);
1010        let adjust_max_width = !max_width.is_finite() && paint_offset_alignment != 0.0;
1011        let adjusted_max_width = if !adjust_max_width {
1012            Some(max_width)
1013        } else {
1014            self.layout_cache
1015                .as_ref()
1016                .map(|cached| cached.layout.max_intrinsic_line_extent())
1017        };
1018        let layout_max_width = adjusted_max_width.unwrap_or(max_width);
1019
1020        // Only rebuild the paragraph when there're layout changes, even when
1021        // `_rebuildParagraphForPaint` is true. It's best to not eagerly rebuild
1022        // the paragraph to avoid the extra work, because:
1023        // 1. the text color could change again before `paint` is called (so one of
1024        //    the paragraph rebuilds is unnecessary)
1025        // 2. the user could be measuring the text layout so `paint` will never be
1026        //    called.
1027        let mut paragraph = match self.layout_cache.take() {
1028            Some(cached) => cached.layout.paragraph,
1029            None => self.create_paragraph(fonts, &text),
1030        };
1031        paragraph.layout(ParagraphConstraints::new(layout_max_width));
1032        let layout = TextLayout::new(paragraph, text_direction);
1033        let content_width = layout.content_width_for(min_width, max_width, self.text_width_basis);
1034
1035        let new_layout_cache = if adjusted_max_width.is_none() && min_width.is_finite() {
1036            debug_assert!(max_width.is_infinite());
1037            let new_input_width = layout.max_intrinsic_line_extent();
1038            let mut layout = layout;
1039            layout
1040                .paragraph
1041                .layout(ParagraphConstraints::new(new_input_width));
1042            TextPainterLayoutCacheWithOffset::new(
1043                layout,
1044                paint_offset_alignment,
1045                new_input_width,
1046                content_width,
1047            )
1048        } else {
1049            TextPainterLayoutCacheWithOffset::new(
1050                layout,
1051                paint_offset_alignment,
1052                layout_max_width,
1053                content_width,
1054            )
1055        };
1056        self.layout_cache = Some(new_layout_cache);
1057    }
1058
1059    /// Paints the text onto the given canvas at the given offset.
1060    ///
1061    /// Valid only after [`layout`](Self::layout) has been called.
1062    ///
1063    /// If you cannot see the text being painted, check that your text color does not conflict
1064    /// with the background on which you are drawing. The default text color is white (to
1065    /// contrast with the default black background color), so if you are writing an
1066    /// application with a white background, the text will not be visible by default.
1067    ///
1068    /// To set the text style, specify a `TextStyle` when creating the `TextSpan` that you
1069    /// pass to the [`TextPainter`].
1070    pub fn paint(&mut self, fonts: &mut FontCollection, canvas: &mut Canvas, offset: Offset) {
1071        assert!(
1072            self.layout_cache.is_some(),
1073            "TextPainter.paint called when text geometry was not yet calculated.\n\
1074             Please call layout() before paint() to position the text before painting it."
1075        );
1076        let paint_offset = self.layout_cache().paint_offset();
1077        if !paint_offset.dx().is_finite() || !paint_offset.dy().is_finite() {
1078            return;
1079        }
1080
1081        if self.rebuild_paragraph_for_paint {
1082            let debug_size = cfg!(debug_assertions).then(|| self.size());
1083            let text = self.text.clone().expect("a laid-out painter has text");
1084            let layout_max_width = self.layout_cache().layout_max_width;
1085            debug_assert!(!layout_max_width.is_nan());
1086            let mut rebuilt = self.create_paragraph(fonts, &text);
1087            rebuilt.layout(ParagraphConstraints::new(layout_max_width));
1088            let layout_cache = self.layout_cache.as_mut().expect("checked above");
1089            debug_assert!(layout_cache.paragraph().width() == rebuilt.width());
1090            let mut previous = std::mem::replace(&mut layout_cache.layout.paragraph, rebuilt);
1091            previous.dispose();
1092            debug_assert!(debug_size.is_none_or(|size| size == self.size()));
1093        }
1094        debug_assert!(!self.rebuild_paragraph_for_paint);
1095        if self.debug_paint_text_layout_boxes {
1096            self.debug_paint_character_layout_boxes(canvas, offset);
1097        }
1098        canvas.draw_paragraph(self.layout_cache().paragraph(), offset + paint_offset);
1099    }
1100
1101    fn debug_paint_character_layout_boxes(&mut self, canvas: &mut Canvas, offset: Offset) {
1102        let paint = Paint {
1103            style: PaintStyle::Stroke(Stroke::new(1.0)),
1104            color: Color::from_argb(255, 0, 255, 255).into(),
1105            ..Paint::default()
1106        };
1107        let length = utf16_len(self.plain_text());
1108        let text_boxes = self.get_boxes_for_selection(
1109            TextSelection::new(0, length),
1110            BoxHeightStyle::Tight,
1111            BoxWidthStyle::Tight,
1112        );
1113        for text_box in text_boxes {
1114            let host_rect: waft_embedder::valo::Rect = text_box.to_rect().shift(offset).into();
1115            canvas.draw_rect(host_rect, &paint);
1116        }
1117    }
1118
1119    /// Whether `value` is a high surrogate UTF-16 code unit.
1120    pub fn is_high_surrogate(value: u16) -> bool {
1121        value & 0xFC00 == 0xD800
1122    }
1123
1124    /// Whether `value` is a low surrogate UTF-16 code unit.
1125    pub fn is_low_surrogate(value: u16) -> bool {
1126        value & 0xFC00 == 0xDC00
1127    }
1128
1129    /// Returns the closest offset after `offset` at which the input cursor can be positioned.
1130    pub fn get_offset_after(&self, offset: i32) -> Option<i32> {
1131        let next_code_unit = self.text.clone()?.code_unit_at(offset)?;
1132        // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one
1133        // Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
1134        Some(if TextPainter::is_high_surrogate(next_code_unit) {
1135            offset + 2
1136        } else {
1137            offset + 1
1138        })
1139    }
1140
1141    /// Returns the closest offset before `offset` at which the input cursor can be
1142    /// positioned.
1143    pub fn get_offset_before(&self, offset: i32) -> Option<i32> {
1144        let prev_code_unit = self.text.clone()?.code_unit_at(offset - 1)?;
1145        // TODO(goderbauer): doesn't handle extended grapheme clusters with more than one
1146        // Unicode scalar value (https://github.com/flutter/flutter/issues/13404).
1147        Some(if TextPainter::is_low_surrogate(prev_code_unit) {
1148            offset - 2
1149        } else {
1150            offset - 1
1151        })
1152    }
1153
1154    /// Returns the offset at which to paint the caret.
1155    ///
1156    /// Valid only after [`layout`](Self::layout) has been called.
1157    pub fn get_offset_for_caret(
1158        &mut self,
1159        fonts: &mut FontCollection,
1160        position: TextPosition,
1161        caret_prototype: Rect,
1162    ) -> Offset {
1163        let Some(caret_metrics) = self.compute_caret_metrics(fonts, position) else {
1164            let text_direction = self.text_direction.expect("laid out");
1165            let paint_offset_alignment =
1166                compute_paint_offset_fraction(self.text_align, text_direction);
1167            let dx = if paint_offset_alignment == 0.0 {
1168                0.0
1169            } else {
1170                paint_offset_alignment * self.layout_cache().content_width
1171            };
1172            return Offset::new(dx, 0.0);
1173        };
1174        let layout_cache = self.layout_cache();
1175        let raw_offset = match caret_metrics.writing_direction {
1176            TextDirection::Ltr => caret_metrics.offset,
1177            TextDirection::Rtl => Offset::new(
1178                caret_metrics.offset.dx() - caret_prototype.width(),
1179                caret_metrics.offset.dy(),
1180            ),
1181        };
1182        // If the caret is at the end of the paragraph and beyond the layout width
1183        // (thus disregarding the paragraph's width), clamp it to the content width.
1184        let adjusted_dx = clamp_double(
1185            raw_offset.dx() + layout_cache.paint_offset().dx(),
1186            0.0,
1187            layout_cache.content_width,
1188        );
1189        Offset::new(
1190            adjusted_dx,
1191            raw_offset.dy() + layout_cache.paint_offset().dy(),
1192        )
1193    }
1194
1195    /// The condition is derived from skparagraph's `TextLine.cpp` and the engine's
1196    /// `paragraph_builder_skia.cc`: a strut is disabled when it is absent,
1197    /// [`StrutStyle::DISABLED`], or has a font size of zero.
1198    fn strut_disabled(&self) -> bool {
1199        match &self.strut_style {
1200            None => true,
1201            Some(strut_style) => {
1202                *strut_style == StrutStyle::DISABLED || strut_style.font_size == Some(0.0)
1203            }
1204        }
1205    }
1206
1207    /// Returns the strut bounded height of the glyph at the given `position`.
1208    ///
1209    /// Valid only after [`layout`](Self::layout) has been called. With no strut, or a disabled
1210    /// one, the caret metrics decide; the layout template is the fallback.
1211    pub fn get_full_height_for_caret(
1212        &mut self,
1213        fonts: &mut FontCollection,
1214        position: TextPosition,
1215        caret_prototype: Rect,
1216    ) -> f64 {
1217        let _ = caret_prototype;
1218        if self.strut_disabled()
1219            && let Some(metrics) = self.compute_caret_metrics(fonts, position)
1220        {
1221            return metrics.height;
1222        }
1223        let preferred_line_height = self.preferred_line_height(fonts);
1224        let boxes = self
1225            .get_or_create_layout_template(fonts)
1226            .get_boxes_for_range(0, 1, BoxHeightStyle::Strut, BoxWidthStyle::Tight);
1227        match boxes.as_slice() {
1228            [single] => single.to_rect().height(),
1229            _ => preferred_line_height,
1230        }
1231    }
1232
1233    fn is_newline_at_offset(&mut self, offset: i32) -> bool {
1234        if offset < 0 {
1235            return false;
1236        }
1237        self.plain_text()
1238            .encode_utf16()
1239            .nth(offset as usize)
1240            .is_some_and(|unit| is_newline(u32::from(unit)))
1241    }
1242
1243    // Cached caret metrics. This allows multiple invokes of [getOffsetForCaret] and
1244    // [getFullHeightForCaret] in a row without performing redundant and expensive
1245    // get rect calls to the paragraph.
1246    //
1247    // The cache implementation assumes (and asserts) the caller does not directly
1248    // call methods on the underlying paragraph after the text layout changes.
1249    fn compute_caret_metrics(
1250        &mut self,
1251        fonts: &mut FontCollection,
1252        position: TextPosition,
1253    ) -> Option<LineCaretMetrics> {
1254        debug_assert!(self.debug_assert_text_layout_is_valid());
1255        debug_assert!(!self.debug_needs_relayout);
1256        if self.layout_cache().paragraph().number_of_lines() < 1 {
1257            return None;
1258        }
1259        let upstream_after_newline = position.affinity == TextAffinity::Upstream
1260            && self.is_newline_at_offset(position.offset - 1);
1261        let (offset, anchor_to_leading_edge) = match position {
1262            // As a special case, always anchor to the leading edge of the first
1263            // grapheme regardless of the affinity.
1264            TextPosition { offset: 0, .. } => (0, true),
1265            TextPosition {
1266                offset,
1267                affinity: TextAffinity::Downstream,
1268            } => (offset, true),
1269            TextPosition {
1270                offset,
1271                affinity: TextAffinity::Upstream,
1272            } if upstream_after_newline => (offset, true),
1273            TextPosition {
1274                offset,
1275                affinity: TextAffinity::Upstream,
1276            } => (offset - 1, false),
1277        };
1278        let caret_position_cache_key = if anchor_to_leading_edge {
1279            offset
1280        } else {
1281            -offset - 1
1282        };
1283        if Some(caret_position_cache_key) == self.layout_cache().previous_caret_position_key {
1284            return self.caret_metrics;
1285        }
1286
1287        let Some(glyph_info) = self.layout_cache().paragraph().get_glyph_info_at(offset) else {
1288            // If the glyph isn't laid out, then the caret can't be placed after it. Use the
1289            // end-of-text caret instead.
1290            let plain_text = self.plain_text().to_owned();
1291            let baseline_offset = self
1292                .get_or_create_layout_template(fonts)
1293                .get_line_metrics_at(0)
1294                .expect("the template has one line")
1295                .baseline;
1296            let layout = &self.layout_cache().layout;
1297            return Some(
1298                layout
1299                    .end_of_text_caret_metrics(&plain_text)
1300                    .shift(Offset::new(0.0, -baseline_offset)),
1301            );
1302        };
1303        let grapheme_range = glyph_info.grapheme_cluster_code_unit_range;
1304
1305        // Works around a SkParagraph bug (https://github.com/flutter/flutter/issues/120836#issuecomment-1937343854):
1306        // placeholders with a size of (0, 0) always have a rect of Rect.zero and a
1307        // range of (0, 0).
1308        if grapheme_range.is_collapsed() {
1309            debug_assert!(grapheme_range.start == 0);
1310            return self.compute_caret_metrics(fonts, TextPosition::new(offset + 1));
1311        }
1312        if anchor_to_leading_edge && grapheme_range.start != offset {
1313            debug_assert!(grapheme_range.end > grapheme_range.start + 1);
1314            // This is a pretty rare case, the glyph info at the offset is a grapheme cluster
1315            // (probably a ligature) that starts before the given offset. Anchor the caret to
1316            // the trailing edge of the cluster.
1317            return self.compute_caret_metrics(fonts, TextPosition::new(grapheme_range.end));
1318        }
1319
1320        let boxes = self.layout_cache().paragraph().get_boxes_for_range(
1321            grapheme_range.start,
1322            grapheme_range.end,
1323            BoxHeightStyle::Strut,
1324            BoxWidthStyle::Tight,
1325        );
1326        let anchor_to_left = match glyph_info.writing_direction {
1327            TextDirection::Ltr => anchor_to_leading_edge,
1328            TextDirection::Rtl => !anchor_to_leading_edge,
1329        };
1330        let text_box = if anchor_to_left {
1331            boxes.first()
1332        } else {
1333            boxes.last()
1334        }?;
1335        let metrics = LineCaretMetrics {
1336            offset: Offset::new(
1337                if anchor_to_left {
1338                    text_box.left
1339                } else {
1340                    text_box.right
1341                },
1342                text_box.top,
1343            ),
1344            writing_direction: text_box.direction,
1345            height: text_box.bottom - text_box.top,
1346        };
1347        self.layout_cache
1348            .as_mut()
1349            .expect("checked above")
1350            .previous_caret_position_key = Some(caret_position_cache_key);
1351        self.caret_metrics = Some(metrics);
1352        Some(metrics)
1353    }
1354
1355    /// Returns a list of rects that bound the given selection.
1356    ///
1357    /// The `box_height_style` and `box_width_style` arguments may be used to select the
1358    /// shape of the [`TextBox`]es. These properties default to [`BoxHeightStyle::Tight`] and
1359    /// [`BoxWidthStyle::Tight`] respectively.
1360    ///
1361    /// A given selection might have more than one rect if this text painter contains
1362    /// bidirectional text because logically contiguous text might not be visually contiguous.
1363    ///
1364    /// Leading or trailing newline characters will be represented by zero-width [`TextBox`]es.
1365    ///
1366    /// The method only returns [`TextBox`]es of glyphs that are entirely enclosed by the given
1367    /// `selection`: a multi-code-unit glyph will be excluded if only part of its code units
1368    /// are in `selection`.
1369    pub fn get_boxes_for_selection(
1370        &self,
1371        selection: TextSelection,
1372        box_height_style: BoxHeightStyle,
1373        box_width_style: BoxWidthStyle,
1374    ) -> Vec<TextBox> {
1375        debug_assert!(self.debug_assert_text_layout_is_valid());
1376        debug_assert!(selection.is_valid());
1377        debug_assert!(!self.debug_needs_relayout);
1378        let cached_layout = self.layout_cache();
1379        let offset = cached_layout.paint_offset();
1380        if !offset.dx().is_finite() || !offset.dy().is_finite() {
1381            return Vec::new();
1382        }
1383        let boxes = cached_layout.paragraph().get_boxes_for_range(
1384            selection.start(),
1385            selection.end(),
1386            box_height_style,
1387            box_width_style,
1388        );
1389        if offset == Offset::ZERO {
1390            boxes
1391        } else {
1392            boxes
1393                .into_iter()
1394                .map(|text_box| shift_text_box(text_box, offset))
1395                .collect()
1396        }
1397    }
1398
1399    /// Returns the [`GlyphInfo`] of the glyph closest to the given `offset` in the paragraph
1400    /// coordinate system, or `None` if the text is empty, or is entirely clipped or
1401    /// ellipsized away.
1402    ///
1403    /// This method first finds the line closest to `offset.dy`, and then returns the
1404    /// [`GlyphInfo`] of the closest glyph(s) within that line.
1405    pub fn get_closest_glyph_for_offset(&self, offset: Offset) -> Option<GlyphInfo> {
1406        debug_assert!(self.debug_assert_text_layout_is_valid());
1407        debug_assert!(!self.debug_needs_relayout);
1408        let cached_layout = self.layout_cache();
1409        let raw_glyph_info = cached_layout
1410            .paragraph()
1411            .get_closest_glyph_info_for_offset(offset - cached_layout.paint_offset())?;
1412        if cached_layout.paint_offset() == Offset::ZERO {
1413            return Some(raw_glyph_info);
1414        }
1415        Some(GlyphInfo {
1416            grapheme_cluster_layout_bounds: raw_glyph_info
1417                .grapheme_cluster_layout_bounds
1418                .shift(cached_layout.paint_offset()),
1419            grapheme_cluster_code_unit_range: raw_glyph_info.grapheme_cluster_code_unit_range,
1420            writing_direction: raw_glyph_info.writing_direction,
1421        })
1422    }
1423
1424    /// Returns the closest position within the text for the given pixel offset.
1425    pub fn get_position_for_offset(&self, offset: Offset) -> TextPosition {
1426        debug_assert!(self.debug_assert_text_layout_is_valid());
1427        debug_assert!(!self.debug_needs_relayout);
1428        let cached_layout = self.layout_cache();
1429        cached_layout
1430            .paragraph()
1431            .get_position_for_offset(offset - cached_layout.paint_offset())
1432    }
1433
1434    /// Returns the text range of the word at the given offset. Characters not part of a word,
1435    /// such as spaces, symbols, and punctuation, have word breaks on both sides. In such
1436    /// cases, this method will return a text range that contains the given text position.
1437    ///
1438    /// Word boundaries are defined more precisely in Unicode Standard Annex #29
1439    /// <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
1440    pub fn get_word_boundary(&self, position: TextPosition) -> TextRange {
1441        debug_assert!(self.debug_assert_text_layout_is_valid());
1442        self.layout_cache().paragraph().get_word_boundary(position)
1443    }
1444
1445    /// Returns the text range of the line at the given offset.
1446    ///
1447    /// The newline (if any) is not returned as part of the range.
1448    pub fn get_line_boundary(&self, position: TextPosition) -> TextRange {
1449        debug_assert!(self.debug_assert_text_layout_is_valid());
1450        self.layout_cache().paragraph().get_line_boundary(position)
1451    }
1452
1453    /// Returns the full list of [`LineMetrics`] that describe in detail the various metrics
1454    /// of each laid out line.
1455    ///
1456    /// The [`LineMetrics`] list is presented in the order of the lines they represent.
1457    ///
1458    /// Valid only after [`layout`](Self::layout) has been called.
1459    pub fn compute_line_metrics(&mut self) -> Vec<LineMetrics> {
1460        debug_assert!(self.debug_assert_text_layout_is_valid());
1461        debug_assert!(!self.debug_needs_relayout);
1462        let layout = self.layout_cache.as_mut().expect("laid out");
1463        let offset = layout.paint_offset();
1464        if !offset.dx().is_finite() || !offset.dy().is_finite() {
1465            return Vec::new();
1466        }
1467        let raw_metrics = layout.line_metrics();
1468        if offset == Offset::ZERO {
1469            raw_metrics.to_vec()
1470        } else {
1471            raw_metrics
1472                .iter()
1473                .map(|metrics| shift_line_metrics(*metrics, offset))
1474                .collect()
1475        }
1476    }
1477
1478    /// Whether this object has been disposed or not.
1479    pub fn debug_disposed(&self) -> bool {
1480        self.disposed
1481    }
1482
1483    /// Releases the resources associated with this painter.
1484    ///
1485    /// After disposal this painter is unusable.
1486    pub fn dispose(&mut self) {
1487        debug_assert!(!self.debug_disposed());
1488        self.disposed = true;
1489        if let Some(mut template) = self.layout_template.take() {
1490            template.dispose();
1491        }
1492        if let Some(mut cache) = self.layout_cache.take() {
1493            cache.layout.paragraph.dispose();
1494        }
1495        self.text = None;
1496    }
1497}
1498
1499fn compute_paint_offset_fraction(text_align: TextAlign, text_direction: TextDirection) -> f64 {
1500    match (text_align, text_direction) {
1501        (TextAlign::Left, _) => 0.0,
1502        (TextAlign::Right, _) => 1.0,
1503        (TextAlign::Center, _) => 0.5,
1504        (TextAlign::Start | TextAlign::Justify, TextDirection::Ltr) => 0.0,
1505        (TextAlign::Start | TextAlign::Justify, TextDirection::Rtl) => 1.0,
1506        (TextAlign::End, TextDirection::Ltr) => 1.0,
1507        (TextAlign::End, TextDirection::Rtl) => 0.0,
1508    }
1509}
1510
1511fn shift_line_metrics(metrics: LineMetrics, offset: Offset) -> LineMetrics {
1512    debug_assert!(offset.dx().is_finite());
1513    debug_assert!(offset.dy().is_finite());
1514    LineMetrics {
1515        left: metrics.left + offset.dx(),
1516        baseline: metrics.baseline + offset.dy(),
1517        ..metrics
1518    }
1519}
1520
1521fn shift_text_box(text_box: TextBox, offset: Offset) -> TextBox {
1522    debug_assert!(offset.dx().is_finite());
1523    debug_assert!(offset.dy().is_finite());
1524    TextBox::from_ltrbd(
1525        text_box.left + offset.dx(),
1526        text_box.top + offset.dy(),
1527        text_box.right + offset.dx(),
1528        text_box.bottom + offset.dy(),
1529        text_box.direction,
1530    )
1531}
1532
1533#[cfg(test)]
1534mod tests {
1535    use super::*;
1536    use waft_embedder::TextLeadingDistribution;
1537
1538    use crate::text_span::TextSpan;
1539
1540    fn fonts() -> FontCollection {
1541        let mut fonts = FontCollection::new();
1542        fonts.add_source(valo_system_fonts::SystemFonts::load());
1543        fonts
1544    }
1545
1546    fn painter(text: &str) -> TextPainter {
1547        let mut painter = TextPainter::new();
1548        painter.set_text(Some(
1549            TextSpan::new()
1550                .text(text)
1551                .style(TextStyle::new().font_size(20.0))
1552                .into_span(),
1553        ));
1554        painter.set_text_direction(Some(TextDirection::Ltr));
1555        painter
1556    }
1557
1558    #[test]
1559    fn layout_sizes_the_text_and_paint_records_it() {
1560        let mut fonts = fonts();
1561        let mut painter = painter("Hello world");
1562        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1563        assert!(painter.width() > 0.0);
1564        assert!(painter.height() > 0.0);
1565        assert_eq!(painter.size(), Size::new(painter.width(), painter.height()));
1566        assert!(painter.compute_distance_to_actual_baseline(TextBaseline::Alphabetic) > 0.0);
1567        assert_eq!(painter.compute_line_metrics().len(), 1);
1568        let mut canvas = Canvas::new();
1569        painter.paint(&mut fonts, &mut canvas, Offset::new(5.0, 5.0));
1570        assert!(!canvas.build().ops().is_empty());
1571        painter.dispose();
1572    }
1573
1574    #[test]
1575    fn a_min_width_widens_the_reported_width_without_relayout() {
1576        let mut fonts = fonts();
1577        let mut painter = painter("Hi");
1578        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1579        let natural = painter.width();
1580        painter.layout(&mut fonts, natural + 100.0, f64::INFINITY);
1581        assert_eq!(painter.width(), natural + 100.0);
1582        assert_eq!(painter.max_intrinsic_width(), natural);
1583    }
1584
1585    #[test]
1586    fn right_alignment_offsets_the_paint_and_the_caret() {
1587        let mut fonts = fonts();
1588        let mut painter = painter("Hi");
1589        painter.set_text_align(TextAlign::Right);
1590        painter.layout(&mut fonts, 200.0, 200.0);
1591        let natural = painter.max_intrinsic_width();
1592        let caret = painter.get_offset_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO);
1593        assert!(
1594            (caret.dx() - (200.0 - natural)).abs() < 1.0,
1595            "caret at {caret:?}"
1596        );
1597        let end = painter.get_offset_for_caret(&mut fonts, TextPosition::new(2), Rect::ZERO);
1598        assert!((end.dx() - 200.0).abs() < 1.0, "end caret at {end:?}");
1599    }
1600
1601    #[test]
1602    fn changing_only_the_color_does_not_drop_the_layout() {
1603        let mut fonts = fonts();
1604        let mut painter = painter("Hi");
1605        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1606        painter.set_text(Some(
1607            TextSpan::new()
1608                .text("Hi")
1609                .style(
1610                    TextStyle::new()
1611                        .font_size(20.0)
1612                        .color(Color::from_argb(255, 255, 0, 0)),
1613                )
1614                .into_span(),
1615        ));
1616        assert!(
1617            painter.layout_cache.is_some(),
1618            "a paint-only change keeps the layout"
1619        );
1620        assert!(painter.rebuild_paragraph_for_paint);
1621        let mut canvas = Canvas::new();
1622        painter.paint(&mut fonts, &mut canvas, Offset::ZERO);
1623        assert!(!painter.rebuild_paragraph_for_paint);
1624    }
1625
1626    #[test]
1627    fn max_lines_and_ellipsis_report_overflow() {
1628        let mut fonts = fonts();
1629        let mut painter = painter("one two three four five six");
1630        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1631        let full = painter.width();
1632        painter.set_max_lines(Some(1));
1633        painter.set_ellipsis(Some("\u{2026}".to_owned()));
1634        painter.layout(&mut fonts, 0.0, full / 2.0);
1635        assert!(painter.did_exceed_max_lines());
1636        assert_eq!(painter.compute_line_metrics().len(), 1);
1637    }
1638
1639    #[test]
1640    fn positions_words_and_lines_round_trip() {
1641        let mut fonts = fonts();
1642        let mut painter = painter("ab cd");
1643        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1644        let end = painter.get_position_for_offset(Offset::new(painter.width() + 10.0, 1.0));
1645        assert_eq!(end.offset, 5);
1646        assert_eq!(
1647            painter.get_word_boundary(TextPosition::new(4)),
1648            TextRange::new(3, 5)
1649        );
1650        assert_eq!(
1651            painter.get_line_boundary(TextPosition::new(1)),
1652            TextRange::new(0, 5)
1653        );
1654        let boxes = painter.get_boxes_for_selection(
1655            TextSelection::new(0, 5),
1656            BoxHeightStyle::Tight,
1657            BoxWidthStyle::Tight,
1658        );
1659        assert!(!boxes.is_empty());
1660        assert_eq!(painter.get_offset_after(0), Some(1));
1661        assert_eq!(painter.get_offset_before(1), Some(0));
1662        assert_eq!(painter.get_offset_after(5), None);
1663    }
1664
1665    /// The carets of Flutter's `handles newlines properly`, for explicit newlines: a caret is
1666    /// where its offset says whatever its affinity, before a newline at the end of that line's
1667    /// text, and after one at the start of the next line.
1668    #[test]
1669    fn a_caret_beside_a_newline_is_on_the_line_its_offset_says() {
1670        let mut fonts = fonts();
1671        let mut painter = painter("aaa\n\n\n");
1672        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1673        let lines = painter.compute_line_metrics();
1674        let top_of = |line: usize| lines[line].baseline - lines[line].ascent;
1675        let text_width = lines[0].width;
1676        assert!(text_width > 0.0);
1677        let wanted = [
1678            (3, Offset::new(text_width, top_of(0))),
1679            (4, Offset::new(0.0, top_of(1))),
1680            (5, Offset::new(0.0, top_of(2))),
1681            (6, Offset::new(0.0, top_of(3))),
1682        ];
1683        for (offset, caret) in wanted {
1684            for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1685                let position = TextPosition::with_affinity(offset, affinity);
1686                let found = painter.get_offset_for_caret(&mut fonts, position, Rect::ZERO);
1687                assert!(
1688                    (found - caret).distance() < 0.01,
1689                    "the caret at {position:?} is at {found:?}, not {caret:?}"
1690                );
1691            }
1692        }
1693    }
1694
1695    /// A caret as `(offset, line, x)`: at `offset`, whatever its affinity, at `x` on top of
1696    /// `line`.
1697    type Caret = (i32, usize, f64);
1698
1699    /// Fails unless each of `wanted` is where its caret is.
1700    fn assert_carets(painter: &mut TextPainter, fonts: &mut FontCollection, wanted: &[Caret]) {
1701        let lines = painter.compute_line_metrics();
1702        for &(offset, line, x) in wanted {
1703            let caret = Offset::new(x, lines[line].baseline - lines[line].ascent);
1704            for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1705                let position = TextPosition::with_affinity(offset, affinity);
1706                let found = painter.get_offset_for_caret(fonts, position, Rect::ZERO);
1707                assert!(
1708                    (found - caret).distance() < 0.01,
1709                    "the caret at {position:?} is at {found:?}, not {caret:?}"
1710                );
1711            }
1712        }
1713    }
1714
1715    /// The rest of Flutter's `handles newlines properly` for explicit newlines: blank lines,
1716    /// leading and trailing newlines, and a newline between lines of text.
1717    #[test]
1718    fn handles_newlines_properly() {
1719        let mut fonts = fonts();
1720        let cases: [(&str, &[Caret]); 4] = [
1721            ("\n\n", &[(0, 0, 0.0), (1, 1, 0.0), (2, 2, 0.0)]),
1722            ("\naaa", &[(0, 0, 0.0), (1, 1, 0.0)]),
1723            ("aaa\naaa", &[(4, 1, 0.0)]),
1724            (
1725                "\n\n\naaa",
1726                &[(0, 0, 0.0), (1, 1, 0.0), (2, 2, 0.0), (3, 3, 0.0)],
1727            ),
1728        ];
1729        for (text, wanted) in cases {
1730            let mut painter = painter(text);
1731            painter.layout(&mut fonts, 0.0, f64::INFINITY);
1732            assert_carets(&mut painter, &mut fonts, wanted);
1733        }
1734        let mut painter = painter("aaa\n");
1735        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1736        assert_carets(&mut painter, &mut fonts, &[(4, 1, 0.0)]);
1737    }
1738
1739    /// Flutter's `handles newlines properly` for a soft wrap: affinity tells the end of the
1740    /// first line from the start of the second. Wrapped at a space, which ends the first line
1741    /// as a ghost: the width fits the longer word, so neither word breaks between clusters.
1742    #[test]
1743    fn affinity_tells_a_soft_wraps_two_carets_apart() {
1744        let mut fonts = fonts();
1745        let mut first = painter("aaaa");
1746        first.layout(&mut fonts, 0.0, f64::INFINITY);
1747        let mut painter = painter("aaa aaaa");
1748        painter.layout(&mut fonts, 0.0, first.max_intrinsic_width() + 1.0);
1749        let lines = painter.compute_line_metrics();
1750        assert_eq!(lines.len(), 2);
1751        let downstream = painter.get_offset_for_caret(&mut fonts, TextPosition::new(4), Rect::ZERO);
1752        let start_of_second = Offset::new(0.0, lines[1].baseline - lines[1].ascent);
1753        assert!(
1754            (downstream - start_of_second).distance() < 0.01,
1755            "{downstream:?}"
1756        );
1757        let space = painter.get_boxes_for_selection(
1758            TextSelection::new(3, 4),
1759            BoxHeightStyle::Tight,
1760            BoxWidthStyle::Tight,
1761        );
1762        assert!(
1763            space[0].right > lines[0].width,
1764            "the space hangs past the line's width"
1765        );
1766        // `getOffsetForCaret` clamps a caret after trailing whitespace to the content width.
1767        let end_of_first = Offset::new(
1768            space[0].right.min(painter.width()),
1769            lines[0].baseline - lines[0].ascent,
1770        );
1771        let upstream = TextPosition::with_affinity(4, TextAffinity::Upstream);
1772        let upstream = painter.get_offset_for_caret(&mut fonts, upstream, Rect::ZERO);
1773        assert!(
1774            (upstream - end_of_first).distance() < 0.01,
1775            "{upstream:?} is not {end_of_first:?}"
1776        );
1777    }
1778
1779    /// Flutter's `trailing newlines`: the end-of-text caret after trailing spaces sits after
1780    /// the last space, which the line keeps outside its width.
1781    #[test]
1782    fn the_end_of_text_caret_follows_trailing_spaces() {
1783        let mut fonts = fonts();
1784        let mut painter = painter("a    ");
1785        painter.layout(&mut fonts, 1000.0, 1000.0);
1786        let end = painter.get_offset_for_caret(&mut fonts, TextPosition::new(5), Rect::ZERO);
1787        let boxes = painter.get_boxes_for_selection(
1788            TextSelection::new(0, 5),
1789            BoxHeightStyle::Tight,
1790            BoxWidthStyle::Tight,
1791        );
1792        let right = boxes
1793            .iter()
1794            .map(|text_box| text_box.right)
1795            .fold(f64::MIN, f64::max);
1796        assert!(
1797            right > painter.compute_line_metrics()[0].width + 1.0,
1798            "the spaces are boxed"
1799        );
1800        assert!((end.dx() - right).abs() < 0.01, "{end:?} is not at {right}");
1801    }
1802
1803    /// A caret before a newline that text follows stays at the end of its own line.
1804    #[test]
1805    fn a_caret_before_a_newline_between_lines_of_text_ends_its_line() {
1806        let mut fonts = fonts();
1807        let mut painter = painter("aaa\naaa");
1808        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1809        let lines = painter.compute_line_metrics();
1810        let end_of_first = Offset::new(lines[0].width, lines[0].baseline - lines[0].ascent);
1811        let start_of_second = Offset::new(0.0, lines[1].baseline - lines[1].ascent);
1812        for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1813            let before = TextPosition::with_affinity(3, affinity);
1814            let found = painter.get_offset_for_caret(&mut fonts, before, Rect::ZERO);
1815            assert!(
1816                (found - end_of_first).distance() < 0.01,
1817                "the caret at {before:?} is at {found:?}, not {end_of_first:?}"
1818            );
1819            let after = TextPosition::with_affinity(4, affinity);
1820            let found = painter.get_offset_for_caret(&mut fonts, after, Rect::ZERO);
1821            assert!(
1822                (found - start_of_second).distance() < 0.01,
1823                "the caret at {after:?} is at {found:?}, not {start_of_second:?}"
1824            );
1825        }
1826    }
1827
1828    #[test]
1829    fn preferred_line_height_needs_no_layout() {
1830        let mut fonts = fonts();
1831        let mut painter = painter("x");
1832        assert!(painter.preferred_line_height(&mut fonts) > 0.0);
1833    }
1834
1835    #[test]
1836    fn compute_width_is_the_laid_out_width() {
1837        let mut fonts = fonts();
1838        let span = TextSpan::new().text("Hello").into_span();
1839        let width = TextPainter::compute_width(
1840            &mut fonts,
1841            span.clone(),
1842            TextDirection::Ltr,
1843            0.0,
1844            f64::INFINITY,
1845        );
1846        let mut painter = TextPainter::new();
1847        painter.set_text(Some(span));
1848        painter.set_text_direction(Some(TextDirection::Ltr));
1849        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1850        assert_eq!(width, painter.width());
1851    }
1852
1853    /// FlutterTest's metrics, as `flutter_test` installs them: ascent 0.75 em, descent
1854    /// 0.25 em, no line gap, every glyph an em wide.
1855    fn flutter_test_fonts() -> FontCollection {
1856        use waft_embedder::Platform as _;
1857
1858        let mut fonts = FontCollection::new();
1859        waft_embedder::set_default_font_manager(
1860            &mut fonts,
1861            Box::new(waft_embedder::TestFontSource::new()),
1862            &waft_embedder::InertPlatform.default_font_families(),
1863        );
1864        fonts
1865    }
1866
1867    fn strut_painter(text: InlineSpanRef, strut: StrutStyle) -> TextPainter {
1868        let mut painter = TextPainter::new();
1869        painter.set_text(Some(text));
1870        painter.set_text_direction(Some(TextDirection::Ltr));
1871        painter.set_strut_style(Some(strut));
1872        painter
1873    }
1874
1875    #[test]
1876    fn strut_style_applies_when_the_span_has_no_style() {
1877        let mut fonts = flutter_test_fonts();
1878        let empty = TextSpan::new().into_span();
1879        let mut painter = strut_painter(empty, StrutStyle::new().height(10.0).font_size(10.0));
1880        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1881        assert_eq!(painter.height(), 100.0);
1882    }
1883
1884    #[test]
1885    fn strut_style_leading_is_a_font_size_multiplier() {
1886        let mut fonts = flutter_test_fonts();
1887        let empty = TextSpan::new().into_span();
1888        let mut painter = strut_painter(
1889            empty,
1890            StrutStyle::new().height(10.0).font_size(10.0).leading(2.0),
1891        );
1892        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1893        assert_eq!(painter.height(), 100.0 + 20.0);
1894        // Top leading + scaled ascent.
1895        assert_eq!(
1896            painter.compute_distance_to_actual_baseline(TextBaseline::Alphabetic),
1897            10.0 + 10.0 * 7.5
1898        );
1899    }
1900
1901    #[test]
1902    fn strut_no_half_leading_plus_force_strut_height() {
1903        let mut fonts = flutter_test_fonts();
1904        let text = TextSpan::new()
1905            .text("A")
1906            .style(TextStyle::new().font_size(20.0))
1907            .into_span();
1908        let mut painter = strut_painter(
1909            text,
1910            StrutStyle::new()
1911                .height(10.0)
1912                .font_size(10.0)
1913                .force_strut_height(true),
1914        );
1915        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1916        assert_eq!(painter.height(), 100.0);
1917        let baseline = 75.0;
1918        let boxes = painter.get_boxes_for_selection(
1919            TextSelection::new(0, 1),
1920            BoxHeightStyle::Tight,
1921            BoxWidthStyle::Tight,
1922        );
1923        assert_eq!(
1924            boxes,
1925            vec![TextBox::from_ltrbd(
1926                0.0,
1927                baseline - 15.0,
1928                20.0,
1929                baseline + 5.0,
1930                TextDirection::Ltr
1931            )]
1932        );
1933    }
1934
1935    #[test]
1936    fn strut_half_leading_plus_force_strut_height() {
1937        let mut fonts = flutter_test_fonts();
1938        let text = TextSpan::new()
1939            .text("A")
1940            .style(TextStyle::new().font_size(20.0))
1941            .into_span();
1942        let mut painter = strut_painter(
1943            text,
1944            StrutStyle::new()
1945                .height(10.0)
1946                .font_size(10.0)
1947                .force_strut_height(true)
1948                .leading_distribution(TextLeadingDistribution::Even),
1949        );
1950        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1951        assert_eq!(painter.height(), 100.0);
1952        let baseline = 45.0 + 7.5;
1953        let boxes = painter.get_boxes_for_selection(
1954            TextSelection::new(0, 1),
1955            BoxHeightStyle::Tight,
1956            BoxWidthStyle::Tight,
1957        );
1958        assert_eq!(
1959            boxes,
1960            vec![TextBox::from_ltrbd(
1961                0.0,
1962                baseline - 15.0,
1963                20.0,
1964                baseline + 5.0,
1965                TextDirection::Ltr
1966            )]
1967        );
1968    }
1969
1970    #[test]
1971    fn text_height_behavior_with_strut_on_empty_paragraph() {
1972        let mut fonts = flutter_test_fonts();
1973        let style = TextStyle::new().height(11.0).font_size(7.0);
1974        let simple = TextSpan::new().text("x").style(style.clone()).into_span();
1975        let empty_string = TextSpan::new().text("").style(style.clone()).into_span();
1976        let empty_paragraph = TextSpan::new().style(style.clone()).into_span();
1977        let strut = StrutStyle::from_text_style(&style)
1978            .force_strut_height(true)
1979            .build();
1980
1981        let mut painter = strut_painter(simple.clone(), strut);
1982        painter.set_text_height_behavior(Some(TextHeightBehavior {
1983            apply_height_to_first_ascent: false,
1984            apply_height_to_last_descent: false,
1985            leading_distribution: TextLeadingDistribution::Proportional,
1986        }));
1987        painter.layout(&mut fonts, 0.0, f64::INFINITY);
1988        let height = painter.height();
1989        for span in [simple, empty_string, empty_paragraph] {
1990            painter.set_text(Some(span));
1991            painter.layout(&mut fonts, 0.0, f64::INFINITY);
1992            assert_eq!(painter.height(), height);
1993            assert_eq!(painter.preferred_line_height(&mut fonts), height);
1994        }
1995    }
1996
1997    #[test]
1998    fn text_painter_caret_height_and_line_height() {
1999        let mut fonts = flutter_test_fonts();
2000        let mut painter = TextPainter::new();
2001        painter.set_text_direction(Some(TextDirection::Ltr));
2002        painter.set_strut_style(Some(StrutStyle::new().font_size(50.0)));
2003        painter.set_text(Some(
2004            TextSpan::new()
2005                .text("A")
2006                .style(TextStyle::new().height(1.0))
2007                .into_span(),
2008        ));
2009        painter.layout(&mut fonts, 0.0, f64::INFINITY);
2010
2011        let caret_height =
2012            painter.get_full_height_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO);
2013        assert_eq!(caret_height, 50.0);
2014    }
2015
2016    #[test]
2017    fn caret_height_reflects_run_height_if_strut_is_disabled() {
2018        let mut fonts = flutter_test_fonts();
2019        let span = TextSpan::new()
2020            .text("M")
2021            .style(TextStyle::new().font_size(128.0))
2022            .children(vec![
2023                TextSpan::new()
2024                    .text("M")
2025                    .style(TextStyle::new().font_size(32.0))
2026                    .into_span(),
2027                TextSpan::new()
2028                    .text("M")
2029                    .style(TextStyle::new().font_size(64.0))
2030                    .into_span(),
2031            ])
2032            .into_span();
2033        let mut painter = TextPainter::new();
2034        painter.set_text(Some(span));
2035        painter.set_text_direction(Some(TextDirection::Ltr));
2036        painter.layout(&mut fonts, 0.0, f64::INFINITY);
2037
2038        let heights = [
2039            (0, TextAffinity::Upstream, 128.0),
2040            (0, TextAffinity::Downstream, 128.0),
2041            (1, TextAffinity::Upstream, 128.0),
2042            (1, TextAffinity::Downstream, 32.0),
2043            (2, TextAffinity::Upstream, 32.0),
2044            (2, TextAffinity::Downstream, 64.0),
2045            (3, TextAffinity::Upstream, 64.0),
2046            (3, TextAffinity::Downstream, 128.0),
2047        ];
2048        for (offset, affinity, expected) in heights {
2049            assert_eq!(
2050                painter.get_full_height_for_caret(
2051                    &mut fonts,
2052                    TextPosition::with_affinity(offset, affinity),
2053                    Rect::ZERO
2054                ),
2055                expected,
2056                "offset {offset} {affinity:?}"
2057            );
2058        }
2059    }
2060
2061    #[test]
2062    fn get_full_height_for_caret_handles_degenerate_layout_without_crashing() {
2063        let mut fonts = flutter_test_fonts();
2064        let mut painter = TextPainter::new();
2065        painter.set_text(Some(
2066            TextSpan::new()
2067                .text("")
2068                .style(TextStyle::new().height(1.0).font_size(0.0))
2069                .into_span(),
2070        ));
2071        painter.set_text_direction(Some(TextDirection::Ltr));
2072        painter.layout(&mut fonts, 0.0, f64::INFINITY);
2073        assert_eq!(
2074            painter.get_full_height_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO),
2075            painter.preferred_line_height(&mut fonts)
2076        );
2077    }
2078}