Skip to main content

uncurses/text/
display.rs

1//! Serialize a [`Surface`] back into escape sequences and text.
2//!
3//! This is the inverse of [`Painter`](super::Painter). Where a painter parses
4//! a string of text and escape sequences *onto* a surface, [`Encode`] walks a
5//! surface row by row and emits its styled cells *back out* as a stream of SGR
6//! and OSC 8 sequences interleaved with grapheme-cluster content.
7//!
8//! Each terminal row becomes one output line, rows are separated by CRLF
9//! (`\r\n`) so the result reproduces the surface when written to a terminal,
10//! and every row begins and ends in the default style. Style transitions
11//! between adjacent cells are minimized the same way the renderer minimizes
12//! them, so a run of identically styled cells emits a single opener.
13//!
14//! ```
15//! use uncurses::buffer::{Buffer, SurfaceMut};
16//! use uncurses::cell::Cell;
17//! use uncurses::style::Style;
18//! use uncurses::text::Encode;
19//!
20//! let mut buf = Buffer::new(2, 1);
21//! let mut h = Cell::new("h", 1);
22//! h.set_style(Style::new().bold());
23//! let mut i = Cell::new("i", 1);
24//! i.set_style(h.style());
25//! buf.set_cell((0, 0).into(), &h);
26//! buf.set_cell((1, 0).into(), &i);
27//!
28//! // Render into a String via the Display adapter.
29//! let s = buf.display().to_string();
30//! assert!(s.contains("hi"));
31//! ```
32
33use std::fmt;
34use std::io::{self, Write};
35
36use crate::buffer::Surface;
37use crate::cell::Cell;
38use crate::color::Profile;
39use crate::layout::Position;
40use crate::style::diff::{convert_style, write_link, write_style_diff};
41use crate::style::{Style, UnderlineStyle};
42
43/// Serialize a [`Surface`] into escape sequences and text.
44///
45/// This extension trait is implemented for every [`Surface`], so any cell
46/// grid (a [`Buffer`](crate::buffer::Buffer),
47/// [`Window`](crate::buffer::Window), [`TextBuffer`](crate::buffer::TextBuffer), or
48/// [`Screen`](crate::screen::Screen)) can be rendered back to its escape-code
49/// form.
50///
51/// Use [`encode`](Self::encode) to stream straight into an [`io::Write`], or
52/// [`display`](Self::display) to borrow the surface as a
53/// [`Display`](fmt::Display) for `format!`, `to_string`, and the `write!`
54/// macros. The [`encode_with`](Self::encode_with) and
55/// [`display_with`](Self::display_with) variants downsample every cell's
56/// colors to a [`Profile`] first, the same way the renderer adapts output to a
57/// terminal's color capability.
58pub trait Encode: Surface {
59    /// Write the surface to `w` as escape sequences and text.
60    ///
61    /// One terminal row is written per line, separated by CRLF (`\r\n`) with
62    /// no trailing newline after the final row. Each row starts and ends in
63    /// the default style: any open SGR state or hyperlink is reset at the end
64    /// of the row.
65    ///
66    /// Trailing unstyled blank cells are trimmed from each row, so a row with
67    /// nothing but default spaces emits an empty line. A blank cell still
68    /// counts as visible when it carries a style (for example a space with a
69    /// background color), so styled trailing space is preserved.
70    ///
71    /// Wide-cell continuation placeholders are skipped because the wide
72    /// primary already carries the full grapheme cluster. Colors are written
73    /// as stored; use [`encode_with`](Self::encode_with) to downsample them to
74    /// a color [`Profile`].
75    ///
76    /// # Errors
77    ///
78    /// Propagates any [`io::Error`] from `w`.
79    fn encode<W: Write>(&self, w: &mut W) -> io::Result<()> {
80        encode_surface(self, w, Profile::TrueColor)
81    }
82
83    /// Write the surface to `w`, downsampling colors to `profile`.
84    ///
85    /// Each cell's style is converted for `profile` before it is emitted, so
86    /// the output matches what the renderer would produce for a terminal with
87    /// that color capability: [`Profile::Ansi`] and [`Profile::Ansi256`]
88    /// quantize to the nearest palette color, [`Profile::Ascii`] drops colors
89    /// but keeps attributes, and [`Profile::Disabled`] drops all styling
90    /// (including hyperlinks). [`Profile::TrueColor`] is identical to
91    /// [`encode`](Self::encode).
92    ///
93    /// # Errors
94    ///
95    /// Propagates any [`io::Error`] from `w`.
96    fn encode_with<W: Write>(&self, w: &mut W, profile: Profile) -> io::Result<()> {
97        encode_surface(self, w, profile)
98    }
99
100    /// Borrow the surface as a [`Display`](fmt::Display) adapter.
101    ///
102    /// The returned value renders the same bytes as [`encode`](Self::encode)
103    /// when formatted, so `surface.display().to_string()` produces the encoded
104    /// string and `write!(w, "{}", surface.display())` writes it to any
105    /// [`io::Write`] or [`fmt::Write`] sink.
106    fn display(&self) -> SurfaceDisplay<'_, Self> {
107        SurfaceDisplay {
108            surface: self,
109            profile: Profile::TrueColor,
110        }
111    }
112
113    /// Borrow the surface as a [`Display`](fmt::Display) adapter that
114    /// downsamples colors to `profile`.
115    ///
116    /// Formatting it renders the same bytes as
117    /// [`encode_with`](Self::encode_with) with the same profile.
118    fn display_with(&self, profile: Profile) -> SurfaceDisplay<'_, Self> {
119        SurfaceDisplay {
120            surface: self,
121            profile,
122        }
123    }
124}
125
126impl<S: Surface + ?Sized> Encode for S {}
127
128/// A [`Display`](fmt::Display) adapter over a [`Surface`], returned by
129/// [`Encode::display`] and [`Encode::display_with`].
130///
131/// Formatting it emits the same bytes as [`Encode::encode_with`] with the
132/// adapter's profile.
133pub struct SurfaceDisplay<'a, S: Surface + ?Sized> {
134    surface: &'a S,
135    profile: Profile,
136}
137
138impl<S: Surface + ?Sized> fmt::Display for SurfaceDisplay<'_, S> {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        // SGR/OSC sequences are ASCII and cell content is UTF-8, so the
141        // encoded bytes are always valid UTF-8.
142        let mut buf = Vec::new();
143        encode_surface(self.surface, &mut buf, self.profile).map_err(|_| fmt::Error)?;
144        let s = std::str::from_utf8(&buf).map_err(|_| fmt::Error)?;
145        f.write_str(s)
146    }
147}
148
149/// Encode `surface` into `w`, row by row, downsampling colors to `profile`.
150fn encode_surface<S: Surface + ?Sized, W: Write>(
151    surface: &S,
152    w: &mut W,
153    profile: Profile,
154) -> io::Result<()> {
155    match profile {
156        Profile::Disabled => encode_impl::<false, false, _, _>(surface, w, std::convert::identity),
157        Profile::Ascii => encode_impl::<true, false, _, _>(surface, w, std::convert::identity),
158        Profile::TrueColor => encode_impl::<true, true, _, _>(surface, w, std::convert::identity),
159        Profile::Ansi => {
160            encode_impl::<true, true, _, _>(surface, w, |style| convert_style(style, Profile::Ansi))
161        }
162        Profile::Ansi256 => encode_impl::<true, true, _, _>(surface, w, |style| {
163            convert_style(style, Profile::Ansi256)
164        }),
165    }
166}
167
168// Keep profile specializations separate instead of merging their stack frames.
169#[inline(never)]
170fn encode_impl<const STYLED: bool, const COLORS: bool, S: Surface + ?Sized, W: Write>(
171    surface: &S,
172    w: &mut W,
173    convert: impl Fn(Style) -> Style,
174) -> io::Result<()> {
175    let bounds = surface.bounds();
176    let default = Style::default();
177    let x_end = bounds.x.saturating_add(bounds.width);
178    let y_end = bounds.y.saturating_add(bounds.height);
179
180    for (row, y) in (bounds.y..y_end).enumerate() {
181        if row > 0 {
182            w.write_all(b"\r\n")?;
183        }
184
185        // Trim trailing unstyled blank space: find the last column that is
186        // visible, i.e. has real content or a non-empty style after
187        // downsampling. A blank cell whose style is empty (a styled space with
188        // a background still counts as visible) contributes nothing once the
189        // row resets to default, so everything past `last_visible` is dropped.
190        let last_visible = (bounds.x..x_end).rev().find(|&x| {
191            surface.cell(Position::new(x, y)).is_some_and(|cell| {
192                !cell.is_blank()
193                    || (STYLED
194                        && ((if COLORS {
195                            !cell.style().is_empty()
196                        } else {
197                            !cell.attrs.is_empty() || cell.underline != UnderlineStyle::None
198                        }) || cell.link().is_some()))
199            })
200        });
201        let Some(last_visible) = last_visible else {
202            // Entirely blank row: emit nothing between the separators.
203            continue;
204        };
205
206        // The pen starts each row in the default style with no open link.
207        let mut raw = &Cell::BLANK;
208        let mut pen = default;
209        let mut link = None;
210        for x in bounds.x..=last_visible {
211            let Some(cell) = surface.cell(Position::new(x, y)) else {
212                continue;
213            };
214            // Wide continuations carry no content of their own; the primary
215            // cell already emitted the whole grapheme cluster.
216            if cell.is_continuation() {
217                continue;
218            }
219
220            // Convert only changed visual state. Links form an independent run.
221            if STYLED {
222                let changed = if COLORS {
223                    cell.fg != raw.fg
224                        || cell.bg != raw.bg
225                        || cell.underline_color != raw.underline_color
226                        || cell.attrs != raw.attrs
227                        || cell.underline != raw.underline
228                } else {
229                    cell.attrs != pen.attrs || cell.underline != pen.underline
230                };
231                if changed {
232                    let to = if COLORS {
233                        convert(cell.style())
234                    } else {
235                        Style {
236                            attrs: cell.attrs,
237                            underline: cell.underline,
238                            ..default
239                        }
240                    };
241                    write_style_diff(w, &pen, &to)?;
242                    raw = cell;
243                    pen = to;
244                }
245                let to_link = cell.link();
246                if link != to_link {
247                    write_link(w, to_link)?;
248                    link = to_link;
249                }
250            }
251            w.write_all(cell.draw_bytes())?;
252        }
253
254        // Return the row to the default style, closing any open SGR state and
255        // hyperlink so the next row starts clean.
256        if STYLED {
257            write_style_diff(w, &pen, &default)?;
258            if link.is_some() {
259                write_link(w, None)?;
260            }
261        }
262    }
263
264    Ok(())
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::buffer::{Buffer, SurfaceMut};
271    use crate::cell::Cell;
272    use crate::style::{RESET, Style};
273
274    fn reset() -> &'static str {
275        std::str::from_utf8(RESET).unwrap()
276    }
277
278    #[test]
279    fn visual_and_link_runs_transition_independently() {
280        use crate::color::Color;
281
282        let open = "\x1b]8;id=run;https://x\x1b\\";
283        let close = "\x1b]8;;\x1b\\";
284        for (profile, red, blue) in [
285            (Profile::TrueColor, "\x1b[31m", "\x1b[34m"),
286            (Profile::Ascii, "", ""),
287        ] {
288            let mut buf = Buffer::new(5, 1);
289            let link = crate::style::test_link("https://x", "id=run");
290            let equal = crate::style::test_link("https://x", "id=run");
291            for (x, text, style, target) in [
292                (0, "a", Style::new().fg(Color::Red), Some(&link)),
293                (1, "b", Style::new().fg(Color::Red), Some(&equal)),
294                (2, "c", Style::new().fg(Color::Blue), Some(&link)),
295                (3, "d", Style::new().fg(Color::Blue).bold(), None),
296                (4, " ", Style::new().fg(Color::Blue).bold(), Some(&link)),
297            ] {
298                let mut cell = Cell::new(text, 1).with_style(style);
299                cell.set_link(target.cloned());
300                buf.set_cell((x, 0).into(), &cell);
301            }
302            assert_eq!(
303                buf.display_with(profile).to_string(),
304                format!("{red}{open}ab{blue}c\x1b[1m{close}d{open} \x1b[m{close}"),
305                "{profile:?}"
306            );
307        }
308    }
309
310    #[test]
311    fn styled_run_emits_one_opener_and_a_trailing_reset() {
312        let mut buf = Buffer::new(2, 1);
313        let bold = Style::new().bold();
314        buf.set_cell((0, 0).into(), &Cell::new("h", 1).with_style(bold));
315        buf.set_cell((1, 0).into(), &Cell::new("i", 1).with_style(bold));
316
317        let out = buf.display().to_string();
318        // The run shares a style, so the opener appears once before the text
319        // and a single reset closes the row.
320        assert!(out.contains("hi"), "content present: {out:?}");
321        assert!(out.ends_with(reset()), "row reset: {out:?}");
322        assert_eq!(out.matches(reset()).count(), 1, "single reset: {out:?}");
323        assert_eq!(
324            out.matches("\x1b[").count(),
325            2,
326            "one opener + reset: {out:?}"
327        );
328    }
329
330    #[test]
331    fn a_cell_that_stores_nothing_is_blanked_across_its_whole_width() {
332        let mut buf = Buffer::new(5, 1);
333        buf.set_cell((0, 0).into(), &Cell::new("A", 1));
334        buf.set_cell(
335            (1, 0).into(),
336            &Cell::new("", 3).with_style(Style::new().bold()),
337        );
338        buf.set_cell((4, 0).into(), &Cell::new("B", 1));
339
340        // The empty cell owns three columns, so it draws three blanks. Were
341        // its content written as it stands, the row would lose them and `B`
342        // would sit right beside `A`.
343        let out = buf.display().to_string();
344        assert!(out.contains("   "), "three blanks between: {out:?}");
345        assert!(out.starts_with('A'), "row starts at A: {out:?}");
346        assert!(out.ends_with(&format!("{}B", reset())), "B last: {out:?}");
347    }
348
349    #[test]
350    fn wide_continuation_is_skipped() {
351        let mut buf = Buffer::new(2, 1);
352        buf.set_cell((0, 0).into(), &Cell::new("世", 2));
353        // (1,0) is the continuation placeholder written by set_cell.
354        let out = buf.display().to_string();
355        // No stray empty content or extra cell after the wide grapheme.
356        assert_eq!(out, "世");
357    }
358
359    #[test]
360    fn encode_matches_display() {
361        let mut buf = Buffer::new(2, 1);
362        buf.set_cell(
363            (0, 0).into(),
364            &Cell::new("A", 1).with_style(Style::new().bold()),
365        );
366        let mut bytes = Vec::new();
367        buf.encode(&mut bytes).unwrap();
368        assert_eq!(String::from_utf8(bytes).unwrap(), buf.display().to_string());
369    }
370
371    #[test]
372    fn rows_are_crlf_separated_without_trailing_newline() {
373        let buf = Buffer::new(1, 3);
374        // Blank rows trim to empty, leaving just the CRLF separators.
375        let out = buf.display().to_string();
376        assert_eq!(out, "\r\n\r\n");
377    }
378
379    #[test]
380    fn trailing_unstyled_spaces_are_trimmed() {
381        let mut buf = Buffer::new(5, 1);
382        buf.set_cell((0, 0).into(), &Cell::new("h", 1));
383        buf.set_cell((1, 0).into(), &Cell::new("i", 1));
384        // Columns 2..5 stay blank and unstyled, so they are trimmed.
385        assert_eq!(buf.display().to_string(), "hi");
386    }
387
388    #[test]
389    fn a_trailing_column_holding_nothing_trims_like_one_holding_a_space() {
390        // Three cells that each put one space on the screen. `draw_bytes`
391        // gives `b" "` for all three, so the trim has to drop all three.
392        for tail in [Cell::BLANK, Cell::new(" ", 1), Cell::new("", 1)] {
393            let mut buf = Buffer::new(5, 1);
394            buf.set_cell((0, 0).into(), &Cell::new("h", 1));
395            buf.set_cell((1, 0).into(), &tail);
396            assert_eq!(buf.display().to_string(), "h", "tail {tail:?}");
397        }
398    }
399
400    #[test]
401    fn interior_blanks_are_kept_only_trailing_trimmed() {
402        let mut buf = Buffer::new(5, 1);
403        buf.set_cell((0, 0).into(), &Cell::new("a", 1));
404        buf.set_cell((2, 0).into(), &Cell::new("b", 1));
405        // The blank at column 1 is positional and kept; columns 3..5 trim.
406        assert_eq!(buf.display().to_string(), "a b");
407    }
408
409    #[test]
410    fn linked_trailing_spaces_close_at_each_row() {
411        let mut buf = Buffer::new(4, 2);
412        let mut space = Cell::BLANK;
413        space.set_link(Some(crate::style::test_link("https://x", "")));
414        for y in 0..2 {
415            buf.set_cell((1, y).into(), &space);
416        }
417        assert_eq!(
418            buf.display().to_string(),
419            " \x1b]8;;https://x\x1b\\ \x1b]8;;\x1b\\\r\n \x1b]8;;https://x\x1b\\ \x1b]8;;\x1b\\"
420        );
421        assert_eq!(buf.display_with(Profile::Disabled).to_string(), "\r\n");
422    }
423
424    #[test]
425    fn styled_trailing_space_is_not_trimmed() {
426        use crate::color::Color;
427        let mut buf = Buffer::new(3, 1);
428        buf.set_cell((0, 0).into(), &Cell::new("a", 1));
429        // A trailing space with a background is visible, so it survives.
430        let bg = Style::new().bg(Color::Red);
431        buf.set_cell((2, 0).into(), &Cell::new(" ", 1).with_style(bg));
432        // "a", a positional blank, then the bg-styled space, then reset.
433        assert_eq!(buf.display().to_string(), "a \x1b[41m \x1b[m");
434    }
435
436    #[test]
437    fn disabled_profile_trims_styled_trailing_space() {
438        use crate::color::{Color, Profile};
439        let mut buf = Buffer::new(3, 1);
440        buf.set_cell((0, 0).into(), &Cell::new("a", 1));
441        let mut tail = Cell::new(" ", 1).with_style(Style::new().bg(Color::Red));
442        tail.set_link(Some(crate::style::test_link(
443            "https://example.test/tail",
444            "",
445        )));
446        buf.set_cell((2, 0).into(), &tail);
447        // Under Disabled the background is dropped, so the trailing space is
448        // unstyled and gets trimmed along with the interior blank.
449        assert_eq!(buf.display_with(Profile::Disabled).to_string(), "a");
450    }
451
452    #[test]
453    fn profile_disabled_drops_all_styling() {
454        use crate::color::{Color, Profile};
455        let mut buf = Buffer::new(2, 1);
456        let styled = Style::new().bold().fg(Color::Red);
457        for (x, text) in ["h", "i"].into_iter().enumerate() {
458            let mut cell = Cell::new(text, 1).with_style(styled);
459            cell.set_link(Some(crate::style::test_link(
460                "https://example.test/text",
461                "",
462            )));
463            buf.set_cell((x as u16, 0).into(), &cell);
464        }
465        // Disabled strips every escape: only the text remains.
466        assert_eq!(buf.display_with(Profile::Disabled).to_string(), "hi");
467    }
468
469    #[test]
470    fn color_profiles_preserve_raw_transitions_and_merge_equal_palette_colors() {
471        use crate::color::{Color, Profile};
472        let mut buf = Buffer::new(6, 1);
473        let colors = Style::new()
474            .italic()
475            .underline()
476            .fg(Color::Rgb(255, 0, 0))
477            .bg(Color::Rgb(0, 255, 0))
478            .underline_color(Color::Rgb(0, 0, 255));
479        let fg = colors.fg(Color::Rgb(254, 0, 0));
480        let bg = fg.bg(Color::Rgb(0, 254, 0));
481        let underline_color = bg.underline_color(Color::Rgb(0, 0, 254));
482        let link = crate::style::test_link("https://x", "id=colors");
483        let equal = crate::style::test_link("https://x", "id=colors");
484        for (x, text, style, target) in [
485            (0, "a", colors, Some(&link)),
486            (1, "b", fg, Some(&equal)),
487            (2, "c", bg, Some(&link)),
488            (3, "d", underline_color, Some(&link)),
489            (4, "e", Style::new().italic().underline(), None),
490            (5, "f", Style::EMPTY, None),
491        ] {
492            let mut cell = Cell::new(text, 1).with_style(style);
493            cell.set_link(target.cloned());
494            buf.set_cell((x, 0).into(), &cell);
495        }
496        let open = "\x1b]8;id=colors;https://x\x1b\\";
497        let close = "\x1b]8;;\x1b\\";
498        for (profile, start, run) in [
499            (
500                Profile::TrueColor,
501                "\x1b[3;4;38;2;255;0;0;48;2;0;255;0;58:2::0:0:255m",
502                "a\x1b[38;2;254;0;0mb\x1b[48;2;0;254;0mc\x1b[58:2::0:0:254md",
503            ),
504            (
505                Profile::Ansi256,
506                "\x1b[3;4;38;5;196;48;5;46;58:5:21m",
507                "abcd",
508            ),
509            (Profile::Ansi, "\x1b[3;4;91;102;58:5:12m", "abcd"),
510        ] {
511            assert_eq!(
512                buf.display_with(profile).to_string(),
513                format!("{start}{open}{run}\x1b[39;49;59m{close}e\x1b[mf"),
514                "{profile:?}"
515            );
516        }
517    }
518
519    #[test]
520    fn profile_ascii_keeps_visual_and_link_transitions_but_drops_colors() {
521        use crate::color::{Color, Profile};
522        let mut buf = Buffer::new(10, 1);
523        let colors = Style::new()
524            .fg(Color::Rgb(10, 20, 30))
525            .bg(Color::Red)
526            .underline_color(Color::Blue);
527        let decorated = colors.bold().underline_style(UnderlineStyle::Curly);
528        let fg = decorated.fg(Color::Green);
529        let bg = fg.bg(Color::Yellow);
530        let underline_color = bg.underline_color(Color::Cyan);
531        let link = crate::style::test_link("https://x", "id=ascii");
532        let equal = crate::style::test_link("https://x", "id=ascii");
533        for (x, text, style, target) in [
534            (0, "a", colors, None),
535            (1, "b", decorated, Some(&link)),
536            (2, "c", fg, Some(&equal)),
537            (3, "d", bg, Some(&link)),
538            (4, "e", underline_color, Some(&link)),
539            (5, "f", underline_color, None),
540            (
541                6,
542                "g",
543                underline_color.underline_style(UnderlineStyle::Dotted),
544                None,
545            ),
546            (7, "h", colors, Some(&link)),
547            (8, " ", colors, Some(&link)),
548            (9, " ", colors, None),
549        ] {
550            let mut cell = Cell::new(text, 1).with_style(style);
551            cell.set_link(target.cloned());
552            buf.set_cell((x, 0).into(), &cell);
553        }
554        let open = "\x1b]8;id=ascii;https://x\x1b\\";
555        let close = "\x1b]8;;\x1b\\";
556        assert_eq!(
557            buf.display_with(Profile::Ascii).to_string(),
558            format!("a\x1b[1;4:3m{open}bcde{close}f\x1b[4:4mg\x1b[m{open}h {close}")
559        );
560    }
561
562    #[test]
563    fn truecolor_profile_matches_default() {
564        use crate::color::{Color, Profile};
565        let mut buf = Buffer::new(2, 1);
566        let styled = Style::new().fg(Color::Rgb(1, 2, 3));
567        for (x, text) in ["h", "i"].into_iter().enumerate() {
568            let mut cell = Cell::new(text, 1).with_style(styled);
569            cell.set_link(Some(crate::style::test_link("https://e.x", "")));
570            buf.set_cell((x as u16, 0).into(), &cell);
571        }
572        assert_eq!(
573            buf.display_with(Profile::TrueColor).to_string(),
574            buf.display().to_string(),
575        );
576    }
577}