Skip to main content

waft_embedder/
paragraph.rs

1//! Flutter counterpart: `engine/src/flutter/lib/ui/text.dart`, the paragraph half:
2//! `TextStyle`, `ParagraphStyle`, `ParagraphBuilder`, `Paragraph`, and the position, range,
3//! box, and line-metric value types.
4//!
5//! Flutter's engine implements these on top of Skia's paragraph library; here they wrap valo's.
6//! Offsets are UTF-16 code units, as in Dart; valo works in UTF-8 bytes and the wrapper
7//! translates.
8
9use std::fmt;
10use std::ops::Range;
11
12use crate::fonts::FontCollection;
13use crate::text::{
14    FontFeature, FontStyle, FontVariation, FontWeight, K_TEXT_HEIGHT_NONE, TextAlign, TextBaseline,
15    TextDecoration, TextDecorationStyle, TextDirection, TextHeightBehavior,
16    TextLeadingDistribution,
17};
18use crate::{Canvas, Color, Offset, Paint, Rect, Shadow};
19
20/// A position in a string of text.
21///
22/// A `TextPosition` can be used to describe a caret position in between characters. The
23/// [`offset`](Self::offset) points to the position between `offset - 1` and `offset`
24/// characters of the string, and the [`affinity`](Self::affinity) is used to describe which
25/// character this position affiliates with.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct TextPosition {
28    /// The index of the character that immediately follows the position in the string
29    /// representation of the text.
30    pub offset: i32,
31    /// Disambiguates cases where the offset could be at the end of one line or the
32    /// start of the next.
33    pub affinity: TextAffinity,
34}
35
36impl TextPosition {
37    /// Creates an object representing a particular position in a string, with downstream
38    /// affinity.
39    pub const fn new(offset: i32) -> TextPosition {
40        TextPosition {
41            offset,
42            affinity: TextAffinity::Downstream,
43        }
44    }
45
46    /// Creates an object representing a particular position in a string.
47    pub const fn with_affinity(offset: i32, affinity: TextAffinity) -> TextPosition {
48        TextPosition { offset, affinity }
49    }
50}
51
52/// A way to disambiguate a [`TextPosition`] when its offset could match two
53/// different locations in the rendered string.
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
55pub enum TextAffinity {
56    /// The position has affinity for the upstream side of the text position, i.e. in the
57    /// direction of the beginning of the string.
58    Upstream,
59    /// The position has affinity for the downstream side of the text position, i.e. in the
60    /// direction of the end of the string.
61    #[default]
62    Downstream,
63}
64
65/// A range of characters in a string of text.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub struct TextRange {
68    /// The index of the first character in the range.
69    ///
70    /// If [`start`](Self::start) and [`end`](Self::end) are both -1, the text range is empty.
71    pub start: i32,
72    /// The next index after the characters in this range.
73    pub end: i32,
74}
75
76impl TextRange {
77    /// A text range that starts and ends at offset -1: the empty range.
78    pub const EMPTY: TextRange = TextRange { start: -1, end: -1 };
79
80    /// Creates a new [`TextRange`]. The `start` and `end` must be at least -1.
81    pub const fn new(start: i32, end: i32) -> TextRange {
82        debug_assert!(start >= -1);
83        debug_assert!(end >= -1);
84        TextRange { start, end }
85    }
86
87    /// A text range that starts and ends at `offset`.
88    pub const fn collapsed(offset: i32) -> TextRange {
89        debug_assert!(offset >= -1);
90        TextRange {
91            start: offset,
92            end: offset,
93        }
94    }
95
96    /// Whether this range represents a valid position in the text.
97    pub fn is_valid(&self) -> bool {
98        self.start >= 0 && self.end >= 0
99    }
100
101    /// Whether this range is empty (but still potentially placed inside the text).
102    pub fn is_collapsed(&self) -> bool {
103        self.start == self.end
104    }
105
106    /// Whether the start of this range precedes the end.
107    pub fn is_normalized(&self) -> bool {
108        self.end >= self.start
109    }
110
111    /// The text before this range.
112    pub fn text_before<'a>(&self, text: &'a str) -> &'a str {
113        debug_assert!(self.is_normalized());
114        let start = byte_of_code_unit(text, self.start as usize);
115        &text[..start]
116    }
117
118    /// The text after this range.
119    pub fn text_after<'a>(&self, text: &'a str) -> &'a str {
120        debug_assert!(self.is_normalized());
121        let end = byte_of_code_unit(text, self.end as usize);
122        &text[end..]
123    }
124
125    /// The text inside this range.
126    pub fn text_inside<'a>(&self, text: &'a str) -> &'a str {
127        debug_assert!(self.is_normalized());
128        let start = byte_of_code_unit(text, self.start as usize);
129        let end = byte_of_code_unit(text, self.end as usize);
130        &text[start..end]
131    }
132}
133
134/// Layout constraints for [`Paragraph`] objects.
135///
136/// Instances of this class are typically used with [`Paragraph::layout`].
137#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct ParagraphConstraints {
139    /// The width the paragraph should use whey computing the positions of glyphs.
140    ///
141    /// If possible, the paragraph will select a soft line break prior to reaching this width.
142    /// If no soft line break is available, the paragraph will select a hard line break prior
143    /// to reaching this width. If that would force a line break without any glyphs, the
144    /// paragraph will place the first glyph on the line anyway.
145    pub width: f64,
146}
147
148impl ParagraphConstraints {
149    /// Creates constraints for laying out a paragraph.
150    pub const fn new(width: f64) -> ParagraphConstraints {
151        ParagraphConstraints { width }
152    }
153}
154
155/// A rectangle enclosing a run of text.
156///
157/// This is similar to [`Rect`] but includes an inherent [`TextDirection`].
158#[derive(Clone, Copy, Debug, PartialEq)]
159pub struct TextBox {
160    /// The left edge of the text box, relative to the parent widget.
161    pub left: f64,
162    /// The top edge of the text box, relative to the parent widget.
163    pub top: f64,
164    /// The right edge of the text box, relative to the parent widget.
165    pub right: f64,
166    /// The bottom edge of the text box, relative to the parent widget.
167    pub bottom: f64,
168    /// The direction in which text inside this box flows.
169    pub direction: TextDirection,
170}
171
172impl TextBox {
173    /// Creates an object that describes a box containing text.
174    pub const fn from_ltrbd(
175        left: f64,
176        top: f64,
177        right: f64,
178        bottom: f64,
179        direction: TextDirection,
180    ) -> TextBox {
181        TextBox {
182            left,
183            top,
184            right,
185            bottom,
186            direction,
187        }
188    }
189
190    /// Returns a rect of the same size as this box.
191    pub fn to_rect(&self) -> Rect {
192        Rect::from_ltrb(self.left, self.top, self.right, self.bottom)
193    }
194
195    /// The [`left`](Self::left) edge of the box for left-to-right text; the
196    /// [`right`](Self::right) edge of the box for right-to-left text.
197    pub fn start(&self) -> f64 {
198        match self.direction {
199            TextDirection::Ltr => self.left,
200            TextDirection::Rtl => self.right,
201        }
202    }
203
204    /// The [`right`](Self::right) edge of the box for left-to-right text; the
205    /// [`left`](Self::left) edge of the box for right-to-left text.
206    pub fn end(&self) -> f64 {
207        match self.direction {
208            TextDirection::Ltr => self.right,
209            TextDirection::Rtl => self.left,
210        }
211    }
212}
213
214/// Where to vertically align the placeholder relative to the surrounding text.
215#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
216pub enum PlaceholderAlignment {
217    Baseline,
218    AboveBaseline,
219    BelowBaseline,
220    Top,
221    Bottom,
222    Middle,
223}
224
225/// Defines various ways to vertically bound the boxes returned by
226/// [`Paragraph::get_boxes_for_range`].
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
228pub enum BoxHeightStyle {
229    #[default]
230    Tight,
231    Max,
232    IncludeLineSpacingMiddle,
233    IncludeLineSpacingTop,
234    IncludeLineSpacingBottom,
235    Strut,
236}
237
238/// Defines various ways to horizontally bound the boxes returned by
239/// [`Paragraph::get_boxes_for_range`].
240#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
241pub enum BoxWidthStyle {
242    #[default]
243    Tight,
244    Max,
245}
246
247/// The measurements of a character (or a sequence of visually connected characters) within
248/// a paragraph.
249#[derive(Clone, Copy, Debug, PartialEq)]
250pub struct GlyphInfo {
251    /// The layout bounding rect of the associated character, in the paragraph's coordinates.
252    pub grapheme_cluster_layout_bounds: Rect,
253    /// The UTF-16 range of the associated character in the text.
254    pub grapheme_cluster_code_unit_range: TextRange,
255    /// The writing direction within the glyph.
256    pub writing_direction: TextDirection,
257}
258
259/// [`LineMetrics`] stores the measurements and statistics of a single line in the paragraph.
260#[derive(Clone, Copy, Debug, PartialEq)]
261pub struct LineMetrics {
262    /// True if this line ends with an explicit line break (e.g. `\n`) or is the end of the
263    /// paragraph. False otherwise.
264    pub hard_break: bool,
265    /// The rise from the [`baseline`](Self::baseline) as calculated from the font and style
266    /// for this line.
267    pub ascent: f64,
268    /// The drop from the [`baseline`](Self::baseline) as calculated from the font and style
269    /// for this line.
270    pub descent: f64,
271    /// The rise from the [`baseline`](Self::baseline) as calculated from the font and style
272    /// for this line ignoring the `TextStyle.height`.
273    pub unscaled_ascent: f64,
274    /// Total height of the line from the top edge to the bottom edge.
275    pub height: f64,
276    /// Width of the line from the left edge of the leftmost glyph to the right edge of the
277    /// rightmost glyph.
278    pub width: f64,
279    /// The x coordinate of left edge of the line.
280    pub left: f64,
281    /// The y coordinate of the baseline for this line from the top of the paragraph.
282    pub baseline: f64,
283    /// The number of this line in the overall paragraph, with the first line being index zero.
284    pub line_number: i32,
285}
286
287/// An opaque object that determines the size, position, and rendering of text.
288///
289/// Every field is optional, as in Dart: a field left `None` inherits from the style below it
290/// on the [`ParagraphBuilder`]'s stack, or from the paragraph style.
291#[derive(Clone, Debug, Default, PartialEq)]
292pub struct TextStyle {
293    pub color: Option<Color>,
294    pub decoration: Option<TextDecoration>,
295    pub decoration_color: Option<Color>,
296    pub decoration_style: Option<TextDecorationStyle>,
297    pub decoration_thickness: Option<f64>,
298    pub font_weight: Option<FontWeight>,
299    pub font_style: Option<FontStyle>,
300    pub text_baseline: Option<TextBaseline>,
301    pub font_family: Option<String>,
302    pub font_family_fallback: Option<Vec<String>>,
303    pub font_size: Option<f64>,
304    pub letter_spacing: Option<f64>,
305    pub word_spacing: Option<f64>,
306    pub height: Option<f64>,
307    pub leading_distribution: Option<TextLeadingDistribution>,
308    pub background: Option<Paint>,
309    pub foreground: Option<Paint>,
310    pub shadows: Option<Vec<Shadow>>,
311    pub font_features: Option<Vec<FontFeature>>,
312    pub font_variations: Option<Vec<FontVariation>>,
313}
314
315impl TextStyle {
316    /// Creates a new text style with every field unset.
317    pub fn new() -> TextStyle {
318        TextStyle::default()
319    }
320
321    /// The style with `other`'s set fields laid over this one, the engine's `pushStyle`
322    /// inheritance.
323    fn merged_with(&self, other: &TextStyle) -> TextStyle {
324        TextStyle {
325            color: other.color.or(self.color),
326            decoration: other.decoration.or(self.decoration),
327            decoration_color: other.decoration_color.or(self.decoration_color),
328            decoration_style: other.decoration_style.or(self.decoration_style),
329            decoration_thickness: other.decoration_thickness.or(self.decoration_thickness),
330            font_weight: other.font_weight.or(self.font_weight),
331            font_style: other.font_style.or(self.font_style),
332            text_baseline: other.text_baseline.or(self.text_baseline),
333            font_family: other
334                .font_family
335                .clone()
336                .or_else(|| self.font_family.clone()),
337            font_family_fallback: other
338                .font_family_fallback
339                .clone()
340                .or_else(|| self.font_family_fallback.clone()),
341            font_size: other.font_size.or(self.font_size),
342            letter_spacing: other.letter_spacing.or(self.letter_spacing),
343            word_spacing: other.word_spacing.or(self.word_spacing),
344            height: other.height.or(self.height),
345            leading_distribution: other.leading_distribution.or(self.leading_distribution),
346            background: other.background.clone().or_else(|| self.background.clone()),
347            foreground: other.foreground.clone().or_else(|| self.foreground.clone()),
348            shadows: other.shadows.clone().or_else(|| self.shadows.clone()),
349            font_features: other
350                .font_features
351                .clone()
352                .or_else(|| self.font_features.clone()),
353            font_variations: other
354                .font_variations
355                .clone()
356                .or_else(|| self.font_variations.clone()),
357        }
358    }
359
360    /// The host span style: unset fields take the host's defaults (14px, black).
361    fn to_native(&self) -> valo::TextStyle {
362        let mut style = valo::TextStyle::default();
363        let mut families = Vec::new();
364        if let Some(family) = &self.font_family {
365            families.push(family.clone());
366        }
367        if let Some(fallback) = &self.font_family_fallback {
368            families.extend(fallback.iter().cloned());
369        }
370        style.families = families;
371        if let Some(weight) = self.font_weight {
372            style.weight = weight.value as u16;
373        }
374        style.italic = self.font_style == Some(FontStyle::Italic);
375        if let Some(size) = self.font_size {
376            style.size = size as f32;
377        }
378        if let Some(foreground) = &self.foreground {
379            style.color = foreground.color;
380        } else if let Some(color) = self.color {
381            style.color = color.into();
382        }
383        style.foreground = self.foreground.clone();
384        style.background = self.background.clone();
385        if let Some(letter_spacing) = self.letter_spacing {
386            style.letter_spacing = letter_spacing as f32;
387        }
388        if let Some(word_spacing) = self.word_spacing {
389            style.word_spacing = word_spacing as f32;
390        }
391        style.height = match self.height {
392            Some(height) if height != crate::text::K_TEXT_HEIGHT_NONE => Some(height as f32),
393            _ => None,
394        };
395        style.leading_distribution = native_leading_distribution(self.leading_distribution);
396        style.decoration = native_decoration(
397            self.decoration,
398            self.decoration_color,
399            self.decoration_thickness,
400        );
401        if let Some(shadows) = &self.shadows {
402            style.shadows = shadows
403                .iter()
404                .map(|shadow| valo::Shadow {
405                    color: shadow.color.into(),
406                    offset: shadow.offset.into(),
407                    blur: shadow.blur_sigma() as f32,
408                })
409                .collect();
410        }
411        style
412    }
413}
414
415/// Flutter's default, `Proportional`, when unset.
416fn native_leading_distribution(
417    distribution: Option<TextLeadingDistribution>,
418) -> valo::LeadingDistribution {
419    match distribution {
420        None | Some(TextLeadingDistribution::Proportional) => {
421            valo::LeadingDistribution::Proportional
422        }
423        Some(TextLeadingDistribution::Even) => valo::LeadingDistribution::Even,
424    }
425}
426
427/// Underline before overline before line-through: valo draws one decoration per run.
428fn native_decoration(
429    decoration: Option<TextDecoration>,
430    color: Option<Color>,
431    thickness: Option<f64>,
432) -> Option<valo::Decoration> {
433    let decoration = decoration?;
434    let kind = if decoration.contains(TextDecoration::UNDERLINE) {
435        valo::DecorationKind::Underline
436    } else if decoration.contains(TextDecoration::OVERLINE) {
437        valo::DecorationKind::Overline
438    } else if decoration.contains(TextDecoration::LINE_THROUGH) {
439        valo::DecorationKind::LineThrough
440    } else {
441        return None;
442    };
443    Some(valo::Decoration {
444        kind,
445        color: color.map(Into::into),
446        thickness: thickness.unwrap_or(1.0) as f32,
447    })
448}
449
450/// Defines the strut, which sets the minimum height a line can be relative to the baseline.
451///
452/// Strut applies to all lines in the paragraph. Strut is a feature that allows minimum line
453/// heights to be set. The effect is as if a zero width space was included at the beginning of
454/// each line in the paragraph. This imaginary space is "shaped" according the properties
455/// defined in this class.
456///
457/// Omitted or `None` properties take the engine's defaults: family unset (the platform's
458/// default font), size 14, the font's own ascent and descent when `height` is unset, normal
459/// weight, upright, and no forced height.
460#[derive(Clone, Debug, Default, PartialEq)]
461pub struct StrutStyle {
462    /// The name of the font to use when calculating the strut (e.g., Roboto). If the font
463    /// is defined in a package this is prefixed with `packages/package_name/`.
464    ///
465    /// No glyphs from the font are drawn; the font is used purely for metrics.
466    pub font_family: Option<String>,
467
468    /// The ordered list of font families to fall back on when a higher priority font family
469    /// cannot be found.
470    ///
471    /// When [`font_family`](Self::font_family) is `None`, the first value here acts as the
472    /// preferred family. When neither is provided, the default platform font is used.
473    pub font_family_fallback: Option<Vec<String>>,
474
475    /// The size of the ascent plus descent in logical pixels, and the basis of the leading
476    /// calculation.
477    ///
478    /// This value cannot be negative. The default is 14 logical pixels.
479    pub font_size: Option<f64>,
480
481    /// The multiple of [`font_size`](Self::font_size) the line's height should be.
482    ///
483    /// When `None` (or [`K_TEXT_HEIGHT_NONE`]) the line takes the font's ascent and descent.
484    pub height: Option<f64>,
485
486    /// How the extra vertical space added by [`height`](Self::height) is distributed over and
487    /// under the strut.
488    ///
489    /// Defaults to `None`, which distributes it proportionally.
490    pub leading_distribution: Option<TextLeadingDistribution>,
491
492    /// The additional leading to apply to the strut as a multiple of
493    /// [`font_size`](Self::font_size), independent of [`height`](Self::height).
494    ///
495    /// Half of the leading is added above the text and half below. Defaults to `None`, which
496    /// adds none.
497    pub leading: Option<f64>,
498
499    /// The typeface thickness to use when calculating the strut (e.g. bold).
500    ///
501    /// The default is w400.
502    pub font_weight: Option<FontWeight>,
503
504    /// The typeface variant to use when calculating the strut (e.g. italic).
505    ///
506    /// The default is upright.
507    pub font_style: Option<FontStyle>,
508
509    /// Whether all lines should take exactly the strut's height, ignoring the text's own
510    /// metrics.
511    ///
512    /// The default is `None`, which raises each side of a line to the strut's only where the
513    /// text is shorter.
514    pub force_strut_height: Option<bool>,
515}
516
517impl StrutStyle {
518    /// Creates a strut style with every field unset.
519    pub fn new() -> StrutStyle {
520        StrutStyle::default()
521    }
522
523    /// Whether the engine would encode this style: whether any field but
524    /// [`font_family_fallback`](Self::font_family_fallback) is set.
525    ///
526    /// A strut whose only field is the fallback list is not encoded, as in `dart:ui`'s
527    /// `_encodeStrut`, and a height of [`K_TEXT_HEIGHT_NONE`] is the absence of a height.
528    fn is_enabled(&self) -> bool {
529        self.font_family.is_some()
530            || self.font_size.is_some()
531            || self
532                .height
533                .is_some_and(|height| height != K_TEXT_HEIGHT_NONE)
534            || self.leading_distribution.is_some()
535            || self.leading.is_some()
536            || self.font_weight.is_some()
537            || self.font_style.is_some()
538            || self.force_strut_height.is_some()
539    }
540
541    /// This style as valo's, as the engine's `ParagraphBuilder` maps dart:ui's encoded strut
542    /// (flutter/engine `lib/ui/text/paragraph_builder.cc`).
543    ///
544    /// `paragraph_distribution` is the paragraph's `TextHeightBehavior.leadingDistribution`,
545    /// which dart:ui's `ParagraphBuilder` encodes for a strut that sets none.
546    fn to_native(&self, paragraph_distribution: TextLeadingDistribution) -> valo::StrutStyle {
547        if !self.is_enabled() {
548            return valo::StrutStyle::default();
549        }
550        let mut families = Vec::new();
551        if let Some(font_family) = &self.font_family {
552            families.push(font_family.clone());
553        }
554        if let Some(fallback) = &self.font_family_fallback {
555            families.extend(fallback.iter().cloned());
556        }
557        if families.is_empty() {
558            // The engine pushes an empty family so the platform default font is used.
559            families.push(String::new());
560        }
561        valo::StrutStyle {
562            enabled: true,
563            families,
564            weight: self
565                .font_weight
566                .map_or(400, |font_weight| font_weight.value as u16),
567            italic: self.font_style == Some(FontStyle::Italic),
568            // Skia's `MakeSkFontStyle` uses the normal width.
569            stretch: 100.0,
570            size: self.font_size.unwrap_or(14.0) as f32,
571            height: self.height.unwrap_or(1.0) as f32,
572            height_override: self
573                .height
574                .is_some_and(|height| height != K_TEXT_HEIGHT_NONE),
575            leading: self.leading.map(|leading| leading as f32),
576            half_leading: self.leading_distribution.unwrap_or(paragraph_distribution)
577                == TextLeadingDistribution::Even,
578            force_height: self.force_strut_height.unwrap_or(false),
579        }
580    }
581}
582
583/// An opaque object that determines the configuration used by [`ParagraphBuilder`] to
584/// position lines within a [`Paragraph`] of text.
585///
586/// The font fields (`font_family`, `font_size`, `height`, `font_weight`, `font_style`) are
587/// the style for text that no pushed [`TextStyle`] covers.
588#[derive(Clone, Debug, Default, PartialEq)]
589pub struct ParagraphStyle {
590    pub text_align: Option<TextAlign>,
591    pub text_direction: Option<TextDirection>,
592    pub max_lines: Option<i32>,
593    pub font_family: Option<String>,
594    pub font_size: Option<f64>,
595    pub height: Option<f64>,
596    pub text_height_behavior: Option<TextHeightBehavior>,
597    pub font_weight: Option<FontWeight>,
598    pub font_style: Option<FontStyle>,
599    pub ellipsis: Option<String>,
600    /// The strut every line keeps room for, as [`StrutStyle`] describes it.
601    pub strut_style: Option<StrutStyle>,
602}
603
604impl ParagraphStyle {
605    /// Creates a new paragraph style with every field unset.
606    pub fn new() -> ParagraphStyle {
607        ParagraphStyle::default()
608    }
609
610    /// The text style the paragraph style implies for text with no pushed style.
611    fn base_text_style(&self) -> TextStyle {
612        TextStyle {
613            font_family: self.font_family.clone(),
614            font_size: self.font_size,
615            height: self.height,
616            leading_distribution: self
617                .text_height_behavior
618                .map(|behavior| behavior.leading_distribution),
619            font_weight: self.font_weight,
620            font_style: self.font_style,
621            ..TextStyle::default()
622        }
623    }
624
625    /// dart:ui's `ParagraphStyle._leadingDistribution`: the text height behavior's, else
626    /// proportional.
627    fn leading_distribution(&self) -> TextLeadingDistribution {
628        self.text_height_behavior
629            .map_or(TextLeadingDistribution::Proportional, |behavior| {
630                behavior.leading_distribution
631            })
632    }
633
634    fn to_native(&self) -> valo::ParagraphStyle {
635        valo::ParagraphStyle {
636            align: native_align(self.text_align, self.text_direction),
637            direction: self.text_direction.map(native_direction),
638            preserve_trailing_whitespace: false,
639            max_lines: self.max_lines.map(|max_lines| max_lines as u32),
640            ellipsis: self.ellipsis.clone(),
641            text_height_behavior: self
642                .text_height_behavior
643                .map(native_height_behavior)
644                .unwrap_or_default(),
645            strut_style: self
646                .strut_style
647                .as_ref()
648                .map(|strut_style| strut_style.to_native(self.leading_distribution()))
649                .unwrap_or_default(),
650        }
651    }
652}
653
654/// The behavior's `leading_distribution` is not here: as in `dart:ui`, it is the default for
655/// spans that set none, through [`ParagraphStyle::base_text_style`].
656fn native_height_behavior(behavior: TextHeightBehavior) -> valo::TextHeightBehavior {
657    valo::TextHeightBehavior {
658        apply_height_to_first_ascent: behavior.apply_height_to_first_ascent,
659        apply_height_to_last_descent: behavior.apply_height_to_last_descent,
660    }
661}
662
663/// valo stores a physical alignment: `Start` / `End` resolve against the direction, LTR when
664/// none is given.
665fn native_align(align: Option<TextAlign>, direction: Option<TextDirection>) -> valo::TextAlign {
666    match align {
667        None | Some(TextAlign::Left) => valo::TextAlign::Left,
668        Some(TextAlign::Right) => valo::TextAlign::Right,
669        Some(TextAlign::Center) => valo::TextAlign::Center,
670        Some(TextAlign::Justify) => valo::TextAlign::Justify,
671        Some(TextAlign::Start) => match direction {
672            Some(TextDirection::Rtl) => valo::TextAlign::Right,
673            _ => valo::TextAlign::Left,
674        },
675        Some(TextAlign::End) => match direction {
676            Some(TextDirection::Rtl) => valo::TextAlign::Left,
677            _ => valo::TextAlign::Right,
678        },
679    }
680}
681
682fn native_placeholder_alignment(alignment: PlaceholderAlignment) -> valo::PlaceholderAlignment {
683    match alignment {
684        PlaceholderAlignment::Baseline => valo::PlaceholderAlignment::Baseline,
685        PlaceholderAlignment::AboveBaseline => valo::PlaceholderAlignment::AboveBaseline,
686        PlaceholderAlignment::BelowBaseline => valo::PlaceholderAlignment::BelowBaseline,
687        PlaceholderAlignment::Top => valo::PlaceholderAlignment::Top,
688        PlaceholderAlignment::Bottom => valo::PlaceholderAlignment::Bottom,
689        PlaceholderAlignment::Middle => valo::PlaceholderAlignment::Middle,
690    }
691}
692
693fn native_baseline(baseline: TextBaseline) -> valo::TextBaseline {
694    match baseline {
695        TextBaseline::Alphabetic => valo::TextBaseline::Alphabetic,
696        TextBaseline::Ideographic => valo::TextBaseline::Ideographic,
697    }
698}
699
700fn native_direction(direction: TextDirection) -> valo::TextDirection {
701    match direction {
702        TextDirection::Ltr => valo::TextDirection::Ltr,
703        TextDirection::Rtl => valo::TextDirection::Rtl,
704    }
705}
706
707/// Builds a [`Paragraph`] containing text with the given styling information.
708///
709/// To set the paragraph's alignment, truncation, and ellipsizing behavior, pass an
710/// appropriately-configured [`ParagraphStyle`] object to [`ParagraphBuilder::new`].
711///
712/// Then, call combinations of [`push_style`](Self::push_style), [`add_text`](Self::add_text),
713/// and [`pop`](Self::pop) to add styled text to the object.
714///
715/// Finally, call [`build`](Self::build) to obtain the constructed [`Paragraph`] object. After
716/// this point, the builder is no longer usable.
717///
718/// After constructing a [`Paragraph`], call [`Paragraph::layout`] on it and then paint it
719/// with [`CanvasText::draw_paragraph`].
720pub struct ParagraphBuilder {
721    paragraph_style: ParagraphStyle,
722    style_stack: Vec<TextStyle>,
723    pieces: Vec<Piece>,
724    placeholder_scales: Vec<f64>,
725}
726
727/// One addition to a [`ParagraphBuilder`], kept until [`ParagraphBuilder::build`] has the fonts
728/// to shape it.
729enum Piece {
730    Text(String, valo::TextStyle),
731    Placeholder(valo::PlaceholderStyle, valo::TextStyle),
732}
733
734impl ParagraphBuilder {
735    /// Creates a new [`ParagraphBuilder`] object, which is used to create a [`Paragraph`].
736    pub fn new(style: ParagraphStyle) -> ParagraphBuilder {
737        let base = style.base_text_style();
738        ParagraphBuilder {
739            paragraph_style: style,
740            style_stack: vec![base],
741            pieces: Vec::new(),
742            placeholder_scales: Vec::new(),
743        }
744    }
745
746    /// The number of placeholders currently in the paragraph.
747    pub fn placeholder_count(&self) -> i32 {
748        self.placeholder_scales.len() as i32
749    }
750
751    /// The scales of the placeholders in the paragraph.
752    pub fn placeholder_scales(&self) -> &[f64] {
753        &self.placeholder_scales
754    }
755
756    /// Applies the given style to the added text until [`pop`](Self::pop) is called.
757    ///
758    /// Fields the style leaves unset inherit from the style below it.
759    pub fn push_style(&mut self, style: TextStyle) {
760        let current = self
761            .style_stack
762            .last()
763            .expect("the base style is never popped");
764        let merged = current.merged_with(&style);
765        self.style_stack.push(merged);
766    }
767
768    /// Ends the effect of the most recent call to [`push_style`](Self::push_style).
769    ///
770    /// Internally, the paragraph builder maintains a stack of text styles. Text added to the
771    /// paragraph is affected by all the styles in the stack. Calling [`pop`](Self::pop)
772    /// removes the topmost style in the stack, leaving the remaining styles in effect.
773    pub fn pop(&mut self) {
774        if self.style_stack.len() > 1 {
775            self.style_stack.pop();
776        }
777    }
778
779    /// Adds the given text to the paragraph.
780    ///
781    /// The text will be styled according to the current stack of text styles.
782    pub fn add_text(&mut self, text: &str) {
783        let style = self.current_style();
784        self.pieces.push(Piece::Text(text.to_owned(), style));
785    }
786
787    /// Adds an inline placeholder space to the paragraph.
788    ///
789    /// The paragraph will contain a rectangular space with no text of the dimensions
790    /// specified.
791    ///
792    /// The `width` and `height` parameters specify the size of the placeholder rectangle.
793    ///
794    /// The `alignment` parameter specifies how the placeholder rectangle will be vertically
795    /// aligned with the surrounding text. When [`PlaceholderAlignment::Baseline`],
796    /// [`PlaceholderAlignment::AboveBaseline`], and [`PlaceholderAlignment::BelowBaseline`]
797    /// alignment modes are used, the baseline needs to be set with the `baseline`.
798    /// When using [`PlaceholderAlignment::Baseline`], `baseline_offset` indicates the distance
799    /// of the baseline down from the top of the rectangle. The default `baseline_offset`
800    /// is the `height`.
801    ///
802    /// Examples:
803    ///
804    /// * For a 30x50 placeholder with the bottom edge aligned with the bottom of the text, use:
805    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::Bottom, 1.0, None, None)`
806    /// * For a 30x50 placeholder that is vertically centered around the text, use:
807    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::Middle, 1.0, None, None)`.
808    /// * For a 30x50 placeholder that sits completely on top of the alphabetic baseline, use:
809    ///   `add_placeholder(30.0, 50.0, PlaceholderAlignment::AboveBaseline, 1.0, None,
810    ///   Some(TextBaseline::Alphabetic))`
811    /// * For a 30x50 placeholder with 40 pixels above and 10 pixels below the alphabetic
812    ///   baseline, use: `add_placeholder(30.0, 50.0, PlaceholderAlignment::Baseline, 1.0,
813    ///   Some(40.0), Some(TextBaseline::Alphabetic))`
814    ///
815    /// Lines are permitted to break around each placeholder.
816    ///
817    /// Decorations will be drawn based on the font defined in the most recently
818    /// pushed [`TextStyle`]. The decorations are drawn as if unicode text were present
819    /// in the placeholder space, and will draw the same regardless of the height and
820    /// alignment of the placeholder. To hide or manually adjust decorations to fit,
821    /// a text style with the desired decoration behavior should be pushed before
822    /// adding a placeholder.
823    ///
824    /// Any decorations drawn through a placeholder will exist on the same canvas/layer
825    /// as the text. This means any content drawn on top of the space reserved by
826    /// the placeholder will be drawn over the decoration, possibly obscuring the
827    /// decoration.
828    ///
829    /// Placeholders are represented by a unicode 0xFFFC "object replacement character"
830    /// in the text buffer. For each placeholder, one object replacement character is
831    /// added on to the text buffer.
832    ///
833    /// The `scale` parameter will scale the `width` and `height` by the specified amount,
834    /// and keep track of the scale. The scales of placeholders added can be accessed
835    /// through [`placeholder_scales`](Self::placeholder_scales). This is primarily used for
836    /// accessibility scaling.
837    pub fn add_placeholder(
838        &mut self,
839        width: f64,
840        height: f64,
841        alignment: PlaceholderAlignment,
842        scale: f64,
843        baseline_offset: Option<f64>,
844        baseline: Option<TextBaseline>,
845    ) {
846        // Require a baseline to be specified if using a baseline-based alignment.
847        debug_assert!(
848            !matches!(
849                alignment,
850                PlaceholderAlignment::AboveBaseline
851                    | PlaceholderAlignment::BelowBaseline
852                    | PlaceholderAlignment::Baseline
853            ) || baseline.is_some()
854        );
855        // Default the baselineOffset to height if null. This will place the placeholder
856        // fully above the baseline, similar to [PlaceholderAlignment.aboveBaseline].
857        let baseline_offset = baseline_offset.unwrap_or(height);
858        let placeholder = valo::PlaceholderStyle {
859            width: (width * scale) as f32,
860            height: (height * scale) as f32,
861            alignment: native_placeholder_alignment(alignment),
862            baseline: native_baseline(baseline.unwrap_or(TextBaseline::Alphabetic)),
863            baseline_offset: (baseline_offset * scale) as f32,
864        };
865        let style = self.current_style();
866        self.pieces.push(Piece::Placeholder(placeholder, style));
867        self.placeholder_scales.push(scale);
868    }
869
870    /// The style on top of the stack, in valo's terms.
871    fn current_style(&self) -> valo::TextStyle {
872        self.style_stack
873            .last()
874            .expect("the base style is never popped")
875            .to_native()
876    }
877
878    /// Applies the given paragraph style and returns a [`Paragraph`] containing the added
879    /// text and associated styling, shaped against `fonts`.
880    ///
881    /// After calling this function, the paragraph builder object is invalid and cannot be
882    /// used further.
883    pub fn build(self, fonts: &mut FontCollection) -> Paragraph {
884        let direction = self
885            .paragraph_style
886            .text_direction
887            .unwrap_or(TextDirection::Ltr);
888        let mut builder = valo::ParagraphBuilder::new(fonts);
889        let native_style = self.paragraph_style.to_native();
890        // skparagraph's `kStrut` boxes take the strut's metrics only for a sized strut.
891        let strut_sizes_boxes =
892            native_style.strut_style.enabled && native_style.strut_style.size > 0.0;
893        builder.style(native_style);
894        for piece in &self.pieces {
895            match piece {
896                Piece::Text(text, style) => builder.add_text(text, style),
897                Piece::Placeholder(placeholder, style) => {
898                    builder.add_placeholder(*placeholder, style)
899                }
900            };
901        }
902        if self.pieces.is_empty() {
903            // Skia measures an empty paragraph by the paragraph's default text style, which
904            // the engine sets from `ParagraphStyle`. valo has no default style field, so the
905            // base style rides an empty span to give the glyphless line the same metrics.
906            builder.add_text("", &self.current_style());
907        }
908        let inner = builder.build();
909        Paragraph {
910            code_units: CodeUnits::of(inner.text()),
911            inner,
912            direction,
913            strut_sizes_boxes,
914            layout_width: 0.0,
915            disposed: false,
916        }
917    }
918}
919
920/// The map between Dart's UTF-16 code unit offsets and valo's UTF-8 byte offsets.
921#[derive(Clone, Debug)]
922struct CodeUnits {
923    /// `byte_of[code_unit]` for every code unit boundary, plus the end.
924    byte_of: Vec<usize>,
925    /// The number of UTF-16 code units.
926    len: usize,
927}
928
929impl CodeUnits {
930    fn of(text: &str) -> CodeUnits {
931        let mut byte_of = Vec::with_capacity(text.len() + 1);
932        for (byte, ch) in text.char_indices() {
933            byte_of.push(byte);
934            if ch.len_utf16() == 2 {
935                // A surrogate pair: the second code unit sits inside the character.
936                byte_of.push(byte);
937            }
938        }
939        byte_of.push(text.len());
940        let len = byte_of.len() - 1;
941        CodeUnits { byte_of, len }
942    }
943
944    fn byte(&self, code_unit: i32) -> usize {
945        let clamped = code_unit.clamp(0, self.len as i32) as usize;
946        self.byte_of[clamped]
947    }
948
949    /// The first code unit at or before `byte` (a surrogate pair's two units share a byte).
950    fn code_unit(&self, byte: usize) -> i32 {
951        let first_at_or_after = self.byte_of.partition_point(|candidate| *candidate < byte);
952        match self.byte_of.get(first_at_or_after) {
953            Some(candidate) if *candidate == byte => first_at_or_after as i32,
954            _ => first_at_or_after.saturating_sub(1) as i32,
955        }
956    }
957}
958
959/// The byte offset of the given UTF-16 code unit in `text`.
960fn byte_of_code_unit(text: &str, code_unit: usize) -> usize {
961    CodeUnits::of(text).byte(code_unit as i32)
962}
963
964/// A paragraph of text.
965///
966/// A paragraph retains the size and position of each glyph in the text and can be
967/// efficiently resized and painted.
968///
969/// To create a [`Paragraph`] object, use a [`ParagraphBuilder`].
970///
971/// Paragraphs can be displayed on a [`Canvas`] using [`CanvasText::draw_paragraph`].
972pub struct Paragraph {
973    inner: valo::Paragraph,
974    code_units: CodeUnits,
975    direction: TextDirection,
976    /// Whether an enabled strut with a positive font size sizes this paragraph's lines, which
977    /// decides what a [`BoxHeightStyle::Strut`] box is.
978    strut_sizes_boxes: bool,
979    /// The width given to the last [`layout`](Self::layout); Skia's `getMaxWidth`.
980    layout_width: f64,
981    disposed: bool,
982}
983
984impl Paragraph {
985    /// The amount of horizontal space this paragraph occupies.
986    ///
987    /// Valid only after [`layout`](Self::layout) has been called. As in Skia, this is the
988    /// width the paragraph was laid out at (possibly infinite), not the widest line: the
989    /// lines are aligned within it.
990    pub fn width(&self) -> f64 {
991        self.layout_width
992    }
993
994    /// The amount of vertical space this paragraph occupies.
995    ///
996    /// Valid only after [`layout`](Self::layout) has been called.
997    pub fn height(&self) -> f64 {
998        f64::from(self.inner.height())
999    }
1000
1001    /// The distance from the left edge of the leftmost glyph to the right edge of the
1002    /// rightmost glyph in the paragraph.
1003    pub fn longest_line(&self) -> f64 {
1004        f64::from(self.inner.longest_line())
1005    }
1006
1007    /// The minimum width that this paragraph could be without failing to paint its
1008    /// contents within itself.
1009    pub fn min_intrinsic_width(&self) -> f64 {
1010        f64::from(self.inner.min_intrinsic_width())
1011    }
1012
1013    /// Returns the smallest width beyond which increasing the width never decreases the
1014    /// height.
1015    pub fn max_intrinsic_width(&self) -> f64 {
1016        f64::from(self.inner.max_intrinsic_width())
1017    }
1018
1019    /// The distance from the top of the paragraph to the alphabetic baseline of the first
1020    /// line, in logical pixels.
1021    pub fn alphabetic_baseline(&self) -> f64 {
1022        self.inner
1023            .lines()
1024            .first()
1025            .map_or(0.0, |line| f64::from(line.baseline))
1026    }
1027
1028    /// The distance from the top of the paragraph to the ideographic baseline of the first
1029    /// line, in logical pixels.
1030    ///
1031    /// The host has no ideographic metrics; this is the bottom of the first line.
1032    pub fn ideographic_baseline(&self) -> f64 {
1033        self.inner
1034            .lines()
1035            .first()
1036            .map_or(0.0, |line| f64::from(line.baseline + line.descent))
1037    }
1038
1039    /// True if there is more vertical content, but the text was truncated, either because we
1040    /// reached `max_lines` lines of text or because the `max_lines` was `None`, `ellipsis`
1041    /// was not `None`, and one of the lines exceeded the width constraint.
1042    pub fn did_exceed_max_lines(&self) -> bool {
1043        self.inner.truncated()
1044    }
1045
1046    /// Computes the size and position of each glyph in the paragraph.
1047    ///
1048    /// The [`ParagraphConstraints`] control how wide the text is allowed to be.
1049    pub fn layout(&mut self, constraints: ParagraphConstraints) {
1050        debug_assert!(!self.disposed);
1051        self.layout_width = constraints.width;
1052        self.inner.layout(constraints.width as f32);
1053    }
1054
1055    /// Returns a list of text boxes that enclose the given text range.
1056    ///
1057    /// Each run's box spans its glyphs in the range, and its height is as skparagraph's
1058    /// `TextLine::getRectsForRange` gives it for `box_height_style`, from what valo exposes:
1059    /// see [`run_box_extent`](Self::run_box_extent). `box_width_style` does not change the
1060    /// result.
1061    pub fn get_boxes_for_range(
1062        &self,
1063        start: i32,
1064        end: i32,
1065        box_height_style: BoxHeightStyle,
1066        box_width_style: BoxWidthStyle,
1067    ) -> Vec<TextBox> {
1068        let _ = box_width_style;
1069        let range = self.code_units.byte(start)..self.code_units.byte(end);
1070        let mut rects: Vec<valo::Rect> = Vec::new();
1071        for line in self.inner.lines() {
1072            if range.end <= line.range.start || range.start >= line.range.end {
1073                continue;
1074            }
1075            let mut previous: Option<&valo::PlacedRun> = None;
1076            for run in &line.runs {
1077                let Some((left, right)) = glyph_span(run, &range) else {
1078                    continue;
1079                };
1080                let (top, bottom) = self.run_box_extent(line, run, box_height_style);
1081                let rect = valo::Rect::from_ltrb(left, top, right, bottom);
1082                match (rects.last_mut(), previous) {
1083                    (Some(last), Some(before)) if boxes_join(before, run, last, &rect) => {
1084                        *last = last.union(&rect);
1085                    }
1086                    _ => rects.push(rect),
1087                }
1088                previous = Some(run);
1089            }
1090        }
1091        rects
1092            .into_iter()
1093            .map(|rect| text_box(rect, self.direction))
1094            .collect()
1095    }
1096
1097    /// The top and bottom of `run`'s box on `line` for `box_height_style`.
1098    ///
1099    /// `Tight` is the run's font ascent and descent when it has a height multiplier, and its
1100    /// measured clip otherwise. `Strut` is the measured clip when no strut sizes the lines, and
1101    /// the line's box when one does, for valo exposes no strut metrics. `Max` is the line's
1102    /// box, and so are the include-line-spacing styles, for valo exposes no raw line metrics.
1103    fn run_box_extent(
1104        &self,
1105        line: &valo::Line,
1106        run: &valo::PlacedRun,
1107        box_height_style: BoxHeightStyle,
1108    ) -> (f32, f32) {
1109        let line_box = (line.baseline - line.ascent, line.baseline + line.descent);
1110        match box_height_style {
1111            BoxHeightStyle::Tight if run.height.is_some_and(|height| height > 0.0) => {
1112                (run.bounds.y, run.bounds.bottom())
1113            }
1114            BoxHeightStyle::Tight => self.measured_clip(run).unwrap_or(line_box),
1115            BoxHeightStyle::Strut if !self.strut_sizes_boxes => {
1116                self.measured_clip(run).unwrap_or(line_box)
1117            }
1118            BoxHeightStyle::Strut
1119            | BoxHeightStyle::Max
1120            | BoxHeightStyle::IncludeLineSpacingMiddle
1121            | BoxHeightStyle::IncludeLineSpacingTop
1122            | BoxHeightStyle::IncludeLineSpacingBottom => line_box,
1123        }
1124    }
1125
1126    /// skparagraph's measured clip of a run without a height multiplier: its font's ascent
1127    /// and descent with half the font's line gap on each, as `Run::calculateMetrics` sets
1128    /// them. A placeholder's is its box. `None` for a run with a height multiplier, whose
1129    /// scaled metrics valo does not expose.
1130    fn measured_clip(&self, run: &valo::PlacedRun) -> Option<(f32, f32)> {
1131        if run.placeholder.is_some() {
1132            return Some((run.bounds.y, run.bounds.bottom()));
1133        }
1134        if run.height.is_some_and(|height| height > 0.0) {
1135            return None;
1136        }
1137        let font = self.inner.faces().get(run.font);
1138        let half_gap =
1139            (font.line_height_px(run.size) - font.ascent_px(run.size) - font.descent_px(run.size))
1140                / 2.0;
1141        Some((run.bounds.y - half_gap, run.bounds.bottom() + half_gap))
1142    }
1143
1144    /// Returns a list of text boxes that enclose all placeholders in the paragraph.
1145    ///
1146    /// The order of the boxes are in the same order as passed in through
1147    /// [`ParagraphBuilder::add_placeholder`].
1148    ///
1149    /// Coordinates of the [`TextBox`] are relative to the upper-left corner of the paragraph,
1150    /// where positive y values indicate down.
1151    pub fn get_boxes_for_placeholders(&self) -> Vec<TextBox> {
1152        self.inner
1153            .placeholder_boxes()
1154            .into_iter()
1155            .map(|placeholder| {
1156                let direction = match placeholder.direction {
1157                    valo::TextDirection::Ltr => TextDirection::Ltr,
1158                    valo::TextDirection::Rtl => TextDirection::Rtl,
1159                };
1160                text_box(placeholder.rect, direction)
1161            })
1162            .collect()
1163    }
1164
1165    /// Returns the text position closest to the given offset.
1166    pub fn get_position_for_offset(&self, offset: Offset) -> TextPosition {
1167        let position = self.inner.glyph_position_at(offset.into());
1168        TextPosition::with_affinity(
1169            self.code_units.code_unit(position.offset),
1170            if position.downstream {
1171                TextAffinity::Downstream
1172            } else {
1173                TextAffinity::Upstream
1174            },
1175        )
1176    }
1177
1178    /// Returns the [`GlyphInfo`] of the glyph closest to the given `offset` in the paragraph
1179    /// coordinate system, or `None` if if the text is empty, or is entirely clipped or
1180    /// ellipsized away.
1181    pub fn get_closest_glyph_info_for_offset(&self, offset: Offset) -> Option<GlyphInfo> {
1182        let position = self.inner.glyph_position_at(offset.into());
1183        let anchor = if position.downstream {
1184            position.offset
1185        } else {
1186            position.offset.saturating_sub(1)
1187        };
1188        self.glyph_info_at_byte(anchor)
1189    }
1190
1191    /// Returns the [`GlyphInfo`] located at the given UTF-16 `code_unit_offset` in the
1192    /// paragraph, or `None` if the given `code_unit_offset` is out of the visible lines' range.
1193    pub fn get_glyph_info_at(&self, code_unit_offset: i32) -> Option<GlyphInfo> {
1194        if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
1195            return None;
1196        }
1197        self.glyph_info_at_byte(self.code_units.byte(code_unit_offset))
1198    }
1199
1200    /// The glyph whose cluster contains `byte`: its layout box spans the glyph's advance
1201    /// horizontally and the line vertically.
1202    fn glyph_info_at_byte(&self, byte: usize) -> Option<GlyphInfo> {
1203        for line in self.inner.lines() {
1204            if !line.range.contains(&byte) {
1205                continue;
1206            }
1207            let top = line.baseline - line.ascent;
1208            let bottom = line.baseline + line.descent;
1209            let cluster_starts = cluster_starts(line);
1210            for run in &line.runs {
1211                for glyph in &run.glyphs {
1212                    let cluster = cluster_range(&cluster_starts, glyph.cluster, line.range.end);
1213                    if !cluster.contains(&byte) {
1214                        continue;
1215                    }
1216                    let (left, right) = if glyph.advance >= 0.0 {
1217                        (glyph.x, glyph.x + glyph.advance)
1218                    } else {
1219                        (glyph.x + glyph.advance, glyph.x)
1220                    };
1221                    return Some(GlyphInfo {
1222                        grapheme_cluster_layout_bounds: Rect::from_ltrb(
1223                            f64::from(left),
1224                            f64::from(top),
1225                            f64::from(right),
1226                            f64::from(bottom),
1227                        ),
1228                        grapheme_cluster_code_unit_range: TextRange::new(
1229                            self.code_units.code_unit(cluster.start),
1230                            self.code_units.code_unit(cluster.end),
1231                        ),
1232                        writing_direction: if run.rtl {
1233                            TextDirection::Rtl
1234                        } else {
1235                            TextDirection::Ltr
1236                        },
1237                    });
1238                }
1239            }
1240        }
1241        None
1242    }
1243
1244    /// Returns the [`TextRange`] of the word at the given [`TextPosition`].
1245    pub fn get_word_boundary(&self, position: TextPosition) -> TextRange {
1246        let range = self
1247            .inner
1248            .word_boundary(self.code_units.byte(position.offset));
1249        self.text_range(range)
1250    }
1251
1252    /// Returns the [`TextRange`] of the line at the given [`TextPosition`].
1253    ///
1254    /// The newline (if any) is not returned as part of the range.
1255    pub fn get_line_boundary(&self, position: TextPosition) -> TextRange {
1256        let byte = self.code_units.byte(position.offset);
1257        let Some(line) = self.line_containing(byte, position.affinity) else {
1258            return TextRange::EMPTY;
1259        };
1260        self.text_range(line.range.start..line.text_end)
1261    }
1262
1263    fn line_containing(&self, byte: usize, affinity: TextAffinity) -> Option<&valo::Line> {
1264        let lines = self.inner.lines();
1265        let index = lines.iter().position(|line| {
1266            let starts_next_line = byte == line.range.start && affinity == TextAffinity::Upstream;
1267            (line.range.contains(&byte) && !starts_next_line) || byte == line.range.end
1268        });
1269        index.and_then(|index| lines.get(index)).or_else(|| {
1270            let last = lines.last()?;
1271            (byte >= last.range.end).then_some(last)
1272        })
1273    }
1274
1275    fn text_range(&self, range: Range<usize>) -> TextRange {
1276        TextRange::new(
1277            self.code_units.code_unit(range.start),
1278            self.code_units.code_unit(range.end),
1279        )
1280    }
1281
1282    /// Returns the full list of [`LineMetrics`] that describe in detail the various metrics
1283    /// of each laid out line.
1284    pub fn compute_line_metrics(&self) -> Vec<LineMetrics> {
1285        let lines = self.inner.lines();
1286        lines
1287            .iter()
1288            .enumerate()
1289            .map(|(index, line)| {
1290                let is_last = index + 1 == lines.len();
1291                LineMetrics {
1292                    hard_break: is_last || line.ends_with_hard_break(),
1293                    ascent: f64::from(line.ascent),
1294                    descent: f64::from(line.descent),
1295                    unscaled_ascent: f64::from(line.ascent),
1296                    height: line_height(line),
1297                    width: f64::from(line.width),
1298                    left: f64::from(line.left),
1299                    baseline: f64::from(line.baseline),
1300                    line_number: index as i32,
1301                }
1302            })
1303            .collect()
1304    }
1305
1306    /// Returns the [`LineMetrics`] for the line at `line_number`, or `None` if the given
1307    /// `line_number` is greater than or equal to [`number_of_lines`](Self::number_of_lines).
1308    pub fn get_line_metrics_at(&self, line_number: i32) -> Option<LineMetrics> {
1309        if line_number < 0 {
1310            return None;
1311        }
1312        self.compute_line_metrics()
1313            .into_iter()
1314            .nth(line_number as usize)
1315    }
1316
1317    /// The total number of visible lines in the paragraph.
1318    ///
1319    /// Returns a non-negative number. If `max_lines` is set, the value of this getter never
1320    /// exceeds `max_lines`.
1321    pub fn number_of_lines(&self) -> i32 {
1322        self.inner.lines().len() as i32
1323    }
1324
1325    /// Returns the line number of the line that contains the code unit that
1326    /// `code_unit_offset` points to, or `None` if the `code_unit_offset` is out of range.
1327    pub fn get_line_number_at(&self, code_unit_offset: i32) -> Option<i32> {
1328        if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
1329            return None;
1330        }
1331        let byte = self.code_units.byte(code_unit_offset);
1332        self.inner
1333            .lines()
1334            .iter()
1335            .position(|line| line.range.contains(&byte))
1336            .map(|index| index as i32)
1337    }
1338
1339    /// Release the resources used by this object. The object is no longer usable after this
1340    /// method is called.
1341    pub fn dispose(&mut self) {
1342        debug_assert!(!self.disposed);
1343        self.disposed = true;
1344    }
1345
1346    /// Whether this reference to the underlying paragraph is disposed.
1347    pub fn debug_disposed(&self) -> bool {
1348        self.disposed
1349    }
1350
1351    /// The host paragraph, for drawing.
1352    pub(crate) fn native(&self) -> &valo::Paragraph {
1353        &self.inner
1354    }
1355}
1356
1357/// The height Valo lays `line` out at: its ascent plus descent rounded to the nearest whole
1358/// pixel, as skparagraph's `InternalLineMetrics::height` rounds a line and Valo's wrap advances
1359/// by. Valo's `Line` keeps the room above and below the baseline but not that rounded sum.
1360fn line_height(line: &valo::Line) -> f64 {
1361    (f64::from(line.ascent) + f64::from(line.descent)).round()
1362}
1363
1364/// The left and right edges of `run`'s glyphs whose clusters start in `range`, or `None` when
1365/// it has none there.
1366fn glyph_span(run: &valo::PlacedRun, range: &Range<usize>) -> Option<(f32, f32)> {
1367    run.glyphs
1368        .iter()
1369        .filter(|glyph| glyph.cluster >= range.start && glyph.cluster < range.end)
1370        .map(|glyph| {
1371            let end = glyph.x + glyph.advance;
1372            (glyph.x.min(end), glyph.x.max(end))
1373        })
1374        .reduce(|(left, right), (glyph_left, glyph_right)| {
1375            (left.min(glyph_left), right.max(glyph_right))
1376        })
1377}
1378
1379/// Whether `rect`, the box of `run`, continues `last`, the box of `before`, the run left of it:
1380/// skparagraph merges the boxes of text runs in one direction, font and height multiplier that
1381/// share a top and bottom and touch, as valo's `rects_for_range` does.
1382fn boxes_join(
1383    before: &valo::PlacedRun,
1384    run: &valo::PlacedRun,
1385    last: &valo::Rect,
1386    rect: &valo::Rect,
1387) -> bool {
1388    let nearly_equal = |a: f32, b: f32| (a - b).abs() < 1e-3;
1389    before.placeholder.is_none()
1390        && run.placeholder.is_none()
1391        && before.rtl == run.rtl
1392        && before.font == run.font
1393        && before.size == run.size
1394        && before.height == run.height
1395        && nearly_equal(last.y, rect.y)
1396        && nearly_equal(last.bottom(), rect.bottom())
1397        && (nearly_equal(last.right(), rect.x) || nearly_equal(rect.right(), last.x))
1398}
1399
1400fn text_box(rect: valo::Rect, direction: TextDirection) -> TextBox {
1401    TextBox::from_ltrbd(
1402        f64::from(rect.x),
1403        f64::from(rect.y),
1404        f64::from(rect.x + rect.width),
1405        f64::from(rect.y + rect.height),
1406        direction,
1407    )
1408}
1409
1410/// Every cluster start on the line, in text order. A cluster runs from its start to the next
1411/// start on the line, whichever run that glyph sits in.
1412fn cluster_starts(line: &valo::Line) -> Vec<usize> {
1413    let mut starts: Vec<usize> = line
1414        .runs
1415        .iter()
1416        .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.cluster))
1417        .collect();
1418    starts.sort_unstable();
1419    starts.dedup();
1420    starts
1421}
1422
1423fn cluster_range(cluster_starts: &[usize], start: usize, line_end: usize) -> Range<usize> {
1424    let next = cluster_starts
1425        .iter()
1426        .find(|candidate| **candidate > start)
1427        .copied()
1428        .unwrap_or(line_end);
1429    start..next.max(start + 1)
1430}
1431
1432impl fmt::Debug for Paragraph {
1433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434        f.debug_struct("Paragraph")
1435            .field("text", &self.inner.text())
1436            .field("width", &self.width())
1437            .field("height", &self.height())
1438            .finish()
1439    }
1440}
1441
1442/// Paragraph drawing on a [`Canvas`] (Dart's `Canvas.drawParagraph`).
1443pub trait CanvasText {
1444    /// Draws the text in the given [`Paragraph`] into this canvas at the given [`Offset`].
1445    ///
1446    /// The [`Paragraph`] object must have had [`Paragraph::layout`] called on it first.
1447    fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset);
1448}
1449
1450impl CanvasText for Canvas {
1451    fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset) {
1452        valo::DrawParagraphExt::draw_paragraph(self, paragraph.native(), offset);
1453    }
1454}
1455
1456#[cfg(test)]
1457mod tests {
1458    use super::*;
1459
1460    #[test]
1461    fn code_units_map_surrogate_pairs_to_one_character() {
1462        let units = CodeUnits::of("a😀b");
1463        assert_eq!(units.len, 4);
1464        assert_eq!(units.byte(0), 0);
1465        assert_eq!(units.byte(1), 1);
1466        assert_eq!(
1467            units.byte(2),
1468            1,
1469            "the second half of the pair maps to the same byte"
1470        );
1471        assert_eq!(units.byte(3), 5);
1472        assert_eq!(units.byte(4), 6);
1473        assert_eq!(units.code_unit(5), 3);
1474        assert_eq!(units.code_unit(6), 4);
1475    }
1476
1477    /// A span's foreground and background paints reach valo whole, as Flutter's paragraph builder
1478    /// hands its `TextStyle`'s paints to Skia's; the colour stays the foreground's, for a
1479    /// decoration with no colour of its own.
1480    #[test]
1481    fn a_spans_paints_reach_valo() {
1482        let outline = Paint {
1483            color: Color::from_argb(255, 0, 0, 0).into(),
1484            style: valo::PaintStyle::Stroke(valo::Stroke::new(2.0)),
1485            ..Paint::default()
1486        };
1487        let box_behind = Paint::from_color(Color::from_argb(160, 0, 0, 0).into());
1488        let style = TextStyle {
1489            foreground: Some(outline.clone()),
1490            background: Some(box_behind.clone()),
1491            ..TextStyle::default()
1492        };
1493        let native = style.to_native();
1494        assert_eq!(native.foreground, Some(outline.clone()));
1495        assert_eq!(native.background, Some(box_behind));
1496        assert_eq!(native.color, outline.color);
1497    }
1498
1499    #[test]
1500    fn text_range_slices_by_code_unit() {
1501        let range = TextRange::new(1, 3);
1502        assert_eq!(range.text_inside("a😀b"), "😀");
1503        assert_eq!(range.text_before("a😀b"), "a");
1504        assert_eq!(range.text_after("a😀b"), "b");
1505        assert!(TextRange::EMPTY.is_collapsed());
1506        assert!(!TextRange::EMPTY.is_valid());
1507    }
1508
1509    #[test]
1510    fn text_box_start_and_end_follow_direction() {
1511        let ltr = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Ltr);
1512        let rtl = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Rtl);
1513        assert_eq!(ltr.start(), 1.0);
1514        assert_eq!(ltr.end(), 3.0);
1515        assert_eq!(rtl.start(), 3.0);
1516        assert_eq!(rtl.end(), 1.0);
1517        assert_eq!(ltr.to_rect(), Rect::from_ltrb(1.0, 2.0, 3.0, 4.0));
1518    }
1519
1520    fn text_styles(builder: &ParagraphBuilder) -> Vec<&valo::TextStyle> {
1521        builder
1522            .pieces
1523            .iter()
1524            .filter_map(|piece| match piece {
1525                Piece::Text(_, style) => Some(style),
1526                Piece::Placeholder(..) => None,
1527            })
1528            .collect()
1529    }
1530
1531    #[test]
1532    fn a_strut_style_maps_to_valos_as_the_engine_maps_it() {
1533        let style = ParagraphStyle {
1534            strut_style: Some(StrutStyle {
1535                font_family: Some("Serif".to_owned()),
1536                font_family_fallback: Some(vec!["Sans".to_owned()]),
1537                font_size: Some(10.0),
1538                height: Some(2.0),
1539                leading_distribution: Some(TextLeadingDistribution::Even),
1540                leading: Some(0.5),
1541                font_weight: Some(FontWeight::W700),
1542                font_style: Some(FontStyle::Italic),
1543                force_strut_height: Some(true),
1544            }),
1545            ..ParagraphStyle::default()
1546        };
1547        let native = style.to_native().strut_style;
1548        assert!(native.enabled);
1549        assert_eq!(native.families, ["Serif", "Sans"]);
1550        assert_eq!(native.weight, 700);
1551        assert!(native.italic);
1552        assert_eq!(native.size, 10.0);
1553        assert_eq!(native.height, 2.0);
1554        assert!(native.height_override);
1555        assert_eq!(native.leading, Some(0.5));
1556        assert!(native.half_leading);
1557        assert!(native.force_height);
1558
1559        // A fallback list alone is not encoded, as in `dart:ui`'s `_encodeStrut`.
1560        let fallback_only = ParagraphStyle {
1561            strut_style: Some(StrutStyle {
1562                font_family_fallback: Some(vec!["Sans".to_owned()]),
1563                ..StrutStyle::default()
1564            }),
1565            ..ParagraphStyle::default()
1566        };
1567        assert!(!fallback_only.to_native().strut_style.enabled);
1568
1569        // A height of `kTextHeightNone` is the absence of a height override.
1570        let no_height = ParagraphStyle {
1571            strut_style: Some(StrutStyle {
1572                font_size: Some(10.0),
1573                height: Some(K_TEXT_HEIGHT_NONE),
1574                ..StrutStyle::default()
1575            }),
1576            ..ParagraphStyle::default()
1577        };
1578        let native = no_height.to_native().strut_style;
1579        assert!(native.enabled);
1580        assert!(!native.height_override);
1581        assert_eq!(native.families, [""], "the platform default font");
1582
1583        // A strut that sets no leading distribution takes the paragraph's, as dart:ui's
1584        // `ParagraphBuilder` encodes it.
1585        let paragraph_even = ParagraphStyle {
1586            text_height_behavior: Some(TextHeightBehavior {
1587                leading_distribution: TextLeadingDistribution::Even,
1588                ..TextHeightBehavior::default()
1589            }),
1590            strut_style: Some(StrutStyle {
1591                height: Some(2.0),
1592                ..StrutStyle::default()
1593            }),
1594            ..ParagraphStyle::default()
1595        };
1596        assert!(paragraph_even.to_native().strut_style.half_leading);
1597    }
1598
1599    #[test]
1600    fn placeholders_are_counted_with_their_scales() {
1601        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1602        builder.add_text("a");
1603        builder.add_placeholder(10.0, 20.0, PlaceholderAlignment::Middle, 2.0, None, None);
1604        builder.add_placeholder(5.0, 5.0, PlaceholderAlignment::Bottom, 1.0, None, None);
1605        assert_eq!(builder.placeholder_count(), 2);
1606        assert_eq!(builder.placeholder_scales(), [2.0, 1.0]);
1607    }
1608
1609    #[test]
1610    fn pushed_styles_inherit_unset_fields() {
1611        let mut builder = ParagraphBuilder::new(ParagraphStyle {
1612            font_size: Some(20.0),
1613            ..ParagraphStyle::default()
1614        });
1615        builder.push_style(TextStyle {
1616            color: Some(Color::from_argb(255, 255, 0, 0)),
1617            ..TextStyle::default()
1618        });
1619        builder.add_text("x");
1620        builder.pop();
1621        builder.add_text("y");
1622        let styles = text_styles(&builder);
1623        assert_eq!(styles[0].size, 20.0, "the child keeps the paragraph's size");
1624        assert_eq!(styles[0].color, Color::from_argb(255, 255, 0, 0).into());
1625        assert_eq!(styles[1].size, 20.0);
1626        assert_eq!(
1627            styles[1].color,
1628            valo::Color::BLACK,
1629            "popping restores the base"
1630        );
1631    }
1632
1633    /// As in `dart:ui`, the paragraph's `TextHeightBehavior::leading_distribution` is the share
1634    /// for spans that set none, and a span's own wins.
1635    #[test]
1636    fn the_paragraphs_leading_distribution_is_the_spans_default() {
1637        let mut builder = ParagraphBuilder::new(ParagraphStyle {
1638            text_height_behavior: Some(TextHeightBehavior {
1639                leading_distribution: TextLeadingDistribution::Even,
1640                ..TextHeightBehavior::default()
1641            }),
1642            ..ParagraphStyle::default()
1643        });
1644        builder.add_text("x");
1645        builder.push_style(TextStyle {
1646            leading_distribution: Some(TextLeadingDistribution::Proportional),
1647            ..TextStyle::default()
1648        });
1649        builder.add_text("y");
1650        let styles = text_styles(&builder);
1651        assert_eq!(
1652            styles[0].leading_distribution,
1653            valo::LeadingDistribution::Even
1654        );
1655        assert_eq!(
1656            styles[1].leading_distribution,
1657            valo::LeadingDistribution::Proportional
1658        );
1659        assert_eq!(
1660            ParagraphBuilder::new(ParagraphStyle::new())
1661                .current_style()
1662                .leading_distribution,
1663            valo::LeadingDistribution::Proportional,
1664            "unset is Flutter's default"
1665        );
1666    }
1667
1668    #[test]
1669    fn the_height_flags_reach_valo() {
1670        let style = ParagraphStyle {
1671            text_height_behavior: Some(TextHeightBehavior {
1672                apply_height_to_first_ascent: false,
1673                ..TextHeightBehavior::default()
1674            }),
1675            ..ParagraphStyle::default()
1676        };
1677        assert_eq!(
1678            style.to_native().text_height_behavior,
1679            valo::TextHeightBehavior {
1680                apply_height_to_first_ascent: false,
1681                apply_height_to_last_descent: true,
1682            }
1683        );
1684        assert_eq!(
1685            ParagraphStyle::new().to_native().text_height_behavior,
1686            valo::TextHeightBehavior::default()
1687        );
1688    }
1689
1690    #[test]
1691    fn start_and_end_alignment_resolve_against_direction() {
1692        assert_eq!(
1693            native_align(Some(TextAlign::Start), Some(TextDirection::Rtl)),
1694            valo::TextAlign::Right
1695        );
1696        assert_eq!(
1697            native_align(Some(TextAlign::End), None),
1698            valo::TextAlign::Right,
1699            "no direction reads as LTR"
1700        );
1701    }
1702
1703    #[test]
1704    fn unspecified_font_family_stays_unset_on_the_native_style() {
1705        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1706        builder.add_text("x");
1707        assert!(
1708            text_styles(&builder)[0].families.is_empty(),
1709            "dart:ui leaves fontFamily unset; the collection's default manager supplies the face"
1710        );
1711    }
1712}
1713
1714#[cfg(test)]
1715mod layout_tests {
1716    //! Shaping needs real fonts: these shape against the OS fonts.
1717
1718    use super::*;
1719    use crate::TargetPlatform;
1720
1721    /// The engine's default families on the OS these tests run on, as its embedder answers them.
1722    fn this_os_default_families() -> Vec<String> {
1723        let os = if cfg!(target_os = "windows") {
1724            TargetPlatform::Windows
1725        } else if cfg!(target_os = "linux") {
1726            TargetPlatform::Linux
1727        } else if cfg!(target_os = "android") {
1728            TargetPlatform::Android
1729        } else {
1730            TargetPlatform::MacOS
1731        };
1732        crate::default_font_families(os)
1733    }
1734
1735    fn fonts() -> FontCollection {
1736        let mut fonts = FontCollection::new();
1737        fonts.add_source(valo_system_fonts::SystemFonts::load());
1738        fonts
1739    }
1740
1741    fn paragraph(text: &str, style: ParagraphStyle, width: f64) -> Paragraph {
1742        let mut builder = ParagraphBuilder::new(style);
1743        builder.push_style(TextStyle {
1744            font_size: Some(20.0),
1745            ..TextStyle::default()
1746        });
1747        builder.add_text(text);
1748        let mut paragraph = builder.build(&mut fonts());
1749        paragraph.layout(ParagraphConstraints::new(width));
1750        paragraph
1751    }
1752
1753    #[test]
1754    fn a_laid_out_paragraph_has_a_size_and_one_line() {
1755        let paragraph = paragraph("Hello", ParagraphStyle::new(), f64::INFINITY);
1756        assert_eq!(
1757            paragraph.width(),
1758            f64::INFINITY,
1759            "the layout width, as in Skia"
1760        );
1761        assert!(paragraph.longest_line() > 0.0);
1762        assert!(paragraph.height() > 0.0);
1763        assert_eq!(paragraph.number_of_lines(), 1);
1764        assert!(paragraph.alphabetic_baseline() > 0.0);
1765        assert!(paragraph.alphabetic_baseline() < paragraph.height());
1766        assert!(!paragraph.did_exceed_max_lines());
1767        assert_eq!(paragraph.max_intrinsic_width(), paragraph.longest_line());
1768    }
1769
1770    /// A 14 px line at a height of 1.43 asks for 20.02 pixels; skparagraph, and Valo with it,
1771    /// lays it out at the nearest whole pixel, and its metrics say so.
1772    #[test]
1773    fn a_lines_height_is_rounded_to_a_whole_pixel() {
1774        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1775        builder.push_style(TextStyle {
1776            font_size: Some(14.0),
1777            height: Some(1.43),
1778            ..TextStyle::default()
1779        });
1780        builder.add_text("Hello");
1781        let mut paragraph = builder.build(&mut fonts());
1782        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
1783        let metrics = paragraph.compute_line_metrics();
1784        assert_eq!(metrics[0].height, 20.0);
1785        assert_eq!(paragraph.height(), 20.0);
1786    }
1787
1788    #[test]
1789    fn a_narrow_width_wraps_onto_more_lines() {
1790        let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
1791        let narrow = paragraph(
1792            "one two three four",
1793            ParagraphStyle::new(),
1794            wide.longest_line() / 2.0,
1795        );
1796        assert!(narrow.number_of_lines() > 1);
1797        assert!(narrow.height() > wide.height());
1798        let metrics = narrow.compute_line_metrics();
1799        assert_eq!(metrics.len() as i32, narrow.number_of_lines());
1800        assert!(
1801            metrics.last().unwrap().hard_break,
1802            "the last line is a hard break"
1803        );
1804        assert!(!metrics[0].hard_break, "a wrapped line is a soft break");
1805        assert_eq!(metrics[1].line_number, 1);
1806    }
1807
1808    #[test]
1809    fn max_lines_with_an_ellipsis_truncates() {
1810        let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
1811        let style = ParagraphStyle {
1812            max_lines: Some(1),
1813            ellipsis: Some("\u{2026}".to_owned()),
1814            ..ParagraphStyle::default()
1815        };
1816        let clipped = paragraph("one two three four", style, wide.longest_line() / 2.0);
1817        assert_eq!(clipped.number_of_lines(), 1);
1818        assert!(clipped.did_exceed_max_lines());
1819    }
1820
1821    #[test]
1822    fn positions_boxes_and_boundaries_use_code_units() {
1823        let paragraph = paragraph("ab cd", ParagraphStyle::new(), f64::INFINITY);
1824        let start = paragraph.get_position_for_offset(Offset::new(0.0, 1.0));
1825        assert_eq!(start.offset, 0);
1826        let end =
1827            paragraph.get_position_for_offset(Offset::new(paragraph.longest_line() + 50.0, 1.0));
1828        assert_eq!(end.offset, 5);
1829
1830        let boxes =
1831            paragraph.get_boxes_for_range(0, 2, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
1832        assert_eq!(boxes.len(), 1);
1833        assert!(boxes[0].right > boxes[0].left);
1834        assert_eq!(boxes[0].direction, TextDirection::Ltr);
1835
1836        assert_eq!(
1837            paragraph.get_word_boundary(TextPosition::new(4)),
1838            TextRange::new(3, 5)
1839        );
1840        assert_eq!(
1841            paragraph.get_line_boundary(TextPosition::new(1)),
1842            TextRange::new(0, 5)
1843        );
1844        assert_eq!(paragraph.get_line_number_at(4), Some(0));
1845        assert_eq!(paragraph.get_line_number_at(5), None);
1846
1847        let glyph = paragraph.get_glyph_info_at(3).expect("the c glyph");
1848        assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(3, 4));
1849        assert!(glyph.grapheme_cluster_layout_bounds.width() > 0.0);
1850        assert!(paragraph.get_glyph_info_at(5).is_none());
1851    }
1852
1853    #[test]
1854    fn a_surrogate_pair_is_one_glyph_of_two_code_units() {
1855        let paragraph = paragraph("a😀b", ParagraphStyle::new(), f64::INFINITY);
1856        let glyph = paragraph.get_glyph_info_at(1).expect("the emoji");
1857        assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(1, 3));
1858        assert_eq!(
1859            paragraph
1860                .get_glyph_info_at(3)
1861                .unwrap()
1862                .grapheme_cluster_code_unit_range,
1863            TextRange::new(3, 4)
1864        );
1865    }
1866
1867    /// Either half of a glyph finds that glyph, and a point past the end of the line finds the
1868    /// last glyph.
1869    #[test]
1870    fn the_closest_glyph_is_the_one_under_the_point() {
1871        let paragraph = paragraph("abc", ParagraphStyle::new(), f64::INFINITY);
1872        let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
1873        let bounds = b.grapheme_cluster_layout_bounds;
1874        let y = bounds.center().dy();
1875        for x in [bounds.left + 0.5, bounds.right - 0.5] {
1876            let closest = paragraph
1877                .get_closest_glyph_info_for_offset(Offset::new(x, y))
1878                .expect("a glyph");
1879            assert_eq!(
1880                closest.grapheme_cluster_code_unit_range,
1881                TextRange::new(1, 2)
1882            );
1883        }
1884        let past_the_end = paragraph
1885            .get_closest_glyph_info_for_offset(Offset::new(1000.0, y))
1886            .expect("a glyph");
1887        assert_eq!(
1888            past_the_end.grapheme_cluster_code_unit_range,
1889            TextRange::new(2, 3)
1890        );
1891    }
1892
1893    /// Fails unless `found` is `wanted`, to within what adding a line's advances in another
1894    /// order changes.
1895    fn assert_same_place(found: Rect, wanted: Rect) {
1896        let apart = [
1897            found.left - wanted.left,
1898            found.top - wanted.top,
1899            found.right - wanted.right,
1900            found.bottom - wanted.bottom,
1901        ];
1902        assert!(
1903            apart.iter().all(|distance| distance.abs() < 0.01),
1904            "{found:?} is not {wanted:?}"
1905        );
1906    }
1907
1908    /// A newline is a grapheme of its own, zero-width where its line's text ends, as Skia's
1909    /// paragraph measures a hard line break: a caret before it stays on its line.
1910    #[test]
1911    fn a_newline_is_a_zero_width_glyph_where_its_lines_text_ends() {
1912        let paragraph = paragraph("ab\ncd", ParagraphStyle::new(), f64::INFINITY);
1913        let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
1914        assert_eq!(b.grapheme_cluster_code_unit_range, TextRange::new(1, 2));
1915        let end_of_line = Rect::from_ltrb(
1916            b.grapheme_cluster_layout_bounds.right,
1917            b.grapheme_cluster_layout_bounds.top,
1918            b.grapheme_cluster_layout_bounds.right,
1919            b.grapheme_cluster_layout_bounds.bottom,
1920        );
1921
1922        let newline = paragraph.get_glyph_info_at(2).expect("the newline");
1923        assert_eq!(
1924            newline.grapheme_cluster_code_unit_range,
1925            TextRange::new(2, 3)
1926        );
1927        assert_same_place(newline.grapheme_cluster_layout_bounds, end_of_line);
1928        assert_eq!(newline.writing_direction, TextDirection::Ltr);
1929
1930        let boxes =
1931            paragraph.get_boxes_for_range(2, 3, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
1932        assert_eq!(boxes.len(), 1, "{boxes:?}");
1933        assert_same_place(boxes[0].to_rect(), end_of_line);
1934    }
1935
1936    /// An empty line has no glyph but its newline's, which is at the line's start.
1937    #[test]
1938    fn an_empty_lines_newline_is_a_zero_width_glyph_at_the_lines_start() {
1939        let paragraph = paragraph("ab\n\ncd", ParagraphStyle::new(), f64::INFINITY);
1940        let empty_line = paragraph.get_line_metrics_at(1).expect("the empty line");
1941        let start_of_line = Rect::from_ltrb(
1942            empty_line.left,
1943            empty_line.baseline - empty_line.ascent,
1944            empty_line.left,
1945            empty_line.baseline + empty_line.descent,
1946        );
1947
1948        let newline = paragraph
1949            .get_glyph_info_at(3)
1950            .expect("the empty line's newline");
1951        assert_eq!(
1952            newline.grapheme_cluster_code_unit_range,
1953            TextRange::new(3, 4)
1954        );
1955        assert_same_place(newline.grapheme_cluster_layout_bounds, start_of_line);
1956
1957        let boxes =
1958            paragraph.get_boxes_for_range(3, 4, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
1959        assert_eq!(boxes.len(), 1, "{boxes:?}");
1960        assert_same_place(boxes[0].to_rect(), start_of_line);
1961    }
1962
1963    /// A range that selects a line's text with its newline has the text's box alone, and one
1964    /// across lines no box of a newline between them.
1965    #[test]
1966    fn a_newline_selected_with_text_adds_no_box() {
1967        let paragraph = paragraph("ab\ncd", ParagraphStyle::new(), f64::INFINITY);
1968        let boxes_of = |start, end| {
1969            paragraph.get_boxes_for_range(start, end, BoxHeightStyle::Tight, BoxWidthStyle::Tight)
1970        };
1971        assert_eq!(boxes_of(0, 3), boxes_of(0, 2));
1972        assert_eq!(boxes_of(0, 5).len(), 2);
1973    }
1974
1975    /// A line separator ends its line as a newline does: Skia's paragraph treats every
1976    /// character of the line-break classes LF and BK as a hard break.
1977    #[test]
1978    fn a_line_separator_ends_its_line_like_a_newline() {
1979        let paragraph = paragraph("ab\u{2028}cd", ParagraphStyle::new(), f64::INFINITY);
1980        assert_eq!(paragraph.number_of_lines(), 2);
1981        let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
1982        let separator = paragraph.get_glyph_info_at(2).expect("the separator");
1983        assert_eq!(
1984            separator.grapheme_cluster_code_unit_range,
1985            TextRange::new(2, 3)
1986        );
1987        let bounds = b.grapheme_cluster_layout_bounds;
1988        let end_of_line = Rect::from_ltrb(bounds.right, bounds.top, bounds.right, bounds.bottom);
1989        assert_same_place(separator.grapheme_cluster_layout_bounds, end_of_line);
1990        assert_eq!(
1991            paragraph.get_line_boundary(TextPosition::new(0)),
1992            TextRange::new(0, 2)
1993        );
1994        assert!(paragraph.compute_line_metrics()[0].hard_break);
1995    }
1996
1997    /// "\r\n" breaks once, at its line feed: the carriage return is trailing whitespace of the
1998    /// line's text, where Skia's line text ends.
1999    #[test]
2000    fn a_carriage_return_line_feed_ends_its_line_at_the_line_feed() {
2001        let paragraph = paragraph("ab\r\ncd", ParagraphStyle::new(), f64::INFINITY);
2002        assert_eq!(paragraph.number_of_lines(), 2);
2003        assert_eq!(paragraph.get_line_number_at(3), Some(0));
2004        assert_eq!(paragraph.get_line_number_at(4), Some(1));
2005        let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
2006        let carriage_return = paragraph.get_glyph_info_at(2).expect("the carriage return");
2007        assert_eq!(
2008            carriage_return.grapheme_cluster_layout_bounds.left,
2009            b.grapheme_cluster_layout_bounds.right
2010        );
2011        let line_feed = paragraph.get_glyph_info_at(3).expect("the line feed");
2012        assert_eq!(
2013            line_feed.grapheme_cluster_code_unit_range,
2014            TextRange::new(3, 4)
2015        );
2016        assert_eq!(line_feed.grapheme_cluster_layout_bounds.width(), 0.0);
2017        assert_eq!(
2018            line_feed.grapheme_cluster_layout_bounds.left,
2019            carriage_return.grapheme_cluster_layout_bounds.right
2020        );
2021        assert_eq!(
2022            paragraph.get_line_boundary(TextPosition::new(0)),
2023            TextRange::new(0, 3)
2024        );
2025    }
2026
2027    /// In a right-to-left paragraph the newline takes the paragraph's direction, so it sits at
2028    /// the left end of its line, where right-to-left text ends.
2029    #[test]
2030    fn a_right_to_left_lines_newline_is_at_its_left_end() {
2031        let style = ParagraphStyle {
2032            text_align: Some(TextAlign::Start),
2033            text_direction: Some(TextDirection::Rtl),
2034            ..ParagraphStyle::new()
2035        };
2036        let paragraph = paragraph("שלום\nשלום", style, 300.0);
2037        let line = paragraph.get_line_metrics_at(0).expect("the first line");
2038        let newline = paragraph.get_glyph_info_at(4).expect("the newline");
2039        assert_eq!(newline.writing_direction, TextDirection::Rtl);
2040        let start_of_line = Rect::from_ltrb(
2041            line.left,
2042            line.baseline - line.ascent,
2043            line.left,
2044            line.baseline + line.descent,
2045        );
2046        assert_same_place(newline.grapheme_cluster_layout_bounds, start_of_line);
2047        assert!(line.left > 0.0, "the line is right-aligned");
2048    }
2049
2050    #[test]
2051    fn placeholder_boxes_come_in_the_order_added_at_their_scaled_size() {
2052        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
2053        builder.push_style(TextStyle {
2054            font_size: Some(20.0),
2055            ..TextStyle::default()
2056        });
2057        builder.add_text("ab");
2058        builder.add_placeholder(
2059            30.0,
2060            50.0,
2061            PlaceholderAlignment::Baseline,
2062            1.0,
2063            Some(40.0),
2064            Some(TextBaseline::Alphabetic),
2065        );
2066        builder.add_text("cd");
2067        builder.add_placeholder(10.0, 10.0, PlaceholderAlignment::Bottom, 2.0, None, None);
2068        let mut paragraph = builder.build(&mut fonts());
2069        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
2070
2071        let boxes = paragraph.get_boxes_for_placeholders();
2072        assert_eq!(boxes.len(), 2);
2073        let baseline = paragraph.alphabetic_baseline();
2074        let (first, second) = (boxes[0], boxes[1]);
2075        assert!((first.right - first.left - 30.0).abs() < 1e-3);
2076        assert!(
2077            (first.top - (baseline - 40.0)).abs() < 1e-3,
2078            "40 above the baseline"
2079        );
2080        assert!(
2081            (first.bottom - (baseline + 10.0)).abs() < 1e-3,
2082            "10 below it"
2083        );
2084        assert!(
2085            (second.right - second.left - 20.0).abs() < 1e-3,
2086            "scaled by 2"
2087        );
2088        assert!((second.bottom - second.top - 20.0).abs() < 1e-3);
2089        assert!(second.left > first.right, "after the text between them");
2090        assert_eq!(
2091            paragraph.get_line_boundary(TextPosition::new(0)),
2092            TextRange::new(0, 6),
2093            "each placeholder is one code unit"
2094        );
2095    }
2096
2097    #[test]
2098    fn drawing_records_the_paragraph() {
2099        let paragraph = paragraph("Hi", ParagraphStyle::new(), f64::INFINITY);
2100        let mut canvas = Canvas::new();
2101        canvas.draw_paragraph(&paragraph, Offset::new(10.0, 10.0));
2102        let picture = canvas.build();
2103        assert!(!picture.ops().is_empty());
2104    }
2105
2106    #[test]
2107    fn unspecified_family_at_black_weight_covers_latin() {
2108        let mut fonts = FontCollection::new();
2109        crate::set_default_font_manager(
2110            &mut fonts,
2111            Box::new(crate::SystemFontSource::new(
2112                valo_system_fonts::fontmgr::platform(),
2113            )),
2114            &this_os_default_families(),
2115        );
2116        let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
2117        builder.push_style(TextStyle {
2118            font_size: Some(10.2),
2119            font_weight: Some(FontWeight::W900),
2120            ..TextStyle::default()
2121        });
2122        builder.add_text("DEBUG");
2123        let mut paragraph = builder.build(&mut fonts);
2124        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
2125        assert!(paragraph.longest_line() > 0.0);
2126        assert!(
2127            fonts.take_unanswered().is_empty(),
2128            "the engine default family covers Latin at weight 900"
2129        );
2130        for line in paragraph.inner.lines() {
2131            for run in &line.runs {
2132                assert!(
2133                    run.glyphs.iter().all(|glyph| glyph.id != 0),
2134                    "no .notdef tofu"
2135                );
2136            }
2137        }
2138    }
2139}
2140
2141#[cfg(all(test, feature = "test-support"))]
2142mod box_height_style_tests {
2143    //! These measure boxes against FlutterTest, whose metrics are exact.
2144
2145    use super::*;
2146    use crate::Platform;
2147
2148    /// FlutterTest's metrics: ascent 0.75 em, descent 0.25 em, no line gap.
2149    fn flutter_test_paragraph(spans: &[(&str, TextStyle)], style: ParagraphStyle) -> Paragraph {
2150        let mut fonts = FontCollection::new();
2151        crate::set_default_font_manager(
2152            &mut fonts,
2153            Box::new(crate::TestFontSource::new()),
2154            &crate::InertPlatform.default_font_families(),
2155        );
2156        let mut builder = ParagraphBuilder::new(style);
2157        for (text, style) in spans {
2158            builder.push_style(style.clone());
2159            builder.add_text(text);
2160            builder.pop();
2161        }
2162        let mut paragraph = builder.build(&mut fonts);
2163        paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
2164        paragraph
2165    }
2166
2167    /// skparagraph's `kTight` box of a run with a height multiplier is its font's ascent and
2168    /// descent at the baseline, where `kMax` is the line's box.
2169    #[test]
2170    fn a_tight_box_of_a_run_with_a_height_is_its_font_box() {
2171        let tall = TextStyle {
2172            font_size: Some(10.0),
2173            height: Some(3.0),
2174            ..TextStyle::default()
2175        };
2176        let paragraph = flutter_test_paragraph(&[("A", tall)], ParagraphStyle::new());
2177        assert_eq!(paragraph.height(), 30.0);
2178        let baseline = paragraph.alphabetic_baseline();
2179        let tight =
2180            paragraph.get_boxes_for_range(0, 1, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
2181        assert_eq!(
2182            tight,
2183            [TextBox::from_ltrbd(
2184                0.0,
2185                baseline - 7.5,
2186                10.0,
2187                baseline + 2.5,
2188                TextDirection::Ltr
2189            )]
2190        );
2191        let max = paragraph.get_boxes_for_range(0, 1, BoxHeightStyle::Max, BoxWidthStyle::Tight);
2192        assert_eq!(
2193            max,
2194            [TextBox::from_ltrbd(
2195                0.0,
2196                0.0,
2197                10.0,
2198                30.0,
2199                TextDirection::Ltr
2200            )]
2201        );
2202    }
2203
2204    /// Without a strut, skparagraph's `kStrut` box is the run's measured clip, as for a strut
2205    /// whose font size is 0.
2206    #[test]
2207    fn a_strut_box_without_a_sized_strut_is_the_runs_box() {
2208        let spans = [
2209            (
2210                "A",
2211                TextStyle {
2212                    font_size: Some(10.0),
2213                    ..TextStyle::default()
2214                },
2215            ),
2216            (
2217                "B",
2218                TextStyle {
2219                    font_size: Some(20.0),
2220                    ..TextStyle::default()
2221                },
2222            ),
2223        ];
2224        let paragraph = flutter_test_paragraph(&spans, ParagraphStyle::new());
2225        let baseline = paragraph.alphabetic_baseline();
2226        let small_run = TextBox::from_ltrbd(
2227            0.0,
2228            baseline - 7.5,
2229            10.0,
2230            baseline + 2.5,
2231            TextDirection::Ltr,
2232        );
2233        assert_eq!(
2234            paragraph.get_boxes_for_range(0, 1, BoxHeightStyle::Strut, BoxWidthStyle::Tight),
2235            [small_run]
2236        );
2237
2238        let zero_size_strut = ParagraphStyle {
2239            strut_style: Some(StrutStyle {
2240                font_size: Some(0.0),
2241                ..StrutStyle::default()
2242            }),
2243            ..ParagraphStyle::default()
2244        };
2245        let paragraph = flutter_test_paragraph(&spans, zero_size_strut);
2246        assert_eq!(
2247            paragraph.get_boxes_for_range(0, 1, BoxHeightStyle::Strut, BoxWidthStyle::Tight),
2248            [small_run]
2249        );
2250    }
2251}