1use std::cell::OnceCell;
7
8use waft_embedder::{
9 BoxHeightStyle, BoxWidthStyle, Canvas, CanvasText, Color, FontCollection, GlyphInfo,
10 LineMetrics, Offset, Paint, PaintStyle, Paragraph, ParagraphBuilder, ParagraphConstraints,
11 ParagraphStyle, Rect, Size, Stroke, TextAffinity, TextAlign, TextBaseline, TextBox,
12 TextDirection, TextHeightBehavior, TextPosition, TextRange, TextSelection, clamp_double,
13};
14use waft_foundation::PRECISION_ERROR_TOLERANCE;
15
16use crate::basic_types::RenderComparison;
17use crate::inline_span::{InlineSpanRef, utf16_len};
18use crate::strut_style::StrutStyle;
19use crate::text_scaler::TextScaler;
20use crate::text_style::TextStyle;
21
22pub const K_DEFAULT_FONT_SIZE: f64 = 14.0;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum TextOverflow {
35 Clip,
37
38 Fade,
40
41 Ellipsis,
43
44 Visible,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct PlaceholderDimensions {
55 pub size: Size,
57 pub alignment: waft_embedder::PlaceholderAlignment,
59 pub baseline_offset: Option<f64>,
61 pub baseline: Option<TextBaseline>,
64}
65
66impl PlaceholderDimensions {
67 pub const EMPTY: PlaceholderDimensions = PlaceholderDimensions {
69 size: Size::ZERO,
70 alignment: waft_embedder::PlaceholderAlignment::Bottom,
71 baseline_offset: None,
72 baseline: None,
73 };
74
75 pub const fn new(
77 size: Size,
78 alignment: waft_embedder::PlaceholderAlignment,
79 ) -> PlaceholderDimensions {
80 PlaceholderDimensions {
81 size,
82 alignment,
83 baseline_offset: None,
84 baseline: None,
85 }
86 }
87}
88
89#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
91pub enum TextWidthBasis {
92 #[default]
96 Parent,
97
98 LongestLine,
101}
102
103fn is_newline(code_point: u32) -> bool {
105 matches!(
106 code_point,
107 0x000A | 0x0085 | 0x000B | 0x000C | 0x2028 | 0x2029 )
114}
115
116struct TextLayout {
118 paragraph: Paragraph,
119 writing_direction: TextDirection,
120 end_of_text_caret_metrics: OnceCell<LineCaretMetrics>,
121}
122
123impl TextLayout {
124 fn new(paragraph: Paragraph, writing_direction: TextDirection) -> TextLayout {
125 TextLayout {
126 paragraph,
127 writing_direction,
128 end_of_text_caret_metrics: OnceCell::new(),
129 }
130 }
131
132 fn height(&self) -> f64 {
133 self.paragraph.height()
134 }
135
136 fn min_intrinsic_line_extent(&self) -> f64 {
137 self.paragraph.min_intrinsic_width()
138 }
139
140 fn max_intrinsic_line_extent(&self) -> f64 {
141 self.paragraph.max_intrinsic_width()
142 }
143
144 fn longest_line(&self) -> f64 {
145 self.paragraph.longest_line()
146 }
147
148 fn get_distance_to_baseline(&self, baseline: TextBaseline) -> f64 {
149 match baseline {
150 TextBaseline::Alphabetic => self.paragraph.alphabetic_baseline(),
151 TextBaseline::Ideographic => self.paragraph.ideographic_baseline(),
152 }
153 }
154
155 fn end_of_text_caret_metrics(&self, plain_text: &str) -> LineCaretMetrics {
157 *self
158 .end_of_text_caret_metrics
159 .get_or_init(|| self.compute_end_of_text_caret_anchor_offset(plain_text))
160 }
161
162 fn compute_end_of_text_caret_anchor_offset(&self, raw_string: &str) -> LineCaretMetrics {
163 let last_line_index = self.paragraph.number_of_lines() - 1;
164 debug_assert!(last_line_index >= 0);
165 let line_metrics = self
166 .paragraph
167 .get_line_metrics_at(last_line_index)
168 .expect("the last line exists");
169 let last_code_unit = raw_string.encode_utf16().last().unwrap_or(0);
170 let has_trailing_spaces = match last_code_unit {
171 0x0009 => true, 0x00A0 | 0x2007 | 0x202F => false, unit => char::from_u32(u32::from(unit)).is_some_and(is_space_separator),
174 };
175 let baseline = line_metrics.baseline;
176 let last_glyph = self.paragraph.get_glyph_info_at(utf16_len(raw_string) - 1);
177 let (dx, height) = match last_glyph {
178 Some(last_glyph) if has_trailing_spaces => {
179 let glyph_bounds = last_glyph.grapheme_cluster_layout_bounds;
180 debug_assert!(!glyph_bounds.is_empty());
181 let dx = match self.writing_direction {
182 TextDirection::Ltr => glyph_bounds.right,
183 TextDirection::Rtl => glyph_bounds.left,
184 };
185 (dx, glyph_bounds.height())
186 }
187 _ => {
188 let dx = match self.writing_direction {
189 TextDirection::Ltr => line_metrics.left + line_metrics.width,
190 TextDirection::Rtl => line_metrics.left,
191 };
192 (dx, line_metrics.height)
193 }
194 };
195 LineCaretMetrics {
196 offset: Offset::new(dx, baseline),
197 writing_direction: self.writing_direction,
198 height,
199 }
200 }
201
202 fn content_width_for(
203 &self,
204 min_width: f64,
205 max_width: f64,
206 width_basis: TextWidthBasis,
207 ) -> f64 {
208 match width_basis {
209 TextWidthBasis::LongestLine => clamp_double(self.longest_line(), min_width, max_width),
210 TextWidthBasis::Parent => {
211 clamp_double(self.max_intrinsic_line_extent(), min_width, max_width)
212 }
213 }
214 }
215}
216
217fn is_space_separator(ch: char) -> bool {
219 matches!(
220 ch,
221 '\u{0020}' | '\u{00A0}' | '\u{1680}' | '\u{2000}'
222 ..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
223 )
224}
225
226struct TextPainterLayoutCacheWithOffset {
231 layout: TextLayout,
232 layout_max_width: f64,
234 content_width: f64,
237 text_alignment: f64,
240 cached_inline_placeholder_boxes: Option<Vec<TextBox>>,
241 cached_line_metrics: Option<Vec<LineMetrics>>,
242 previous_caret_position_key: Option<i32>,
244}
245
246impl TextPainterLayoutCacheWithOffset {
247 fn new(
248 layout: TextLayout,
249 text_alignment: f64,
250 layout_max_width: f64,
251 content_width: f64,
252 ) -> TextPainterLayoutCacheWithOffset {
253 debug_assert!((0.0..=1.0).contains(&text_alignment));
254 debug_assert!(!layout_max_width.is_nan());
255 debug_assert!(!content_width.is_nan());
256 TextPainterLayoutCacheWithOffset {
257 layout,
258 layout_max_width,
259 content_width,
260 text_alignment,
261 cached_inline_placeholder_boxes: None,
262 cached_line_metrics: None,
263 previous_caret_position_key: None,
264 }
265 }
266
267 fn paint_offset(&self) -> Offset {
269 if self.text_alignment == 0.0 {
270 return Offset::ZERO;
271 }
272 if !self.paragraph().width().is_finite() {
273 return Offset::new(f64::INFINITY, 0.0);
274 }
275 let dx = self.text_alignment * (self.content_width - self.paragraph().width());
276 debug_assert!(!dx.is_nan());
277 Offset::new(dx, 0.0)
278 }
279
280 fn paragraph(&self) -> &Paragraph {
281 &self.layout.paragraph
282 }
283
284 fn resize_to_fit(
289 &mut self,
290 min_width: f64,
291 max_width: f64,
292 width_basis: TextWidthBasis,
293 ) -> bool {
294 debug_assert!(self.layout.max_intrinsic_line_extent().is_finite());
295 debug_assert!(min_width <= max_width);
296 if max_width == self.content_width && min_width == self.content_width {
300 self.content_width = self
301 .layout
302 .content_width_for(min_width, max_width, width_basis);
303 return true;
304 }
305
306 if !self.paint_offset().dx().is_finite()
312 && !self.paragraph().width().is_finite()
313 && min_width.is_finite()
314 {
315 debug_assert!(self.paint_offset().dx() == f64::INFINITY);
316 debug_assert!(self.paragraph().width() == f64::INFINITY);
317 return false;
318 }
319
320 let max_intrinsic_width = self.paragraph().max_intrinsic_width();
321 let skip_line_breaking = max_width == self.layout_max_width || ((self.paragraph().width() - max_intrinsic_width) > -PRECISION_ERROR_TOLERANCE
325 && (max_width - max_intrinsic_width) > -PRECISION_ERROR_TOLERANCE);
326 if skip_line_breaking {
327 self.content_width = self
329 .layout
330 .content_width_for(min_width, max_width, width_basis);
331 return true;
332 }
333 false
334 }
335
336 fn inline_placeholder_boxes(&mut self) -> &[TextBox] {
339 self.cached_inline_placeholder_boxes
340 .get_or_insert_with(|| self.layout.paragraph.get_boxes_for_placeholders())
341 }
342
343 fn line_metrics(&mut self) -> &[LineMetrics] {
344 self.cached_line_metrics
345 .get_or_insert_with(|| self.layout.paragraph.compute_line_metrics())
346 }
347}
348
349#[derive(Clone, Copy, Debug, PartialEq)]
352struct LineCaretMetrics {
353 offset: Offset,
356 writing_direction: TextDirection,
359 height: f64,
361}
362
363impl LineCaretMetrics {
364 fn shift(&self, offset: Offset) -> LineCaretMetrics {
365 if offset == Offset::ZERO {
366 *self
367 } else {
368 LineCaretMetrics {
369 offset: offset + self.offset,
370 writing_direction: self.writing_direction,
371 height: self.height,
372 }
373 }
374 }
375}
376
377pub struct TextPainter {
398 text: Option<InlineSpanRef>,
399 text_align: TextAlign,
400 text_direction: Option<TextDirection>,
401 text_scaler: TextScaler,
402 ellipsis: Option<String>,
403 max_lines: Option<i32>,
404 text_width_basis: TextWidthBasis,
405 text_height_behavior: Option<TextHeightBehavior>,
406 strut_style: Option<StrutStyle>,
407 placeholder_dimensions: Option<Vec<PlaceholderDimensions>>,
408 layout_cache: Option<TextPainterLayoutCacheWithOffset>,
409 layout_template: Option<Paragraph>,
410 rebuild_paragraph_for_paint: bool,
418 cached_plain_text: Option<String>,
419 caret_metrics: Option<LineCaretMetrics>,
420 debug_needs_relayout: bool,
421 pub debug_paint_text_layout_boxes: bool,
423 disposed: bool,
424}
425
426impl Default for TextPainter {
427 fn default() -> TextPainter {
428 TextPainter::new()
429 }
430}
431
432impl TextPainter {
433 pub fn new() -> TextPainter {
438 TextPainter {
439 text: None,
440 text_align: TextAlign::Start,
441 text_direction: None,
442 text_scaler: TextScaler::NO_SCALING,
443 ellipsis: None,
444 max_lines: None,
445 text_width_basis: TextWidthBasis::Parent,
446 text_height_behavior: None,
447 strut_style: None,
448 placeholder_dimensions: None,
449 layout_cache: None,
450 layout_template: None,
451 rebuild_paragraph_for_paint: true,
452 cached_plain_text: None,
453 caret_metrics: None,
454 debug_needs_relayout: true,
455 debug_paint_text_layout_boxes: false,
456 disposed: false,
457 }
458 }
459
460 pub fn compute_width(
467 fonts: &mut FontCollection,
468 text: InlineSpanRef,
469 text_direction: TextDirection,
470 min_width: f64,
471 max_width: f64,
472 ) -> f64 {
473 let mut painter = TextPainter::new();
474 painter.set_text(Some(text));
475 painter.set_text_direction(Some(text_direction));
476 painter.layout(fonts, min_width, max_width);
477 let width = painter.width();
478 painter.dispose();
479 width
480 }
481
482 pub fn compute_max_intrinsic_width(
488 fonts: &mut FontCollection,
489 text: InlineSpanRef,
490 text_direction: TextDirection,
491 min_width: f64,
492 max_width: f64,
493 ) -> f64 {
494 let mut painter = TextPainter::new();
495 painter.set_text(Some(text));
496 painter.set_text_direction(Some(text_direction));
497 painter.layout(fonts, min_width, max_width);
498 let width = painter.max_intrinsic_width();
499 painter.dispose();
500 width
501 }
502
503 fn debug_assert_text_layout_is_valid(&self) -> bool {
504 debug_assert!(!self.debug_disposed());
505 assert!(
506 self.layout_cache.is_some(),
507 "Text layout not available: the TextPainter has never been laid out."
508 );
509 true
510 }
511
512 pub fn mark_needs_layout(&mut self) {
517 if let Some(mut cache) = self.layout_cache.take() {
518 cache.layout.paragraph.dispose();
519 }
520 }
521
522 pub fn text(&self) -> Option<&InlineSpanRef> {
527 self.text.as_ref()
528 }
529
530 pub fn set_text(&mut self, value: Option<InlineSpanRef>) {
532 debug_assert!(
533 value
534 .as_ref()
535 .is_none_or(|value| value.debug_assert_is_valid())
536 );
537 let same = match (&self.text, &value) {
538 (None, None) => true,
539 (Some(current), Some(value)) => current.eq_span(&**value),
540 _ => false,
541 };
542 if same {
543 return;
544 }
545 let style_changed = self.text.as_ref().and_then(|text| text.style())
546 != value.as_ref().and_then(|value| value.style());
547 if style_changed && let Some(mut template) = self.layout_template.take() {
548 template.dispose();
549 }
550
551 let comparison = match (&self.text, &value) {
552 (_, None) => RenderComparison::Layout,
553 (Some(current), Some(value)) => current.compare_to(&**value),
554 (None, Some(_)) => RenderComparison::Layout,
555 };
556
557 self.text = value;
558 self.cached_plain_text = None;
559
560 if comparison >= RenderComparison::Layout {
561 self.mark_needs_layout();
562 } else if comparison >= RenderComparison::Paint {
563 self.rebuild_paragraph_for_paint = true;
566 }
567 }
569
570 pub fn plain_text(&mut self) -> &str {
575 if self.cached_plain_text.is_none() {
576 self.cached_plain_text = Some(
577 self.text
578 .as_ref()
579 .map(|text| text.to_plain_text(false, true))
580 .unwrap_or_default(),
581 );
582 }
583 self.cached_plain_text.as_deref().unwrap_or("")
584 }
585
586 pub fn text_align(&self) -> TextAlign {
593 self.text_align
594 }
595
596 pub fn set_text_align(&mut self, value: TextAlign) {
598 if self.text_align == value {
599 return;
600 }
601 self.text_align = value;
602 self.mark_needs_layout();
603 }
604
605 pub fn text_direction(&self) -> Option<TextDirection> {
621 self.text_direction
622 }
623
624 pub fn set_text_direction(&mut self, value: Option<TextDirection>) {
626 if self.text_direction == value {
627 return;
628 }
629 self.text_direction = value;
630 self.mark_needs_layout();
631 if let Some(mut template) = self.layout_template.take() {
633 template.dispose();
634 }
635 }
636
637 pub fn text_scaler(&self) -> &TextScaler {
648 &self.text_scaler
649 }
650
651 pub fn set_text_scaler(&mut self, value: TextScaler) {
653 if value == self.text_scaler {
654 return;
655 }
656 self.text_scaler = value;
657 self.mark_needs_layout();
658 if let Some(mut template) = self.layout_template.take() {
659 template.dispose();
660 }
661 }
662
663 pub fn ellipsis(&self) -> Option<&str> {
679 self.ellipsis.as_deref()
680 }
681
682 pub fn set_ellipsis(&mut self, value: Option<String>) {
684 debug_assert!(value.as_ref().is_none_or(|value| !value.is_empty()));
685 if self.ellipsis == value {
686 return;
687 }
688 self.ellipsis = value;
689 self.mark_needs_layout();
690 }
691
692 pub fn max_lines(&self) -> Option<i32> {
700 self.max_lines
701 }
702
703 pub fn set_max_lines(&mut self, value: Option<i32>) {
706 debug_assert!(value.is_none_or(|value| value > 0));
707 if self.max_lines == value {
708 return;
709 }
710 self.max_lines = value;
711 self.mark_needs_layout();
712 }
713
714 pub fn strut_style(&self) -> Option<&StrutStyle> {
723 self.strut_style.as_ref()
724 }
725
726 pub fn set_strut_style(&mut self, value: Option<StrutStyle>) {
728 if self.strut_style == value {
729 return;
730 }
731 self.strut_style = value;
732 self.mark_needs_layout();
733 }
734
735 pub fn text_width_basis(&self) -> TextWidthBasis {
737 self.text_width_basis
738 }
739
740 pub fn set_text_width_basis(&mut self, value: TextWidthBasis) {
742 if self.text_width_basis == value {
743 return;
744 }
745 if cfg!(debug_assertions) {
746 self.debug_needs_relayout = true;
747 }
748 self.text_width_basis = value;
749 }
750
751 pub fn text_height_behavior(&self) -> Option<TextHeightBehavior> {
753 self.text_height_behavior
754 }
755
756 pub fn set_text_height_behavior(&mut self, value: Option<TextHeightBehavior>) {
758 if self.text_height_behavior == value {
759 return;
760 }
761 self.text_height_behavior = value;
762 self.mark_needs_layout();
763 }
764
765 pub fn inline_placeholder_boxes(&mut self) -> Option<Vec<TextBox>> {
771 let layout = self.layout_cache.as_mut()?;
772 let offset = layout.paint_offset();
773 if !offset.dx().is_finite() || !offset.dy().is_finite() {
774 return Some(Vec::new());
775 }
776 let raw_boxes = layout.inline_placeholder_boxes();
777 if offset == Offset::ZERO {
778 return Some(raw_boxes.to_vec());
779 }
780 Some(
781 raw_boxes
782 .iter()
783 .map(|text_box| shift_text_box(*text_box, offset))
784 .collect(),
785 )
786 }
787
788 pub fn set_placeholder_dimensions(&mut self, value: Option<Vec<PlaceholderDimensions>>) {
797 let Some(value) = value else {
798 return;
799 };
800 if value.is_empty() || Some(&value) == self.placeholder_dimensions.as_ref() {
801 return;
802 }
803 if cfg!(debug_assertions) {
804 let mut placeholder_count = 0;
805 if let Some(text) = &self.text {
806 text.clone().visit_children(&mut |span| {
807 if span.as_placeholder_span().is_some() {
808 placeholder_count += 1;
809 }
810 value.len() >= placeholder_count
811 });
812 }
813 assert_eq!(placeholder_count, value.len());
814 }
815 self.placeholder_dimensions = Some(value);
816 self.mark_needs_layout();
817 }
818
819 fn create_paragraph_style(&self, text_align_override: Option<TextAlign>) -> ParagraphStyle {
820 debug_assert!(
821 self.text_direction.is_some(),
822 "TextPainter.textDirection must be set to a non-null value before using the TextPainter."
823 );
824 let default_style = TextStyle::new();
825 let base_style = self
826 .text
827 .as_ref()
828 .and_then(|text| text.style())
829 .unwrap_or(&default_style);
830 let mut paragraph_style = base_style
831 .get_paragraph_style()
832 .text_align(text_align_override.unwrap_or(self.text_align))
833 .text_scaler(self.text_scaler.clone());
834 if let Some(text_direction) = self.text_direction {
835 paragraph_style = paragraph_style.text_direction(text_direction);
836 }
837 if let Some(max_lines) = self.max_lines {
838 paragraph_style = paragraph_style.max_lines(max_lines);
839 }
840 if let Some(text_height_behavior) = self.text_height_behavior {
841 paragraph_style = paragraph_style.text_height_behavior(text_height_behavior);
842 }
843 if let Some(ellipsis) = &self.ellipsis {
844 paragraph_style = paragraph_style.ellipsis(ellipsis.clone());
845 }
846 if let Some(strut_style) = &self.strut_style {
847 paragraph_style = paragraph_style.strut_style(strut_style.clone());
848 }
849 paragraph_style.build()
850 }
851
852 fn create_layout_template(&self, fonts: &mut FontCollection) -> Paragraph {
853 let mut builder = ParagraphBuilder::new(self.create_paragraph_style(Some(TextAlign::Left)));
855 let text_style = self
856 .text
857 .as_ref()
858 .and_then(|text| text.style())
859 .map(|style| style.get_text_style_with(&self.text_scaler));
860 if let Some(text_style) = text_style {
861 builder.push_style(text_style);
862 }
863 builder.add_text(" ");
864 let mut template = builder.build(fonts);
865 template.layout(ParagraphConstraints::new(f64::INFINITY));
866 template
867 }
868
869 fn get_or_create_layout_template(&mut self, fonts: &mut FontCollection) -> &Paragraph {
870 if self.layout_template.is_none() {
871 self.layout_template = Some(self.create_layout_template(fonts));
872 }
873 self.layout_template.as_ref().expect("just created")
874 }
875
876 pub fn preferred_line_height(&mut self, fonts: &mut FontCollection) -> f64 {
889 self.get_or_create_layout_template(fonts).height()
890 }
891
892 pub fn min_intrinsic_width(&self) -> f64 {
897 debug_assert!(self.debug_assert_text_layout_is_valid());
898 self.layout_cache().layout.min_intrinsic_line_extent()
899 }
900
901 pub fn max_intrinsic_width(&self) -> f64 {
905 debug_assert!(self.debug_assert_text_layout_is_valid());
906 self.layout_cache().layout.max_intrinsic_line_extent()
907 }
908
909 pub fn width(&self) -> f64 {
913 debug_assert!(self.debug_assert_text_layout_is_valid());
914 debug_assert!(!self.debug_needs_relayout);
915 self.layout_cache().content_width
916 }
917
918 pub fn height(&self) -> f64 {
922 debug_assert!(self.debug_assert_text_layout_is_valid());
923 self.layout_cache().layout.height()
924 }
925
926 pub fn size(&self) -> Size {
930 debug_assert!(self.debug_assert_text_layout_is_valid());
931 debug_assert!(!self.debug_needs_relayout);
932 Size::new(self.width(), self.height())
933 }
934
935 pub fn compute_distance_to_actual_baseline(&self, baseline: TextBaseline) -> f64 {
940 debug_assert!(self.debug_assert_text_layout_is_valid());
941 self.layout_cache()
942 .layout
943 .get_distance_to_baseline(baseline)
944 }
945
946 pub fn did_exceed_max_lines(&self) -> bool {
956 debug_assert!(self.debug_assert_text_layout_is_valid());
957 self.layout_cache().paragraph().did_exceed_max_lines()
958 }
959
960 fn layout_cache(&self) -> &TextPainterLayoutCacheWithOffset {
961 self.layout_cache
962 .as_ref()
963 .expect("Text layout not available: the TextPainter has never been laid out.")
964 }
965
966 fn create_paragraph(&mut self, fonts: &mut FontCollection, text: &InlineSpanRef) -> Paragraph {
969 let mut builder = ParagraphBuilder::new(self.create_paragraph_style(None));
970 text.build(
971 &mut builder,
972 &self.text_scaler,
973 self.placeholder_dimensions.as_deref(),
974 );
975 self.rebuild_paragraph_for_paint = false;
976 builder.build(fonts)
977 }
978
979 pub fn layout(&mut self, fonts: &mut FontCollection, min_width: f64, max_width: f64) {
989 debug_assert!(!max_width.is_nan());
990 debug_assert!(!min_width.is_nan());
991 if cfg!(debug_assertions) {
992 self.debug_needs_relayout = false;
993 }
994
995 if let Some(cached_layout) = self.layout_cache.as_mut()
996 && cached_layout.resize_to_fit(min_width, max_width, self.text_width_basis)
997 {
998 return;
999 }
1000
1001 let text = self.text.clone().expect(
1002 "TextPainter.text must be set to a non-null value before using the TextPainter.",
1003 );
1004 let text_direction = self.text_direction.expect(
1005 "TextPainter.textDirection must be set to a non-null value before using the TextPainter.",
1006 );
1007
1008 let paint_offset_alignment = compute_paint_offset_fraction(self.text_align, text_direction);
1010 let adjust_max_width = !max_width.is_finite() && paint_offset_alignment != 0.0;
1011 let adjusted_max_width = if !adjust_max_width {
1012 Some(max_width)
1013 } else {
1014 self.layout_cache
1015 .as_ref()
1016 .map(|cached| cached.layout.max_intrinsic_line_extent())
1017 };
1018 let layout_max_width = adjusted_max_width.unwrap_or(max_width);
1019
1020 let mut paragraph = match self.layout_cache.take() {
1028 Some(cached) => cached.layout.paragraph,
1029 None => self.create_paragraph(fonts, &text),
1030 };
1031 paragraph.layout(ParagraphConstraints::new(layout_max_width));
1032 let layout = TextLayout::new(paragraph, text_direction);
1033 let content_width = layout.content_width_for(min_width, max_width, self.text_width_basis);
1034
1035 let new_layout_cache = if adjusted_max_width.is_none() && min_width.is_finite() {
1036 debug_assert!(max_width.is_infinite());
1037 let new_input_width = layout.max_intrinsic_line_extent();
1038 let mut layout = layout;
1039 layout
1040 .paragraph
1041 .layout(ParagraphConstraints::new(new_input_width));
1042 TextPainterLayoutCacheWithOffset::new(
1043 layout,
1044 paint_offset_alignment,
1045 new_input_width,
1046 content_width,
1047 )
1048 } else {
1049 TextPainterLayoutCacheWithOffset::new(
1050 layout,
1051 paint_offset_alignment,
1052 layout_max_width,
1053 content_width,
1054 )
1055 };
1056 self.layout_cache = Some(new_layout_cache);
1057 }
1058
1059 pub fn paint(&mut self, fonts: &mut FontCollection, canvas: &mut Canvas, offset: Offset) {
1071 assert!(
1072 self.layout_cache.is_some(),
1073 "TextPainter.paint called when text geometry was not yet calculated.\n\
1074 Please call layout() before paint() to position the text before painting it."
1075 );
1076 let paint_offset = self.layout_cache().paint_offset();
1077 if !paint_offset.dx().is_finite() || !paint_offset.dy().is_finite() {
1078 return;
1079 }
1080
1081 if self.rebuild_paragraph_for_paint {
1082 let debug_size = cfg!(debug_assertions).then(|| self.size());
1083 let text = self.text.clone().expect("a laid-out painter has text");
1084 let layout_max_width = self.layout_cache().layout_max_width;
1085 debug_assert!(!layout_max_width.is_nan());
1086 let mut rebuilt = self.create_paragraph(fonts, &text);
1087 rebuilt.layout(ParagraphConstraints::new(layout_max_width));
1088 let layout_cache = self.layout_cache.as_mut().expect("checked above");
1089 debug_assert!(layout_cache.paragraph().width() == rebuilt.width());
1090 let mut previous = std::mem::replace(&mut layout_cache.layout.paragraph, rebuilt);
1091 previous.dispose();
1092 debug_assert!(debug_size.is_none_or(|size| size == self.size()));
1093 }
1094 debug_assert!(!self.rebuild_paragraph_for_paint);
1095 if self.debug_paint_text_layout_boxes {
1096 self.debug_paint_character_layout_boxes(canvas, offset);
1097 }
1098 canvas.draw_paragraph(self.layout_cache().paragraph(), offset + paint_offset);
1099 }
1100
1101 fn debug_paint_character_layout_boxes(&mut self, canvas: &mut Canvas, offset: Offset) {
1102 let paint = Paint {
1103 style: PaintStyle::Stroke(Stroke::new(1.0)),
1104 color: Color::from_argb(255, 0, 255, 255).into(),
1105 ..Paint::default()
1106 };
1107 let length = utf16_len(self.plain_text());
1108 let text_boxes = self.get_boxes_for_selection(
1109 TextSelection::new(0, length),
1110 BoxHeightStyle::Tight,
1111 BoxWidthStyle::Tight,
1112 );
1113 for text_box in text_boxes {
1114 let host_rect: waft_embedder::valo::Rect = text_box.to_rect().shift(offset).into();
1115 canvas.draw_rect(host_rect, &paint);
1116 }
1117 }
1118
1119 pub fn is_high_surrogate(value: u16) -> bool {
1121 value & 0xFC00 == 0xD800
1122 }
1123
1124 pub fn is_low_surrogate(value: u16) -> bool {
1126 value & 0xFC00 == 0xDC00
1127 }
1128
1129 pub fn get_offset_after(&self, offset: i32) -> Option<i32> {
1131 let next_code_unit = self.text.clone()?.code_unit_at(offset)?;
1132 Some(if TextPainter::is_high_surrogate(next_code_unit) {
1135 offset + 2
1136 } else {
1137 offset + 1
1138 })
1139 }
1140
1141 pub fn get_offset_before(&self, offset: i32) -> Option<i32> {
1144 let prev_code_unit = self.text.clone()?.code_unit_at(offset - 1)?;
1145 Some(if TextPainter::is_low_surrogate(prev_code_unit) {
1148 offset - 2
1149 } else {
1150 offset - 1
1151 })
1152 }
1153
1154 pub fn get_offset_for_caret(
1158 &mut self,
1159 fonts: &mut FontCollection,
1160 position: TextPosition,
1161 caret_prototype: Rect,
1162 ) -> Offset {
1163 let Some(caret_metrics) = self.compute_caret_metrics(fonts, position) else {
1164 let text_direction = self.text_direction.expect("laid out");
1165 let paint_offset_alignment =
1166 compute_paint_offset_fraction(self.text_align, text_direction);
1167 let dx = if paint_offset_alignment == 0.0 {
1168 0.0
1169 } else {
1170 paint_offset_alignment * self.layout_cache().content_width
1171 };
1172 return Offset::new(dx, 0.0);
1173 };
1174 let layout_cache = self.layout_cache();
1175 let raw_offset = match caret_metrics.writing_direction {
1176 TextDirection::Ltr => caret_metrics.offset,
1177 TextDirection::Rtl => Offset::new(
1178 caret_metrics.offset.dx() - caret_prototype.width(),
1179 caret_metrics.offset.dy(),
1180 ),
1181 };
1182 let adjusted_dx = clamp_double(
1185 raw_offset.dx() + layout_cache.paint_offset().dx(),
1186 0.0,
1187 layout_cache.content_width,
1188 );
1189 Offset::new(
1190 adjusted_dx,
1191 raw_offset.dy() + layout_cache.paint_offset().dy(),
1192 )
1193 }
1194
1195 fn strut_disabled(&self) -> bool {
1199 match &self.strut_style {
1200 None => true,
1201 Some(strut_style) => {
1202 *strut_style == StrutStyle::DISABLED || strut_style.font_size == Some(0.0)
1203 }
1204 }
1205 }
1206
1207 pub fn get_full_height_for_caret(
1212 &mut self,
1213 fonts: &mut FontCollection,
1214 position: TextPosition,
1215 caret_prototype: Rect,
1216 ) -> f64 {
1217 let _ = caret_prototype;
1218 if self.strut_disabled()
1219 && let Some(metrics) = self.compute_caret_metrics(fonts, position)
1220 {
1221 return metrics.height;
1222 }
1223 let preferred_line_height = self.preferred_line_height(fonts);
1224 let boxes = self
1225 .get_or_create_layout_template(fonts)
1226 .get_boxes_for_range(0, 1, BoxHeightStyle::Strut, BoxWidthStyle::Tight);
1227 match boxes.as_slice() {
1228 [single] => single.to_rect().height(),
1229 _ => preferred_line_height,
1230 }
1231 }
1232
1233 fn is_newline_at_offset(&mut self, offset: i32) -> bool {
1234 if offset < 0 {
1235 return false;
1236 }
1237 self.plain_text()
1238 .encode_utf16()
1239 .nth(offset as usize)
1240 .is_some_and(|unit| is_newline(u32::from(unit)))
1241 }
1242
1243 fn compute_caret_metrics(
1250 &mut self,
1251 fonts: &mut FontCollection,
1252 position: TextPosition,
1253 ) -> Option<LineCaretMetrics> {
1254 debug_assert!(self.debug_assert_text_layout_is_valid());
1255 debug_assert!(!self.debug_needs_relayout);
1256 if self.layout_cache().paragraph().number_of_lines() < 1 {
1257 return None;
1258 }
1259 let upstream_after_newline = position.affinity == TextAffinity::Upstream
1260 && self.is_newline_at_offset(position.offset - 1);
1261 let (offset, anchor_to_leading_edge) = match position {
1262 TextPosition { offset: 0, .. } => (0, true),
1265 TextPosition {
1266 offset,
1267 affinity: TextAffinity::Downstream,
1268 } => (offset, true),
1269 TextPosition {
1270 offset,
1271 affinity: TextAffinity::Upstream,
1272 } if upstream_after_newline => (offset, true),
1273 TextPosition {
1274 offset,
1275 affinity: TextAffinity::Upstream,
1276 } => (offset - 1, false),
1277 };
1278 let caret_position_cache_key = if anchor_to_leading_edge {
1279 offset
1280 } else {
1281 -offset - 1
1282 };
1283 if Some(caret_position_cache_key) == self.layout_cache().previous_caret_position_key {
1284 return self.caret_metrics;
1285 }
1286
1287 let Some(glyph_info) = self.layout_cache().paragraph().get_glyph_info_at(offset) else {
1288 let plain_text = self.plain_text().to_owned();
1291 let baseline_offset = self
1292 .get_or_create_layout_template(fonts)
1293 .get_line_metrics_at(0)
1294 .expect("the template has one line")
1295 .baseline;
1296 let layout = &self.layout_cache().layout;
1297 return Some(
1298 layout
1299 .end_of_text_caret_metrics(&plain_text)
1300 .shift(Offset::new(0.0, -baseline_offset)),
1301 );
1302 };
1303 let grapheme_range = glyph_info.grapheme_cluster_code_unit_range;
1304
1305 if grapheme_range.is_collapsed() {
1309 debug_assert!(grapheme_range.start == 0);
1310 return self.compute_caret_metrics(fonts, TextPosition::new(offset + 1));
1311 }
1312 if anchor_to_leading_edge && grapheme_range.start != offset {
1313 debug_assert!(grapheme_range.end > grapheme_range.start + 1);
1314 return self.compute_caret_metrics(fonts, TextPosition::new(grapheme_range.end));
1318 }
1319
1320 let boxes = self.layout_cache().paragraph().get_boxes_for_range(
1321 grapheme_range.start,
1322 grapheme_range.end,
1323 BoxHeightStyle::Strut,
1324 BoxWidthStyle::Tight,
1325 );
1326 let anchor_to_left = match glyph_info.writing_direction {
1327 TextDirection::Ltr => anchor_to_leading_edge,
1328 TextDirection::Rtl => !anchor_to_leading_edge,
1329 };
1330 let text_box = if anchor_to_left {
1331 boxes.first()
1332 } else {
1333 boxes.last()
1334 }?;
1335 let metrics = LineCaretMetrics {
1336 offset: Offset::new(
1337 if anchor_to_left {
1338 text_box.left
1339 } else {
1340 text_box.right
1341 },
1342 text_box.top,
1343 ),
1344 writing_direction: text_box.direction,
1345 height: text_box.bottom - text_box.top,
1346 };
1347 self.layout_cache
1348 .as_mut()
1349 .expect("checked above")
1350 .previous_caret_position_key = Some(caret_position_cache_key);
1351 self.caret_metrics = Some(metrics);
1352 Some(metrics)
1353 }
1354
1355 pub fn get_boxes_for_selection(
1370 &self,
1371 selection: TextSelection,
1372 box_height_style: BoxHeightStyle,
1373 box_width_style: BoxWidthStyle,
1374 ) -> Vec<TextBox> {
1375 debug_assert!(self.debug_assert_text_layout_is_valid());
1376 debug_assert!(selection.is_valid());
1377 debug_assert!(!self.debug_needs_relayout);
1378 let cached_layout = self.layout_cache();
1379 let offset = cached_layout.paint_offset();
1380 if !offset.dx().is_finite() || !offset.dy().is_finite() {
1381 return Vec::new();
1382 }
1383 let boxes = cached_layout.paragraph().get_boxes_for_range(
1384 selection.start(),
1385 selection.end(),
1386 box_height_style,
1387 box_width_style,
1388 );
1389 if offset == Offset::ZERO {
1390 boxes
1391 } else {
1392 boxes
1393 .into_iter()
1394 .map(|text_box| shift_text_box(text_box, offset))
1395 .collect()
1396 }
1397 }
1398
1399 pub fn get_closest_glyph_for_offset(&self, offset: Offset) -> Option<GlyphInfo> {
1406 debug_assert!(self.debug_assert_text_layout_is_valid());
1407 debug_assert!(!self.debug_needs_relayout);
1408 let cached_layout = self.layout_cache();
1409 let raw_glyph_info = cached_layout
1410 .paragraph()
1411 .get_closest_glyph_info_for_offset(offset - cached_layout.paint_offset())?;
1412 if cached_layout.paint_offset() == Offset::ZERO {
1413 return Some(raw_glyph_info);
1414 }
1415 Some(GlyphInfo {
1416 grapheme_cluster_layout_bounds: raw_glyph_info
1417 .grapheme_cluster_layout_bounds
1418 .shift(cached_layout.paint_offset()),
1419 grapheme_cluster_code_unit_range: raw_glyph_info.grapheme_cluster_code_unit_range,
1420 writing_direction: raw_glyph_info.writing_direction,
1421 })
1422 }
1423
1424 pub fn get_position_for_offset(&self, offset: Offset) -> TextPosition {
1426 debug_assert!(self.debug_assert_text_layout_is_valid());
1427 debug_assert!(!self.debug_needs_relayout);
1428 let cached_layout = self.layout_cache();
1429 cached_layout
1430 .paragraph()
1431 .get_position_for_offset(offset - cached_layout.paint_offset())
1432 }
1433
1434 pub fn get_word_boundary(&self, position: TextPosition) -> TextRange {
1441 debug_assert!(self.debug_assert_text_layout_is_valid());
1442 self.layout_cache().paragraph().get_word_boundary(position)
1443 }
1444
1445 pub fn get_line_boundary(&self, position: TextPosition) -> TextRange {
1449 debug_assert!(self.debug_assert_text_layout_is_valid());
1450 self.layout_cache().paragraph().get_line_boundary(position)
1451 }
1452
1453 pub fn compute_line_metrics(&mut self) -> Vec<LineMetrics> {
1460 debug_assert!(self.debug_assert_text_layout_is_valid());
1461 debug_assert!(!self.debug_needs_relayout);
1462 let layout = self.layout_cache.as_mut().expect("laid out");
1463 let offset = layout.paint_offset();
1464 if !offset.dx().is_finite() || !offset.dy().is_finite() {
1465 return Vec::new();
1466 }
1467 let raw_metrics = layout.line_metrics();
1468 if offset == Offset::ZERO {
1469 raw_metrics.to_vec()
1470 } else {
1471 raw_metrics
1472 .iter()
1473 .map(|metrics| shift_line_metrics(*metrics, offset))
1474 .collect()
1475 }
1476 }
1477
1478 pub fn debug_disposed(&self) -> bool {
1480 self.disposed
1481 }
1482
1483 pub fn dispose(&mut self) {
1487 debug_assert!(!self.debug_disposed());
1488 self.disposed = true;
1489 if let Some(mut template) = self.layout_template.take() {
1490 template.dispose();
1491 }
1492 if let Some(mut cache) = self.layout_cache.take() {
1493 cache.layout.paragraph.dispose();
1494 }
1495 self.text = None;
1496 }
1497}
1498
1499fn compute_paint_offset_fraction(text_align: TextAlign, text_direction: TextDirection) -> f64 {
1500 match (text_align, text_direction) {
1501 (TextAlign::Left, _) => 0.0,
1502 (TextAlign::Right, _) => 1.0,
1503 (TextAlign::Center, _) => 0.5,
1504 (TextAlign::Start | TextAlign::Justify, TextDirection::Ltr) => 0.0,
1505 (TextAlign::Start | TextAlign::Justify, TextDirection::Rtl) => 1.0,
1506 (TextAlign::End, TextDirection::Ltr) => 1.0,
1507 (TextAlign::End, TextDirection::Rtl) => 0.0,
1508 }
1509}
1510
1511fn shift_line_metrics(metrics: LineMetrics, offset: Offset) -> LineMetrics {
1512 debug_assert!(offset.dx().is_finite());
1513 debug_assert!(offset.dy().is_finite());
1514 LineMetrics {
1515 left: metrics.left + offset.dx(),
1516 baseline: metrics.baseline + offset.dy(),
1517 ..metrics
1518 }
1519}
1520
1521fn shift_text_box(text_box: TextBox, offset: Offset) -> TextBox {
1522 debug_assert!(offset.dx().is_finite());
1523 debug_assert!(offset.dy().is_finite());
1524 TextBox::from_ltrbd(
1525 text_box.left + offset.dx(),
1526 text_box.top + offset.dy(),
1527 text_box.right + offset.dx(),
1528 text_box.bottom + offset.dy(),
1529 text_box.direction,
1530 )
1531}
1532
1533#[cfg(test)]
1534mod tests {
1535 use super::*;
1536 use waft_embedder::TextLeadingDistribution;
1537
1538 use crate::text_span::TextSpan;
1539
1540 fn fonts() -> FontCollection {
1541 let mut fonts = FontCollection::new();
1542 fonts.add_source(valo_system_fonts::SystemFonts::load());
1543 fonts
1544 }
1545
1546 fn painter(text: &str) -> TextPainter {
1547 let mut painter = TextPainter::new();
1548 painter.set_text(Some(
1549 TextSpan::new()
1550 .text(text)
1551 .style(TextStyle::new().font_size(20.0))
1552 .into_span(),
1553 ));
1554 painter.set_text_direction(Some(TextDirection::Ltr));
1555 painter
1556 }
1557
1558 #[test]
1559 fn layout_sizes_the_text_and_paint_records_it() {
1560 let mut fonts = fonts();
1561 let mut painter = painter("Hello world");
1562 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1563 assert!(painter.width() > 0.0);
1564 assert!(painter.height() > 0.0);
1565 assert_eq!(painter.size(), Size::new(painter.width(), painter.height()));
1566 assert!(painter.compute_distance_to_actual_baseline(TextBaseline::Alphabetic) > 0.0);
1567 assert_eq!(painter.compute_line_metrics().len(), 1);
1568 let mut canvas = Canvas::new();
1569 painter.paint(&mut fonts, &mut canvas, Offset::new(5.0, 5.0));
1570 assert!(!canvas.build().ops().is_empty());
1571 painter.dispose();
1572 }
1573
1574 #[test]
1575 fn a_min_width_widens_the_reported_width_without_relayout() {
1576 let mut fonts = fonts();
1577 let mut painter = painter("Hi");
1578 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1579 let natural = painter.width();
1580 painter.layout(&mut fonts, natural + 100.0, f64::INFINITY);
1581 assert_eq!(painter.width(), natural + 100.0);
1582 assert_eq!(painter.max_intrinsic_width(), natural);
1583 }
1584
1585 #[test]
1586 fn right_alignment_offsets_the_paint_and_the_caret() {
1587 let mut fonts = fonts();
1588 let mut painter = painter("Hi");
1589 painter.set_text_align(TextAlign::Right);
1590 painter.layout(&mut fonts, 200.0, 200.0);
1591 let natural = painter.max_intrinsic_width();
1592 let caret = painter.get_offset_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO);
1593 assert!(
1594 (caret.dx() - (200.0 - natural)).abs() < 1.0,
1595 "caret at {caret:?}"
1596 );
1597 let end = painter.get_offset_for_caret(&mut fonts, TextPosition::new(2), Rect::ZERO);
1598 assert!((end.dx() - 200.0).abs() < 1.0, "end caret at {end:?}");
1599 }
1600
1601 #[test]
1602 fn changing_only_the_color_does_not_drop_the_layout() {
1603 let mut fonts = fonts();
1604 let mut painter = painter("Hi");
1605 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1606 painter.set_text(Some(
1607 TextSpan::new()
1608 .text("Hi")
1609 .style(
1610 TextStyle::new()
1611 .font_size(20.0)
1612 .color(Color::from_argb(255, 255, 0, 0)),
1613 )
1614 .into_span(),
1615 ));
1616 assert!(
1617 painter.layout_cache.is_some(),
1618 "a paint-only change keeps the layout"
1619 );
1620 assert!(painter.rebuild_paragraph_for_paint);
1621 let mut canvas = Canvas::new();
1622 painter.paint(&mut fonts, &mut canvas, Offset::ZERO);
1623 assert!(!painter.rebuild_paragraph_for_paint);
1624 }
1625
1626 #[test]
1627 fn max_lines_and_ellipsis_report_overflow() {
1628 let mut fonts = fonts();
1629 let mut painter = painter("one two three four five six");
1630 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1631 let full = painter.width();
1632 painter.set_max_lines(Some(1));
1633 painter.set_ellipsis(Some("\u{2026}".to_owned()));
1634 painter.layout(&mut fonts, 0.0, full / 2.0);
1635 assert!(painter.did_exceed_max_lines());
1636 assert_eq!(painter.compute_line_metrics().len(), 1);
1637 }
1638
1639 #[test]
1640 fn positions_words_and_lines_round_trip() {
1641 let mut fonts = fonts();
1642 let mut painter = painter("ab cd");
1643 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1644 let end = painter.get_position_for_offset(Offset::new(painter.width() + 10.0, 1.0));
1645 assert_eq!(end.offset, 5);
1646 assert_eq!(
1647 painter.get_word_boundary(TextPosition::new(4)),
1648 TextRange::new(3, 5)
1649 );
1650 assert_eq!(
1651 painter.get_line_boundary(TextPosition::new(1)),
1652 TextRange::new(0, 5)
1653 );
1654 let boxes = painter.get_boxes_for_selection(
1655 TextSelection::new(0, 5),
1656 BoxHeightStyle::Tight,
1657 BoxWidthStyle::Tight,
1658 );
1659 assert!(!boxes.is_empty());
1660 assert_eq!(painter.get_offset_after(0), Some(1));
1661 assert_eq!(painter.get_offset_before(1), Some(0));
1662 assert_eq!(painter.get_offset_after(5), None);
1663 }
1664
1665 #[test]
1669 fn a_caret_beside_a_newline_is_on_the_line_its_offset_says() {
1670 let mut fonts = fonts();
1671 let mut painter = painter("aaa\n\n\n");
1672 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1673 let lines = painter.compute_line_metrics();
1674 let top_of = |line: usize| lines[line].baseline - lines[line].ascent;
1675 let text_width = lines[0].width;
1676 assert!(text_width > 0.0);
1677 let wanted = [
1678 (3, Offset::new(text_width, top_of(0))),
1679 (4, Offset::new(0.0, top_of(1))),
1680 (5, Offset::new(0.0, top_of(2))),
1681 (6, Offset::new(0.0, top_of(3))),
1682 ];
1683 for (offset, caret) in wanted {
1684 for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1685 let position = TextPosition::with_affinity(offset, affinity);
1686 let found = painter.get_offset_for_caret(&mut fonts, position, Rect::ZERO);
1687 assert!(
1688 (found - caret).distance() < 0.01,
1689 "the caret at {position:?} is at {found:?}, not {caret:?}"
1690 );
1691 }
1692 }
1693 }
1694
1695 type Caret = (i32, usize, f64);
1698
1699 fn assert_carets(painter: &mut TextPainter, fonts: &mut FontCollection, wanted: &[Caret]) {
1701 let lines = painter.compute_line_metrics();
1702 for &(offset, line, x) in wanted {
1703 let caret = Offset::new(x, lines[line].baseline - lines[line].ascent);
1704 for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1705 let position = TextPosition::with_affinity(offset, affinity);
1706 let found = painter.get_offset_for_caret(fonts, position, Rect::ZERO);
1707 assert!(
1708 (found - caret).distance() < 0.01,
1709 "the caret at {position:?} is at {found:?}, not {caret:?}"
1710 );
1711 }
1712 }
1713 }
1714
1715 #[test]
1718 fn handles_newlines_properly() {
1719 let mut fonts = fonts();
1720 let cases: [(&str, &[Caret]); 4] = [
1721 ("\n\n", &[(0, 0, 0.0), (1, 1, 0.0), (2, 2, 0.0)]),
1722 ("\naaa", &[(0, 0, 0.0), (1, 1, 0.0)]),
1723 ("aaa\naaa", &[(4, 1, 0.0)]),
1724 (
1725 "\n\n\naaa",
1726 &[(0, 0, 0.0), (1, 1, 0.0), (2, 2, 0.0), (3, 3, 0.0)],
1727 ),
1728 ];
1729 for (text, wanted) in cases {
1730 let mut painter = painter(text);
1731 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1732 assert_carets(&mut painter, &mut fonts, wanted);
1733 }
1734 let mut painter = painter("aaa\n");
1735 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1736 assert_carets(&mut painter, &mut fonts, &[(4, 1, 0.0)]);
1737 }
1738
1739 #[test]
1743 fn affinity_tells_a_soft_wraps_two_carets_apart() {
1744 let mut fonts = fonts();
1745 let mut first = painter("aaaa");
1746 first.layout(&mut fonts, 0.0, f64::INFINITY);
1747 let mut painter = painter("aaa aaaa");
1748 painter.layout(&mut fonts, 0.0, first.max_intrinsic_width() + 1.0);
1749 let lines = painter.compute_line_metrics();
1750 assert_eq!(lines.len(), 2);
1751 let downstream = painter.get_offset_for_caret(&mut fonts, TextPosition::new(4), Rect::ZERO);
1752 let start_of_second = Offset::new(0.0, lines[1].baseline - lines[1].ascent);
1753 assert!(
1754 (downstream - start_of_second).distance() < 0.01,
1755 "{downstream:?}"
1756 );
1757 let space = painter.get_boxes_for_selection(
1758 TextSelection::new(3, 4),
1759 BoxHeightStyle::Tight,
1760 BoxWidthStyle::Tight,
1761 );
1762 assert!(
1763 space[0].right > lines[0].width,
1764 "the space hangs past the line's width"
1765 );
1766 let end_of_first = Offset::new(
1768 space[0].right.min(painter.width()),
1769 lines[0].baseline - lines[0].ascent,
1770 );
1771 let upstream = TextPosition::with_affinity(4, TextAffinity::Upstream);
1772 let upstream = painter.get_offset_for_caret(&mut fonts, upstream, Rect::ZERO);
1773 assert!(
1774 (upstream - end_of_first).distance() < 0.01,
1775 "{upstream:?} is not {end_of_first:?}"
1776 );
1777 }
1778
1779 #[test]
1782 fn the_end_of_text_caret_follows_trailing_spaces() {
1783 let mut fonts = fonts();
1784 let mut painter = painter("a ");
1785 painter.layout(&mut fonts, 1000.0, 1000.0);
1786 let end = painter.get_offset_for_caret(&mut fonts, TextPosition::new(5), Rect::ZERO);
1787 let boxes = painter.get_boxes_for_selection(
1788 TextSelection::new(0, 5),
1789 BoxHeightStyle::Tight,
1790 BoxWidthStyle::Tight,
1791 );
1792 let right = boxes
1793 .iter()
1794 .map(|text_box| text_box.right)
1795 .fold(f64::MIN, f64::max);
1796 assert!(
1797 right > painter.compute_line_metrics()[0].width + 1.0,
1798 "the spaces are boxed"
1799 );
1800 assert!((end.dx() - right).abs() < 0.01, "{end:?} is not at {right}");
1801 }
1802
1803 #[test]
1805 fn a_caret_before_a_newline_between_lines_of_text_ends_its_line() {
1806 let mut fonts = fonts();
1807 let mut painter = painter("aaa\naaa");
1808 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1809 let lines = painter.compute_line_metrics();
1810 let end_of_first = Offset::new(lines[0].width, lines[0].baseline - lines[0].ascent);
1811 let start_of_second = Offset::new(0.0, lines[1].baseline - lines[1].ascent);
1812 for affinity in [TextAffinity::Downstream, TextAffinity::Upstream] {
1813 let before = TextPosition::with_affinity(3, affinity);
1814 let found = painter.get_offset_for_caret(&mut fonts, before, Rect::ZERO);
1815 assert!(
1816 (found - end_of_first).distance() < 0.01,
1817 "the caret at {before:?} is at {found:?}, not {end_of_first:?}"
1818 );
1819 let after = TextPosition::with_affinity(4, affinity);
1820 let found = painter.get_offset_for_caret(&mut fonts, after, Rect::ZERO);
1821 assert!(
1822 (found - start_of_second).distance() < 0.01,
1823 "the caret at {after:?} is at {found:?}, not {start_of_second:?}"
1824 );
1825 }
1826 }
1827
1828 #[test]
1829 fn preferred_line_height_needs_no_layout() {
1830 let mut fonts = fonts();
1831 let mut painter = painter("x");
1832 assert!(painter.preferred_line_height(&mut fonts) > 0.0);
1833 }
1834
1835 #[test]
1836 fn compute_width_is_the_laid_out_width() {
1837 let mut fonts = fonts();
1838 let span = TextSpan::new().text("Hello").into_span();
1839 let width = TextPainter::compute_width(
1840 &mut fonts,
1841 span.clone(),
1842 TextDirection::Ltr,
1843 0.0,
1844 f64::INFINITY,
1845 );
1846 let mut painter = TextPainter::new();
1847 painter.set_text(Some(span));
1848 painter.set_text_direction(Some(TextDirection::Ltr));
1849 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1850 assert_eq!(width, painter.width());
1851 }
1852
1853 fn flutter_test_fonts() -> FontCollection {
1856 use waft_embedder::Platform as _;
1857
1858 let mut fonts = FontCollection::new();
1859 waft_embedder::set_default_font_manager(
1860 &mut fonts,
1861 Box::new(waft_embedder::TestFontSource::new()),
1862 &waft_embedder::InertPlatform.default_font_families(),
1863 );
1864 fonts
1865 }
1866
1867 fn strut_painter(text: InlineSpanRef, strut: StrutStyle) -> TextPainter {
1868 let mut painter = TextPainter::new();
1869 painter.set_text(Some(text));
1870 painter.set_text_direction(Some(TextDirection::Ltr));
1871 painter.set_strut_style(Some(strut));
1872 painter
1873 }
1874
1875 #[test]
1876 fn strut_style_applies_when_the_span_has_no_style() {
1877 let mut fonts = flutter_test_fonts();
1878 let empty = TextSpan::new().into_span();
1879 let mut painter = strut_painter(empty, StrutStyle::new().height(10.0).font_size(10.0));
1880 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1881 assert_eq!(painter.height(), 100.0);
1882 }
1883
1884 #[test]
1885 fn strut_style_leading_is_a_font_size_multiplier() {
1886 let mut fonts = flutter_test_fonts();
1887 let empty = TextSpan::new().into_span();
1888 let mut painter = strut_painter(
1889 empty,
1890 StrutStyle::new().height(10.0).font_size(10.0).leading(2.0),
1891 );
1892 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1893 assert_eq!(painter.height(), 100.0 + 20.0);
1894 assert_eq!(
1896 painter.compute_distance_to_actual_baseline(TextBaseline::Alphabetic),
1897 10.0 + 10.0 * 7.5
1898 );
1899 }
1900
1901 #[test]
1902 fn strut_no_half_leading_plus_force_strut_height() {
1903 let mut fonts = flutter_test_fonts();
1904 let text = TextSpan::new()
1905 .text("A")
1906 .style(TextStyle::new().font_size(20.0))
1907 .into_span();
1908 let mut painter = strut_painter(
1909 text,
1910 StrutStyle::new()
1911 .height(10.0)
1912 .font_size(10.0)
1913 .force_strut_height(true),
1914 );
1915 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1916 assert_eq!(painter.height(), 100.0);
1917 let baseline = 75.0;
1918 let boxes = painter.get_boxes_for_selection(
1919 TextSelection::new(0, 1),
1920 BoxHeightStyle::Tight,
1921 BoxWidthStyle::Tight,
1922 );
1923 assert_eq!(
1924 boxes,
1925 vec![TextBox::from_ltrbd(
1926 0.0,
1927 baseline - 15.0,
1928 20.0,
1929 baseline + 5.0,
1930 TextDirection::Ltr
1931 )]
1932 );
1933 }
1934
1935 #[test]
1936 fn strut_half_leading_plus_force_strut_height() {
1937 let mut fonts = flutter_test_fonts();
1938 let text = TextSpan::new()
1939 .text("A")
1940 .style(TextStyle::new().font_size(20.0))
1941 .into_span();
1942 let mut painter = strut_painter(
1943 text,
1944 StrutStyle::new()
1945 .height(10.0)
1946 .font_size(10.0)
1947 .force_strut_height(true)
1948 .leading_distribution(TextLeadingDistribution::Even),
1949 );
1950 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1951 assert_eq!(painter.height(), 100.0);
1952 let baseline = 45.0 + 7.5;
1953 let boxes = painter.get_boxes_for_selection(
1954 TextSelection::new(0, 1),
1955 BoxHeightStyle::Tight,
1956 BoxWidthStyle::Tight,
1957 );
1958 assert_eq!(
1959 boxes,
1960 vec![TextBox::from_ltrbd(
1961 0.0,
1962 baseline - 15.0,
1963 20.0,
1964 baseline + 5.0,
1965 TextDirection::Ltr
1966 )]
1967 );
1968 }
1969
1970 #[test]
1971 fn text_height_behavior_with_strut_on_empty_paragraph() {
1972 let mut fonts = flutter_test_fonts();
1973 let style = TextStyle::new().height(11.0).font_size(7.0);
1974 let simple = TextSpan::new().text("x").style(style.clone()).into_span();
1975 let empty_string = TextSpan::new().text("").style(style.clone()).into_span();
1976 let empty_paragraph = TextSpan::new().style(style.clone()).into_span();
1977 let strut = StrutStyle::from_text_style(&style)
1978 .force_strut_height(true)
1979 .build();
1980
1981 let mut painter = strut_painter(simple.clone(), strut);
1982 painter.set_text_height_behavior(Some(TextHeightBehavior {
1983 apply_height_to_first_ascent: false,
1984 apply_height_to_last_descent: false,
1985 leading_distribution: TextLeadingDistribution::Proportional,
1986 }));
1987 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1988 let height = painter.height();
1989 for span in [simple, empty_string, empty_paragraph] {
1990 painter.set_text(Some(span));
1991 painter.layout(&mut fonts, 0.0, f64::INFINITY);
1992 assert_eq!(painter.height(), height);
1993 assert_eq!(painter.preferred_line_height(&mut fonts), height);
1994 }
1995 }
1996
1997 #[test]
1998 fn text_painter_caret_height_and_line_height() {
1999 let mut fonts = flutter_test_fonts();
2000 let mut painter = TextPainter::new();
2001 painter.set_text_direction(Some(TextDirection::Ltr));
2002 painter.set_strut_style(Some(StrutStyle::new().font_size(50.0)));
2003 painter.set_text(Some(
2004 TextSpan::new()
2005 .text("A")
2006 .style(TextStyle::new().height(1.0))
2007 .into_span(),
2008 ));
2009 painter.layout(&mut fonts, 0.0, f64::INFINITY);
2010
2011 let caret_height =
2012 painter.get_full_height_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO);
2013 assert_eq!(caret_height, 50.0);
2014 }
2015
2016 #[test]
2017 fn caret_height_reflects_run_height_if_strut_is_disabled() {
2018 let mut fonts = flutter_test_fonts();
2019 let span = TextSpan::new()
2020 .text("M")
2021 .style(TextStyle::new().font_size(128.0))
2022 .children(vec![
2023 TextSpan::new()
2024 .text("M")
2025 .style(TextStyle::new().font_size(32.0))
2026 .into_span(),
2027 TextSpan::new()
2028 .text("M")
2029 .style(TextStyle::new().font_size(64.0))
2030 .into_span(),
2031 ])
2032 .into_span();
2033 let mut painter = TextPainter::new();
2034 painter.set_text(Some(span));
2035 painter.set_text_direction(Some(TextDirection::Ltr));
2036 painter.layout(&mut fonts, 0.0, f64::INFINITY);
2037
2038 let heights = [
2039 (0, TextAffinity::Upstream, 128.0),
2040 (0, TextAffinity::Downstream, 128.0),
2041 (1, TextAffinity::Upstream, 128.0),
2042 (1, TextAffinity::Downstream, 32.0),
2043 (2, TextAffinity::Upstream, 32.0),
2044 (2, TextAffinity::Downstream, 64.0),
2045 (3, TextAffinity::Upstream, 64.0),
2046 (3, TextAffinity::Downstream, 128.0),
2047 ];
2048 for (offset, affinity, expected) in heights {
2049 assert_eq!(
2050 painter.get_full_height_for_caret(
2051 &mut fonts,
2052 TextPosition::with_affinity(offset, affinity),
2053 Rect::ZERO
2054 ),
2055 expected,
2056 "offset {offset} {affinity:?}"
2057 );
2058 }
2059 }
2060
2061 #[test]
2062 fn get_full_height_for_caret_handles_degenerate_layout_without_crashing() {
2063 let mut fonts = flutter_test_fonts();
2064 let mut painter = TextPainter::new();
2065 painter.set_text(Some(
2066 TextSpan::new()
2067 .text("")
2068 .style(TextStyle::new().height(1.0).font_size(0.0))
2069 .into_span(),
2070 ));
2071 painter.set_text_direction(Some(TextDirection::Ltr));
2072 painter.layout(&mut fonts, 0.0, f64::INFINITY);
2073 assert_eq!(
2074 painter.get_full_height_for_caret(&mut fonts, TextPosition::new(0), Rect::ZERO),
2075 painter.preferred_line_height(&mut fonts)
2076 );
2077 }
2078}