1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub struct TextPosition {
28 pub offset: i32,
31 pub affinity: TextAffinity,
34}
35
36impl TextPosition {
37 pub const fn new(offset: i32) -> TextPosition {
40 TextPosition {
41 offset,
42 affinity: TextAffinity::Downstream,
43 }
44 }
45
46 pub const fn with_affinity(offset: i32, affinity: TextAffinity) -> TextPosition {
48 TextPosition { offset, affinity }
49 }
50}
51
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
55pub enum TextAffinity {
56 Upstream,
59 #[default]
62 Downstream,
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
67pub struct TextRange {
68 pub start: i32,
72 pub end: i32,
74}
75
76impl TextRange {
77 pub const EMPTY: TextRange = TextRange { start: -1, end: -1 };
79
80 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 pub const fn collapsed(offset: i32) -> TextRange {
89 debug_assert!(offset >= -1);
90 TextRange {
91 start: offset,
92 end: offset,
93 }
94 }
95
96 pub fn is_valid(&self) -> bool {
98 self.start >= 0 && self.end >= 0
99 }
100
101 pub fn is_collapsed(&self) -> bool {
103 self.start == self.end
104 }
105
106 pub fn is_normalized(&self) -> bool {
108 self.end >= self.start
109 }
110
111 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 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 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#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct ParagraphConstraints {
139 pub width: f64,
146}
147
148impl ParagraphConstraints {
149 pub const fn new(width: f64) -> ParagraphConstraints {
151 ParagraphConstraints { width }
152 }
153}
154
155#[derive(Clone, Copy, Debug, PartialEq)]
159pub struct TextBox {
160 pub left: f64,
162 pub top: f64,
164 pub right: f64,
166 pub bottom: f64,
168 pub direction: TextDirection,
170}
171
172impl TextBox {
173 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 pub fn to_rect(&self) -> Rect {
192 Rect::from_ltrb(self.left, self.top, self.right, self.bottom)
193 }
194
195 pub fn start(&self) -> f64 {
198 match self.direction {
199 TextDirection::Ltr => self.left,
200 TextDirection::Rtl => self.right,
201 }
202 }
203
204 pub fn end(&self) -> f64 {
207 match self.direction {
208 TextDirection::Ltr => self.right,
209 TextDirection::Rtl => self.left,
210 }
211 }
212}
213
214#[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#[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
241pub enum BoxWidthStyle {
242 #[default]
243 Tight,
244 Max,
245}
246
247#[derive(Clone, Copy, Debug, PartialEq)]
250pub struct GlyphInfo {
251 pub grapheme_cluster_layout_bounds: Rect,
253 pub grapheme_cluster_code_unit_range: TextRange,
255 pub writing_direction: TextDirection,
257}
258
259#[derive(Clone, Copy, Debug, PartialEq)]
261pub struct LineMetrics {
262 pub hard_break: bool,
265 pub ascent: f64,
268 pub descent: f64,
271 pub unscaled_ascent: f64,
274 pub height: f64,
276 pub width: f64,
279 pub left: f64,
281 pub baseline: f64,
283 pub line_number: i32,
285}
286
287#[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 pub fn new() -> TextStyle {
318 TextStyle::default()
319 }
320
321 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 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
415fn 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
427fn 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#[derive(Clone, Debug, Default, PartialEq)]
461pub struct StrutStyle {
462 pub font_family: Option<String>,
467
468 pub font_family_fallback: Option<Vec<String>>,
474
475 pub font_size: Option<f64>,
480
481 pub height: Option<f64>,
485
486 pub leading_distribution: Option<TextLeadingDistribution>,
491
492 pub leading: Option<f64>,
498
499 pub font_weight: Option<FontWeight>,
503
504 pub font_style: Option<FontStyle>,
508
509 pub force_strut_height: Option<bool>,
515}
516
517impl StrutStyle {
518 pub fn new() -> StrutStyle {
520 StrutStyle::default()
521 }
522
523 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 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 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 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#[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 pub strut_style: Option<StrutStyle>,
602}
603
604impl ParagraphStyle {
605 pub fn new() -> ParagraphStyle {
607 ParagraphStyle::default()
608 }
609
610 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 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
654fn 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
663fn 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
707pub struct ParagraphBuilder {
721 paragraph_style: ParagraphStyle,
722 style_stack: Vec<TextStyle>,
723 pieces: Vec<Piece>,
724 placeholder_scales: Vec<f64>,
725}
726
727enum Piece {
730 Text(String, valo::TextStyle),
731 Placeholder(valo::PlaceholderStyle, valo::TextStyle),
732}
733
734impl ParagraphBuilder {
735 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 pub fn placeholder_count(&self) -> i32 {
748 self.placeholder_scales.len() as i32
749 }
750
751 pub fn placeholder_scales(&self) -> &[f64] {
753 &self.placeholder_scales
754 }
755
756 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 pub fn pop(&mut self) {
774 if self.style_stack.len() > 1 {
775 self.style_stack.pop();
776 }
777 }
778
779 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 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 debug_assert!(
848 !matches!(
849 alignment,
850 PlaceholderAlignment::AboveBaseline
851 | PlaceholderAlignment::BelowBaseline
852 | PlaceholderAlignment::Baseline
853 ) || baseline.is_some()
854 );
855 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 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 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 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 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#[derive(Clone, Debug)]
922struct CodeUnits {
923 byte_of: Vec<usize>,
925 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 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 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
959fn byte_of_code_unit(text: &str, code_unit: usize) -> usize {
961 CodeUnits::of(text).byte(code_unit as i32)
962}
963
964pub struct Paragraph {
973 inner: valo::Paragraph,
974 code_units: CodeUnits,
975 direction: TextDirection,
976 strut_sizes_boxes: bool,
979 layout_width: f64,
981 disposed: bool,
982}
983
984impl Paragraph {
985 pub fn width(&self) -> f64 {
991 self.layout_width
992 }
993
994 pub fn height(&self) -> f64 {
998 f64::from(self.inner.height())
999 }
1000
1001 pub fn longest_line(&self) -> f64 {
1004 f64::from(self.inner.longest_line())
1005 }
1006
1007 pub fn min_intrinsic_width(&self) -> f64 {
1010 f64::from(self.inner.min_intrinsic_width())
1011 }
1012
1013 pub fn max_intrinsic_width(&self) -> f64 {
1016 f64::from(self.inner.max_intrinsic_width())
1017 }
1018
1019 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 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 pub fn did_exceed_max_lines(&self) -> bool {
1043 self.inner.truncated()
1044 }
1045
1046 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn number_of_lines(&self) -> i32 {
1322 self.inner.lines().len() as i32
1323 }
1324
1325 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 pub fn dispose(&mut self) {
1342 debug_assert!(!self.disposed);
1343 self.disposed = true;
1344 }
1345
1346 pub fn debug_disposed(&self) -> bool {
1348 self.disposed
1349 }
1350
1351 pub(crate) fn native(&self) -> &valo::Paragraph {
1353 &self.inner
1354 }
1355}
1356
1357fn line_height(line: &valo::Line) -> f64 {
1361 (f64::from(line.ascent) + f64::from(line.descent)).round()
1362}
1363
1364fn 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
1379fn 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
1410fn 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
1442pub trait CanvasText {
1444 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 #[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 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 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 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 #[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 use super::*;
1719 use crate::TargetPlatform;
1720
1721 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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(¶graph, 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 use super::*;
2146 use crate::Platform;
2147
2148 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 #[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 #[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}