Skip to main content

uncurses/text/
surface.rs

1//! [`TextSurface`] — text drawing as an extension of any mutable surface.
2//!
3//! [`SurfaceMut`](crate::buffer::SurfaceMut) reads and writes cells; it does
4//! not decide how many cells a string occupies. `TextSurface` adds that policy
5//! layer. Implementors provide a [width mode](TextSurface::width_mode) and
6//! [East-Asian Ambiguous policy](TextSurface::eaw_wide); the default `set_str`
7//! family segments the input into grapheme clusters and paints each with a
8//! [`Pen`] value. A [`Style`](crate::style::Style) converts directly to
9//! `Pen` when text has no link.
10//!
11//! The default methods paint text **literally**: inline SGR (`CSI … m`) and
12//! OSC 8 hyperlink sequences are not interpreted, so they are segmented and
13//! drawn like any other text. Reach for [`Painter`](super::Painter) — itself a
14//! `TextSurface` — when a string should be parsed for inline style and
15//! hyperlink escapes. Newline and carriage return still move the paint cursor
16//! within the active clip rectangle.
17//!
18//! Use this trait when writing widgets, layout helpers, or tests that should
19//! accept any text-capable destination:
20//!
21//! ```rust,ignore
22//! fn label(surface: &mut impl TextSurface, at: Position, text: &str, pen: Pen) {
23//!     surface.set_str(at, text, pen);
24//! }
25//! ```
26
27use super::{Pen, WidthMode, WrapMode, grapheme_cells};
28use crate::buffer::SurfaceMut;
29use crate::cell::Cell;
30use crate::layout::{Position, Rect, overruns};
31
32/// A [`SurfaceMut`] with a text-measurement policy and string-painting helpers.
33///
34/// Implement this for surface types that can accept styled text. The only
35/// required decisions are [`width_mode`](Self::width_mode), which controls how
36/// grapheme clusters are measured, and [`eaw_wide`](Self::eaw_wide), which
37/// controls East-Asian Ambiguous code points.
38///
39/// The default `set_str` family paints text literally: each grapheme cluster is
40/// drawn with the given [`Pen`] value and inline SGR / OSC 8 escapes are not
41/// interpreted. Use [`Painter`](super::Painter), which is itself a
42/// `TextSurface`, to parse inline style and hyperlink escapes. Newline and
43/// carriage return move the paint cursor within the active clip rectangle.
44pub trait TextSurface: SurfaceMut {
45    /// Return the width-measurement mode used when shaping strings.
46    ///
47    /// [`WidthMode::Wc`] sums the code points of each grapheme cluster;
48    /// [`WidthMode::Grapheme`] measures the whole cluster. The selected mode is
49    /// used by the `set_str` family and [`str_width`](Self::str_width).
50    ///
51    /// This method is pure policy lookup. It should not inspect or mutate the
52    /// surface contents.
53    fn width_mode(&self) -> WidthMode;
54
55    /// Return the East-Asian Ambiguous width policy for this surface.
56    ///
57    /// When `true`, code points whose East-Asian-Width property is
58    /// `Ambiguous` are measured as two cells. When `false`, they are measured
59    /// as one. The flag is passed to [`char_width`](super::char_width) and
60    /// [`grapheme_width`](super::grapheme_width) by all text operations.
61    fn eaw_wide(&self) -> bool;
62
63    /// Paint `s` at `pos`, clipped to the surface bounds.
64    ///
65    /// Every cell painted gets `pen`. This default implementation paints
66    /// *literally*: escape sequences in `s` are drawn as visible characters,
67    /// not interpreted. For SGR/OSC 8-aware painting that turns inline escapes
68    /// into styling, wrap the surface in a [`Painter`](super::Painter). Newline
69    /// moves to the next row at the surface's left edge; carriage return moves
70    /// to that left edge on the current row. If a non-zero-width grapheme
71    /// cluster would cross the right edge, the rest of that row is dropped and
72    /// painting resumes on the next row.
73    ///
74    /// # Parameters
75    ///
76    /// * `pos` — starting cell position.
77    /// * `s` — UTF-8 string to paint. Escape sequences are drawn literally.
78    /// * `pen` — visual style and optional hyperlink for painted cells.
79    ///
80    /// # Returns
81    ///
82    /// The cursor position immediately after the last written cell, or the
83    /// position where painting stopped. The returned position may be outside
84    /// the surface when input reaches the bottom edge.
85    ///
86    /// # Errors and panics
87    ///
88    /// This method does not return errors and does not intentionally panic.
89    ///
90    /// # Usage note
91    ///
92    /// Use [`set_str_wrap`](Self::set_str_wrap) when text should continue on
93    /// following rows instead of truncating at the right edge.
94    fn set_str(&mut self, pos: impl Into<Position>, s: &str, pen: impl Into<Pen>) -> Position {
95        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
96        let clip = self.bounds();
97        let pen = pen.into();
98        paint_literal(
99            self,
100            pos.into(),
101            clip,
102            s,
103            WrapMode::Truncate,
104            mode,
105            eaw,
106            &pen,
107        )
108    }
109
110    /// Paint `s` at `pos` with an explicit right-edge behavior.
111    ///
112    /// This is the same operation as [`set_str`](Self::set_str), except
113    /// `wrap` decides what happens when a non-zero-width grapheme cluster would
114    /// cross the surface's right edge: [`WrapMode::Truncate`] stops, and
115    /// [`WrapMode::Wrap`] continues at the left edge of the next row until the
116    /// bottom edge is reached.
117    ///
118    /// # Parameters
119    ///
120    /// * `pos` — starting cell position.
121    /// * `s` — UTF-8 string to paint.
122    /// * `wrap` — wrapping policy at the right edge.
123    /// * `pen` — visual style and optional hyperlink for painted cells.
124    ///
125    /// # Returns
126    ///
127    /// The cursor position immediately after the last written cell, or where
128    /// painting stopped.
129    ///
130    /// # Errors and panics
131    ///
132    /// This method does not return errors and does not intentionally panic.
133    fn set_str_wrap(
134        &mut self,
135        pos: impl Into<Position>,
136        s: &str,
137        wrap: WrapMode,
138        pen: impl Into<Pen>,
139    ) -> Position {
140        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
141        let clip = self.bounds();
142        let pen = pen.into();
143        paint_literal(self, pos.into(), clip, s, wrap, mode, eaw, &pen)
144    }
145
146    /// Paint `s` inside `rect`, clipped to the surface bounds.
147    ///
148    /// Painting starts at `rect`'s top-left corner and is clipped to
149    /// `rect ∩ self.bounds()`. Newline and carriage return use `rect`'s left
150    /// edge as the return column. If a non-zero-width grapheme cluster would
151    /// cross `rect`'s right edge, the rest of that row is dropped and painting
152    /// resumes on the next row.
153    ///
154    /// # Parameters
155    ///
156    /// * `rect` — clipping rectangle and starting origin.
157    /// * `s` — UTF-8 string to paint.
158    /// * `pen` — visual style and optional hyperlink for painted cells.
159    ///
160    /// # Returns
161    ///
162    /// The cursor position immediately after the last written cell, or where
163    /// painting stopped.
164    ///
165    /// # Errors and panics
166    ///
167    /// This method does not return errors and does not intentionally panic.
168    fn set_str_rect(&mut self, rect: impl Into<Rect>, s: &str, pen: impl Into<Pen>) -> Position {
169        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
170        let rect = rect.into();
171        let clip = rect.intersection(self.bounds());
172        let pen = pen.into();
173        paint_literal(
174            self,
175            rect.position(),
176            clip,
177            s,
178            WrapMode::Truncate,
179            mode,
180            eaw,
181            &pen,
182        )
183    }
184
185    /// Paint `s` inside `rect` with an explicit right-edge behavior.
186    ///
187    /// This is the rectangular form of [`set_str_wrap`](Self::set_str_wrap).
188    /// [`WrapMode::Wrap`] flows to the next row at `rect`'s left edge;
189    /// [`WrapMode::Truncate`] stops at `rect`'s right edge.
190    ///
191    /// # Parameters
192    ///
193    /// * `rect` — clipping rectangle and starting origin.
194    /// * `s` — UTF-8 string to paint.
195    /// * `wrap` — wrapping policy at the rectangle's right edge.
196    /// * `pen` — visual style and optional hyperlink for painted cells.
197    ///
198    /// # Returns
199    ///
200    /// The cursor position immediately after the last written cell, or where
201    /// painting stopped.
202    ///
203    /// # Errors and panics
204    ///
205    /// This method does not return errors and does not intentionally panic.
206    fn set_str_rect_wrap(
207        &mut self,
208        rect: impl Into<Rect>,
209        s: &str,
210        wrap: WrapMode,
211        pen: impl Into<Pen>,
212    ) -> Position {
213        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
214        let rect = rect.into();
215        let clip = rect.intersection(self.bounds());
216        let pen = pen.into();
217        paint_literal(self, rect.position(), clip, s, wrap, mode, eaw, &pen)
218    }
219
220    /// Paint `s` at `pos`, truncating with a `tail` indicator on overflow.
221    ///
222    /// When a cluster would cross the surface's right edge, the rest of that
223    /// row is dropped and `tail` is stamped over its trailing columns, ending
224    /// at the right edge. Painting resumes on the next row if `s` continues
225    /// past a newline, so a multi-line `s` can stamp one tail per overflowing
226    /// row. The tail appears only on rows that actually overflow. `tail` is
227    /// painted literally with `tail_pen`; `s` uses `s_pen`. Use
228    /// [`Painter`](super::Painter) to interpret inline escapes in either
229    /// string. A tail wider than the surface is dropped in favor of a hard
230    /// truncate.
231    ///
232    /// # Parameters
233    ///
234    /// * `pos` — starting cell position.
235    /// * `s` — UTF-8 string to paint.
236    /// * `s_pen` — visual style and optional hyperlink for the main text.
237    /// * `tail` — truncation indicator, painted when `s` overflows.
238    /// * `tail_pen` — visual style and optional hyperlink for the tail.
239    ///
240    /// # Returns
241    ///
242    /// The cursor position immediately after the last written cell, or where
243    /// painting stopped.
244    ///
245    /// # Errors and panics
246    ///
247    /// This method does not return errors and does not intentionally panic.
248    fn set_str_truncate(
249        &mut self,
250        pos: impl Into<Position>,
251        s: &str,
252        s_pen: impl Into<Pen>,
253        tail: &str,
254        tail_pen: impl Into<Pen>,
255    ) -> Position {
256        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
257        let clip = self.bounds();
258        let s_pen = s_pen.into();
259        let tail_pen = tail_pen.into();
260        paint_literal_truncate(
261            self,
262            pos.into(),
263            clip,
264            s,
265            &s_pen,
266            tail,
267            &tail_pen,
268            mode,
269            eaw,
270        )
271    }
272
273    /// Paint `s` inside `rect`, truncating with a `tail` indicator on overflow.
274    ///
275    /// This is the rectangular form of [`set_str_truncate`](Self::set_str_truncate):
276    /// the clip rectangle is `rect ∩ self.bounds()`, and a tail is stamped at
277    /// `rect`'s right edge on each row that overflows it.
278    ///
279    /// # Parameters
280    ///
281    /// * `rect` — clipping rectangle and starting origin.
282    /// * `s` — UTF-8 string to paint.
283    /// * `s_pen` — visual style and optional hyperlink for the main text.
284    /// * `tail` — truncation indicator, painted when `s` overflows.
285    /// * `tail_pen` — visual style and optional hyperlink for the tail.
286    ///
287    /// # Returns
288    ///
289    /// The cursor position immediately after the last written cell, or where
290    /// painting stopped.
291    ///
292    /// # Errors and panics
293    ///
294    /// This method does not return errors and does not intentionally panic.
295    fn set_str_rect_truncate(
296        &mut self,
297        rect: impl Into<Rect>,
298        s: &str,
299        s_pen: impl Into<Pen>,
300        tail: &str,
301        tail_pen: impl Into<Pen>,
302    ) -> Position {
303        let (mode, eaw) = (self.width_mode(), self.eaw_wide());
304        let rect = rect.into();
305        let clip = rect.intersection(self.bounds());
306        let s_pen = s_pen.into();
307        let tail_pen = tail_pen.into();
308        paint_literal_truncate(
309            self,
310            rect.position(),
311            clip,
312            s,
313            &s_pen,
314            tail,
315            &tail_pen,
316            mode,
317            eaw,
318        )
319    }
320
321    /// Measure the display width of `s` in terminal columns.
322    ///
323    /// The measurement segments `s` into grapheme clusters under this
324    /// surface's [`width_mode`](Self::width_mode) and
325    /// [`eaw_wide`](Self::eaw_wide) policy and sums their widths. Like the
326    /// default `set_str` family, this does **not** interpret inline escape
327    /// sequences: an SGR or OSC 8 sequence in `s` is measured as the width of
328    /// its visible bytes. Use [`Painter`](super::Painter), whose `str_width`
329    /// skips recognized escapes, to measure escape-bearing text.
330    ///
331    /// # Parameters
332    ///
333    /// * `s` — string to measure.
334    ///
335    /// # Returns
336    ///
337    /// The display width in cells, saturated at `u16::MAX`.
338    ///
339    /// # Errors and panics
340    ///
341    /// This method does not fail or intentionally panic.
342    fn str_width(&self, s: &str) -> u16 {
343        self.grapheme_cells(s)
344            .fold(0u16, |acc, (_, w)| acc.saturating_add(u16::from(w)))
345    }
346
347    /// Measure one extended grapheme cluster in cells under this surface's
348    /// width mode and East-Asian Ambiguous policy.
349    ///
350    /// # Parameters
351    ///
352    /// * `g` — a single grapheme cluster.
353    ///
354    /// # Returns
355    ///
356    /// The cluster width in cells, normally `0`, `1`, or `2`.
357    ///
358    /// # Errors and panics
359    ///
360    /// This method does not fail or intentionally panic.
361    fn grapheme_width(&self, g: &str) -> u8 {
362        self.width_mode().grapheme_width(g, self.eaw_wide())
363    }
364
365    /// Iterate `s` as `(cluster, width)` pairs under this surface's width mode
366    /// and East-Asian Ambiguous policy.
367    ///
368    /// # Parameters
369    ///
370    /// * `s` — UTF-8 string to segment and measure.
371    ///
372    /// # Returns
373    ///
374    /// An iterator yielding borrowed cluster slices and their cell widths.
375    ///
376    /// # Errors and panics
377    ///
378    /// This method does not fail or intentionally panic.
379    fn grapheme_cells<'a>(&self, s: &'a str) -> impl Iterator<Item = (&'a str, u8)> {
380        grapheme_cells(s, self.width_mode(), self.eaw_wide())
381    }
382}
383
384/// A literal truncation tail: indicator text, its starting style, and its
385/// measured cell width.
386struct LiteralTail<'a> {
387    text: &'a str,
388    pen: &'a Pen,
389    width: u16,
390}
391
392/// Paint `s` literally, clipped to `clip`, with `wrap` behavior at the right
393/// edge. Each grapheme cluster is drawn with `pen`; inline escapes are not
394/// interpreted (they are segmented and drawn like any other text). Newline and
395/// carriage return reposition within `clip`.
396#[allow(clippy::too_many_arguments)]
397fn paint_literal<S: SurfaceMut + ?Sized>(
398    target: &mut S,
399    start: Position,
400    clip: Rect,
401    s: &str,
402    wrap: WrapMode,
403    mode: WidthMode,
404    eaw_wide: bool,
405    pen: &Pen,
406) -> Position {
407    let width = if matches!(s.as_bytes(), [b' '..=b'~']) {
408        1
409    } else {
410        let mut chars = s.chars();
411        match (chars.next(), chars.next()) {
412            (Some(ch), None) if !ch.is_control() => mode.grapheme_width(s, eaw_wide),
413            _ => 0,
414        }
415    };
416    if width > 0 && clip.contains(start) && !overruns(start.x, u16::from(width), clip.right()) {
417        let mut cell = Cell::new(s, width).with_style(pen.style);
418        cell.set_link(pen.link.clone());
419        target.set_cell(start, &cell);
420        return Position::new(start.x + u16::from(width), start.y);
421    }
422    paint_literal_inner(target, start, clip, s, wrap, mode, eaw_wide, pen, None)
423}
424
425/// Paint `s` literally with [`WrapMode::Truncate`], stamping `tail` on overflow.
426///
427/// The main text is drawn with `s_pen`; the tail is drawn with
428/// `tail_pen`. The tail is dropped (hard truncate) when it is empty or wider
429/// than the clip.
430#[allow(clippy::too_many_arguments)]
431fn paint_literal_truncate<S: SurfaceMut + ?Sized>(
432    target: &mut S,
433    start: Position,
434    clip: Rect,
435    s: &str,
436    s_pen: &Pen,
437    tail_text: &str,
438    tail_pen: &Pen,
439    mode: WidthMode,
440    eaw_wide: bool,
441) -> Position {
442    if clip.is_empty() {
443        return start;
444    }
445    let tail_w = grapheme_cells(tail_text, mode, eaw_wide)
446        .fold(0u16, |acc, (_, w)| acc.saturating_add(u16::from(w)));
447    let tail = if tail_w == 0 || tail_w > clip.width {
448        None
449    } else {
450        Some(LiteralTail {
451            text: tail_text,
452            pen: tail_pen,
453            width: tail_w,
454        })
455    };
456    paint_literal_inner(
457        target,
458        start,
459        clip,
460        s,
461        WrapMode::Truncate,
462        mode,
463        eaw_wide,
464        s_pen,
465        tail,
466    )
467}
468
469#[allow(clippy::too_many_arguments)]
470fn paint_literal_inner<S: SurfaceMut + ?Sized>(
471    target: &mut S,
472    start: Position,
473    clip: Rect,
474    s: &str,
475    wrap: WrapMode,
476    mode: WidthMode,
477    eaw_wide: bool,
478    pen: &Pen,
479    tail: Option<LiteralTail<'_>>,
480) -> Position {
481    if clip.is_empty() {
482        return start;
483    }
484    // `y` only ever advances, so a start below the clip can never paint.
485    if start.y >= clip.bottom() {
486        return start;
487    }
488    let mut x = start.x;
489    let mut y = start.y;
490    // Truncation is per row: once a row overflows, clusters are dropped until
491    // `\n` or `\r` puts the cursor back inside the clip.
492    let mut truncated = false;
493
494    for (cluster, w) in grapheme_cells(s, mode, eaw_wide) {
495        // Extended grapheme segmentation joins CR LF into a single cluster, so
496        // it has to be matched alongside a lone `\n` or it reads as zero-width
497        // filler and never breaks the line.
498        if cluster == "\n" || cluster == "\r\n" {
499            y = y.saturating_add(1);
500            x = clip.left();
501            truncated = false;
502            if y >= clip.bottom() {
503                return Position::new(x, y);
504            }
505            continue;
506        }
507        if cluster == "\r" {
508            x = clip.left();
509            truncated = false;
510            continue;
511        }
512        if truncated || w == 0 {
513            continue;
514        }
515        let cw = w;
516        let w = u16::from(w);
517        if overruns(x, w, clip.right()) {
518            match wrap {
519                WrapMode::Truncate => {
520                    if let Some(t) = &tail {
521                        stamp_literal_tail(target, t, clip, y, mode, eaw_wide);
522                        x = clip.right();
523                    }
524                    truncated = true;
525                    continue;
526                }
527                WrapMode::Wrap => {
528                    y = y.saturating_add(1);
529                    x = clip.left();
530                    if y >= clip.bottom() {
531                        return Position::new(x, y);
532                    }
533                    if overruns(x, w, clip.right()) {
534                        return Position::new(x, y);
535                    }
536                }
537            }
538        }
539        if clip.contains(Position::new(x, y)) {
540            let mut cell = Cell::new(cluster, cw).with_style(pen.style);
541            cell.set_link(pen.link.clone());
542            target.set_cell(Position::new(x, y), &cell);
543        }
544        x += w;
545    }
546    Position::new(x, y)
547}
548
549/// Stamp `tail` over the trailing `tail.width` columns of row `y`, ending at
550/// `clip`'s right edge, painted literally with the tail's style.
551fn stamp_literal_tail<S: SurfaceMut + ?Sized>(
552    target: &mut S,
553    tail: &LiteralTail<'_>,
554    clip: Rect,
555    y: u16,
556    mode: WidthMode,
557    eaw_wide: bool,
558) {
559    let tail_x = clip.right().saturating_sub(tail.width);
560    let sub = Rect::new(tail_x, y, tail.width, 1).intersection(clip);
561    paint_literal_inner(
562        target,
563        Position::new(tail_x, y),
564        sub,
565        tail.text,
566        WrapMode::Truncate,
567        mode,
568        eaw_wide,
569        tail.pen,
570        None,
571    );
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577    use crate::buffer::{Buffer, Surface, TextBuffer};
578    use crate::color::Color;
579    use crate::style::{Link, Style};
580    use std::sync::Arc;
581
582    #[test]
583    fn matching_text_creates_a_local_override_on_read_through_surfaces() {
584        use crate::buffer::Bounded;
585
586        struct ReadThrough {
587            inherited: Cell,
588            local: Option<Cell>,
589        }
590
591        impl Bounded for ReadThrough {
592            fn bounds(&self) -> Rect {
593                Rect::new(0, 0, 1, 1)
594            }
595        }
596
597        impl Surface for ReadThrough {
598            fn cell(&self, pos: Position) -> Option<&Cell> {
599                self.contains(pos)
600                    .then(|| self.local.as_ref().unwrap_or(&self.inherited))
601            }
602        }
603
604        impl SurfaceMut for ReadThrough {
605            fn set_cell(&mut self, pos: Position, cell: &Cell) {
606                if self.contains(pos) {
607                    self.local = Some(cell.clone());
608                }
609            }
610
611            fn cell_mut(&mut self, pos: Position) -> Option<&mut Cell> {
612                if self.contains(pos) {
613                    self.local.as_mut()
614                } else {
615                    None
616                }
617            }
618        }
619
620        impl TextSurface for ReadThrough {
621            fn width_mode(&self) -> WidthMode {
622                WidthMode::Wc
623            }
624
625            fn eaw_wide(&self) -> bool {
626                false
627            }
628        }
629
630        for text in ["A", "A\u{301}"] {
631            for stale_link in [false, true] {
632                let expected = Cell::new(text, 1).with_style(Style::new().fg(Color::Green));
633                let mut surface = ReadThrough {
634                    inherited: expected.clone(),
635                    local: None,
636                };
637                if stale_link {
638                    surface
639                        .inherited
640                        .set_link(Some(crate::style::test_link("https://old", "")));
641                }
642                assert_eq!(surface.inherited == expected, !stale_link);
643                assert_eq!(
644                    surface.set_str((0, 0), text, expected.style()),
645                    Position::new(1, 0)
646                );
647                surface.inherited = Cell::new("Z", 1);
648                assert_eq!(
649                    surface.cell((0, 0).into()),
650                    Some(&expected),
651                    "{text:?}, stale_link={stale_link}"
652                );
653            }
654        }
655    }
656
657    #[test]
658    fn literal_shortcuts_preserve_general_positions_and_cells() {
659        let style = Style::new().fg(Color::Green);
660        let mut initial = Buffer::new(8, 3);
661        initial.set((2, 1), &Cell::new("界", 2));
662        for mode in [WidthMode::Wc, WidthMode::Grapheme] {
663            for eaw in [false, true] {
664                for wrap in [WrapMode::Truncate, WrapMode::Wrap] {
665                    for clip in [Rect::new(1, 1, 6, 2), Rect::new(1, 1, 0, 0)] {
666                        for start in [(0, 0), (1, 1), (2, 1), (3, 1), (6, 1), (7, 1), (1, 3)] {
667                            for text in [
668                                "",
669                                "A",
670                                " ",
671                                "é",
672                                "¡",
673                                "界",
674                                "👩",
675                                "\u{301}",
676                                "\u{200d}",
677                                "\n",
678                                "\r",
679                                "\r\n",
680                                "\t",
681                                "\u{7f}",
682                                "A\u{301}",
683                                "👩\u{200d}💻",
684                                "AB",
685                            ] {
686                                let mut fast = initial.clone();
687                                let mut general = initial.clone();
688                                let fast_end = paint_literal(
689                                    &mut fast,
690                                    start.into(),
691                                    clip,
692                                    text,
693                                    wrap,
694                                    mode,
695                                    eaw,
696                                    &Pen::from(style),
697                                );
698                                let general_end = paint_literal_inner(
699                                    &mut general,
700                                    start.into(),
701                                    clip,
702                                    text,
703                                    wrap,
704                                    mode,
705                                    eaw,
706                                    &Pen::from(style),
707                                    None,
708                                );
709                                assert_eq!(fast_end, general_end, "{text:?}, {start:?}, {mode:?}");
710                                for y in 0..3 {
711                                    assert_eq!(
712                                        fast.line(y),
713                                        general.line(y),
714                                        "{text:?}, {start:?}, {mode:?}, row {y}"
715                                    );
716                                }
717                            }
718                        }
719                    }
720                }
721            }
722        }
723    }
724
725    #[test]
726    fn narrow_updates_own_borrowed_clusters_and_replace_links() {
727        let expected = format!("e{}", "\u{301}".repeat(40));
728        let mut buffer = TextBuffer::new(4, 1);
729        {
730            let borrowed = expected.clone();
731            let style = Style::new().fg(Color::Green);
732            assert_eq!(buffer.set_str((0, 0), &borrowed, style), (1, 0).into());
733            buffer
734                .cell_mut((0, 0).into())
735                .unwrap()
736                .set_link(Some(crate::style::test_link(
737                    "https://example.test",
738                    "id=owned",
739                )));
740        }
741        let cell = buffer.cell((0, 0).into()).unwrap();
742        assert_eq!(cell.content(), expected);
743        assert_eq!(cell.link.as_deref().unwrap().url, "https://example.test");
744
745        buffer.set_str((0, 0), "x", Style::EMPTY);
746        let cell = buffer.cell((0, 0).into()).unwrap();
747        assert_eq!(cell.content(), "x");
748        assert_eq!(cell.style(), Style::EMPTY);
749        assert!(cell.link().is_none());
750    }
751
752    #[test]
753    fn paint_links_wrapped_cells_and_keeps_tail_link_independent() {
754        let text_link = Arc::new(Link {
755            url: "https://example.test/text".into(),
756            params: "id=text".into(),
757        });
758        let text_paint = Pen::new()
759            .with_style(Style::new().fg(Color::Green).underline())
760            .with_link(text_link.clone());
761        let mut buffer = TextBuffer::new(3, 2);
762        buffer.set_str_wrap((0, 0), "ab界c", WrapMode::Wrap, text_paint.clone());
763
764        for pos in [(0, 0), (1, 0), (0, 1), (1, 1), (2, 1)] {
765            assert_eq!(buffer.cell(pos.into()).unwrap().link(), Some(&text_link));
766        }
767        assert!(buffer.cell((1, 1).into()).unwrap().is_continuation());
768        assert!(Arc::ptr_eq(
769            buffer.cell((0, 1).into()).unwrap().link().unwrap(),
770            buffer.cell((1, 1).into()).unwrap().link().unwrap()
771        ));
772        assert_eq!(
773            buffer.cell((0, 1).into()).unwrap().style(),
774            text_paint.style
775        );
776
777        let tail_link = Arc::new(Link {
778            url: "https://example.test/tail".into(),
779            params: String::new(),
780        });
781        let mut buffer = TextBuffer::new(3, 1);
782        buffer.set_str_truncate(
783            (0, 0),
784            "abcdef",
785            text_paint,
786            ".",
787            Pen::new()
788                .with_style(Style::new().fg(Color::Red))
789                .with_link(tail_link.clone()),
790        );
791        assert_eq!(buffer.cell((0, 0).into()).unwrap().link(), Some(&text_link));
792        assert_eq!(buffer.cell((1, 0).into()).unwrap().link(), Some(&text_link));
793        assert_eq!(buffer.cell((2, 0).into()).unwrap().link(), Some(&tail_link));
794        assert_eq!(buffer.cell((2, 0).into()).unwrap().content(), ".");
795    }
796
797    #[test]
798    fn link_values_convert_into_text_paints() {
799        let mut buffer = TextBuffer::new(2, 1);
800        buffer.set_str(
801            (0, 0),
802            "a",
803            Link {
804                url: "https://example.test/owned".into(),
805                params: String::new(),
806            },
807        );
808        let shared_link = Arc::new(Link {
809            url: "https://example.test/shared".into(),
810            params: String::new(),
811        });
812        buffer.set_str((1, 0), "b", shared_link.clone());
813
814        assert_eq!(
815            buffer.cell((0, 0).into()).unwrap().link().unwrap().url,
816            "https://example.test/owned"
817        );
818        assert!(Arc::ptr_eq(
819            buffer.cell((1, 0).into()).unwrap().link().unwrap(),
820            &shared_link
821        ));
822    }
823
824    /// `right()` is exclusive and saturates at `u16::MAX`, so a row that ends
825    /// at the top of the address space can leave `x` equal to it. Adding the
826    /// next cluster's width there overflowed and panicked.
827    #[test]
828    fn a_row_ending_at_the_last_addressable_column_truncates_instead_of_panicking() {
829        let mut buf = TextBuffer::new(u16::MAX, 1);
830        let s: String = "a".repeat(usize::from(u16::MAX) + 8);
831        buf.set_str((0, 0), &s, Style::default());
832
833        // A cluster that claims many columns has a wider window in which to
834        // overflow, so check it lands on the same truncating path.
835        let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}";
836        let mut wide = TextBuffer::new(u16::MAX, 1);
837        wide.set_str(
838            (0, 0),
839            &"a".repeat(usize::from(u16::MAX) - 2),
840            Style::default(),
841        );
842        wide.set_str((u16::MAX - 2, 0), family, Style::default());
843    }
844}