1use sui_core::{Color, Point, Rect, Size};
5use sui_layout::LayoutContext;
6use sui_runtime::{MeasureCtx, PaintCtx, window_render_options};
7use sui_text::{
8 TextAlign, TextDocument, TextLayout, TextLayoutRequest, TextMeasurement, TextStyle, TextWrap,
9};
10use unicode_segmentation::UnicodeSegmentation;
11
12pub(crate) struct AlignedTextLayout {
13 pub(crate) rect: Rect,
14 origin: Point,
15 layout: TextLayout,
16 color: Color,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub(crate) enum HorizontalTextAlignmentMode {
21 Advance,
22 Optical,
23}
24
25#[derive(Debug, Clone, Copy)]
26struct HorizontalPlacement {
27 rect_x: f32,
28 rect_width: f32,
29 origin_x: f32,
30}
31
32pub(crate) fn aligned_text_rect_for_text(
33 ctx: &PaintCtx,
34 rect: Rect,
35 text: &str,
36 style: &TextStyle,
37 line_height: f32,
38 horizontal_alignment: f32,
39) -> Rect {
40 aligned_text_rect_for_text_with_mode(
41 ctx,
42 rect,
43 text,
44 style,
45 line_height,
46 horizontal_alignment,
47 HorizontalTextAlignmentMode::Advance,
48 )
49}
50
51pub(crate) fn aligned_text_rect_for_text_with_mode(
52 ctx: &PaintCtx,
53 rect: Rect,
54 text: &str,
55 style: &TextStyle,
56 line_height: f32,
57 horizontal_alignment: f32,
58 horizontal_mode: HorizontalTextAlignmentMode,
59) -> Rect {
60 if let Some(aligned) = aligned_text_layout_for_text_with_mode(
61 ctx,
62 rect,
63 text,
64 style,
65 line_height,
66 horizontal_alignment,
67 horizontal_mode,
68 ) {
69 return aligned.rect;
70 }
71
72 let fallback_measurement = || TextMeasurement {
73 width: text.chars().count() as f32 * style.font_size * 0.56,
74 height: style.line_height,
75 bounds: Rect::ZERO,
76 ascent: style.font_size,
77 descent: 0.0,
78 cap_height: Some(style.font_size),
79 };
80 let measurement = ctx
81 .measure_text(text.to_string(), style.clone())
82 .ok()
83 .unwrap_or_else(fallback_measurement);
84 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
85 let height = line_height.max(measurement.height).min(rect.height());
86 let y = vertically_centered_text_rect_y(ctx, rect, measurement, height);
87
88 Rect::new(placement.rect_x, y, placement.rect_width, height)
89}
90
91pub(crate) fn aligned_text_layout_for_text_with_mode(
92 ctx: &PaintCtx,
93 rect: Rect,
94 text: &str,
95 style: &TextStyle,
96 line_height: f32,
97 horizontal_alignment: f32,
98 horizontal_mode: HorizontalTextAlignmentMode,
99) -> Option<AlignedTextLayout> {
100 aligned_text_layout_for_text_with_mode_and_wrap(
101 ctx,
102 rect,
103 text,
104 style,
105 line_height,
106 horizontal_alignment,
107 horizontal_mode,
108 TextWrap::Word,
109 )
110}
111
112fn aligned_text_layout_for_text_with_mode_and_wrap(
113 ctx: &PaintCtx,
114 rect: Rect,
115 text: &str,
116 style: &TextStyle,
117 line_height: f32,
118 horizontal_alignment: f32,
119 horizontal_mode: HorizontalTextAlignmentMode,
120 wrap: TextWrap,
121) -> Option<AlignedTextLayout> {
122 let color = style.color;
123 let mut layout_style = style.clone();
124 layout_style.color = Color::WHITE;
125 let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
126 let paragraph_align = paragraph_alignment(horizontal_alignment, horizontal_mode);
127 for paragraph in &mut document.paragraphs {
128 paragraph.style.align = paragraph_align;
129 paragraph.style.wrap = wrap;
130 }
131 let layout = ctx
132 .layout_text_document(
133 TextLayoutRequest::new(document)
134 .with_box_size(Size::new(rect.width().max(1.0), rect.height().max(1.0))),
135 )
136 .ok()?;
137 let measurement = layout.measurement();
138 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
139 let aligned_rect = aligned_text_rect_for_layout_with_mode(
140 ctx,
141 rect,
142 &layout,
143 line_height,
144 horizontal_alignment,
145 horizontal_mode,
146 );
147 Some(AlignedTextLayout {
148 origin: Point::new(placement.origin_x, aligned_rect.y()),
149 rect: aligned_rect,
150 layout,
151 color,
152 })
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
157pub enum VerticalAlign {
158 Top,
160 #[default]
164 Center,
165 Bottom,
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub struct TextPlacement {
172 pub horizontal: TextAlign,
173 pub vertical: VerticalAlign,
174}
175
176impl TextPlacement {
177 pub const fn new(horizontal: TextAlign, vertical: VerticalAlign) -> Self {
178 Self {
179 horizontal,
180 vertical,
181 }
182 }
183
184 pub const START: Self = Self::new(TextAlign::Start, VerticalAlign::Center);
186 pub const CENTER: Self = Self::new(TextAlign::Center, VerticalAlign::Center);
188 pub const END: Self = Self::new(TextAlign::End, VerticalAlign::Center);
190 pub const TOP_START: Self = Self::new(TextAlign::Start, VerticalAlign::Top);
192}
193
194impl From<TextAlign> for TextPlacement {
195 fn from(horizontal: TextAlign) -> Self {
197 Self::new(horizontal, VerticalAlign::Center)
198 }
199}
200
201pub(crate) const fn alignment_fraction(align: TextAlign) -> f32 {
203 match align {
204 TextAlign::Start | TextAlign::Left | TextAlign::Justified => 0.0,
205 TextAlign::Center => 0.5,
206 TextAlign::End | TextAlign::Right => 1.0,
207 }
208}
209
210pub trait TextShaper {
213 fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout>;
214}
215
216impl TextShaper for LayoutContext {
217 fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
218 self.layout_document(request)
219 }
220}
221
222impl TextShaper for MeasureCtx {
223 fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
224 self.layout().layout_document(request)
225 }
226}
227
228impl TextShaper for PaintCtx {
229 fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
230 self.layout_text_document(request)
231 }
232}
233
234#[derive(Debug, Clone, Default)]
257pub struct Paragraph {
258 text: String,
259 style: TextStyle,
260 align: TextAlign,
261 layout: Option<TextLayout>,
262 box_width: f32,
264}
265
266impl Paragraph {
267 pub fn new(
270 shaper: &(impl TextShaper + ?Sized),
271 text: impl Into<String>,
272 style: &TextStyle,
273 align: TextAlign,
274 max_width: f32,
275 ) -> Self {
276 let text = text.into();
277 let width = if max_width.is_finite() {
278 max_width.max(1.0)
279 } else {
280 f32::INFINITY
281 };
282 let request = |paragraph_align| {
283 let mut layout_style = style.clone();
286 layout_style.color = Color::WHITE;
287 let mut document = TextDocument::from_plain_text(text.clone(), layout_style);
288 for paragraph in &mut document.paragraphs {
289 paragraph.style.align = paragraph_align;
290 paragraph.style.wrap = TextWrap::Word;
291 }
292 TextLayoutRequest::new(document).with_box_size(Size::new(width, f32::INFINITY))
293 };
294 let mut layout = shaper.shape_document(request(TextAlign::Left)).ok();
298 if !matches!(align, TextAlign::Left | TextAlign::Start)
299 && layout
300 .as_ref()
301 .is_some_and(|layout| layout.lines().len() > 1)
302 {
303 layout = shaper.shape_document(request(align)).ok().or(layout);
304 }
305 let box_width = layout
306 .as_ref()
307 .map_or(0.0, |layout| layout.box_size().width);
308 Self {
309 text,
310 style: style.clone(),
311 align,
312 layout,
313 box_width,
314 }
315 }
316
317 pub fn text(&self) -> &str {
318 &self.text
319 }
320
321 pub fn size(&self) -> Size {
323 self.layout.as_ref().map_or_else(
324 || Size::new(0.0, self.style.line_height),
325 |layout| {
326 let measurement = layout.measurement();
327 Size::new(measurement.width, measurement.height)
328 },
329 )
330 }
331
332 pub fn line_count(&self) -> usize {
333 self.layout
334 .as_ref()
335 .map_or(0, |layout| layout.lines().len())
336 }
337
338 pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, vertical: VerticalAlign) {
341 self.paint_with_color(ctx, rect, vertical, self.style.color);
342 }
343
344 pub fn paint_with_color(
347 &self,
348 ctx: &mut PaintCtx,
349 rect: Rect,
350 vertical: VerticalAlign,
351 color: Color,
352 ) {
353 let Some(layout) = &self.layout else {
354 if !self.text.is_empty() {
355 let style = TextStyle {
356 color,
357 ..self.style.clone()
358 };
359 ctx.draw_text(rect, self.text.clone(), style);
360 }
361 return;
362 };
363 let origin = paragraph_origin(
364 ctx,
365 rect,
366 layout,
367 alignment_fraction(self.align),
368 self.box_width,
369 vertical,
370 );
371 ctx.draw_text_layout_with_color(origin, layout, color);
372 }
373}
374
375pub(crate) fn paragraph_origin(
381 ctx: &PaintCtx,
382 rect: Rect,
383 layout: &TextLayout,
384 horizontal: f32,
385 box_width: f32,
386 vertical: VerticalAlign,
387) -> Point {
388 let measurement = layout.measurement();
389 let lines = layout.lines();
390 let left_aligned = lines.len() <= 1
391 || layout
392 .paragraphs()
393 .iter()
394 .all(|paragraph| matches!(paragraph.style.align, TextAlign::Left | TextAlign::Start));
395 let x = if left_aligned {
396 horizontal_placement(
397 rect,
398 measurement,
399 horizontal,
400 HorizontalTextAlignmentMode::Optical,
401 )
402 .origin_x
403 } else {
404 rect.x() + (rect.width() - box_width) * horizontal
405 };
406 let (height, lone_line) = match lines {
410 [line] => (measurement.height, Some(line)),
411 [first, second, ..] if rect.height() < second.rect.max_y() => {
412 (first.rect.max_y(), Some(first))
413 }
414 _ => (measurement.height, None),
415 };
416 let room = (rect.height() - height).max(0.0);
417 let y = match vertical {
418 VerticalAlign::Top => rect.y(),
419 VerticalAlign::Bottom => rect.y() + room,
420 VerticalAlign::Center => match lone_line {
421 Some(line) => {
422 rect.y() + rect.height() * 0.5 - line.baseline - visual_center(ctx, measurement)
423 }
424 None => rect.y() + room * 0.5,
425 },
426 };
427 Point::new(x, y)
428}
429
430pub fn paint_text(
436 ctx: &mut PaintCtx,
437 rect: Rect,
438 text: &str,
439 style: &TextStyle,
440 placement: impl Into<TextPlacement>,
441) {
442 let placement = placement.into();
443 let paragraph = Paragraph::new(ctx, text, style, placement.horizontal, rect.width());
444 paragraph.paint(ctx, rect, placement.vertical);
445}
446
447pub fn paint_text_line(
450 ctx: &mut PaintCtx,
451 rect: Rect,
452 text: &str,
453 style: &TextStyle,
454 align: TextAlign,
455) {
456 let horizontal = alignment_fraction(align);
457 let horizontal_mode = HorizontalTextAlignmentMode::Optical;
458 if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
459 ctx,
460 rect,
461 text,
462 style,
463 style.line_height,
464 horizontal,
465 horizontal_mode,
466 TextWrap::NoWrap,
467 ) {
468 ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
469 return;
470 }
471
472 let fallback_rect = aligned_text_rect_for_text_with_mode(
473 ctx,
474 rect,
475 text,
476 style,
477 style.line_height,
478 horizontal,
479 horizontal_mode,
480 );
481 ctx.draw_text(fallback_rect, text.to_string(), style.clone());
482}
483
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
486pub enum TextOverflow {
487 #[default]
490 Clip,
491 Ellipsis,
494}
495
496const ELLIPSIS: &str = "\u{2026}";
497
498const FIT_TOLERANCE: f32 = 0.01;
501
502#[derive(Debug, Clone, Default)]
515pub struct ElidedLine {
516 text: String,
517 style: TextStyle,
518 elided: bool,
519 width: f32,
520}
521
522impl ElidedLine {
523 pub fn new(
526 shaper: &(impl TextShaper + ?Sized),
527 text: &str,
528 style: &TextStyle,
529 max_width: f32,
530 ) -> Self {
531 let line_end = text.find(['\n', '\r']);
532 let line = &text[..line_end.unwrap_or(text.len())];
533 let more_lines = line_end.is_some();
534 let fitted = |text: String, elided: bool, width: f32| Self {
535 text,
536 style: style.clone(),
537 elided,
538 width,
539 };
540 let fits = |width: f32| width <= max_width + FIT_TOLERANCE;
541 let Some(full) = single_line_layout(shaper, line, style) else {
542 return fitted(line.to_string(), more_lines, 0.0);
544 };
545 let full_width = full.measurement().width;
546 if !more_lines && (!max_width.is_finite() || fits(full_width)) {
547 return fitted(line.to_string(), false, full_width);
548 }
549 let width_of = |text: &str| {
550 single_line_layout(shaper, text, style).map(|layout| layout.measurement().width)
551 };
552 let ellipsis_width = width_of(ELLIPSIS).unwrap_or(0.0);
553
554 let boundaries = line
557 .grapheme_indices(true)
558 .map(|(start, _)| start)
559 .chain([line.len()])
560 .collect::<Vec<_>>();
561 let mut widths = vec![0.0_f32; boundaries.len() - 1];
562 for cluster in full.clusters() {
563 let index = boundaries
564 .partition_point(|&boundary| boundary <= cluster.byte_range.start)
565 .saturating_sub(1);
566 if let Some(width) = widths.get_mut(index) {
567 *width += cluster.rect.width();
568 }
569 }
570 let budget = max_width - ellipsis_width;
571 let mut kept = 0;
572 let mut kept_width = 0.0;
573 for width in &widths {
574 if kept_width + width > budget + FIT_TOLERANCE {
575 break;
576 }
577 kept_width += width;
578 kept += 1;
579 }
580 if !more_lines {
581 kept = kept.min(widths.len().saturating_sub(1));
583 }
584
585 while kept > 0 {
588 let start = line[..boundaries[kept]].trim_end();
589 if start.is_empty() {
590 break;
591 }
592 let shown = format!("{start}{ELLIPSIS}");
593 match width_of(&shown) {
594 Some(width) if fits(width) => return fitted(shown, true, width),
595 Some(_) => kept -= 1,
596 None => return fitted(shown, true, 0.0),
597 }
598 }
599 if fits(ellipsis_width) || line.is_empty() {
600 return fitted(ELLIPSIS.to_string(), true, ellipsis_width);
601 }
602 let first = line.graphemes(true).next().unwrap_or(line);
603 fitted(first.to_string(), true, width_of(first).unwrap_or(0.0))
604 }
605
606 pub fn text(&self) -> &str {
608 &self.text
609 }
610
611 pub fn is_elided(&self) -> bool {
613 self.elided
614 }
615
616 pub fn width(&self) -> f32 {
618 self.width
619 }
620
621 pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign) {
624 self.paint_with_color(ctx, rect, align, self.style.color);
625 }
626
627 pub fn paint_with_color(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign, color: Color) {
629 let style = TextStyle {
630 color,
631 ..self.style.clone()
632 };
633 let overflows = self.width > rect.width() + FIT_TOLERANCE;
634 if overflows {
635 let slack = style.line_height.max(rect.height());
638 ctx.push_clip_rect(Rect::new(
639 rect.x(),
640 rect.y() - slack,
641 rect.width().max(0.0),
642 rect.height() + slack * 2.0,
643 ));
644 }
645 paint_text_line(ctx, rect, &self.text, &style, align);
646 if overflows {
647 ctx.pop_clip();
648 }
649 }
650}
651
652pub fn paint_text_line_elided(
656 ctx: &mut PaintCtx,
657 rect: Rect,
658 text: &str,
659 style: &TextStyle,
660 align: TextAlign,
661) {
662 ElidedLine::new(ctx, text, style, rect.width()).paint(ctx, rect, align);
663}
664
665fn single_line_layout(
667 shaper: &(impl TextShaper + ?Sized),
668 text: &str,
669 style: &TextStyle,
670) -> Option<TextLayout> {
671 let mut layout_style = style.clone();
672 layout_style.color = Color::WHITE;
673 let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
674 for paragraph in &mut document.paragraphs {
675 paragraph.style.align = TextAlign::Left;
676 paragraph.style.wrap = TextWrap::NoWrap;
677 }
678 shaper.shape_document(TextLayoutRequest::new(document)).ok()
679}
680
681pub(crate) fn paint_aligned_text_contained(
682 ctx: &mut PaintCtx,
683 rect: Rect,
684 text: &str,
685 style: &TextStyle,
686 line_height: f32,
687 horizontal_alignment: f32,
688) {
689 let horizontal_mode = HorizontalTextAlignmentMode::Optical;
690 if let Some(aligned) = aligned_text_layout_for_text_with_mode(
691 ctx,
692 rect,
693 text,
694 style,
695 line_height,
696 horizontal_alignment,
697 horizontal_mode,
698 ) {
699 let painted = painted_layout_rect(aligned.origin, &aligned.layout);
700 let offset = containment_offset(painted, rect);
701 ctx.draw_text_layout_with_color(aligned.origin + offset, &aligned.layout, aligned.color);
702 return;
703 }
704
705 let fallback_rect = aligned_text_rect_for_text_with_mode(
706 ctx,
707 rect,
708 text,
709 style,
710 line_height,
711 horizontal_alignment,
712 horizontal_mode,
713 );
714 ctx.draw_text(
715 fallback_rect.translate(containment_offset(fallback_rect, rect)),
716 text.to_string(),
717 style.clone(),
718 );
719}
720
721fn painted_layout_rect(origin: Point, layout: &TextLayout) -> Rect {
722 let measurement = layout.measurement();
723 let bounds = measurement.bounds;
724 let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
725 bounds.width()
726 } else {
727 measurement.width
728 };
729 Rect::new(
730 origin.x + bounds.x(),
731 origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
732 width,
733 layout.style().line_height.max(measurement.height),
734 )
735}
736
737fn containment_offset(inner: Rect, outer: Rect) -> sui_core::Vector {
738 fn axis_offset(inner_min: f32, inner_max: f32, outer_min: f32, outer_max: f32) -> f32 {
739 let inner_size = inner_max - inner_min;
740 let outer_size = outer_max - outer_min;
741 if inner_size > outer_size || inner_min < outer_min {
742 outer_min - inner_min
743 } else if inner_max > outer_max {
744 outer_max - inner_max
745 } else {
746 0.0
747 }
748 }
749
750 sui_core::Vector::new(
751 axis_offset(inner.x(), inner.max_x(), outer.x(), outer.max_x()),
752 axis_offset(inner.y(), inner.max_y(), outer.y(), outer.max_y()),
753 )
754}
755
756pub fn wrap_text_lines(
762 text: &str,
763 max_width: f32,
764 mut measure: impl FnMut(&str) -> f32,
765) -> Vec<String> {
766 let mut lines = Vec::new();
767 let space_width = measure(" ");
768
769 for paragraph in text.split('\n') {
770 if paragraph.is_empty() {
771 lines.push(String::new());
772 continue;
773 }
774
775 let mut current = String::new();
776 let mut current_width = 0.0_f32;
777 for word in paragraph.split(' ') {
778 let word_width = measure(word);
779 if current.is_empty() {
780 current.push_str(word);
781 current_width = word_width;
782 } else if current_width + space_width + word_width <= max_width {
783 current.push(' ');
784 current.push_str(word);
785 current_width += space_width + word_width;
786 } else {
787 lines.push(std::mem::take(&mut current));
788 current.push_str(word);
789 current_width = word_width;
790 }
791 }
792 lines.push(current);
793 }
794
795 lines
796}
797
798fn paragraph_alignment(
799 horizontal_alignment: f32,
800 horizontal_mode: HorizontalTextAlignmentMode,
801) -> TextAlign {
802 if horizontal_mode == HorizontalTextAlignmentMode::Optical {
803 return TextAlign::Left;
804 }
805
806 let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
807 if horizontal_alignment <= 0.0 {
808 TextAlign::Left
809 } else if horizontal_alignment >= 1.0 {
810 TextAlign::Right
811 } else {
812 TextAlign::Center
813 }
814}
815
816pub(crate) fn aligned_text_rect_for_layout(
817 ctx: &PaintCtx,
818 rect: Rect,
819 layout: &TextLayout,
820 line_height: f32,
821 horizontal_alignment: f32,
822) -> Rect {
823 aligned_text_rect_for_layout_with_mode(
824 ctx,
825 rect,
826 layout,
827 line_height,
828 horizontal_alignment,
829 HorizontalTextAlignmentMode::Advance,
830 )
831}
832
833pub(crate) fn aligned_text_rect_for_layout_with_mode(
834 ctx: &PaintCtx,
835 rect: Rect,
836 layout: &TextLayout,
837 line_height: f32,
838 horizontal_alignment: f32,
839 horizontal_mode: HorizontalTextAlignmentMode,
840) -> Rect {
841 let measurement = layout.measurement();
842 let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
843 let height = line_height.max(measurement.height).min(rect.height());
844 let y = layout
845 .lines()
846 .first()
847 .map(|line| {
848 rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
849 })
850 .unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));
851
852 Rect::new(placement.rect_x, y, placement.rect_width, height)
853}
854
855fn horizontal_placement(
856 rect: Rect,
857 measurement: TextMeasurement,
858 horizontal_alignment: f32,
859 horizontal_mode: HorizontalTextAlignmentMode,
860) -> HorizontalPlacement {
861 let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
862 let (width, origin_shift) = match horizontal_mode {
863 HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
864 HorizontalTextAlignmentMode::Optical => {
865 let bounds = measurement.bounds;
866 if bounds.width().is_finite() && bounds.width() > 0.0 {
867 (bounds.width(), -bounds.x())
868 } else {
869 (measurement.width, 0.0)
870 }
871 }
872 };
873 let rect_width = width.min(rect.width()).max(0.0);
874 let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);
875
876 HorizontalPlacement {
877 rect_x,
878 rect_width,
879 origin_x: rect_x + origin_shift,
880 }
881}
882
883pub(crate) fn vertically_centered_text_rect_y(
884 ctx: &PaintCtx,
885 rect: Rect,
886 measurement: TextMeasurement,
887 height: f32,
888) -> f32 {
889 let visual_center = visual_center(ctx, measurement);
890 let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
891 let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;
892
893 baseline - measurement.ascent - leading_above
894}
895
896fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
897 let optical_centering = window_render_options(ctx.window_id())
898 .map(|options| options.optical_vertical_text_alignment_enabled)
899 .unwrap_or(true);
900 let top = if optical_centering {
901 -measurement.cap_height.unwrap_or(measurement.ascent)
902 } else {
903 -measurement.ascent
904 };
905 let bottom = if optical_centering {
906 measurement.descent * 0.5
907 } else {
908 measurement.descent
909 };
910 (top + bottom) * 0.5
911}
912
913#[cfg(test)]
914mod tests {
915 use super::wrap_text_lines;
916 use std::{cell::RefCell, rc::Rc};
917
918 use sui_core::{Color, Point, Rect, Size};
919 use sui_layout::Constraints;
920 use sui_runtime::{Application, MeasureCtx, PaintCtx, Widget, WindowBuilder};
921 use sui_scene::SceneCommand;
922 use sui_text::{TextAlign, TextStyle};
923
924 use super::{
925 ELLIPSIS, ElidedLine, HorizontalTextAlignmentMode, Paragraph, TextPlacement, VerticalAlign,
926 aligned_text_layout_for_text_with_mode, paint_text, paint_text_line_elided,
927 };
928 use unicode_segmentation::UnicodeSegmentation;
929
930 type Paint = Box<dyn Fn(&mut PaintCtx)>;
931 type Measure = Box<dyn Fn(&mut MeasureCtx)>;
932
933 struct Probe {
935 measure: Option<Measure>,
936 paint: Paint,
937 }
938
939 impl Widget for Probe {
940 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
941 if let Some(measure) = &self.measure {
942 measure(ctx);
943 }
944 constraints.clamp(Size::new(400.0, 600.0))
945 }
946
947 fn paint(&self, ctx: &mut PaintCtx) {
948 (self.paint)(ctx);
949 }
950 }
951
952 #[derive(Debug, Clone, PartialEq)]
955 struct Drawn {
956 text: String,
957 origin: Point,
958 first_baseline: f32,
959 size: Size,
960 line_starts: Vec<f32>,
961 }
962
963 fn render(probe: Probe) -> Vec<Drawn> {
964 let mut runtime = Application::new()
965 .window(WindowBuilder::new().title("Text").root(probe))
966 .build()
967 .unwrap();
968 let window_id = runtime.window_ids()[0];
969 let output = runtime.render(window_id).unwrap();
970 let registry = output.frame.text_layout_registry.as_ref();
971 let mut drawn = Vec::new();
972 output.frame.scene.visit_commands(&mut |command| {
973 if let SceneCommand::DrawShapedText(text) = command
974 && let Some(layout) = text.resolve(registry)
975 {
976 drawn.push(Drawn {
977 text: layout.text().to_string(),
978 origin: text.origin,
979 first_baseline: text.origin.y + layout.lines()[0].baseline,
980 size: Size::new(layout.measurement().width, layout.measurement().height),
981 line_starts: layout.lines().iter().map(|line| line.rect.x()).collect(),
982 });
983 }
984 });
985 drawn
986 }
987
988 fn style() -> TextStyle {
989 TextStyle::new(Color::BLACK)
990 }
991
992 const PARAGRAPH: &str = "several words that wrap onto more than one line of text here";
993
994 #[test]
995 fn a_single_line_is_placed_as_before() {
996 for (align, fraction) in [
999 (TextAlign::Start, 0.0),
1000 (TextAlign::Center, 0.5),
1001 (TextAlign::End, 1.0),
1002 ] {
1003 let drawn = render(Probe {
1004 measure: None,
1005 paint: Box::new(move |ctx| {
1006 let rect = Rect::new(20.0, 30.0, 300.0, 44.0);
1007 paint_text(ctx, rect, "Label", &style(), align);
1008 let before = aligned_text_layout_for_text_with_mode(
1009 ctx,
1010 rect.translate(sui_core::Vector::new(0.0, 100.0)),
1011 "Label",
1012 &style(),
1013 style().line_height,
1014 fraction,
1015 HorizontalTextAlignmentMode::Optical,
1016 )
1017 .unwrap();
1018 ctx.draw_text_layout_with_color(before.origin, &before.layout, Color::BLACK);
1019 }),
1020 });
1021 let [now, before] = &drawn[..] else {
1022 panic!("two texts are drawn: {drawn:?}");
1023 };
1024 assert!(
1025 (now.origin.x - before.origin.x).abs() < 0.001,
1026 "{align:?}: {now:?} vs {before:?}"
1027 );
1028 assert!(
1029 (now.first_baseline + 100.0 - before.first_baseline).abs() < 0.001,
1030 "{align:?}: {now:?} vs {before:?}"
1031 );
1032 }
1033 }
1034
1035 #[test]
1036 fn several_lines_are_placed_as_a_block() {
1037 let rect = Rect::new(10.0, 20.0, 160.0, 300.0);
1038 let placed = |vertical| {
1039 render(Probe {
1040 measure: None,
1041 paint: Box::new(move |ctx| {
1042 paint_text(
1043 ctx,
1044 rect,
1045 PARAGRAPH,
1046 &style(),
1047 TextPlacement::new(TextAlign::Start, vertical),
1048 );
1049 }),
1050 })
1051 .remove(0)
1052 };
1053
1054 let top = placed(VerticalAlign::Top);
1055 assert!(top.line_starts.len() > 2, "{top:?}");
1056 let height = top.size.height;
1057 assert!((top.origin.y - rect.y()).abs() < 0.001, "{top:?}");
1058 let center = placed(VerticalAlign::Center);
1059 assert!(
1060 (center.origin.y - (rect.y() + (rect.height() - height) * 0.5)).abs() < 0.001,
1061 "{center:?}"
1062 );
1063 let bottom = placed(VerticalAlign::Bottom);
1064 assert!(
1065 (bottom.origin.y - (rect.max_y() - height)).abs() < 0.001,
1066 "{bottom:?}"
1067 );
1068
1069 let shorter = Rect::new(10.0, 20.0, 160.0, height * 0.9);
1072 let overflowing = render(Probe {
1073 measure: None,
1074 paint: Box::new(move |ctx| {
1075 paint_text(ctx, shorter, PARAGRAPH, &style(), TextAlign::Start);
1076 }),
1077 })
1078 .remove(0);
1079 assert!(
1080 (overflowing.origin.y - shorter.y()).abs() < 0.001,
1081 "{overflowing:?}"
1082 );
1083
1084 let one_line = Rect::new(10.0, 20.0, 160.0, 12.0);
1087 let drawn = render(Probe {
1088 measure: None,
1089 paint: Box::new(move |ctx| {
1090 paint_text(ctx, one_line, PARAGRAPH, &style(), TextAlign::Start);
1091 paint_text(ctx, one_line, "several", &style(), TextAlign::Start);
1092 }),
1093 });
1094 let [wrapped, alone] = &drawn[..] else {
1095 panic!("two texts are drawn: {drawn:?}");
1096 };
1097 assert!(wrapped.line_starts.len() > 1, "{wrapped:?}");
1098 assert!(
1099 (wrapped.first_baseline - alone.first_baseline).abs() < 0.001,
1100 "{wrapped:?} vs {alone:?}"
1101 );
1102 }
1103
1104 #[test]
1105 fn centered_lines_are_centered_one_by_one() {
1106 let drawn = render(Probe {
1107 measure: None,
1108 paint: Box::new(|ctx| {
1109 paint_text(
1110 ctx,
1111 Rect::new(0.0, 0.0, 160.0, 300.0),
1112 PARAGRAPH,
1113 &style(),
1114 TextAlign::Center,
1115 );
1116 }),
1117 })
1118 .remove(0);
1119 let first = drawn.line_starts[0];
1120 assert!(
1121 drawn
1122 .line_starts
1123 .iter()
1124 .any(|start| (start - first).abs() > 1.0),
1125 "lines of different widths start at different places: {drawn:?}"
1126 );
1127 }
1128
1129 #[test]
1130 fn a_paragraph_paints_the_layout_it_measured() {
1131 let measured = Rc::new(RefCell::new(Paragraph::default()));
1132 let laid_out = Rc::clone(&measured);
1133 let painted = Rc::clone(&measured);
1134 let drawn = render(Probe {
1135 measure: Some(Box::new(move |ctx| {
1136 *laid_out.borrow_mut() =
1137 Paragraph::new(ctx, PARAGRAPH, &style(), TextAlign::Start, 160.0);
1138 })),
1139 paint: Box::new(move |ctx| {
1140 let paragraph = painted.borrow();
1141 let rect = Rect::from_origin_size(Point::new(5.0, 7.0), paragraph.size());
1142 paragraph.paint(ctx, rect, VerticalAlign::Top);
1143 }),
1144 })
1145 .remove(0);
1146
1147 let paragraph = measured.borrow();
1148 assert!(paragraph.line_count() > 2);
1149 assert_eq!(drawn.text, PARAGRAPH);
1150 assert_eq!(drawn.size, paragraph.size());
1151 assert!((drawn.origin.y - 7.0).abs() < 0.001, "{drawn:?}");
1152 }
1153
1154 fn fit(texts: &[&str], widths: &[f32]) -> Vec<(String, f32, ElidedLine)> {
1156 let fitted = Rc::new(RefCell::new(Vec::new()));
1157 let results = Rc::clone(&fitted);
1158 let texts = texts
1159 .iter()
1160 .map(|text| text.to_string())
1161 .collect::<Vec<_>>();
1162 let widths = widths.to_vec();
1163 render(Probe {
1164 measure: Some(Box::new(move |ctx| {
1165 let mut results = results.borrow_mut();
1166 results.clear();
1167 for text in &texts {
1168 for &width in &widths {
1169 let line = ElidedLine::new(ctx, text, &style(), width);
1170 results.push((text.clone(), width, line));
1171 }
1172 }
1173 })),
1174 paint: Box::new(|_| {}),
1175 });
1176 fitted.take()
1177 }
1178
1179 fn full_width(text: &str) -> f32 {
1180 fit(&[text], &[f32::INFINITY])[0].2.width()
1181 }
1182
1183 #[test]
1184 fn an_elided_line_keeps_text_that_fits() {
1185 let text = "Channels";
1186 let width = full_width(text);
1187 for max_width in [width, width + 40.0, f32::INFINITY] {
1188 let (_, _, line) = &fit(&[text], &[max_width])[0];
1189 assert_eq!(line.text(), text);
1190 assert!(!line.is_elided());
1191 assert!((line.width() - width).abs() < 0.001, "{line:?}");
1192 }
1193 }
1194
1195 #[test]
1196 fn an_elided_line_cuts_between_characters_and_ends_in_an_ellipsis() {
1197 let texts = [
1198 "The user asks to reply exactly V5_OK",
1199 "Cafe\u{301} cre\u{300}me bru\u{302}le\u{301}e",
1200 "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467} family \u{1F44D}\u{1F3FD} ok",
1201 "\u{5E9}\u{5DC}\u{5D5}\u{5DD} \u{5E2}\u{5D5}\u{5DC}\u{5DD} \u{5D8}\u{5D5}\u{5D1}",
1202 "Mixed \u{5E2}\u{5D1}\u{5E8}\u{5D9}\u{5EA} and English text",
1203 ];
1204 let ellipsis = full_width(ELLIPSIS);
1205 let widths = (0..=60).map(|step| step as f32 * 6.0).collect::<Vec<_>>();
1206 for (text, max_width, line) in fit(&texts, &widths) {
1207 let width = full_width(&text);
1208 if !line.is_elided() {
1209 assert!(
1210 width <= max_width + 0.01,
1211 "{text:?} in {max_width}: {line:?}"
1212 );
1213 assert_eq!(line.text(), text);
1214 continue;
1215 }
1216 assert!(width > max_width, "{text:?} in {max_width} fits: {line:?}");
1217 if max_width < ellipsis {
1218 let first = text.graphemes(true).next().unwrap();
1219 assert_eq!(line.text(), first, "{text:?} in {max_width}");
1220 continue;
1221 }
1222 assert!(
1223 line.width() <= max_width + 0.01,
1224 "{text:?} in {max_width}: {line:?}"
1225 );
1226 let start = line
1227 .text()
1228 .strip_suffix(ELLIPSIS)
1229 .unwrap_or_else(|| panic!("{text:?} in {max_width}: {line:?}"));
1230 assert!(text.starts_with(start), "{text:?} in {max_width}: {line:?}");
1231 assert!(
1232 text.grapheme_indices(true)
1233 .any(|(index, _)| index == start.len())
1234 || start.is_empty(),
1235 "{text:?} in {max_width} is cut inside a character: {line:?}"
1236 );
1237 assert_eq!(start, start.trim_end(), "{text:?} in {max_width}: {line:?}");
1238 }
1239 }
1240
1241 #[test]
1242 fn an_elided_line_keeps_as_many_characters_as_fit() {
1243 let text = "abcdefghijklmnopqrstuvwxyz";
1244 let width = full_width(text);
1245 for (_, max_width, line) in fit(&[text], &[width * 0.3, width * 0.6, width - 1.0]) {
1246 let kept = line.text().strip_suffix(ELLIPSIS).unwrap();
1247 let one_more = format!("{}{ELLIPSIS}", &text[..kept.len() + 1]);
1248 assert!(
1249 full_width(&one_more) > max_width,
1250 "one more character would have fit in {max_width}: {line:?}"
1251 );
1252 }
1253 }
1254
1255 #[test]
1256 fn an_elided_line_shows_the_first_line_of_several() {
1257 let (_, _, line) = &fit(&["First line\nSecond line"], &[f32::INFINITY])[0];
1258 assert_eq!(line.text(), "First line\u{2026}");
1259 assert!(line.is_elided());
1260 }
1261
1262 #[test]
1263 fn a_line_too_narrow_for_an_ellipsis_shows_its_first_character_clipped() {
1264 let rect = Rect::new(20.0, 30.0, 2.0, 20.0);
1265 let clips = Rc::new(RefCell::new(Vec::new()));
1266 let mut runtime = Application::new()
1267 .window(WindowBuilder::new().title("Text").root(Probe {
1268 measure: None,
1269 paint: Box::new(move |ctx| {
1270 paint_text_line_elided(ctx, rect, "Channels", &style(), TextAlign::Start);
1271 }),
1272 }))
1273 .build()
1274 .unwrap();
1275 let window_id = runtime.window_ids()[0];
1276 let output = runtime.render(window_id).unwrap();
1277 let registry = output.frame.text_layout_registry.as_ref();
1278 let mut stack = Vec::new();
1279 output
1280 .frame
1281 .scene
1282 .visit_commands(&mut |command| match command {
1283 SceneCommand::PushClip { rect } => stack.push(*rect),
1284 SceneCommand::PopClip => {
1285 stack.pop();
1286 }
1287 SceneCommand::DrawShapedText(text) => {
1288 let layout = text.resolve(registry).unwrap();
1289 clips
1290 .borrow_mut()
1291 .push((layout.text().to_string(), stack.last().copied()));
1292 }
1293 _ => {}
1294 });
1295 let [(text, Some(clip))] = &clips.borrow()[..] else {
1296 panic!("one clipped text is drawn: {:?}", clips.borrow());
1297 };
1298 assert_eq!(text, "C");
1299 assert_eq!((clip.x(), clip.width()), (rect.x(), rect.width()));
1300 assert!(
1301 clip.y() < rect.y() && clip.max_y() > rect.max_y(),
1302 "{clip:?}"
1303 );
1304 }
1305
1306 #[test]
1307 fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
1308 let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
1309 text.chars().count() as f32
1310 });
1311
1312 assert_eq!(
1313 lines,
1314 vec![
1315 "alpha beta".to_string(),
1316 "superlongword".to_string(),
1317 "gamma".to_string(),
1318 ]
1319 );
1320 }
1321}