Skip to main content

uncurses/text/
painter.rs

1//! [`Painter`] — styled string painting into a mutable surface.
2//!
3//! A painter owns no cells and no style. It temporarily binds a
4//! [`SurfaceMut`](crate::buffer::SurfaceMut), a [`WidthMode`], and an
5//! East-Asian Ambiguous policy. Calls to
6//! [`set_str`](Painter::set_str) or [`set_str_rect`](Painter::set_str_rect)
7//! tokenize the input into text clusters, inline escapes, and control bytes,
8//! then write terminal cells into the target.
9//!
10//! Construct a painter over any [`TextSurface`]:
11//!
12//! ```rust,ignore
13//! use uncurses::text::Painter;
14//! use uncurses::style::Style;
15//!
16//! Painter::new(&mut surface)
17//!     .set_str((0, 0), "hello \x1b[1mworld\x1b[m", Style::default());
18//! ```
19//!
20//! ## Style and hyperlink state
21//!
22//! Each paint call takes a base [`Pen`]. Inline SGR sequences build a visual
23//! style as the string is scanned, and each cell inherits it onto the base
24//! style. Inline fields win, and the base fills any unset fields. An inline
25//! reset (`\x1b[0m`) clears the inline style, so later cells use the base.
26//! The base link applies until an inline OSC 8 sequence changes it. SGR resets
27//! preserve the active link, and an OSC 8 close clears it.
28//! The painter keeps no style of its own between calls: every call starts with
29//! an empty inline style over the base pen, so calls are independent.
30//!
31//! ## Cells, clipping, and wrapping
32//!
33//! Each non-zero-width grapheme cluster becomes one
34//! [`Cell`](crate::cell::Cell) holding the whole cluster, with its measured
35//! width. A cluster wider than one column occupies a primary cell plus the
36//! `width - 1` continuation cells maintained by the buffer layer.
37//! Zero-width clusters are appended to the previous pending cluster before it
38//! is flushed.
39//!
40//! ```text
41//! input clusters      pending cell       surface cells
42//! ┌────┬──────┐       ┌────────────┐         ┌────┬────┬────┬────┐
43//! │ e  │ ◌́    │ ───▶  │ "e\u{301}" │ ─────▶  │ é  │    │    │    │
44//! └────┴──────┘       └────────────┘         └────┴────┴────┴────┘
45//!
46//! ┌────┐              ┌─────────┐        ┌────┬────┬────┬────┐
47//! │ 中 │ ─────────▶   │ width 2 │ ────▶  │ 中 │ ▶  │    │    │
48//! └────┘              └─────────┘        └────┴────┴────┴────┘
49//!
50//! ┌────┐              ┌─────────┐        ┌────┬────┬────┬────┐
51//! │ 👍🏽 │ ─────────▶   │ width 4 │ ────▶  │ 👍🏽 │ ▶  │ ▶  │ ▶  │
52//! └────┘              └─────────┘        └────┴────┴────┴────┘
53//! ```
54//!
55//! The last row measures under [`WidthMode::Wc`], which sums the code points
56//! of a cluster: the thumbs-up and the skin tone own two columns each. The
57//! same cluster measures two under [`WidthMode::Grapheme`], and the painter
58//! lays out whatever width the mode reports.
59//!
60//! Painting is clipped to either the target bounds or the intersection of a
61//! supplied rectangle with those bounds. [`WrapMode`] applies only when a
62//! non-zero-width cluster would cross the right edge.
63
64use 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
74/// Paint styled strings into a [`TextSurface`].
75///
76/// The painter snapshots its target's [`WidthMode`] and `eaw_wide` policy at
77/// construction, both fixed for the painter's lifetime. It holds no style of
78/// its own: each paint call starts with an empty SGR pen and the base link from
79/// its [`Pen`] value. It parses inline SGR and OSC 8 sequences, then writes
80/// each cell with the inherited visual style and active link. Text is written
81/// into the borrowed target surface; dropping a painter has no side effects.
82pub struct Painter<'s, S: TextSurface + ?Sized> {
83    target: &'s mut S,
84    /// Width measurement policy, snapshotted from the target at construction.
85    mode: WidthMode,
86    /// Whether East Asian Ambiguous characters are treated as wide,
87    /// snapshotted from the target at construction.
88    eaw_wide: bool,
89}
90
91impl<'s, S: TextSurface + ?Sized> Painter<'s, S> {
92    /// Create a new painter over `target`.
93    ///
94    /// # Parameters
95    ///
96    /// * `target` — mutable surface receiving painted cells.
97    ///
98    /// # Returns
99    ///
100    /// A painter bound to `target`.
101    ///
102    /// # Errors and panics
103    ///
104    /// This constructor does not fail or intentionally panic.
105    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    /// Paint `s` with [`WrapMode::Truncate`], stamping `tail` on overflow.
116    ///
117    /// Falls back to a plain hard truncate when the tail is empty or cannot
118    /// fit within `clip`.
119    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    /// Stamp `tail` over the trailing `tail.width` columns of row `y`, ending
145    /// at `clip`'s right edge, painted with the tail's pen.
146    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        // `y` only ever advances, so a start below the clip can never paint.
183        if start.y >= clip.bottom() {
184            return start;
185        }
186        let mut x = start.x;
187        let mut y = start.y;
188        // `pen` accumulates inline SGR state, starting empty; an inline reset
189        // clears it, so later cells fall back to `base.style`. `link` starts
190        // from the base and changes only for inline OSC 8 sequences. `pending`
191        // holds the cell being built, including its origin, text, and width.
192        // Zero-width clusters join it before the next cell starts.
193        let mut pen = Style::default();
194        let mut link = base.link.clone();
195        let mut pending: Option<(u16, u16, String, u8)> = None;
196        // Truncation is per row: once a row overflows, clusters are dropped
197        // until `\n` or `\r` puts the cursor back inside the clip. Escapes
198        // still run, so the pen carries over to the next row.
199        let mut truncated = false;
200
201        for tok in tokenize(s.as_bytes(), self.mode, self.eaw_wide) {
202            // A zero-width grapheme appends to the pending cell without
203            // finalizing it. Everything else finalizes the pending cell first,
204            // writing it with the current style: the pen inherited onto base.
205            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                // SAFETY (all `from_utf8_unchecked`): the tokenizer cuts on
216                // grapheme-cluster boundaries of a valid `&str`, so each slice
217                // is valid UTF-8. Checked under `debug_assert!` for the same
218                // reason as `ansi::wrap::bs` - the invariant is the tokenizer's
219                // to keep, and when it stopped keeping it this was UB.
220                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        // Finalize the last cell.
297        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
346/// A [`Painter`] is itself a [`TextSurface`] whose `set_str` family recognizes
347/// inline SGR and OSC 8 hyperlink sequences, updating the running
348/// the running style as the input is parsed. This is the escape-aware
349/// counterpart to the literal painting of the default [`TextSurface`] methods.
350impl<'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    /// Measure `s`, skipping recognized inline SGR and OSC 8 escape
360    /// sequences so they contribute no width. This is the escape-aware
361    /// counterpart to the literal default
362    /// [`str_width`](crate::text::TextSurface::str_width).
363    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    /// Paint `s` starting at `pos`, clipped to the target bounds.
368    ///
369    /// Inline SGR state inherits unset fields from `pen.style`, and the
370    /// optional link applies until an inline OSC 8 sequence changes it. Each
371    /// call starts from its own pen. Newline advances
372    /// to the next row at the bounds' left edge; carriage return returns to that
373    /// left edge on the current row. Right-edge behavior is
374    /// [`WrapMode::Truncate`].
375    ///
376    /// # Parameters
377    ///
378    /// * `pos` — starting cell position.
379    /// * `s` — UTF-8 input string.
380    /// * `pen` — base visual style and optional link for painted cells.
381    ///
382    /// # Returns
383    ///
384    /// The cursor position immediately after the last written cell, or where
385    /// painting stopped.
386    ///
387    /// # Errors and panics
388    ///
389    /// This method does not return errors and does not intentionally panic.
390    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    /// Paint `s` starting at `pos` with explicit wrapping behavior.
396    ///
397    /// The target bounds are the clipping rectangle. [`WrapMode::Truncate`]
398    /// drops the rest of the row at the right edge and resumes on the next
399    /// row; [`WrapMode::Wrap`] continues on the next row
400    /// at the bounds' left edge until the bottom edge is reached.
401    ///
402    /// # Parameters
403    ///
404    /// * `pos` — starting cell position.
405    /// * `s` — UTF-8 input string.
406    /// * `wrap` — right-edge behavior for non-zero-width clusters.
407    /// * `pen` — base visual style and optional link for this call.
408    ///
409    /// # Returns
410    ///
411    /// The cursor position immediately after the last written cell, or where
412    /// painting stopped.
413    ///
414    /// # Errors and panics
415    ///
416    /// This method does not return errors and does not intentionally panic.
417    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    /// Paint `s` into `rect`, clipped to `rect ∩ target.bounds()`.
429    ///
430    /// Painting starts at `rect`'s top-left. Newline and carriage return use
431    /// `rect`'s left edge as the return column. Right-edge behavior is
432    /// [`WrapMode::Truncate`].
433    ///
434    /// # Parameters
435    ///
436    /// * `rect` — origin and clipping rectangle.
437    /// * `s` — UTF-8 input string.
438    /// * `pen` — base visual style and optional link for this call.
439    ///
440    /// # Returns
441    ///
442    /// The cursor position immediately after the last written cell, or where
443    /// painting stopped.
444    ///
445    /// # Errors and panics
446    ///
447    /// This method does not return errors and does not intentionally panic.
448    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    /// Paint `s` into `rect` with explicit wrapping behavior.
455    ///
456    /// The clipping rectangle is `rect ∩ target.bounds()`. [`WrapMode::Wrap`]
457    /// flows down inside `rect`; [`WrapMode::Truncate`] stops at `rect`'s
458    /// right edge.
459    ///
460    /// # Parameters
461    ///
462    /// * `rect` — origin and clipping rectangle.
463    /// * `s` — UTF-8 input string.
464    /// * `wrap` — right-edge behavior for non-zero-width clusters.
465    /// * `pen` — base visual style and optional link for this call.
466    ///
467    /// # Returns
468    ///
469    /// The cursor position immediately after the last written cell, or where
470    /// painting stopped.
471    ///
472    /// # Errors and panics
473    ///
474    /// This method does not return errors and does not intentionally panic.
475    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    /// Paint `s` starting at `pos`, truncating with a `tail` indicator.
488    ///
489    /// Text is painted across the target bounds. When a non-zero-width cluster
490    /// would cross the right edge, the rest of that row is dropped and `tail`
491    /// is stamped over its trailing columns so it ends exactly at the right
492    /// edge. Painting resumes on the next row if the text continues past a
493    /// newline, so a multi-line `s` can stamp one tail per overflowing row.
494    /// The tail appears only on rows that actually overflow; a row that fits
495    /// is left untouched.
496    ///
497    /// `tail` is painted with `tail_pen` and may carry
498    /// its own inline escape sequences, so it can be a single glyph (`"…"`), a
499    /// word (`" more"`), or a multi-style span. If the tail is wider than the
500    /// available space, it is dropped and the text is hard-truncated instead.
501    ///
502    /// # Parameters
503    ///
504    /// * `pos` — starting cell position.
505    /// * `s` — UTF-8 string to paint.
506    /// * `s_pen` — base pen for the main text; inline escapes can change it.
507    /// * `tail` — truncation indicator, painted when `s` overflows.
508    /// * `tail_pen` — base pen for the tail.
509    ///
510    /// # Returns
511    ///
512    /// The cursor position immediately after the last written cell, or where
513    /// painting stopped.
514    ///
515    /// # Errors and panics
516    ///
517    /// This method does not return errors and does not intentionally panic.
518    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    /// Paint `s` inside `rect`, truncating with a `tail` indicator.
531    ///
532    /// This is the rectangular form of
533    /// [`set_str_truncate`](Self::set_str_truncate): the clip rectangle is
534    /// `rect ∩ target.bounds()`, and a tail is stamped at `rect`'s right
535    /// edge on each row that overflows it.
536    ///
537    /// # Parameters
538    ///
539    /// * `rect` — clipping rectangle and starting origin.
540    /// * `s` — UTF-8 string to paint.
541    /// * `s_pen` — base pen for the main text; inline escapes can change it.
542    /// * `tail` — truncation indicator, painted when `s` overflows.
543    /// * `tail_pen` — base pen for the tail.
544    ///
545    /// # Returns
546    ///
547    /// The cursor position immediately after the last written cell, or where
548    /// painting stopped.
549    ///
550    /// # Errors and panics
551    ///
552    /// This method does not return errors and does not intentionally panic.
553    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/// A truncation tail: borrowed indicator text, its starting pen, and its
575/// measured cell width. `Copy` so the overflow branch can hand it to
576/// [`Painter::paint_tail`] without moving out of the `Option`.
577#[derive(Clone, Copy)]
578struct Tail<'a> {
579    text: &'a str,
580    pen: &'a Pen,
581    width: u16,
582}
583
584/// Return the body of a CSI sequence (between introducer and final byte).
585///
586/// Recognizes 7-bit, raw C1, and UTF-8 C1 forms, with a final byte
587/// in `0x40..=0x7e`. Returns `None` for any
588/// other escape or for an incomplete sequence missing its final byte.
589fn 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
604/// Return the body of an OSC sequence (between introducer and string
605/// terminator). Recognizes 7-bit, raw C1, and UTF-8 C1 forms.
606/// A terminator is BEL or ST in any supported encoding. An incomplete sequence
607/// missing its terminator still returns its content; a non-OSC sequence
608/// returns `None`.
609fn 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    /// The painter's `from_utf8_unchecked` on a text token, driven by the
700    /// sequences that used to break the tokenizer's promise.
701    ///
702    /// Every other painter test uses ASCII-only escape payloads, so reverting
703    /// the scanner fix left them all green while the painter took ill-formed
704    /// bytes on trust. `\u{2705}` is `E2 9C 85` and carries an 8-bit ST byte;
705    /// `\u{dc}` carries a continuation byte equal to ST.
706    #[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    /// An OSC 8 whose URL carries a C1 continuation byte still yields a link
734    /// with the whole URL, and the styled text after it.
735    #[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        // Missing the second `;` -> not a valid OSC 8; should not affect
764        // the currently active link.
765        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        // 'X' overwrites 'a', 'Y' overwrites 'b', 'c' remains.
798        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        // Row 2 is out of bounds; "c" never lands.
816    }
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        // "中" needs two columns and only one is left; "c" must not slot into
897        // the gap ahead of it.
898        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        // Extended grapheme segmentation joins CR LF into one zero-width
905        // cluster, so it has to be matched explicitly to break the line.
906        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        // The pen keeps advancing through the dropped part of the row, so a
930        // style opened there lands on the next row.
931        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        // The CRLF fix is shared with WrapMode::Wrap: a joined cluster has to
974        // break the line there too, not read as zero-width filler.
975        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        // Outside the rect must remain blank.
1020        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        // Newline returns x to rect.left() = 2, not to 0.
1036        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        // First call: paint with bold + a link.
1158        painter.set_str_wrap(
1159            (0, 0),
1160            "\x1b]8;;https://x\x1b\\a",
1161            WrapMode::Truncate,
1162            Style::default().bold(),
1163        );
1164        // Second call with `_with` and an empty style must reset.
1165        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        // Inline SGR bolds within the first call only.
1177        p.set_str_wrap((0, 0), "\x1b[1ma", WrapMode::Truncate, Style::default());
1178        // The next call starts fresh from its base: no bold carries over.
1179        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        // "a" gets the base red; the inline bold adds to "b"; the inline reset
1189        // clears only the inline state, so "c" falls back to the base red
1190        // rather than to a fully default style.
1191        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        // "abc" fits in 5 columns, so no tail is stamped.
1234        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        // 5 columns: 4 text columns + the 1-wide tail at the right edge.
1249        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        // 8 columns: 3 text columns + the 5-wide " more" tail.
1264        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        // The tail cell gets the supplied base style.
1278        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        // The tail's inline SGR bolds it even though the base style is empty.
1392        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        // " more" is 5 wide but the clip is only 3, so it is dropped and the
1406        // text is hard-truncated with no tail.
1407        assert_eq!(row(&b, 0), "abc");
1408        assert_eq!(end, Position::new(3, 0));
1409    }
1410
1411    /// The module diagram shows a cluster laid across four columns. Measure
1412    /// the cluster it names so the picture stays answerable to the code.
1413    #[test]
1414    fn a_cluster_measuring_four_claims_four_columns() {
1415        let mut b = buf(6, 1).with_width_mode(WidthMode::Wc);
1416        // Thumbs-up plus a skin tone. `Wc` sums the code points, and each of
1417        // the two owns two columns.
1418        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        // A wide cluster sits where the tail's left edge lands; stamping the
1434        // tail must blank the dangling wide primary.
1435        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        // "abc" + wide "中" fills columns 0..5; the tail overwrites column 4,
1444        // which is the continuation of "中", so the wide primary at 3 must be
1445        // blanked rather than left dangling.
1446        assert_eq!(cell_at(&b, 4, 0).content(), "…");
1447        assert!(!cell_at(&b, 3, 0).is_wide());
1448    }
1449}