1use std::fmt;
10use std::ops::Range;
11
12use crate::fonts::FontCollection;
13use crate::text::{
14 FontFeature, FontStyle, FontVariation, FontWeight, TextAlign, TextBaseline, TextDecoration,
15 TextDecorationStyle, TextDirection, TextHeightBehavior, TextLeadingDistribution,
16};
17use crate::{Canvas, Color, Offset, Paint, Rect, Shadow};
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub struct TextPosition {
27 pub offset: i32,
30 pub affinity: TextAffinity,
33}
34
35impl TextPosition {
36 pub const fn new(offset: i32) -> TextPosition {
39 TextPosition {
40 offset,
41 affinity: TextAffinity::Downstream,
42 }
43 }
44
45 pub const fn with_affinity(offset: i32, affinity: TextAffinity) -> TextPosition {
47 TextPosition { offset, affinity }
48 }
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
54pub enum TextAffinity {
55 Upstream,
58 #[default]
61 Downstream,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
66pub struct TextRange {
67 pub start: i32,
71 pub end: i32,
73}
74
75impl TextRange {
76 pub const EMPTY: TextRange = TextRange { start: -1, end: -1 };
78
79 pub const fn new(start: i32, end: i32) -> TextRange {
81 debug_assert!(start >= -1);
82 debug_assert!(end >= -1);
83 TextRange { start, end }
84 }
85
86 pub const fn collapsed(offset: i32) -> TextRange {
88 debug_assert!(offset >= -1);
89 TextRange {
90 start: offset,
91 end: offset,
92 }
93 }
94
95 pub fn is_valid(&self) -> bool {
97 self.start >= 0 && self.end >= 0
98 }
99
100 pub fn is_collapsed(&self) -> bool {
102 self.start == self.end
103 }
104
105 pub fn is_normalized(&self) -> bool {
107 self.end >= self.start
108 }
109
110 pub fn text_before<'a>(&self, text: &'a str) -> &'a str {
112 debug_assert!(self.is_normalized());
113 let start = byte_of_code_unit(text, self.start as usize);
114 &text[..start]
115 }
116
117 pub fn text_after<'a>(&self, text: &'a str) -> &'a str {
119 debug_assert!(self.is_normalized());
120 let end = byte_of_code_unit(text, self.end as usize);
121 &text[end..]
122 }
123
124 pub fn text_inside<'a>(&self, text: &'a str) -> &'a str {
126 debug_assert!(self.is_normalized());
127 let start = byte_of_code_unit(text, self.start as usize);
128 let end = byte_of_code_unit(text, self.end as usize);
129 &text[start..end]
130 }
131}
132
133#[derive(Clone, Copy, Debug, PartialEq)]
137pub struct ParagraphConstraints {
138 pub width: f64,
145}
146
147impl ParagraphConstraints {
148 pub const fn new(width: f64) -> ParagraphConstraints {
150 ParagraphConstraints { width }
151 }
152}
153
154#[derive(Clone, Copy, Debug, PartialEq)]
158pub struct TextBox {
159 pub left: f64,
161 pub top: f64,
163 pub right: f64,
165 pub bottom: f64,
167 pub direction: TextDirection,
169}
170
171impl TextBox {
172 pub const fn from_ltrbd(
174 left: f64,
175 top: f64,
176 right: f64,
177 bottom: f64,
178 direction: TextDirection,
179 ) -> TextBox {
180 TextBox {
181 left,
182 top,
183 right,
184 bottom,
185 direction,
186 }
187 }
188
189 pub fn to_rect(&self) -> Rect {
191 Rect::from_ltrb(self.left, self.top, self.right, self.bottom)
192 }
193
194 pub fn start(&self) -> f64 {
197 match self.direction {
198 TextDirection::Ltr => self.left,
199 TextDirection::Rtl => self.right,
200 }
201 }
202
203 pub fn end(&self) -> f64 {
206 match self.direction {
207 TextDirection::Ltr => self.right,
208 TextDirection::Rtl => self.left,
209 }
210 }
211}
212
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
215pub enum PlaceholderAlignment {
216 Baseline,
217 AboveBaseline,
218 BelowBaseline,
219 Top,
220 Bottom,
221 Middle,
222}
223
224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
227pub enum BoxHeightStyle {
228 #[default]
229 Tight,
230 Max,
231 IncludeLineSpacingMiddle,
232 IncludeLineSpacingTop,
233 IncludeLineSpacingBottom,
234 Strut,
235}
236
237#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
240pub enum BoxWidthStyle {
241 #[default]
242 Tight,
243 Max,
244}
245
246#[derive(Clone, Copy, Debug, PartialEq)]
249pub struct GlyphInfo {
250 pub grapheme_cluster_layout_bounds: Rect,
252 pub grapheme_cluster_code_unit_range: TextRange,
254 pub writing_direction: TextDirection,
256}
257
258#[derive(Clone, Copy, Debug, PartialEq)]
260pub struct LineMetrics {
261 pub hard_break: bool,
264 pub ascent: f64,
267 pub descent: f64,
270 pub unscaled_ascent: f64,
273 pub height: f64,
275 pub width: f64,
278 pub left: f64,
280 pub baseline: f64,
282 pub line_number: i32,
284}
285
286#[derive(Clone, Debug, Default, PartialEq)]
291pub struct TextStyle {
292 pub color: Option<Color>,
293 pub decoration: Option<TextDecoration>,
294 pub decoration_color: Option<Color>,
295 pub decoration_style: Option<TextDecorationStyle>,
296 pub decoration_thickness: Option<f64>,
297 pub font_weight: Option<FontWeight>,
298 pub font_style: Option<FontStyle>,
299 pub text_baseline: Option<TextBaseline>,
300 pub font_family: Option<String>,
301 pub font_family_fallback: Option<Vec<String>>,
302 pub font_size: Option<f64>,
303 pub letter_spacing: Option<f64>,
304 pub word_spacing: Option<f64>,
305 pub height: Option<f64>,
306 pub leading_distribution: Option<TextLeadingDistribution>,
307 pub background: Option<Paint>,
308 pub foreground: Option<Paint>,
309 pub shadows: Option<Vec<Shadow>>,
310 pub font_features: Option<Vec<FontFeature>>,
311 pub font_variations: Option<Vec<FontVariation>>,
312}
313
314impl TextStyle {
315 pub fn new() -> TextStyle {
317 TextStyle::default()
318 }
319
320 fn merged_with(&self, other: &TextStyle) -> TextStyle {
323 TextStyle {
324 color: other.color.or(self.color),
325 decoration: other.decoration.or(self.decoration),
326 decoration_color: other.decoration_color.or(self.decoration_color),
327 decoration_style: other.decoration_style.or(self.decoration_style),
328 decoration_thickness: other.decoration_thickness.or(self.decoration_thickness),
329 font_weight: other.font_weight.or(self.font_weight),
330 font_style: other.font_style.or(self.font_style),
331 text_baseline: other.text_baseline.or(self.text_baseline),
332 font_family: other
333 .font_family
334 .clone()
335 .or_else(|| self.font_family.clone()),
336 font_family_fallback: other
337 .font_family_fallback
338 .clone()
339 .or_else(|| self.font_family_fallback.clone()),
340 font_size: other.font_size.or(self.font_size),
341 letter_spacing: other.letter_spacing.or(self.letter_spacing),
342 word_spacing: other.word_spacing.or(self.word_spacing),
343 height: other.height.or(self.height),
344 leading_distribution: other.leading_distribution.or(self.leading_distribution),
345 background: other.background.clone().or_else(|| self.background.clone()),
346 foreground: other.foreground.clone().or_else(|| self.foreground.clone()),
347 shadows: other.shadows.clone().or_else(|| self.shadows.clone()),
348 font_features: other
349 .font_features
350 .clone()
351 .or_else(|| self.font_features.clone()),
352 font_variations: other
353 .font_variations
354 .clone()
355 .or_else(|| self.font_variations.clone()),
356 }
357 }
358
359 fn to_native(&self) -> valo::TextStyle {
361 let mut style = valo::TextStyle::default();
362 let mut families = Vec::new();
363 if let Some(family) = &self.font_family {
364 families.push(family.clone());
365 }
366 if let Some(fallback) = &self.font_family_fallback {
367 families.extend(fallback.iter().cloned());
368 }
369 style.families = families;
370 if let Some(weight) = self.font_weight {
371 style.weight = weight.value as u16;
372 }
373 style.italic = self.font_style == Some(FontStyle::Italic);
374 if let Some(size) = self.font_size {
375 style.size = size as f32;
376 }
377 if let Some(foreground) = &self.foreground {
378 style.color = foreground.color;
379 } else if let Some(color) = self.color {
380 style.color = color.into();
381 }
382 style.foreground = self.foreground.clone();
383 style.background = self.background.clone();
384 if let Some(letter_spacing) = self.letter_spacing {
385 style.letter_spacing = letter_spacing as f32;
386 }
387 if let Some(word_spacing) = self.word_spacing {
388 style.word_spacing = word_spacing as f32;
389 }
390 style.height = match self.height {
391 Some(height) if height != crate::text::K_TEXT_HEIGHT_NONE => Some(height as f32),
392 _ => None,
393 };
394 style.leading_distribution = native_leading_distribution(self.leading_distribution);
395 style.decoration = native_decoration(
396 self.decoration,
397 self.decoration_color,
398 self.decoration_thickness,
399 );
400 if let Some(shadows) = &self.shadows {
401 style.shadows = shadows
402 .iter()
403 .map(|shadow| valo::Shadow {
404 color: shadow.color.into(),
405 offset: shadow.offset.into(),
406 blur: shadow.blur_sigma() as f32,
407 })
408 .collect();
409 }
410 style
411 }
412}
413
414fn native_leading_distribution(
416 distribution: Option<TextLeadingDistribution>,
417) -> valo::LeadingDistribution {
418 match distribution {
419 None | Some(TextLeadingDistribution::Proportional) => {
420 valo::LeadingDistribution::Proportional
421 }
422 Some(TextLeadingDistribution::Even) => valo::LeadingDistribution::Even,
423 }
424}
425
426fn native_decoration(
428 decoration: Option<TextDecoration>,
429 color: Option<Color>,
430 thickness: Option<f64>,
431) -> Option<valo::Decoration> {
432 let decoration = decoration?;
433 let kind = if decoration.contains(TextDecoration::UNDERLINE) {
434 valo::DecorationKind::Underline
435 } else if decoration.contains(TextDecoration::OVERLINE) {
436 valo::DecorationKind::Overline
437 } else if decoration.contains(TextDecoration::LINE_THROUGH) {
438 valo::DecorationKind::LineThrough
439 } else {
440 return None;
441 };
442 Some(valo::Decoration {
443 kind,
444 color: color.map(Into::into),
445 thickness: thickness.unwrap_or(1.0) as f32,
446 })
447}
448
449#[derive(Clone, Debug, Default, PartialEq)]
455pub struct ParagraphStyle {
456 pub text_align: Option<TextAlign>,
457 pub text_direction: Option<TextDirection>,
458 pub max_lines: Option<i32>,
459 pub font_family: Option<String>,
460 pub font_size: Option<f64>,
461 pub height: Option<f64>,
462 pub text_height_behavior: Option<TextHeightBehavior>,
463 pub font_weight: Option<FontWeight>,
464 pub font_style: Option<FontStyle>,
465 pub ellipsis: Option<String>,
466}
467
468impl ParagraphStyle {
469 pub fn new() -> ParagraphStyle {
471 ParagraphStyle::default()
472 }
473
474 fn base_text_style(&self) -> TextStyle {
476 TextStyle {
477 font_family: self.font_family.clone(),
478 font_size: self.font_size,
479 height: self.height,
480 leading_distribution: self
481 .text_height_behavior
482 .map(|behavior| behavior.leading_distribution),
483 font_weight: self.font_weight,
484 font_style: self.font_style,
485 ..TextStyle::default()
486 }
487 }
488
489 fn to_native(&self) -> valo::ParagraphStyle {
490 valo::ParagraphStyle {
491 align: native_align(self.text_align, self.text_direction),
492 direction: self.text_direction.map(native_direction),
493 preserve_trailing_whitespace: false,
494 max_lines: self.max_lines.map(|max_lines| max_lines as u32),
495 ellipsis: self.ellipsis.clone(),
496 text_height_behavior: self
497 .text_height_behavior
498 .map(native_height_behavior)
499 .unwrap_or_default(),
500 }
501 }
502}
503
504fn native_height_behavior(behavior: TextHeightBehavior) -> valo::TextHeightBehavior {
507 valo::TextHeightBehavior {
508 apply_height_to_first_ascent: behavior.apply_height_to_first_ascent,
509 apply_height_to_last_descent: behavior.apply_height_to_last_descent,
510 }
511}
512
513fn native_align(align: Option<TextAlign>, direction: Option<TextDirection>) -> valo::TextAlign {
516 match align {
517 None | Some(TextAlign::Left) => valo::TextAlign::Left,
518 Some(TextAlign::Right) => valo::TextAlign::Right,
519 Some(TextAlign::Center) => valo::TextAlign::Center,
520 Some(TextAlign::Justify) => valo::TextAlign::Justify,
521 Some(TextAlign::Start) => match direction {
522 Some(TextDirection::Rtl) => valo::TextAlign::Right,
523 _ => valo::TextAlign::Left,
524 },
525 Some(TextAlign::End) => match direction {
526 Some(TextDirection::Rtl) => valo::TextAlign::Left,
527 _ => valo::TextAlign::Right,
528 },
529 }
530}
531
532fn native_placeholder_alignment(alignment: PlaceholderAlignment) -> valo::PlaceholderAlignment {
533 match alignment {
534 PlaceholderAlignment::Baseline => valo::PlaceholderAlignment::Baseline,
535 PlaceholderAlignment::AboveBaseline => valo::PlaceholderAlignment::AboveBaseline,
536 PlaceholderAlignment::BelowBaseline => valo::PlaceholderAlignment::BelowBaseline,
537 PlaceholderAlignment::Top => valo::PlaceholderAlignment::Top,
538 PlaceholderAlignment::Bottom => valo::PlaceholderAlignment::Bottom,
539 PlaceholderAlignment::Middle => valo::PlaceholderAlignment::Middle,
540 }
541}
542
543fn native_baseline(baseline: TextBaseline) -> valo::TextBaseline {
544 match baseline {
545 TextBaseline::Alphabetic => valo::TextBaseline::Alphabetic,
546 TextBaseline::Ideographic => valo::TextBaseline::Ideographic,
547 }
548}
549
550fn native_direction(direction: TextDirection) -> valo::TextDirection {
551 match direction {
552 TextDirection::Ltr => valo::TextDirection::Ltr,
553 TextDirection::Rtl => valo::TextDirection::Rtl,
554 }
555}
556
557pub struct ParagraphBuilder {
571 paragraph_style: ParagraphStyle,
572 style_stack: Vec<TextStyle>,
573 pieces: Vec<Piece>,
574 placeholder_scales: Vec<f64>,
575}
576
577enum Piece {
580 Text(String, valo::TextStyle),
581 Placeholder(valo::PlaceholderStyle, valo::TextStyle),
582}
583
584impl ParagraphBuilder {
585 pub fn new(style: ParagraphStyle) -> ParagraphBuilder {
587 let base = style.base_text_style();
588 ParagraphBuilder {
589 paragraph_style: style,
590 style_stack: vec![base],
591 pieces: Vec::new(),
592 placeholder_scales: Vec::new(),
593 }
594 }
595
596 pub fn placeholder_count(&self) -> i32 {
598 self.placeholder_scales.len() as i32
599 }
600
601 pub fn placeholder_scales(&self) -> &[f64] {
603 &self.placeholder_scales
604 }
605
606 pub fn push_style(&mut self, style: TextStyle) {
610 let current = self
611 .style_stack
612 .last()
613 .expect("the base style is never popped");
614 let merged = current.merged_with(&style);
615 self.style_stack.push(merged);
616 }
617
618 pub fn pop(&mut self) {
624 if self.style_stack.len() > 1 {
625 self.style_stack.pop();
626 }
627 }
628
629 pub fn add_text(&mut self, text: &str) {
633 let style = self.current_style();
634 self.pieces.push(Piece::Text(text.to_owned(), style));
635 }
636
637 pub fn add_placeholder(
688 &mut self,
689 width: f64,
690 height: f64,
691 alignment: PlaceholderAlignment,
692 scale: f64,
693 baseline_offset: Option<f64>,
694 baseline: Option<TextBaseline>,
695 ) {
696 debug_assert!(
698 !matches!(
699 alignment,
700 PlaceholderAlignment::AboveBaseline
701 | PlaceholderAlignment::BelowBaseline
702 | PlaceholderAlignment::Baseline
703 ) || baseline.is_some()
704 );
705 let baseline_offset = baseline_offset.unwrap_or(height);
708 let placeholder = valo::PlaceholderStyle {
709 width: (width * scale) as f32,
710 height: (height * scale) as f32,
711 alignment: native_placeholder_alignment(alignment),
712 baseline: native_baseline(baseline.unwrap_or(TextBaseline::Alphabetic)),
713 baseline_offset: (baseline_offset * scale) as f32,
714 };
715 let style = self.current_style();
716 self.pieces.push(Piece::Placeholder(placeholder, style));
717 self.placeholder_scales.push(scale);
718 }
719
720 fn current_style(&self) -> valo::TextStyle {
722 self.style_stack
723 .last()
724 .expect("the base style is never popped")
725 .to_native()
726 }
727
728 pub fn build(self, fonts: &mut FontCollection) -> Paragraph {
734 let direction = self
735 .paragraph_style
736 .text_direction
737 .unwrap_or(TextDirection::Ltr);
738 let mut builder = valo::ParagraphBuilder::new(fonts);
739 builder.style(self.paragraph_style.to_native());
740 for piece in &self.pieces {
741 match piece {
742 Piece::Text(text, style) => builder.add_text(text, style),
743 Piece::Placeholder(placeholder, style) => {
744 builder.add_placeholder(*placeholder, style)
745 }
746 };
747 }
748 let inner = builder.build();
749 Paragraph {
750 code_units: CodeUnits::of(inner.text()),
751 inner,
752 direction,
753 layout_width: 0.0,
754 disposed: false,
755 }
756 }
757}
758
759#[derive(Clone, Debug)]
761struct CodeUnits {
762 byte_of: Vec<usize>,
764 len: usize,
766}
767
768impl CodeUnits {
769 fn of(text: &str) -> CodeUnits {
770 let mut byte_of = Vec::with_capacity(text.len() + 1);
771 for (byte, ch) in text.char_indices() {
772 byte_of.push(byte);
773 if ch.len_utf16() == 2 {
774 byte_of.push(byte);
776 }
777 }
778 byte_of.push(text.len());
779 let len = byte_of.len() - 1;
780 CodeUnits { byte_of, len }
781 }
782
783 fn byte(&self, code_unit: i32) -> usize {
784 let clamped = code_unit.clamp(0, self.len as i32) as usize;
785 self.byte_of[clamped]
786 }
787
788 fn code_unit(&self, byte: usize) -> i32 {
790 let first_at_or_after = self.byte_of.partition_point(|candidate| *candidate < byte);
791 match self.byte_of.get(first_at_or_after) {
792 Some(candidate) if *candidate == byte => first_at_or_after as i32,
793 _ => first_at_or_after.saturating_sub(1) as i32,
794 }
795 }
796}
797
798fn byte_of_code_unit(text: &str, code_unit: usize) -> usize {
800 CodeUnits::of(text).byte(code_unit as i32)
801}
802
803pub struct Paragraph {
812 inner: valo::Paragraph,
813 code_units: CodeUnits,
814 direction: TextDirection,
815 layout_width: f64,
817 disposed: bool,
818}
819
820impl Paragraph {
821 pub fn width(&self) -> f64 {
827 self.layout_width
828 }
829
830 pub fn height(&self) -> f64 {
834 f64::from(self.inner.height())
835 }
836
837 pub fn longest_line(&self) -> f64 {
840 f64::from(self.inner.longest_line())
841 }
842
843 pub fn min_intrinsic_width(&self) -> f64 {
846 f64::from(self.inner.min_intrinsic_width())
847 }
848
849 pub fn max_intrinsic_width(&self) -> f64 {
852 f64::from(self.inner.max_intrinsic_width())
853 }
854
855 pub fn alphabetic_baseline(&self) -> f64 {
858 self.inner
859 .lines()
860 .first()
861 .map_or(0.0, |line| f64::from(line.baseline))
862 }
863
864 pub fn ideographic_baseline(&self) -> f64 {
869 self.inner
870 .lines()
871 .first()
872 .map_or(0.0, |line| f64::from(line.baseline + line.descent))
873 }
874
875 pub fn did_exceed_max_lines(&self) -> bool {
879 self.inner.truncated()
880 }
881
882 pub fn layout(&mut self, constraints: ParagraphConstraints) {
886 debug_assert!(!self.disposed);
887 self.layout_width = constraints.width;
888 self.inner.layout(constraints.width as f32);
889 }
890
891 pub fn get_boxes_for_range(
896 &self,
897 start: i32,
898 end: i32,
899 box_height_style: BoxHeightStyle,
900 box_width_style: BoxWidthStyle,
901 ) -> Vec<TextBox> {
902 let _ = (box_height_style, box_width_style);
903 let range = self.code_units.byte(start)..self.code_units.byte(end);
904 self.inner
905 .rects_for_range(range)
906 .into_iter()
907 .map(|rect| text_box(rect, self.direction))
908 .collect()
909 }
910
911 pub fn get_boxes_for_placeholders(&self) -> Vec<TextBox> {
919 self.inner
920 .placeholder_boxes()
921 .into_iter()
922 .map(|placeholder| {
923 let direction = match placeholder.direction {
924 valo::TextDirection::Ltr => TextDirection::Ltr,
925 valo::TextDirection::Rtl => TextDirection::Rtl,
926 };
927 text_box(placeholder.rect, direction)
928 })
929 .collect()
930 }
931
932 pub fn get_position_for_offset(&self, offset: Offset) -> TextPosition {
934 let position = self.inner.glyph_position_at(offset.into());
935 TextPosition::with_affinity(
936 self.code_units.code_unit(position.offset),
937 if position.downstream {
938 TextAffinity::Downstream
939 } else {
940 TextAffinity::Upstream
941 },
942 )
943 }
944
945 pub fn get_closest_glyph_info_for_offset(&self, offset: Offset) -> Option<GlyphInfo> {
949 let position = self.inner.glyph_position_at(offset.into());
950 let anchor = if position.downstream {
951 position.offset
952 } else {
953 position.offset.saturating_sub(1)
954 };
955 self.glyph_info_at_byte(anchor)
956 }
957
958 pub fn get_glyph_info_at(&self, code_unit_offset: i32) -> Option<GlyphInfo> {
961 if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
962 return None;
963 }
964 self.glyph_info_at_byte(self.code_units.byte(code_unit_offset))
965 }
966
967 fn glyph_info_at_byte(&self, byte: usize) -> Option<GlyphInfo> {
970 for line in self.inner.lines() {
971 if !line.range.contains(&byte) {
972 continue;
973 }
974 let top = line.baseline - line.ascent;
975 let bottom = line.baseline + line.descent;
976 let cluster_starts = cluster_starts(line);
977 for run in &line.runs {
978 for glyph in &run.glyphs {
979 let cluster = cluster_range(&cluster_starts, glyph.cluster, line.range.end);
980 if !cluster.contains(&byte) {
981 continue;
982 }
983 let (left, right) = if glyph.advance >= 0.0 {
984 (glyph.x, glyph.x + glyph.advance)
985 } else {
986 (glyph.x + glyph.advance, glyph.x)
987 };
988 return Some(GlyphInfo {
989 grapheme_cluster_layout_bounds: Rect::from_ltrb(
990 f64::from(left),
991 f64::from(top),
992 f64::from(right),
993 f64::from(bottom),
994 ),
995 grapheme_cluster_code_unit_range: TextRange::new(
996 self.code_units.code_unit(cluster.start),
997 self.code_units.code_unit(cluster.end),
998 ),
999 writing_direction: if run.rtl {
1000 TextDirection::Rtl
1001 } else {
1002 TextDirection::Ltr
1003 },
1004 });
1005 }
1006 }
1007 }
1008 None
1009 }
1010
1011 pub fn get_word_boundary(&self, position: TextPosition) -> TextRange {
1013 let range = self
1014 .inner
1015 .word_boundary(self.code_units.byte(position.offset));
1016 self.text_range(range)
1017 }
1018
1019 pub fn get_line_boundary(&self, position: TextPosition) -> TextRange {
1023 let byte = self.code_units.byte(position.offset);
1024 let Some(line) = self.line_containing(byte, position.affinity) else {
1025 return TextRange::EMPTY;
1026 };
1027 let text = self.inner.text();
1028 let mut end = line.range.end;
1029 if end > line.range.start && text.as_bytes().get(end - 1) == Some(&b'\n') {
1030 end -= 1;
1031 }
1032 self.text_range(line.range.start..end)
1033 }
1034
1035 fn line_containing(&self, byte: usize, affinity: TextAffinity) -> Option<&valo::Line> {
1036 let lines = self.inner.lines();
1037 let index = lines.iter().position(|line| {
1038 let starts_next_line = byte == line.range.start && affinity == TextAffinity::Upstream;
1039 (line.range.contains(&byte) && !starts_next_line) || byte == line.range.end
1040 });
1041 index.and_then(|index| lines.get(index)).or_else(|| {
1042 let last = lines.last()?;
1043 (byte >= last.range.end).then_some(last)
1044 })
1045 }
1046
1047 fn text_range(&self, range: Range<usize>) -> TextRange {
1048 TextRange::new(
1049 self.code_units.code_unit(range.start),
1050 self.code_units.code_unit(range.end),
1051 )
1052 }
1053
1054 pub fn compute_line_metrics(&self) -> Vec<LineMetrics> {
1057 let lines = self.inner.lines();
1058 let text = self.inner.text();
1059 lines
1060 .iter()
1061 .enumerate()
1062 .map(|(index, line)| {
1063 let is_last = index + 1 == lines.len();
1064 let ends_with_newline = line.range.end > line.range.start
1065 && text.as_bytes().get(line.range.end - 1) == Some(&b'\n');
1066 LineMetrics {
1067 hard_break: is_last || ends_with_newline,
1068 ascent: f64::from(line.ascent),
1069 descent: f64::from(line.descent),
1070 unscaled_ascent: f64::from(line.ascent),
1071 height: f64::from(line.ascent + line.descent),
1072 width: f64::from(line.width),
1073 left: f64::from(line.left),
1074 baseline: f64::from(line.baseline),
1075 line_number: index as i32,
1076 }
1077 })
1078 .collect()
1079 }
1080
1081 pub fn get_line_metrics_at(&self, line_number: i32) -> Option<LineMetrics> {
1084 if line_number < 0 {
1085 return None;
1086 }
1087 self.compute_line_metrics()
1088 .into_iter()
1089 .nth(line_number as usize)
1090 }
1091
1092 pub fn number_of_lines(&self) -> i32 {
1097 self.inner.lines().len() as i32
1098 }
1099
1100 pub fn get_line_number_at(&self, code_unit_offset: i32) -> Option<i32> {
1103 if code_unit_offset < 0 || code_unit_offset as usize >= self.code_units.len {
1104 return None;
1105 }
1106 let byte = self.code_units.byte(code_unit_offset);
1107 self.inner
1108 .lines()
1109 .iter()
1110 .position(|line| line.range.contains(&byte))
1111 .map(|index| index as i32)
1112 }
1113
1114 pub fn dispose(&mut self) {
1117 debug_assert!(!self.disposed);
1118 self.disposed = true;
1119 }
1120
1121 pub fn debug_disposed(&self) -> bool {
1123 self.disposed
1124 }
1125
1126 pub(crate) fn native(&self) -> &valo::Paragraph {
1128 &self.inner
1129 }
1130}
1131
1132fn text_box(rect: valo::Rect, direction: TextDirection) -> TextBox {
1133 TextBox::from_ltrbd(
1134 f64::from(rect.x),
1135 f64::from(rect.y),
1136 f64::from(rect.x + rect.width),
1137 f64::from(rect.y + rect.height),
1138 direction,
1139 )
1140}
1141
1142fn cluster_starts(line: &valo::Line) -> Vec<usize> {
1145 let mut starts: Vec<usize> = line
1146 .runs
1147 .iter()
1148 .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.cluster))
1149 .collect();
1150 starts.sort_unstable();
1151 starts.dedup();
1152 starts
1153}
1154
1155fn cluster_range(cluster_starts: &[usize], start: usize, line_end: usize) -> Range<usize> {
1156 let next = cluster_starts
1157 .iter()
1158 .find(|candidate| **candidate > start)
1159 .copied()
1160 .unwrap_or(line_end);
1161 start..next.max(start + 1)
1162}
1163
1164impl fmt::Debug for Paragraph {
1165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1166 f.debug_struct("Paragraph")
1167 .field("text", &self.inner.text())
1168 .field("width", &self.width())
1169 .field("height", &self.height())
1170 .finish()
1171 }
1172}
1173
1174pub trait CanvasText {
1176 fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset);
1180}
1181
1182impl CanvasText for Canvas {
1183 fn draw_paragraph(&mut self, paragraph: &Paragraph, offset: Offset) {
1184 valo::DrawParagraphExt::draw_paragraph(self, paragraph.native(), offset);
1185 }
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190 use super::*;
1191
1192 #[test]
1193 fn code_units_map_surrogate_pairs_to_one_character() {
1194 let units = CodeUnits::of("a😀b");
1195 assert_eq!(units.len, 4);
1196 assert_eq!(units.byte(0), 0);
1197 assert_eq!(units.byte(1), 1);
1198 assert_eq!(
1199 units.byte(2),
1200 1,
1201 "the second half of the pair maps to the same byte"
1202 );
1203 assert_eq!(units.byte(3), 5);
1204 assert_eq!(units.byte(4), 6);
1205 assert_eq!(units.code_unit(5), 3);
1206 assert_eq!(units.code_unit(6), 4);
1207 }
1208
1209 #[test]
1213 fn a_spans_paints_reach_valo() {
1214 let outline = Paint {
1215 color: Color::from_argb(255, 0, 0, 0).into(),
1216 style: valo::PaintStyle::Stroke(valo::Stroke::new(2.0)),
1217 ..Paint::default()
1218 };
1219 let box_behind = Paint::from_color(Color::from_argb(160, 0, 0, 0).into());
1220 let style = TextStyle {
1221 foreground: Some(outline.clone()),
1222 background: Some(box_behind.clone()),
1223 ..TextStyle::default()
1224 };
1225 let native = style.to_native();
1226 assert_eq!(native.foreground, Some(outline.clone()));
1227 assert_eq!(native.background, Some(box_behind));
1228 assert_eq!(native.color, outline.color);
1229 }
1230
1231 #[test]
1232 fn text_range_slices_by_code_unit() {
1233 let range = TextRange::new(1, 3);
1234 assert_eq!(range.text_inside("a😀b"), "😀");
1235 assert_eq!(range.text_before("a😀b"), "a");
1236 assert_eq!(range.text_after("a😀b"), "b");
1237 assert!(TextRange::EMPTY.is_collapsed());
1238 assert!(!TextRange::EMPTY.is_valid());
1239 }
1240
1241 #[test]
1242 fn text_box_start_and_end_follow_direction() {
1243 let ltr = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Ltr);
1244 let rtl = TextBox::from_ltrbd(1.0, 2.0, 3.0, 4.0, TextDirection::Rtl);
1245 assert_eq!(ltr.start(), 1.0);
1246 assert_eq!(ltr.end(), 3.0);
1247 assert_eq!(rtl.start(), 3.0);
1248 assert_eq!(rtl.end(), 1.0);
1249 assert_eq!(ltr.to_rect(), Rect::from_ltrb(1.0, 2.0, 3.0, 4.0));
1250 }
1251
1252 fn text_styles(builder: &ParagraphBuilder) -> Vec<&valo::TextStyle> {
1253 builder
1254 .pieces
1255 .iter()
1256 .filter_map(|piece| match piece {
1257 Piece::Text(_, style) => Some(style),
1258 Piece::Placeholder(..) => None,
1259 })
1260 .collect()
1261 }
1262
1263 #[test]
1264 fn placeholders_are_counted_with_their_scales() {
1265 let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1266 builder.add_text("a");
1267 builder.add_placeholder(10.0, 20.0, PlaceholderAlignment::Middle, 2.0, None, None);
1268 builder.add_placeholder(5.0, 5.0, PlaceholderAlignment::Bottom, 1.0, None, None);
1269 assert_eq!(builder.placeholder_count(), 2);
1270 assert_eq!(builder.placeholder_scales(), [2.0, 1.0]);
1271 }
1272
1273 #[test]
1274 fn pushed_styles_inherit_unset_fields() {
1275 let mut builder = ParagraphBuilder::new(ParagraphStyle {
1276 font_size: Some(20.0),
1277 ..ParagraphStyle::default()
1278 });
1279 builder.push_style(TextStyle {
1280 color: Some(Color::from_argb(255, 255, 0, 0)),
1281 ..TextStyle::default()
1282 });
1283 builder.add_text("x");
1284 builder.pop();
1285 builder.add_text("y");
1286 let styles = text_styles(&builder);
1287 assert_eq!(styles[0].size, 20.0, "the child keeps the paragraph's size");
1288 assert_eq!(styles[0].color, Color::from_argb(255, 255, 0, 0).into());
1289 assert_eq!(styles[1].size, 20.0);
1290 assert_eq!(
1291 styles[1].color,
1292 valo::Color::BLACK,
1293 "popping restores the base"
1294 );
1295 }
1296
1297 #[test]
1300 fn the_paragraphs_leading_distribution_is_the_spans_default() {
1301 let mut builder = ParagraphBuilder::new(ParagraphStyle {
1302 text_height_behavior: Some(TextHeightBehavior {
1303 leading_distribution: TextLeadingDistribution::Even,
1304 ..TextHeightBehavior::default()
1305 }),
1306 ..ParagraphStyle::default()
1307 });
1308 builder.add_text("x");
1309 builder.push_style(TextStyle {
1310 leading_distribution: Some(TextLeadingDistribution::Proportional),
1311 ..TextStyle::default()
1312 });
1313 builder.add_text("y");
1314 let styles = text_styles(&builder);
1315 assert_eq!(
1316 styles[0].leading_distribution,
1317 valo::LeadingDistribution::Even
1318 );
1319 assert_eq!(
1320 styles[1].leading_distribution,
1321 valo::LeadingDistribution::Proportional
1322 );
1323 assert_eq!(
1324 ParagraphBuilder::new(ParagraphStyle::new())
1325 .current_style()
1326 .leading_distribution,
1327 valo::LeadingDistribution::Proportional,
1328 "unset is Flutter's default"
1329 );
1330 }
1331
1332 #[test]
1333 fn the_height_flags_reach_valo() {
1334 let style = ParagraphStyle {
1335 text_height_behavior: Some(TextHeightBehavior {
1336 apply_height_to_first_ascent: false,
1337 ..TextHeightBehavior::default()
1338 }),
1339 ..ParagraphStyle::default()
1340 };
1341 assert_eq!(
1342 style.to_native().text_height_behavior,
1343 valo::TextHeightBehavior {
1344 apply_height_to_first_ascent: false,
1345 apply_height_to_last_descent: true,
1346 }
1347 );
1348 assert_eq!(
1349 ParagraphStyle::new().to_native().text_height_behavior,
1350 valo::TextHeightBehavior::default()
1351 );
1352 }
1353
1354 #[test]
1355 fn start_and_end_alignment_resolve_against_direction() {
1356 assert_eq!(
1357 native_align(Some(TextAlign::Start), Some(TextDirection::Rtl)),
1358 valo::TextAlign::Right
1359 );
1360 assert_eq!(
1361 native_align(Some(TextAlign::End), None),
1362 valo::TextAlign::Right,
1363 "no direction reads as LTR"
1364 );
1365 }
1366
1367 #[test]
1368 fn unspecified_font_family_stays_unset_on_the_native_style() {
1369 let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1370 builder.add_text("x");
1371 assert!(
1372 text_styles(&builder)[0].families.is_empty(),
1373 "dart:ui leaves fontFamily unset; the collection's default manager supplies the face"
1374 );
1375 }
1376}
1377
1378#[cfg(test)]
1379mod layout_tests {
1380 use super::*;
1383 use crate::Platform;
1384
1385 fn fonts() -> FontCollection {
1386 let mut fonts = FontCollection::new();
1387 fonts.add_source(valo_system_fonts::SystemFonts::load());
1388 fonts
1389 }
1390
1391 fn paragraph(text: &str, style: ParagraphStyle, width: f64) -> Paragraph {
1392 let mut builder = ParagraphBuilder::new(style);
1393 builder.push_style(TextStyle {
1394 font_size: Some(20.0),
1395 ..TextStyle::default()
1396 });
1397 builder.add_text(text);
1398 let mut paragraph = builder.build(&mut fonts());
1399 paragraph.layout(ParagraphConstraints::new(width));
1400 paragraph
1401 }
1402
1403 #[test]
1404 fn a_laid_out_paragraph_has_a_size_and_one_line() {
1405 let paragraph = paragraph("Hello", ParagraphStyle::new(), f64::INFINITY);
1406 assert_eq!(
1407 paragraph.width(),
1408 f64::INFINITY,
1409 "the layout width, as in Skia"
1410 );
1411 assert!(paragraph.longest_line() > 0.0);
1412 assert!(paragraph.height() > 0.0);
1413 assert_eq!(paragraph.number_of_lines(), 1);
1414 assert!(paragraph.alphabetic_baseline() > 0.0);
1415 assert!(paragraph.alphabetic_baseline() < paragraph.height());
1416 assert!(!paragraph.did_exceed_max_lines());
1417 assert_eq!(paragraph.max_intrinsic_width(), paragraph.longest_line());
1418 }
1419
1420 #[test]
1421 fn a_narrow_width_wraps_onto_more_lines() {
1422 let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
1423 let narrow = paragraph(
1424 "one two three four",
1425 ParagraphStyle::new(),
1426 wide.longest_line() / 2.0,
1427 );
1428 assert!(narrow.number_of_lines() > 1);
1429 assert!(narrow.height() > wide.height());
1430 let metrics = narrow.compute_line_metrics();
1431 assert_eq!(metrics.len() as i32, narrow.number_of_lines());
1432 assert!(
1433 metrics.last().unwrap().hard_break,
1434 "the last line is a hard break"
1435 );
1436 assert!(!metrics[0].hard_break, "a wrapped line is a soft break");
1437 assert_eq!(metrics[1].line_number, 1);
1438 }
1439
1440 #[test]
1441 fn max_lines_with_an_ellipsis_truncates() {
1442 let wide = paragraph("one two three four", ParagraphStyle::new(), f64::INFINITY);
1443 let style = ParagraphStyle {
1444 max_lines: Some(1),
1445 ellipsis: Some("\u{2026}".to_owned()),
1446 ..ParagraphStyle::default()
1447 };
1448 let clipped = paragraph("one two three four", style, wide.longest_line() / 2.0);
1449 assert_eq!(clipped.number_of_lines(), 1);
1450 assert!(clipped.did_exceed_max_lines());
1451 }
1452
1453 #[test]
1454 fn positions_boxes_and_boundaries_use_code_units() {
1455 let paragraph = paragraph("ab cd", ParagraphStyle::new(), f64::INFINITY);
1456 let start = paragraph.get_position_for_offset(Offset::new(0.0, 1.0));
1457 assert_eq!(start.offset, 0);
1458 let end =
1459 paragraph.get_position_for_offset(Offset::new(paragraph.longest_line() + 50.0, 1.0));
1460 assert_eq!(end.offset, 5);
1461
1462 let boxes =
1463 paragraph.get_boxes_for_range(0, 2, BoxHeightStyle::Tight, BoxWidthStyle::Tight);
1464 assert_eq!(boxes.len(), 1);
1465 assert!(boxes[0].right > boxes[0].left);
1466 assert_eq!(boxes[0].direction, TextDirection::Ltr);
1467
1468 assert_eq!(
1469 paragraph.get_word_boundary(TextPosition::new(4)),
1470 TextRange::new(3, 5)
1471 );
1472 assert_eq!(
1473 paragraph.get_line_boundary(TextPosition::new(1)),
1474 TextRange::new(0, 5)
1475 );
1476 assert_eq!(paragraph.get_line_number_at(4), Some(0));
1477 assert_eq!(paragraph.get_line_number_at(5), None);
1478
1479 let glyph = paragraph.get_glyph_info_at(3).expect("the c glyph");
1480 assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(3, 4));
1481 assert!(glyph.grapheme_cluster_layout_bounds.width() > 0.0);
1482 assert!(paragraph.get_glyph_info_at(5).is_none());
1483 }
1484
1485 #[test]
1486 fn a_surrogate_pair_is_one_glyph_of_two_code_units() {
1487 let paragraph = paragraph("a😀b", ParagraphStyle::new(), f64::INFINITY);
1488 let glyph = paragraph.get_glyph_info_at(1).expect("the emoji");
1489 assert_eq!(glyph.grapheme_cluster_code_unit_range, TextRange::new(1, 3));
1490 assert_eq!(
1491 paragraph
1492 .get_glyph_info_at(3)
1493 .unwrap()
1494 .grapheme_cluster_code_unit_range,
1495 TextRange::new(3, 4)
1496 );
1497 }
1498
1499 #[test]
1502 fn the_closest_glyph_is_the_one_under_the_point() {
1503 let paragraph = paragraph("abc", ParagraphStyle::new(), f64::INFINITY);
1504 let b = paragraph.get_glyph_info_at(1).expect("the b glyph");
1505 let bounds = b.grapheme_cluster_layout_bounds;
1506 let y = bounds.center().dy();
1507 for x in [bounds.left + 0.5, bounds.right - 0.5] {
1508 let closest = paragraph
1509 .get_closest_glyph_info_for_offset(Offset::new(x, y))
1510 .expect("a glyph");
1511 assert_eq!(
1512 closest.grapheme_cluster_code_unit_range,
1513 TextRange::new(1, 2)
1514 );
1515 }
1516 let past_the_end = paragraph
1517 .get_closest_glyph_info_for_offset(Offset::new(1000.0, y))
1518 .expect("a glyph");
1519 assert_eq!(
1520 past_the_end.grapheme_cluster_code_unit_range,
1521 TextRange::new(2, 3)
1522 );
1523 }
1524
1525 #[test]
1526 fn placeholder_boxes_come_in_the_order_added_at_their_scaled_size() {
1527 let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1528 builder.push_style(TextStyle {
1529 font_size: Some(20.0),
1530 ..TextStyle::default()
1531 });
1532 builder.add_text("ab");
1533 builder.add_placeholder(
1534 30.0,
1535 50.0,
1536 PlaceholderAlignment::Baseline,
1537 1.0,
1538 Some(40.0),
1539 Some(TextBaseline::Alphabetic),
1540 );
1541 builder.add_text("cd");
1542 builder.add_placeholder(10.0, 10.0, PlaceholderAlignment::Bottom, 2.0, None, None);
1543 let mut paragraph = builder.build(&mut fonts());
1544 paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
1545
1546 let boxes = paragraph.get_boxes_for_placeholders();
1547 assert_eq!(boxes.len(), 2);
1548 let baseline = paragraph.alphabetic_baseline();
1549 let (first, second) = (boxes[0], boxes[1]);
1550 assert!((first.right - first.left - 30.0).abs() < 1e-3);
1551 assert!(
1552 (first.top - (baseline - 40.0)).abs() < 1e-3,
1553 "40 above the baseline"
1554 );
1555 assert!(
1556 (first.bottom - (baseline + 10.0)).abs() < 1e-3,
1557 "10 below it"
1558 );
1559 assert!(
1560 (second.right - second.left - 20.0).abs() < 1e-3,
1561 "scaled by 2"
1562 );
1563 assert!((second.bottom - second.top - 20.0).abs() < 1e-3);
1564 assert!(second.left > first.right, "after the text between them");
1565 assert_eq!(
1566 paragraph.get_line_boundary(TextPosition::new(0)),
1567 TextRange::new(0, 6),
1568 "each placeholder is one code unit"
1569 );
1570 }
1571
1572 #[test]
1573 fn drawing_records_the_paragraph() {
1574 let paragraph = paragraph("Hi", ParagraphStyle::new(), f64::INFINITY);
1575 let mut canvas = Canvas::new();
1576 canvas.draw_paragraph(¶graph, Offset::new(10.0, 10.0));
1577 let picture = canvas.build();
1578 assert!(!picture.ops().is_empty());
1579 }
1580
1581 #[test]
1582 fn unspecified_family_at_black_weight_covers_latin() {
1583 let mut fonts = FontCollection::new();
1584 crate::set_default_font_manager(
1585 &mut fonts,
1586 Box::new(crate::SystemFontSource::platform()),
1587 &crate::InertPlatform.default_font_families(),
1588 );
1589 let mut builder = ParagraphBuilder::new(ParagraphStyle::new());
1590 builder.push_style(TextStyle {
1591 font_size: Some(10.2),
1592 font_weight: Some(FontWeight::W900),
1593 ..TextStyle::default()
1594 });
1595 builder.add_text("DEBUG");
1596 let mut paragraph = builder.build(&mut fonts);
1597 paragraph.layout(ParagraphConstraints::new(f64::INFINITY));
1598 assert!(paragraph.longest_line() > 0.0);
1599 assert!(
1600 fonts.take_unanswered().is_empty(),
1601 "the engine default family covers Latin at weight 900"
1602 );
1603 for line in paragraph.inner.lines() {
1604 for run in &line.runs {
1605 assert!(
1606 run.glyphs.iter().all(|glyph| glyph.id != 0),
1607 "no .notdef tofu"
1608 );
1609 }
1610 }
1611 }
1612}