1use crate::color::{Color, FontStyle};
37use crate::error::Error;
38use crate::geometry::{Point, Rect, Size};
39use crate::widget::VisualState;
40use unicode_segmentation::UnicodeSegmentation;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum TextJustify {
45 Left,
47 Center,
49 Right,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59pub enum Truncate {
60 None,
62 #[default]
64 End,
65 Start,
67 Middle,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73pub enum Wrap {
74 #[default]
76 None,
77 Word,
79 Anywhere,
81}
82
83pub const ELLIPSIS: &str = "\u{2026}";
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct TextDrawn {
89 pub size: Size,
91 pub truncated: bool,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum CachePolicy {
98 #[default]
101 TextureCache,
102
103 DirectDraw,
107}
108
109#[derive(Debug, Clone, PartialEq)]
111pub struct TextStyle {
112 pub font_name: String,
114
115 pub font_style: FontStyle,
117
118 pub font_size: u16,
120
121 pub font_color: Color,
123
124 pub justification: TextJustify,
126}
127
128impl TextStyle {
129 pub fn new(
143 font_name: String,
144 font_style: FontStyle,
145 font_size: u16,
146 font_color: Color,
147 justification: TextJustify,
148 ) -> Self {
149 Self {
150 font_name,
151 font_style,
152 font_size,
153 font_color,
154 justification,
155 }
156 }
157}
158
159pub trait Painter {
165 fn cache_policy(&self) -> CachePolicy;
171
172 fn fill(&mut self, color: Color);
178
179 fn fill_rect(&mut self, bounds: Rect, color: Color);
186
187 fn rect(&mut self, bounds: Rect, color: Color);
194
195 fn line(&mut self, from: Point, to: Point, color: Color);
203
204 fn text(&mut self, bounds: Rect, style: &TextStyle, color: Color, msg: &str) -> Size;
218
219 fn line_height(&mut self, style: &TextStyle) -> u32;
229
230 fn text_width(&mut self, style: &TextStyle, msg: &str) -> u32;
241
242 fn image(&mut self, path: &str, bounds: Rect) -> Result<(), Error>;
257
258 fn dither(&mut self, bounds: Rect, first: Color, second: Color);
267
268 fn dither_overlay(&mut self, bounds: Rect, color: Color);
277
278 fn clip(&mut self, bounds: Option<Rect>);
284}
285
286pub fn fill(p: &mut dyn Painter, color: Color) {
295 p.fill(color);
296}
297
298pub fn border(p: &mut dyn Painter, size: Size, color: Color, width: u8) {
310 for i in 0..width as u32 {
311 if i * 2 >= size.w || i * 2 >= size.h {
312 break;
313 }
314
315 p.rect(
316 Rect::new(i as i32, i as i32, size.w - i * 2, size.h - i * 2),
317 color,
318 );
319 }
320}
321
322pub fn state_overlay(p: &mut dyn Painter, size: Size, state: VisualState) {
339 if size.w == 0 || size.h == 0 {
340 return;
341 }
342
343 if state.contains(VisualState::INDETERMINATE) && size.h >= 3 {
344 let y = (size.h / 2) as i32;
345
346 p.dither_overlay(
347 Rect::new(1, y, size.w.saturating_sub(2).max(1), 1),
348 Color::BLACK,
349 );
350 }
351
352 if state.contains(VisualState::FOCUSED) && size.w > 2 && size.h > 2 {
353 let outline = Color::BLACK;
354 let (w, h) = (size.w - 2, size.h - 2);
355
356 p.dither_overlay(Rect::new(1, 1, w, 1), outline);
357 p.dither_overlay(Rect::new(1, h as i32, w, 1), outline);
358 p.dither_overlay(Rect::new(1, 1, 1, h), outline);
359 p.dither_overlay(Rect::new(w as i32, 1, 1, h), outline);
360 }
361
362 if state.contains(VisualState::DISABLED) {
363 p.dither_overlay(Rect::new(0, 0, size.w, size.h), Color::WHITE);
364 }
365}
366
367pub fn text(
387 p: &mut dyn Painter,
388 bounds: Rect,
389 style: &TextStyle,
390 color: Color,
391 msg: &str,
392 truncate: Truncate,
393) -> TextDrawn {
394 if msg.is_empty() || bounds.w == 0 {
395 return TextDrawn {
396 size: Size::new(0, 0),
397 truncated: false,
398 };
399 }
400
401 let shortened = fit_text(msg, bounds.w, truncate, &mut |s| p.text_width(style, s));
402 let truncated = shortened.is_some();
403 let drawn = shortened.as_deref().unwrap_or(msg);
404
405 if drawn.is_empty() {
406 return TextDrawn {
407 size: Size::new(0, 0),
408 truncated,
409 };
410 }
411
412 TextDrawn {
413 size: p.text(bounds, style, color, drawn),
414 truncated,
415 }
416}
417
418pub fn fit_text(
434 msg: &str,
435 max_width: u32,
436 mode: Truncate,
437 measure: &mut dyn FnMut(&str) -> u32,
438) -> Option<String> {
439 if mode == Truncate::None || msg.contains('\n') || measure(msg) <= max_width {
440 return None;
441 }
442
443 let graphemes: Vec<&str> = msg.graphemes(true).collect();
444 let build = |keep: usize| -> String {
445 match mode {
446 Truncate::Start => {
447 format!("{ELLIPSIS}{}", graphemes[graphemes.len() - keep..].concat())
448 }
449 Truncate::Middle => {
450 let head = keep.div_ceil(2);
451 let tail = keep - head;
452
453 format!(
454 "{}{ELLIPSIS}{}",
455 graphemes[..head].concat(),
456 graphemes[graphemes.len() - tail..].concat()
457 )
458 }
459 _ => format!("{}{ELLIPSIS}", graphemes[..keep].concat()),
460 }
461 };
462
463 let (mut low, mut high) = (0, graphemes.len());
465 let mut best: Option<String> = None;
466
467 while low <= high {
468 let mid = (low + high) / 2;
469 let candidate = build(mid);
470
471 if measure(&candidate) <= max_width {
472 best = Some(candidate);
473 low = mid + 1;
474 } else if mid == 0 {
475 break;
476 } else {
477 high = mid - 1;
478 }
479 }
480
481 Some(best.unwrap_or_default())
482}
483
484pub fn wrap_text(
505 msg: &str,
506 max_width: u32,
507 wrap: Wrap,
508 max_lines: Option<usize>,
509 measure: &mut dyn FnMut(&str) -> u32,
510) -> (Vec<String>, bool) {
511 let mut lines: Vec<String> = Vec::new();
512
513 for paragraph in msg.split('\n') {
514 match wrap {
515 Wrap::None => lines.push(paragraph.to_string()),
516 Wrap::Anywhere => break_graphemes(paragraph, max_width, measure, &mut lines),
517 Wrap::Word => break_words(paragraph, max_width, measure, &mut lines),
518 }
519 }
520
521 let Some(limit) = max_lines.map(|n| n.max(1)) else {
522 return (lines, false);
523 };
524
525 if lines.len() <= limit {
526 return (lines, false);
527 }
528
529 lines.truncate(limit);
530
531 let last = format!("{}{ELLIPSIS}", lines[limit - 1]);
534 let cut = fit_text(&last, max_width, Truncate::End, measure).unwrap_or(last);
535
536 lines[limit - 1] = cut;
537
538 (lines, true)
539}
540
541fn break_graphemes(
550 text: &str,
551 max_width: u32,
552 measure: &mut dyn FnMut(&str) -> u32,
553 out: &mut Vec<String>,
554) {
555 let mut current = String::new();
556
557 for g in text.graphemes(true) {
558 let candidate = format!("{current}{g}");
559
560 if current.is_empty() || measure(&candidate) <= max_width {
561 current = candidate;
562 } else {
563 out.push(std::mem::replace(&mut current, g.to_string()));
564 }
565 }
566
567 out.push(current);
568}
569
570fn break_words(
579 text: &str,
580 max_width: u32,
581 measure: &mut dyn FnMut(&str) -> u32,
582 out: &mut Vec<String>,
583) {
584 let mut current = String::new();
585
586 for word in text.split(' ').filter(|w| !w.is_empty()) {
587 let candidate = if current.is_empty() {
588 word.to_string()
589 } else {
590 format!("{current} {word}")
591 };
592
593 if measure(&candidate) <= max_width {
594 current = candidate;
595 continue;
596 }
597
598 if !current.is_empty() {
599 out.push(std::mem::take(&mut current));
600 }
601
602 if measure(word) <= max_width {
603 current = word.to_string();
604 } else {
605 let mut pieces = Vec::new();
608
609 break_graphemes(word, max_width, measure, &mut pieces);
610 current = pieces.pop().unwrap_or_default();
611 out.extend(pieces);
612 }
613 }
614
615 out.push(current);
616}
617
618pub fn height_for_width(
634 p: &mut dyn Painter,
635 style: &TextStyle,
636 msg: &str,
637 width: u32,
638 wrap: Wrap,
639 max_lines: Option<usize>,
640) -> u32 {
641 if msg.is_empty() {
642 return 0;
643 }
644
645 let (lines, _) = wrap_text(msg, width, wrap, max_lines, &mut |s| p.text_width(style, s));
646
647 lines.len() as u32 * p.line_height(style)
648}
649
650pub fn paragraph(
669 p: &mut dyn Painter,
670 bounds: Rect,
671 style: &TextStyle,
672 color: Color,
673 msg: &str,
674 wrap: Wrap,
675 max_lines: Option<usize>,
676) -> TextDrawn {
677 if msg.is_empty() || bounds.w == 0 {
678 return TextDrawn {
679 size: Size::new(0, 0),
680 truncated: false,
681 };
682 }
683
684 let (lines, truncated) = wrap_text(msg, bounds.w, wrap, max_lines, &mut |s| {
685 p.text_width(style, s)
686 });
687 let line_h = p.line_height(style);
688 let block_h = lines.len() as u32 * line_h;
689 let top = if block_h < bounds.h {
690 bounds.y + (bounds.h - block_h) as i32 / 2
691 } else {
692 bounds.y
693 };
694 let bottom = bounds.y + bounds.h as i32;
695 let mut widest = 0;
696
697 for (i, line) in lines.iter().enumerate() {
698 let y = top + i as i32 * line_h as i32;
699
700 if y >= bottom {
701 break;
702 }
703
704 if !line.is_empty() {
705 let drawn = p.text(Rect::new(bounds.x, y, bounds.w, line_h), style, color, line);
706
707 widest = widest.max(drawn.w);
708 }
709 }
710
711 TextDrawn {
712 size: Size::new(widest, block_h),
713 truncated,
714 }
715}
716
717pub fn align_text(bounds: Rect, text_size: Size, justification: TextJustify) -> Rect {
732 let bounds_width = bounds.w as i32;
733 let x = bounds.x
734 + match justification {
735 TextJustify::Left => 0,
736 TextJustify::Right => bounds_width - text_size.w as i32,
737 TextJustify::Center => (bounds_width - text_size.w as i32) / 2,
738 };
739 let y = if text_size.h < bounds.h {
740 bounds.y + (bounds.h - text_size.h) as i32 / 2
741 } else {
742 bounds.y
743 };
744
745 Rect::new(x, y, text_size.w, text_size.h)
746}
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751 use crate::backend::headless::{PaintCall, RecordingPainter};
752
753 fn style(justification: TextJustify) -> TextStyle {
754 TextStyle::new(
755 String::from("font.ttf"),
756 FontStyle::NORMAL,
757 10,
758 Color::BLACK,
759 justification,
760 )
761 }
762
763 #[test]
764 fn state_overlay_draws_nothing_for_the_normal_state() {
765 let mut p = RecordingPainter::default();
766 state_overlay(&mut p, Size::new(40, 20), VisualState::empty());
767 state_overlay(
768 &mut p,
769 Size::new(40, 20),
770 VisualState::CHECKED | VisualState::HOVERED,
771 );
772 assert!(p.calls.is_empty());
773 }
774
775 #[test]
776 fn state_overlay_dims_disabled_widgets_last() {
777 let mut p = RecordingPainter::default();
778 state_overlay(
779 &mut p,
780 Size::new(40, 20),
781 VisualState::DISABLED | VisualState::FOCUSED,
782 );
783
784 assert_eq!(
785 p.calls.last(),
786 Some(&PaintCall::DitherOverlay(
787 Rect::new(0, 0, 40, 20),
788 Color::WHITE
789 ))
790 );
791 assert_eq!(p.calls.len(), 5, "four focus edges, then the dim");
792 }
793
794 #[test]
795 fn state_overlay_draws_a_focus_outline_and_an_indeterminate_bar() {
796 let mut p = RecordingPainter::default();
797 state_overlay(&mut p, Size::new(40, 20), VisualState::FOCUSED);
798 assert_eq!(p.calls.len(), 4);
799
800 let mut p = RecordingPainter::default();
801 state_overlay(&mut p, Size::new(40, 20), VisualState::INDETERMINATE);
802 assert_eq!(
803 p.calls,
804 vec![PaintCall::DitherOverlay(
805 Rect::new(1, 10, 38, 1),
806 Color::BLACK
807 )]
808 );
809 }
810
811 #[test]
812 fn state_overlay_ignores_empty_and_tiny_surfaces() {
813 let mut p = RecordingPainter::default();
814 state_overlay(&mut p, Size::new(0, 10), VisualState::DISABLED);
815 state_overlay(
816 &mut p,
817 Size::new(2, 2),
818 VisualState::FOCUSED | VisualState::INDETERMINATE,
819 );
820 assert!(p.calls.is_empty());
821 }
822
823 #[test]
824 fn fill_records_one_call() {
825 let mut p = RecordingPainter::default();
826 fill(&mut p, Color::RED);
827 assert_eq!(p.calls, vec![PaintCall::Fill(Color::RED)]);
828 }
829
830 #[test]
831 fn border_insets_each_ring() {
832 let mut p = RecordingPainter::default();
833 border(&mut p, Size::new(10, 10), Color::BLUE, 2);
834 assert_eq!(
835 p.calls,
836 vec![
837 PaintCall::Rect(Rect::new(0, 0, 10, 10), Color::BLUE),
838 PaintCall::Rect(Rect::new(1, 1, 8, 8), Color::BLUE),
839 ]
840 );
841 }
842
843 #[test]
844 fn border_zero_width_draws_nothing() {
845 let mut p = RecordingPainter::default();
846 border(&mut p, Size::new(10, 10), Color::BLUE, 0);
847 assert!(p.calls.is_empty());
848 }
849
850 #[test]
851 fn border_stops_when_it_covers_the_surface() {
852 let mut p = RecordingPainter::default();
853 border(&mut p, Size::new(4, 10), Color::BLUE, 9);
854 assert_eq!(p.calls.len(), 2);
855 }
856
857 #[test]
858 fn empty_text_or_zero_width_draws_nothing() {
859 let mut p = RecordingPainter::default();
860 let s = style(TextJustify::Left);
861 assert_eq!(
862 text(
863 &mut p,
864 Rect::new(0, 0, 50, 20),
865 &s,
866 Color::BLACK,
867 "",
868 Truncate::End
869 )
870 .size,
871 Size::new(0, 0)
872 );
873 assert_eq!(
874 text(
875 &mut p,
876 Rect::new(0, 0, 0, 20),
877 &s,
878 Color::BLACK,
879 "hi",
880 Truncate::End
881 )
882 .size,
883 Size::new(0, 0)
884 );
885 assert!(p.calls.is_empty());
886 }
887
888 #[test]
889 fn text_is_recorded() {
890 let mut p = RecordingPainter::default();
891 let s = style(TextJustify::Left);
892 let drawn = text(
893 &mut p,
894 Rect::new(0, 0, 100, 20),
895 &s,
896 Color::WHITE,
897 "hi",
898 Truncate::End,
899 );
900 assert_ne!(drawn.size, Size::new(0, 0));
901 assert!(!drawn.truncated, "text that fits is drawn unchanged");
902 assert_eq!(
903 p.calls,
904 vec![PaintCall::Text(
905 Rect::new(0, 0, 100, 20),
906 String::from("hi"),
907 Color::WHITE
908 )]
909 );
910 }
911
912 #[test]
913 fn align_text_justifies_and_centers() {
914 let bounds = Rect::new(10, 20, 100, 40);
915 let t = Size::new(30, 10);
916 assert_eq!(
917 align_text(bounds, t, TextJustify::Left),
918 Rect::new(10, 35, 30, 10)
919 );
920 assert_eq!(
921 align_text(bounds, t, TextJustify::Right),
922 Rect::new(80, 35, 30, 10)
923 );
924 assert_eq!(
925 align_text(bounds, t, TextJustify::Center),
926 Rect::new(45, 35, 30, 10)
927 );
928 }
929
930 #[test]
931 fn align_text_top_aligns_when_too_tall() {
932 let bounds = Rect::new(0, 5, 100, 10);
933 assert_eq!(
934 align_text(bounds, Size::new(20, 30), TextJustify::Left),
935 Rect::new(0, 5, 20, 30)
936 );
937 }
938
939 #[test]
940 fn cache_policy_defaults_to_texture_cache() {
941 assert_eq!(CachePolicy::default(), CachePolicy::TextureCache);
942 }
943
944 fn drawn_text(msg: &str, mode: Truncate) -> (String, bool) {
947 let mut p = RecordingPainter::default();
948 let s = style(TextJustify::Left);
949 let drawn = text(&mut p, Rect::new(0, 0, 50, 20), &s, Color::BLACK, msg, mode);
950 let recorded = match p.calls.first() {
951 Some(PaintCall::Text(_, t, _)) => t.clone(),
952 _ => String::new(),
953 };
954
955 (recorded, drawn.truncated)
956 }
957
958 #[test]
959 fn text_that_fits_is_unchanged_in_every_mode() {
960 for mode in [
961 Truncate::None,
962 Truncate::End,
963 Truncate::Start,
964 Truncate::Middle,
965 ] {
966 assert_eq!(
967 drawn_text("0123456789", mode),
968 (String::from("0123456789"), false)
969 );
970 }
971 }
972
973 #[test]
974 fn end_start_and_middle_cut_with_an_ellipsis() {
975 let msg = "Quarterly report.txt";
976
977 assert_eq!(
978 drawn_text(msg, Truncate::End),
979 (String::from("Quarterly\u{2026}"), true)
980 );
981 assert_eq!(
982 drawn_text(msg, Truncate::Start),
983 (String::from("\u{2026}eport.txt"), true)
984 );
985 assert_eq!(
986 drawn_text(msg, Truncate::Middle),
987 (String::from("Quart\u{2026}.txt"), true)
988 );
989 }
990
991 #[test]
992 fn none_leaves_long_text_for_the_backend_to_clip() {
993 assert_eq!(
994 drawn_text("Quarterly report.txt", Truncate::None),
995 (String::from("Quarterly report.txt"), false)
996 );
997 }
998
999 #[test]
1000 fn truncated_text_never_overflows() {
1001 let mut measure = |s: &str| s.chars().count() as u32 * 5;
1002
1003 for mode in [Truncate::End, Truncate::Start, Truncate::Middle] {
1004 for width in 0..60 {
1005 let cut = fit_text("The quick brown fox jumps", width, mode, &mut measure).unwrap();
1006 assert!(measure(&cut) <= width, "{mode:?} at {width}: {cut:?}");
1007 }
1008 }
1009 }
1010
1011 #[test]
1012 fn a_width_too_small_for_the_ellipsis_draws_nothing() {
1013 let mut p = RecordingPainter::default();
1014 let s = style(TextJustify::Left);
1015 let drawn = text(
1016 &mut p,
1017 Rect::new(0, 0, 4, 20),
1018 &s,
1019 Color::BLACK,
1020 "hello",
1021 Truncate::End,
1022 );
1023
1024 assert!(drawn.truncated);
1025 assert_eq!(drawn.size, Size::new(0, 0));
1026 assert!(p.calls.is_empty());
1027 }
1028
1029 #[test]
1030 fn cuts_fall_on_grapheme_boundaries() {
1031 let msg = "e\u{301}e\u{301}e\u{301}\u{1F1FA}\u{1F1F8}\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}ab";
1033 let mut by_graphemes = |s: &str| s.graphemes(true).count() as u32;
1034
1035 for mode in [Truncate::End, Truncate::Start, Truncate::Middle] {
1036 let cut = fit_text(msg, 4, mode, &mut by_graphemes).unwrap();
1037 assert_eq!(cut.graphemes(true).count(), 4, "{mode:?}: {cut:?}");
1038 }
1039
1040 let end = fit_text(msg, 4, Truncate::End, &mut by_graphemes).unwrap();
1041 assert_eq!(end, "e\u{301}e\u{301}e\u{301}\u{2026}");
1042 }
1043
1044 #[test]
1045 fn text_with_a_newline_is_not_truncated() {
1046 let mut measure = |s: &str| s.chars().count() as u32 * 5;
1047
1048 assert_eq!(
1049 fit_text("a long first line\nb", 10, Truncate::End, &mut measure),
1050 None
1051 );
1052 }
1053
1054 #[test]
1055 fn end_is_the_default_mode() {
1056 assert_eq!(Truncate::default(), Truncate::End);
1057 }
1058
1059 fn five(s: &str) -> u32 {
1061 s.chars().count() as u32 * 5
1062 }
1063
1064 #[test]
1065 fn word_wrap_breaks_at_spaces_and_reflows() {
1066 let msg = "the quick brown fox jumps";
1067 let (wide, _) = wrap_text(msg, 100, Wrap::Word, None, &mut five);
1068 let (narrow, _) = wrap_text(msg, 50, Wrap::Word, None, &mut five);
1069
1070 assert_eq!(wide, vec!["the quick brown fox", "jumps"]);
1071 assert_eq!(narrow, vec!["the quick", "brown fox", "jumps"]);
1072 assert!(narrow.iter().all(|l| five(l) <= 50));
1073 }
1074
1075 #[test]
1076 fn explicit_newlines_are_kept_and_blank_lines_stay() {
1077 let (lines, _) = wrap_text("a\n\nb c", 100, Wrap::Word, None, &mut five);
1078
1079 assert_eq!(lines, vec!["a", "", "b c"]);
1080 }
1081
1082 #[test]
1083 fn a_word_wider_than_the_width_is_broken() {
1084 let (lines, _) = wrap_text("abcdefghij kl", 20, Wrap::Word, None, &mut five);
1085
1086 assert_eq!(lines, vec!["abcd", "efgh", "ij", "kl"]);
1087 }
1088
1089 #[test]
1090 fn anywhere_breaks_between_graphemes() {
1091 let (lines, _) = wrap_text("abcdefghij", 25, Wrap::Anywhere, None, &mut five);
1092
1093 assert_eq!(lines, vec!["abcde", "fghij"]);
1094
1095 let (lines, _) = wrap_text(
1096 "e\u{301}e\u{301}e\u{301}",
1097 5,
1098 Wrap::Anywhere,
1099 None,
1100 &mut |s| s.graphemes(true).count() as u32 * 5,
1101 );
1102
1103 assert_eq!(
1104 lines,
1105 vec!["e\u{301}", "e\u{301}", "e\u{301}"],
1106 "accents stay with their letter"
1107 );
1108 }
1109
1110 #[test]
1111 fn max_lines_cuts_the_last_line_with_an_ellipsis() {
1112 let (lines, cut) = wrap_text(
1113 "the quick brown fox jumps",
1114 50,
1115 Wrap::Word,
1116 Some(2),
1117 &mut five,
1118 );
1119
1120 assert!(cut);
1121 assert_eq!(lines.len(), 2);
1122 assert_eq!(lines[0], "the quick");
1123 assert_eq!(lines[1], "brown fox\u{2026}");
1124 assert!(lines.iter().all(|l| five(l) <= 50));
1125
1126 let (lines, cut) = wrap_text("a\nb", 100, Wrap::Word, Some(1), &mut five);
1127
1128 assert!(cut, "an explicit break past the limit also cuts");
1129 assert_eq!(lines, vec!["a\u{2026}"]);
1130
1131 let (_, cut) = wrap_text("a b", 100, Wrap::Word, Some(2), &mut five);
1132
1133 assert!(!cut, "text that fits is not cut");
1134 }
1135
1136 #[test]
1137 fn paragraph_aligns_each_line_and_reports_height() {
1138 let mut p = RecordingPainter::default();
1139 let s = style(TextJustify::Right);
1140 let drawn = paragraph(
1141 &mut p,
1142 Rect::new(0, 0, 50, 40),
1143 &s,
1144 Color::BLACK,
1145 "the quick brown fox",
1146 Wrap::Word,
1147 None,
1148 );
1149
1150 assert_eq!(drawn.size.h, 20, "two lines of ten pixels");
1151 assert!(!drawn.truncated);
1152 assert_eq!(
1153 p.calls,
1154 vec![
1155 PaintCall::Text(
1156 Rect::new(0, 10, 50, 10),
1157 String::from("the quick"),
1158 Color::BLACK
1159 ),
1160 PaintCall::Text(
1161 Rect::new(0, 20, 50, 10),
1162 String::from("brown fox"),
1163 Color::BLACK
1164 ),
1165 ],
1166 "each line gets its own rectangle, so the justification applies per line"
1167 );
1168 }
1169
1170 #[test]
1171 fn paragraph_skips_lines_below_the_bounds() {
1172 let mut p = RecordingPainter::default();
1173 let s = style(TextJustify::Left);
1174
1175 paragraph(
1176 &mut p,
1177 Rect::new(0, 0, 50, 15),
1178 &s,
1179 Color::BLACK,
1180 "a\nb\nc",
1181 Wrap::Word,
1182 None,
1183 );
1184
1185 assert_eq!(
1186 p.calls.len(),
1187 2,
1188 "lines at y 0 and 10 start inside; y 20 does not"
1189 );
1190 }
1191
1192 #[test]
1193 fn height_for_width_grows_as_the_width_shrinks() {
1194 let mut p = RecordingPainter::default();
1195 let s = style(TextJustify::Left);
1196 let msg = "the quick brown fox jumps";
1197
1198 assert_eq!(height_for_width(&mut p, &s, msg, 100, Wrap::Word, None), 20);
1199 assert_eq!(height_for_width(&mut p, &s, msg, 50, Wrap::Word, None), 30);
1200 assert_eq!(
1201 height_for_width(&mut p, &s, msg, 50, Wrap::Word, Some(2)),
1202 20
1203 );
1204 assert_eq!(height_for_width(&mut p, &s, "", 50, Wrap::Word, None), 0);
1205 }
1206}