1use crate::ansi::hyperlink::parse_hyperlink;
65use crate::ansi::params::Params;
66use crate::ansi::text::{TokenKind, string_width, tokenize};
67use crate::buffer::{Bounded, Surface, SurfaceMut};
68use crate::cell::Cell;
69use crate::layout::{Position, Rect, overruns};
70use crate::style::{Style, read_style};
71
72use super::{Pen, TextSurface, WidthMode, WrapMode};
73
74pub struct Painter<'s, S: TextSurface + ?Sized> {
83 target: &'s mut S,
84 mode: WidthMode,
86 eaw_wide: bool,
89}
90
91impl<'s, S: TextSurface + ?Sized> Painter<'s, S> {
92 pub fn new(target: &'s mut S) -> Self {
106 let mode = target.width_mode();
107 let eaw_wide = target.eaw_wide();
108 Self {
109 target,
110 mode,
111 eaw_wide,
112 }
113 }
114
115 fn paint_truncate(
120 &mut self,
121 start: Position,
122 clip: Rect,
123 s: &str,
124 s_pen: Pen,
125 tail_text: &str,
126 tail_pen: Pen,
127 ) -> Position {
128 if clip.is_empty() {
129 return start;
130 }
131 let tail_w = string_width(tail_text.as_bytes(), self.mode, self.eaw_wide) as u16;
132 let tail = if tail_w == 0 || tail_w > clip.width {
133 None
134 } else {
135 Some(Tail {
136 text: tail_text,
137 pen: &tail_pen,
138 width: tail_w,
139 })
140 };
141 self.paint_inner(start, clip, s, WrapMode::Truncate, tail, &s_pen)
142 }
143
144 fn paint_tail(&mut self, tail: Tail<'_>, clip: Rect, y: u16) {
147 let tail_x = clip.right().saturating_sub(tail.width);
148 let sub = Rect::new(tail_x, y, tail.width, 1).intersection(clip);
149 self.paint_inner(
150 Position::new(tail_x, y),
151 sub,
152 tail.text,
153 WrapMode::Truncate,
154 None,
155 tail.pen,
156 );
157 }
158
159 fn paint(
160 &mut self,
161 start: Position,
162 clip: Rect,
163 s: &str,
164 wrap: WrapMode,
165 pen: Pen,
166 ) -> Position {
167 self.paint_inner(start, clip, s, wrap, None, &pen)
168 }
169
170 fn paint_inner(
171 &mut self,
172 start: Position,
173 clip: Rect,
174 s: &str,
175 wrap: WrapMode,
176 tail: Option<Tail<'_>>,
177 base: &Pen,
178 ) -> Position {
179 if clip.is_empty() {
180 return start;
181 }
182 if start.y >= clip.bottom() {
184 return start;
185 }
186 let mut x = start.x;
187 let mut y = start.y;
188 let mut pen = Style::default();
194 let mut link = base.link.clone();
195 let mut pending: Option<(u16, u16, String, u8)> = None;
196 let mut truncated = false;
200
201 for tok in tokenize(s.as_bytes(), self.mode, self.eaw_wide) {
202 if !(tok.kind == TokenKind::Text && tok.width == 0)
206 && let Some((px, py, content, w)) = pending.take()
207 && clip.contains(Position::new(px, py))
208 {
209 let mut cell = Cell::new(&content, w).with_style(pen.inherit(base.style));
210 cell.set_link(link.clone());
211 self.target.set_cell(Position::new(px, py), &cell);
212 }
213
214 match tok.kind {
215 TokenKind::Text if tok.width == 0 => {
221 let text = tok.bytes;
222 if let Some((_, _, ref mut content, _)) = pending {
223 debug_assert!(std::str::from_utf8(text).is_ok());
224 content.push_str(unsafe { std::str::from_utf8_unchecked(text) });
225 }
226 }
227 TokenKind::Text => {
228 let text = tok.bytes;
229 let width = tok.width;
230 debug_assert!(std::str::from_utf8(text).is_ok());
231 if truncated {
232 continue;
233 }
234 let g = unsafe { std::str::from_utf8_unchecked(text) };
235 let cw = width as u8;
236 if overruns(x, u16::from(cw), clip.right()) {
237 match wrap {
238 WrapMode::Truncate => {
239 if let Some(tail) = tail {
240 self.paint_tail(tail, clip, y);
241 x = clip.right();
242 }
243 truncated = true;
244 continue;
245 }
246 WrapMode::Wrap => {
247 y = y.saturating_add(1);
248 x = clip.left();
249 if y >= clip.bottom() {
250 return Position::new(x, y);
251 }
252 if overruns(x, u16::from(cw), clip.right()) {
253 return Position::new(x, y);
254 }
255 }
256 }
257 }
258 pending = Some((x, y, g.to_string(), cw));
259 x += cw as u16;
260 }
261 TokenKind::Escape => {
262 let seq = tok.bytes;
263 if seq.last() == Some(&b'm')
264 && let Some(body) = csi_body(seq)
265 {
266 read_style(Params::from_raw(body), &mut pen);
267 } else if let Some(body) = osc_body(seq)
268 && let Some((params, url)) = parse_hyperlink(body)
269 {
270 link = if url.is_empty() {
271 None
272 } else {
273 Some(std::sync::Arc::new(crate::style::Link {
274 url: url.into(),
275 params: params.into(),
276 }))
277 };
278 }
279 }
280 TokenKind::Control if tok.control == b'\n' => {
281 y = y.saturating_add(1);
282 x = clip.left();
283 truncated = false;
284 if y >= clip.bottom() {
285 return Position::new(x, y);
286 }
287 }
288 TokenKind::Control if tok.control == b'\r' => {
289 x = clip.left();
290 truncated = false;
291 }
292 TokenKind::Control => {}
293 }
294 }
295
296 if let Some((px, py, content, w)) = pending.take()
298 && clip.contains(Position::new(px, py))
299 {
300 let mut cell = Cell::new(&content, w).with_style(pen.inherit(base.style));
301 cell.set_link(link);
302 self.target.set_cell(Position::new(px, py), &cell);
303 }
304 Position::new(x, y)
305 }
306}
307
308impl<'s, S: TextSurface + ?Sized> Bounded for Painter<'s, S> {
309 fn bounds(&self) -> Rect {
310 self.target.bounds()
311 }
312}
313
314impl<'s, S: TextSurface + ?Sized> Surface for Painter<'s, S> {
315 fn cell(&self, pos: Position) -> Option<&Cell> {
316 self.target.cell(pos)
317 }
318}
319
320impl<'s, S: TextSurface + ?Sized> SurfaceMut for Painter<'s, S> {
321 fn set_cell(&mut self, pos: Position, cell: &Cell) {
322 self.target.set_cell(pos, cell);
323 }
324
325 fn cell_mut(&mut self, pos: Position) -> Option<&mut Cell> {
326 self.target.cell_mut(pos)
327 }
328
329 fn insert_lines(&mut self, y: u16, count: u16, bounds_bottom: u16, fill: &Cell) {
330 self.target.insert_lines(y, count, bounds_bottom, fill);
331 }
332
333 fn delete_lines(&mut self, y: u16, count: u16, bounds_bottom: u16, fill: &Cell) {
334 self.target.delete_lines(y, count, bounds_bottom, fill);
335 }
336
337 fn insert_cells(&mut self, pos: Position, count: u16, bounds_right: u16, fill: &Cell) {
338 self.target.insert_cells(pos, count, bounds_right, fill);
339 }
340
341 fn delete_cells(&mut self, pos: Position, count: u16, bounds_right: u16, fill: &Cell) {
342 self.target.delete_cells(pos, count, bounds_right, fill);
343 }
344}
345
346impl<'s, S: TextSurface + ?Sized> TextSurface for Painter<'s, S> {
351 fn width_mode(&self) -> WidthMode {
352 self.mode
353 }
354
355 fn eaw_wide(&self) -> bool {
356 self.eaw_wide
357 }
358
359 fn str_width(&self, s: &str) -> u16 {
364 string_width(s.as_bytes(), self.mode, self.eaw_wide).min(u16::MAX as usize) as u16
365 }
366
367 fn set_str(&mut self, pos: impl Into<Position>, s: &str, pen: impl Into<Pen>) -> Position {
391 let clip = self.target.bounds();
392 self.paint(pos.into(), clip, s, WrapMode::default(), pen.into())
393 }
394
395 fn set_str_wrap(
418 &mut self,
419 pos: impl Into<Position>,
420 s: &str,
421 wrap: WrapMode,
422 pen: impl Into<Pen>,
423 ) -> Position {
424 let clip = self.target.bounds();
425 self.paint(pos.into(), clip, s, wrap, pen.into())
426 }
427
428 fn set_str_rect(&mut self, rect: impl Into<Rect>, s: &str, pen: impl Into<Pen>) -> Position {
449 let rect = rect.into();
450 let clip = rect.intersection(self.target.bounds());
451 self.paint(rect.position(), clip, s, WrapMode::default(), pen.into())
452 }
453
454 fn set_str_rect_wrap(
476 &mut self,
477 rect: impl Into<Rect>,
478 s: &str,
479 wrap: WrapMode,
480 pen: impl Into<Pen>,
481 ) -> Position {
482 let rect = rect.into();
483 let clip = rect.intersection(self.target.bounds());
484 self.paint(rect.position(), clip, s, wrap, pen.into())
485 }
486
487 fn set_str_truncate(
519 &mut self,
520 pos: impl Into<Position>,
521 s: &str,
522 s_pen: impl Into<Pen>,
523 tail: &str,
524 tail_pen: impl Into<Pen>,
525 ) -> Position {
526 let clip = self.target.bounds();
527 self.paint_truncate(pos.into(), clip, s, s_pen.into(), tail, tail_pen.into())
528 }
529
530 fn set_str_rect_truncate(
554 &mut self,
555 rect: impl Into<Rect>,
556 s: &str,
557 s_pen: impl Into<Pen>,
558 tail: &str,
559 tail_pen: impl Into<Pen>,
560 ) -> Position {
561 let rect = rect.into();
562 let clip = rect.intersection(self.target.bounds());
563 self.paint_truncate(
564 rect.position(),
565 clip,
566 s,
567 s_pen.into(),
568 tail,
569 tail_pen.into(),
570 )
571 }
572}
573
574#[derive(Clone, Copy)]
578struct Tail<'a> {
579 text: &'a str,
580 pen: &'a Pen,
581 width: u16,
582}
583
584fn csi_body(seq: &[u8]) -> Option<&[u8]> {
590 let body_start = if seq.starts_with(b"\x1b[") || seq.starts_with(b"\xc2\x9b") {
591 2
592 } else if !seq.is_empty() && seq[0] == 0x9b {
593 1
594 } else {
595 return None;
596 };
597 let last = *seq.last()?;
598 if !(0x40..=0x7e).contains(&last) || seq.len() <= body_start {
599 return None;
600 }
601 Some(&seq[body_start..seq.len() - 1])
602}
603
604fn osc_body(seq: &[u8]) -> Option<&[u8]> {
610 let body_start = if seq.starts_with(b"\x1b]") || seq.starts_with(b"\xc2\x9d") {
611 2
612 } else if !seq.is_empty() && seq[0] == 0x9d {
613 1
614 } else {
615 return None;
616 };
617 if seq.len() <= body_start {
618 return Some(&[]);
619 }
620 let end = if seq.ends_with(b"\x1b\\") || seq.ends_with(b"\xc2\x9c") {
621 seq.len() - 2
622 } else if matches!(seq.last(), Some(0x07 | 0x9c)) {
623 seq.len() - 1
624 } else {
625 seq.len()
626 };
627 if end < body_start {
628 return Some(&[]);
629 }
630 Some(&seq[body_start..end])
631}
632
633#[cfg(test)]
634mod tests {
635 use super::*;
636 use crate::buffer::{Surface, TextBuffer};
637 use crate::color::Color;
638 use crate::style::AttrFlags;
639
640 fn buf(width: u16, height: u16) -> TextBuffer {
641 TextBuffer::new(width, height)
642 }
643
644 fn cell_at(b: &TextBuffer, x: u16, y: u16) -> Cell {
645 b.cell(Position::new(x, y)).cloned().unwrap()
646 }
647
648 fn link_of(cell: &Cell) -> Option<(&str, &str)> {
649 cell.link
650 .as_deref()
651 .map(|l| (l.url.as_str(), l.params.as_str()))
652 }
653
654 #[test]
655 fn plain_text() {
656 for mode in [WidthMode::Wc, WidthMode::Grapheme] {
657 let mut b = buf(10, 1).with_width_mode(mode);
658 let end = Painter::new(&mut b).set_str_wrap(
659 (0, 0),
660 "abc",
661 WrapMode::Truncate,
662 Style::default(),
663 );
664 assert_eq!(end, Position::new(3, 0));
665 assert_eq!(cell_at(&b, 0, 0).content(), "a");
666 assert_eq!(cell_at(&b, 2, 0).content(), "c");
667 }
668 }
669
670 #[test]
671 fn sgr_updates_style_mid_stream() {
672 for csi in ["\x1b[", "\u{9b}"] {
673 let mut b = buf(10, 1);
674 let end = Painter::new(&mut b).set_str_wrap(
675 (0, 0),
676 &format!("a{csi}1mb{csi}mc"),
677 WrapMode::Truncate,
678 Style::default(),
679 );
680 assert_eq!(end, Position::new(3, 0));
681 assert!(!cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
682 assert!(cell_at(&b, 1, 0).attrs.contains(AttrFlags::BOLD));
683 assert!(!cell_at(&b, 2, 0).attrs.contains(AttrFlags::BOLD));
684 }
685 }
686
687 #[test]
688 fn sgr_color() {
689 let mut b = buf(5, 1);
690 Painter::new(&mut b).set_str_wrap(
691 (0, 0),
692 "\x1b[31mr",
693 WrapMode::Truncate,
694 Style::default(),
695 );
696 assert_eq!(cell_at(&b, 0, 0).fg, Some(Color::Red));
697 }
698
699 #[test]
707 fn utf8_payloads_in_sequences_paint_the_text_after_them() {
708 for input in [
709 "\x1b]0;\u{2705}\x07ab",
710 "\x1b]0;x\u{dc}y\x07ab",
711 "\x1b]0;x\u{9d}y\x07ab",
712 "\x1bP1$r\u{2705}\x1b\\ab",
713 "\x1b_G\u{2705}\x1b\\ab",
714 "\x1b#\u{2705}ab",
715 ] {
716 let mut b = buf(10, 1);
717 let end = Painter::new(&mut b).set_str_wrap(
718 (0, 0),
719 input,
720 WrapMode::Truncate,
721 Style::default(),
722 );
723 assert_eq!(
724 end,
725 Position::new(2, 0),
726 "{input:?} painted the wrong width"
727 );
728 assert_eq!(cell_at(&b, 0, 0).content(), "a", "{input:?}");
729 assert_eq!(cell_at(&b, 1, 0).content(), "b", "{input:?}");
730 }
731 }
732
733 #[test]
736 fn osc8_with_a_utf8_url() {
737 for osc in ["\x1b]", "\u{9d}"] {
738 for end in ["\x07", "\x1b\\", "\u{9c}"] {
739 for close in ["\x07", "\x1b\\", "\u{9c}"] {
740 let mut b = buf(10, 1);
741 let input = format!("{osc}8;;https://x/\u{2705}{end}a{osc}8;;{close}b");
742 let position = Painter::new(&mut b).set_str_wrap(
743 (0, 0),
744 &input,
745 WrapMode::Truncate,
746 Style::default(),
747 );
748 assert_eq!(position, Position::new(2, 0), "{input:?}");
749 assert_eq!(
750 link_of(&cell_at(&b, 0, 0)),
751 Some(("https://x/\u{2705}", ""))
752 );
753 assert_eq!(cell_at(&b, 0, 0).content(), "a");
754 assert!(cell_at(&b, 1, 0).link.as_deref().is_none());
755 assert_eq!(cell_at(&b, 1, 0).content(), "b");
756 }
757 }
758 }
759 }
760
761 #[test]
762 fn osc8_malformed_ignored() {
763 let mut b = buf(10, 1);
766 let mut p = Painter::new(&mut b);
767 p.set_str_wrap(
768 (0, 0),
769 "\x1b]8;;https://x\x1b\\a\x1b]8;garbage\x1b\\b",
770 WrapMode::Truncate,
771 Style::default(),
772 );
773 assert_eq!(link_of(&cell_at(&b, 0, 0)), Some(("https://x", "")));
774 assert_eq!(link_of(&cell_at(&b, 1, 0)), Some(("https://x", "")));
775 }
776
777 #[test]
778 fn newline_advances_row() {
779 let mut b = buf(5, 3);
780 let end = Painter::new(&mut b).set_str_wrap(
781 (0, 0),
782 "ab\ncd",
783 WrapMode::Truncate,
784 Style::default(),
785 );
786 assert_eq!(cell_at(&b, 0, 0).content(), "a");
787 assert_eq!(cell_at(&b, 1, 0).content(), "b");
788 assert_eq!(cell_at(&b, 0, 1).content(), "c");
789 assert_eq!(cell_at(&b, 1, 1).content(), "d");
790 assert_eq!(end, Position::new(2, 1));
791 }
792
793 #[test]
794 fn cr_returns_to_left() {
795 let mut b = buf(5, 1);
796 Painter::new(&mut b).set_str_wrap((0, 0), "abc\rXY", WrapMode::Truncate, Style::default());
797 assert_eq!(cell_at(&b, 0, 0).content(), "X");
799 assert_eq!(cell_at(&b, 1, 0).content(), "Y");
800 assert_eq!(cell_at(&b, 2, 0).content(), "c");
801 }
802
803 #[test]
804 fn newline_past_bottom_returns() {
805 let mut b = buf(5, 2);
806 let end = Painter::new(&mut b).set_str_wrap(
807 (0, 0),
808 "a\nb\nc",
809 WrapMode::Truncate,
810 Style::default(),
811 );
812 assert_eq!(end, Position::new(0, 2));
813 assert_eq!(cell_at(&b, 0, 0).content(), "a");
814 assert_eq!(cell_at(&b, 0, 1).content(), "b");
815 }
817
818 #[test]
819 fn truncate_at_right_edge() {
820 let mut b = buf(3, 1);
821 let end = Painter::new(&mut b).set_str_wrap(
822 (0, 0),
823 "abcdef",
824 WrapMode::Truncate,
825 Style::default(),
826 );
827 assert_eq!(end, Position::new(3, 0));
828 assert_eq!(cell_at(&b, 0, 0).content(), "a");
829 assert_eq!(cell_at(&b, 2, 0).content(), "c");
830 }
831
832 #[test]
833 fn truncate_resumes_on_next_row() {
834 let mut b = buf(3, 2);
835 let end = Painter::new(&mut b).set_str_wrap(
836 (0, 0),
837 "abcdef\nxy",
838 WrapMode::Truncate,
839 Style::default(),
840 );
841 assert_eq!(cell_at(&b, 2, 0).content(), "c");
842 assert_eq!(cell_at(&b, 0, 1).content(), "x");
843 assert_eq!(cell_at(&b, 1, 1).content(), "y");
844 assert_eq!(end, Position::new(2, 1));
845 }
846
847 #[test]
848 fn truncate_tail_stamped_per_row() {
849 let mut b = buf(4, 2);
850 Painter::new(&mut b).set_str_truncate(
851 (0, 0),
852 "abcdef\nghijkl",
853 Style::default(),
854 "…",
855 Style::default(),
856 );
857 assert_eq!(cell_at(&b, 3, 0).content(), "…");
858 assert_eq!(cell_at(&b, 0, 1).content(), "g");
859 assert_eq!(cell_at(&b, 3, 1).content(), "…");
860 }
861
862 #[test]
863 fn literal_truncate_resumes_on_next_row() {
864 let mut b = buf(3, 2);
865 b.set_str((0, 0), "abcdef\nxy", Style::default());
866 assert_eq!(cell_at(&b, 2, 0).content(), "c");
867 assert_eq!(cell_at(&b, 0, 1).content(), "x");
868 assert_eq!(cell_at(&b, 1, 1).content(), "y");
869 }
870
871 #[test]
872 fn cr_clears_truncation_for_the_row() {
873 let mut b = buf(3, 1);
874 Painter::new(&mut b).set_str_wrap(
875 (0, 0),
876 "abcdef\rXY",
877 WrapMode::Truncate,
878 Style::default(),
879 );
880 assert_eq!(cell_at(&b, 0, 0).content(), "X");
881 assert_eq!(cell_at(&b, 1, 0).content(), "Y");
882 assert_eq!(cell_at(&b, 2, 0).content(), "c");
883 }
884
885 #[test]
886 fn overflow_drops_rest_of_row_without_backfill() {
887 let mut b = buf(3, 1);
888 let end = Painter::new(&mut b).set_str_wrap(
889 (0, 0),
890 "ab中c",
891 WrapMode::Truncate,
892 Style::default(),
893 );
894 assert_eq!(cell_at(&b, 0, 0).content(), "a");
895 assert_eq!(cell_at(&b, 1, 0).content(), "b");
896 assert_eq!(cell_at(&b, 2, 0).content(), " ");
899 assert_eq!(end, Position::new(2, 0));
900 }
901
902 #[test]
903 fn literal_crlf_breaks_the_line() {
904 let mut b = buf(3, 2);
907 b.set_str((0, 0), "abcdef\r\nxy", Style::default());
908 assert_eq!(cell_at(&b, 2, 0).content(), "c");
909 assert_eq!(cell_at(&b, 0, 1).content(), "x");
910 assert_eq!(cell_at(&b, 1, 1).content(), "y");
911 }
912
913 #[test]
914 fn crlf_breaks_the_line() {
915 let mut b = buf(3, 2);
916 Painter::new(&mut b).set_str_wrap(
917 (0, 0),
918 "abcdef\r\nxy",
919 WrapMode::Truncate,
920 Style::default(),
921 );
922 assert_eq!(cell_at(&b, 2, 0).content(), "c");
923 assert_eq!(cell_at(&b, 0, 1).content(), "x");
924 assert_eq!(cell_at(&b, 1, 1).content(), "y");
925 }
926
927 #[test]
928 fn escapes_still_apply_across_a_truncated_row() {
929 let mut b = buf(2, 2);
932 Painter::new(&mut b).set_str_wrap(
933 (0, 0),
934 "ab\x1b[1mcd\x1b]8;;https://x\x1b\\\nz",
935 WrapMode::Truncate,
936 Style::default(),
937 );
938 assert!(!cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
939 let z = cell_at(&b, 0, 1);
940 assert_eq!(z.content(), "z");
941 assert!(z.attrs.contains(AttrFlags::BOLD));
942 assert_eq!(link_of(&z), Some(("https://x", "")));
943 }
944
945 #[test]
946 fn start_below_clip_paints_nothing() {
947 let mut b = buf(3, 2);
948 let end = Painter::new(&mut b).set_str_wrap(
949 (0, 5),
950 "abcdef\nghi",
951 WrapMode::Truncate,
952 Style::default(),
953 );
954 assert_eq!(end, Position::new(0, 5));
955 for y in 0..2 {
956 for x in 0..3 {
957 assert_eq!(cell_at(&b, x, y).content(), " ");
958 }
959 }
960 }
961
962 #[test]
963 fn literal_start_below_clip_paints_nothing() {
964 let mut b = buf(3, 2);
965 let end = b.set_str((0, 5), "abcdef\nghi", Style::default());
966 assert_eq!(end, Position::new(0, 5));
967 assert_eq!(cell_at(&b, 0, 0).content(), " ");
968 assert_eq!(cell_at(&b, 0, 1).content(), " ");
969 }
970
971 #[test]
972 fn wrap_breaks_on_crlf() {
973 let mut b = buf(4, 3);
976 Painter::new(&mut b).set_str_wrap((0, 0), "ab\r\ncd", WrapMode::Wrap, Style::default());
977 assert_eq!(cell_at(&b, 0, 0).content(), "a");
978 assert_eq!(cell_at(&b, 1, 0).content(), "b");
979 assert_eq!(cell_at(&b, 0, 1).content(), "c");
980 assert_eq!(cell_at(&b, 1, 1).content(), "d");
981 }
982
983 #[test]
984 fn literal_wrap_breaks_on_crlf() {
985 let mut b = buf(4, 3);
986 b.set_str_wrap((0, 0), "ab\r\ncd", WrapMode::Wrap, Style::default());
987 assert_eq!(cell_at(&b, 0, 0).content(), "a");
988 assert_eq!(cell_at(&b, 1, 0).content(), "b");
989 assert_eq!(cell_at(&b, 0, 1).content(), "c");
990 assert_eq!(cell_at(&b, 1, 1).content(), "d");
991 }
992
993 #[test]
994 fn wrap_at_right_edge() {
995 let mut b = buf(3, 3);
996 let end =
997 Painter::new(&mut b).set_str_wrap((0, 0), "abcdef", WrapMode::Wrap, Style::default());
998 assert_eq!(end, Position::new(3, 1));
999 assert_eq!(cell_at(&b, 0, 0).content(), "a");
1000 assert_eq!(cell_at(&b, 2, 0).content(), "c");
1001 assert_eq!(cell_at(&b, 0, 1).content(), "d");
1002 assert_eq!(cell_at(&b, 2, 1).content(), "f");
1003 }
1004
1005 #[test]
1006 fn rect_clip_and_origin() {
1007 let mut b = buf(10, 5);
1008 let end = Painter::new(&mut b).set_str_rect_wrap(
1009 Rect::new(2, 1, 3, 2),
1010 "abcdef",
1011 WrapMode::Wrap,
1012 Style::default(),
1013 );
1014 assert_eq!(end, Position::new(5, 2));
1015 assert_eq!(cell_at(&b, 2, 1).content(), "a");
1016 assert_eq!(cell_at(&b, 4, 1).content(), "c");
1017 assert_eq!(cell_at(&b, 2, 2).content(), "d");
1018 assert_eq!(cell_at(&b, 4, 2).content(), "f");
1019 assert_eq!(cell_at(&b, 0, 0).content(), " ");
1021 assert_eq!(cell_at(&b, 5, 1).content(), " ");
1022 }
1023
1024 #[test]
1025 fn rect_newline_uses_rect_left() {
1026 let mut b = buf(10, 5);
1027 Painter::new(&mut b).set_str_rect_wrap(
1028 Rect::new(2, 1, 4, 3),
1029 "ab\ncd",
1030 WrapMode::Truncate,
1031 Style::default(),
1032 );
1033 assert_eq!(cell_at(&b, 2, 1).content(), "a");
1034 assert_eq!(cell_at(&b, 3, 1).content(), "b");
1035 assert_eq!(cell_at(&b, 2, 2).content(), "c");
1037 assert_eq!(cell_at(&b, 3, 2).content(), "d");
1038 assert_eq!(cell_at(&b, 0, 2).content(), " ");
1039 }
1040
1041 #[test]
1042 fn sgr_reset_preserves_active_hyperlink() {
1043 let mut b = buf(4, 1);
1044 Painter::new(&mut b).set_str(
1045 (0, 0),
1046 "\x1b]8;;https://x\x1b\\\x1b[1ma\x1b[0mb\x1b]8;;\x1b\\c",
1047 Style::EMPTY,
1048 );
1049 assert!(cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
1050 assert_eq!(link_of(&cell_at(&b, 1, 0)), Some(("https://x", "")));
1051 assert!(cell_at(&b, 1, 0).style().attrs.is_empty());
1052 assert_eq!(link_of(&cell_at(&b, 2, 0)), None);
1053 }
1054
1055 #[test]
1056 fn base_pen_link_yields_to_inline_links_and_close_clears_it() {
1057 let mut b = buf(6, 1);
1058 let base_link = std::sync::Arc::new(crate::style::Link {
1059 url: "https://example.test/base".into(),
1060 params: String::new(),
1061 });
1062 Painter::new(&mut b).set_str(
1063 (0, 0),
1064 "a\x1b[1mb\x1b[0mc\x1b]8;;https://example.test/inline\x1b\\d\x1b]8;;\x1b\\e",
1065 Pen::new()
1066 .with_style(Style::new().fg(Color::Green))
1067 .with_link(base_link),
1068 );
1069
1070 assert_eq!(
1071 link_of(&cell_at(&b, 0, 0)),
1072 Some(("https://example.test/base", ""))
1073 );
1074 assert!(cell_at(&b, 1, 0).attrs.contains(AttrFlags::BOLD));
1075 assert_eq!(
1076 link_of(&cell_at(&b, 1, 0)),
1077 Some(("https://example.test/base", ""))
1078 );
1079 assert!(!cell_at(&b, 2, 0).attrs.contains(AttrFlags::BOLD));
1080 assert_eq!(
1081 link_of(&cell_at(&b, 2, 0)),
1082 Some(("https://example.test/base", ""))
1083 );
1084 assert_eq!(
1085 link_of(&cell_at(&b, 3, 0)),
1086 Some(("https://example.test/inline", ""))
1087 );
1088 assert_eq!(link_of(&cell_at(&b, 4, 0)), None);
1089
1090 Painter::new(&mut b).set_str((5, 0), "f", Style::EMPTY);
1091 assert_eq!(link_of(&cell_at(&b, 5, 0)), None);
1092 }
1093
1094 #[test]
1095 fn painter_truncation_uses_independent_base_links() {
1096 let mut b = buf(3, 1);
1097 let text_link = std::sync::Arc::new(crate::style::Link {
1098 url: "https://example.test/text".into(),
1099 params: String::new(),
1100 });
1101 let tail_link = std::sync::Arc::new(crate::style::Link {
1102 url: "https://example.test/tail".into(),
1103 params: String::new(),
1104 });
1105 Painter::new(&mut b).set_str_truncate(
1106 (0, 0),
1107 "abcdef",
1108 Pen::new().with_link(text_link.clone()),
1109 ".",
1110 Pen::new().with_link(tail_link.clone()),
1111 );
1112
1113 assert_eq!(cell_at(&b, 0, 0).link(), Some(&text_link));
1114 assert_eq!(cell_at(&b, 1, 0).link(), Some(&text_link));
1115 assert_eq!(cell_at(&b, 2, 0).link(), Some(&tail_link));
1116 }
1117
1118 #[test]
1119 fn links_follow_wrapped_wide_cells_and_tail_state_is_independent() {
1120 let mut b = buf(3, 2);
1121 let end = Painter::new(&mut b).set_str_wrap(
1122 (0, 0),
1123 "\x1b]8;id=wide;https://x\x1b\\ab\x1b[m界",
1124 WrapMode::Wrap,
1125 Style::new().fg(crate::color::Color::Green),
1126 );
1127 assert_eq!(end, Position::new(2, 1));
1128 let owner = cell_at(&b, 0, 1);
1129 let continuation = cell_at(&b, 1, 1);
1130 assert_eq!(owner.content(), "界");
1131 assert!(continuation.is_continuation());
1132 assert_eq!(link_of(&owner), Some(("https://x", "id=wide")));
1133 assert!(std::sync::Arc::ptr_eq(
1134 owner.link().unwrap(),
1135 continuation.link().unwrap()
1136 ));
1137 assert_eq!(owner.style().fg, Some(crate::color::Color::Green));
1138
1139 Painter::new(&mut b).set_str_truncate(
1140 (0, 0),
1141 "\x1b]8;;https://main\x1b\\abcdef",
1142 Style::EMPTY,
1143 "\x1b]8;;https://tail\x1b\\\x1b[1m.\x1b[m.",
1144 Style::EMPTY,
1145 );
1146 assert_eq!(link_of(&cell_at(&b, 0, 0)), Some(("https://main", "")));
1147 for x in 1..3 {
1148 assert_eq!(link_of(&cell_at(&b, x, 0)), Some(("https://tail", "")));
1149 }
1150 assert!(!cell_at(&b, 2, 0).style().attrs.contains(AttrFlags::BOLD));
1151 }
1152
1153 #[test]
1154 fn with_resets_style_and_link() {
1155 let mut b = buf(10, 1);
1156 let mut painter = Painter::new(&mut b);
1157 painter.set_str_wrap(
1159 (0, 0),
1160 "\x1b]8;;https://x\x1b\\a",
1161 WrapMode::Truncate,
1162 Style::default().bold(),
1163 );
1164 painter.set_str_wrap((1, 0), "b", WrapMode::Truncate, Style::default());
1166 assert!(cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
1167 assert_eq!(link_of(&cell_at(&b, 0, 0)), Some(("https://x", "")));
1168 assert!(!cell_at(&b, 1, 0).attrs.contains(AttrFlags::BOLD));
1169 assert!(cell_at(&b, 1, 0).link.as_deref().is_none());
1170 }
1171
1172 #[test]
1173 fn calls_start_from_their_own_base() {
1174 let mut b = buf(10, 1);
1175 let mut p = Painter::new(&mut b);
1176 p.set_str_wrap((0, 0), "\x1b[1ma", WrapMode::Truncate, Style::default());
1178 p.set_str_wrap((1, 0), "b", WrapMode::Truncate, Style::default());
1180 assert!(cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
1181 assert!(!cell_at(&b, 1, 0).attrs.contains(AttrFlags::BOLD));
1182 }
1183
1184 #[test]
1185 fn base_applies_and_inline_reset_returns_to_base() {
1186 let mut b = buf(10, 1);
1187 let base = Style::default().fg(Color::Red);
1188 Painter::new(&mut b).set_str_wrap((0, 0), "a\x1b[1mb\x1b[0mc", WrapMode::Truncate, base);
1192 let red = Some(Color::Red);
1193 assert_eq!(cell_at(&b, 0, 0).fg, red);
1194 assert!(!cell_at(&b, 0, 0).attrs.contains(AttrFlags::BOLD));
1195 assert_eq!(cell_at(&b, 1, 0).fg, red);
1196 assert!(cell_at(&b, 1, 0).attrs.contains(AttrFlags::BOLD));
1197 assert_eq!(cell_at(&b, 2, 0).fg, red);
1198 assert!(!cell_at(&b, 2, 0).attrs.contains(AttrFlags::BOLD));
1199 }
1200
1201 #[test]
1202 fn position_and_rect_match_when_rect_covers_bounds() {
1203 let mut a = buf(5, 2);
1204 let mut b = buf(5, 2);
1205 let e1 =
1206 Painter::new(&mut a).set_str_wrap((0, 0), "abc", WrapMode::Truncate, Style::default());
1207 let e2 = Painter::new(&mut b).set_str_rect_wrap(
1208 Rect::new(0, 0, 5, 2),
1209 "abc",
1210 WrapMode::Truncate,
1211 Style::default(),
1212 );
1213 assert_eq!(e1, e2);
1214 assert_eq!(cell_at(&a, 2, 0).content(), cell_at(&b, 2, 0).content());
1215 }
1216
1217 fn row(b: &TextBuffer, y: u16) -> String {
1218 (0..b.width())
1219 .map(|x| cell_at(b, x, y).content().to_string())
1220 .collect()
1221 }
1222
1223 #[test]
1224 fn truncate_tail_not_shown_when_text_fits() {
1225 let mut b = buf(5, 1);
1226 let end = Painter::new(&mut b).set_str_truncate(
1227 (0, 0),
1228 "abc",
1229 Style::default(),
1230 "…",
1231 Style::default(),
1232 );
1233 assert_eq!(row(&b, 0), "abc ");
1235 assert_eq!(end, Position::new(3, 0));
1236 }
1237
1238 #[test]
1239 fn truncate_single_cell_tail_on_overflow() {
1240 let mut b = buf(5, 1);
1241 let end = Painter::new(&mut b).set_str_truncate(
1242 (0, 0),
1243 "abcdefgh",
1244 Style::default(),
1245 "…",
1246 Style::default(),
1247 );
1248 assert_eq!(row(&b, 0), "abcd…");
1250 assert_eq!(end, Position::new(5, 0));
1251 }
1252
1253 #[test]
1254 fn truncate_multi_cell_tail_reserves_its_width() {
1255 let mut b = buf(8, 1);
1256 Painter::new(&mut b).set_str_truncate(
1257 (0, 0),
1258 "abcdefghij",
1259 Style::default(),
1260 " more",
1261 Style::default(),
1262 );
1263 assert_eq!(row(&b, 0), "abc more");
1265 }
1266
1267 #[test]
1268 fn truncate_tail_carries_its_style() {
1269 let mut b = buf(5, 1);
1270 Painter::new(&mut b).set_str_truncate(
1271 (0, 0),
1272 "abcdefgh",
1273 Style::default(),
1274 "…",
1275 Style::default().fg(Color::Red),
1276 );
1277 assert_eq!(cell_at(&b, 4, 0).fg, Some(Color::Red));
1279 }
1280
1281 #[test]
1282 fn truncate_methods_keep_text_and_tail_styles_separate() {
1283 fn paint(
1284 target: &mut impl TextSurface,
1285 rect: bool,
1286 text: &str,
1287 style: &Style,
1288 tail: &str,
1289 tail_style: &Style,
1290 ) -> Position {
1291 if rect {
1292 target.set_str_rect_truncate(Rect::new(1, 1, 5, 2), text, style, tail, tail_style)
1293 } else {
1294 target.set_str_truncate((0, 0), text, style, tail, tail_style)
1295 }
1296 }
1297
1298 let style = Style::new().fg(Color::Green).bold();
1299 let tail_style = Style::new().fg(Color::Red).italic();
1300 for painter in [false, true] {
1301 for rect in [false, true] {
1302 for (text, tail, expected) in [
1303 ("abc", ".", "abc "),
1304 ("abcde", ".", "abcde"),
1305 ("abcdefgh", ".", "abcd."),
1306 ("abcdefgh", "", "abcde"),
1307 ("abcdefgh", " more!", "abcde"),
1308 ] {
1309 let mut b = if rect { buf(7, 4) } else { buf(5, 2) };
1310 let text = format!("{text}\n{text}");
1311 let end = if painter {
1312 paint(
1313 &mut Painter::new(&mut b),
1314 rect,
1315 &text,
1316 &style,
1317 tail,
1318 &tail_style,
1319 )
1320 } else {
1321 paint(&mut b, rect, &text, &style, tail, &tail_style)
1322 };
1323 let offset = u16::from(rect);
1324 assert_eq!(
1325 end,
1326 Position::new(offset + expected.trim_end().len() as u16, offset + 1)
1327 );
1328 for y in 0..b.height() {
1329 for x in 0..b.width() {
1330 let expected_cell = if (offset..offset + 2).contains(&y)
1331 && (offset..offset + 5).contains(&x)
1332 {
1333 let ch = expected.as_bytes()[usize::from(x - offset)] as char;
1334 match ch {
1335 ' ' => Cell::BLANK,
1336 '.' => Cell::new(".", 1).with_style(tail_style),
1337 _ => Cell::new(ch.to_string(), 1).with_style(style),
1338 }
1339 } else {
1340 Cell::BLANK
1341 };
1342 assert_eq!(cell_at(&b, x, y), expected_cell);
1343 }
1344 }
1345 }
1346 }
1347 }
1348 }
1349
1350 #[test]
1351 fn truncate_inline_styles_start_from_independent_base_styles() {
1352 for rect in [false, true] {
1353 let mut b = buf(5, 1);
1354 let text_style = Style::new().fg(Color::Green);
1355 let tail_style = Style::new().fg(Color::Red);
1356 let mut painter = Painter::new(&mut b);
1357 if rect {
1358 painter.set_str_rect_truncate(
1359 Rect::new(0, 0, 5, 1),
1360 "\x1b[1mabcdefgh",
1361 text_style,
1362 "\x1b[3m.",
1363 tail_style,
1364 );
1365 } else {
1366 painter.set_str_truncate(
1367 (0, 0),
1368 "\x1b[1mabcdefgh",
1369 text_style,
1370 "\x1b[3m.",
1371 tail_style,
1372 );
1373 }
1374 for x in 0..4 {
1375 assert_eq!(cell_at(&b, x, 0).style(), text_style.bold());
1376 }
1377 assert_eq!(cell_at(&b, 4, 0).style(), tail_style.italic());
1378 }
1379 }
1380
1381 #[test]
1382 fn truncate_tail_inline_escapes_apply() {
1383 let mut b = buf(5, 1);
1384 Painter::new(&mut b).set_str_truncate(
1385 (0, 0),
1386 "abcdefgh",
1387 Style::default(),
1388 "\x1b[1m…",
1389 Style::default(),
1390 );
1391 assert!(cell_at(&b, 4, 0).attrs.contains(AttrFlags::BOLD));
1393 }
1394
1395 #[test]
1396 fn truncate_wide_tail_too_big_hard_truncates() {
1397 let mut b = buf(3, 1);
1398 let end = Painter::new(&mut b).set_str_truncate(
1399 (0, 0),
1400 "abcdef",
1401 Style::default(),
1402 " more",
1403 Style::default(),
1404 );
1405 assert_eq!(row(&b, 0), "abc");
1408 assert_eq!(end, Position::new(3, 0));
1409 }
1410
1411 #[test]
1414 fn a_cluster_measuring_four_claims_four_columns() {
1415 let mut b = buf(6, 1).with_width_mode(WidthMode::Wc);
1416 Painter::new(&mut b).set_str((0, 0), "\u{1f44d}\u{1f3fd}", Style::default());
1419
1420 assert_eq!(cell_at(&b, 0, 0).content(), "\u{1f44d}\u{1f3fd}");
1421 assert_eq!(cell_at(&b, 0, 0).width(), 4);
1422 for x in 1..4 {
1423 assert!(
1424 cell_at(&b, x, 0).is_continuation(),
1425 "column {x} belongs to the cluster"
1426 );
1427 }
1428 assert!(cell_at(&b, 4, 0).is_blank(), "the cluster stops at four");
1429 }
1430
1431 #[test]
1432 fn truncate_tail_overwrites_split_wide_cell() {
1433 let mut b = buf(5, 1);
1436 Painter::new(&mut b).set_str_truncate(
1437 (0, 0),
1438 "abc中def",
1439 Style::default(),
1440 "…",
1441 Style::default(),
1442 );
1443 assert_eq!(cell_at(&b, 4, 0).content(), "…");
1447 assert!(!cell_at(&b, 3, 0).is_wide());
1448 }
1449}