Skip to main content

uncurses/ansi/
mod.rs

1//! ANSI and terminal-control sequence subsystem.
2//!
3//! ## Scope
4//!
5//! The modules under `ansi` are the byte-level building blocks used to emit,
6//! parse, measure, strip, truncate, and wrap terminal control streams. They cover
7//! cursor motion, screen editing, modes, SGR styling, OSC metadata, DCS/APC
8//! payloads, C0/C1 controls, and ANSI-aware text utilities.
9//!
10//! ## Sequence families
11//!
12//! Most writers emit 7-bit forms because they are broadly accepted on byte
13//! streams that are otherwise UTF-8 text:
14//!
15//! ```text
16//! CSI: ESC [ params intermediates final      e.g. ESC [ ? 2048 h
17//! OSC: ESC ] command ; payload BEL|ST        e.g. ESC ] 2 ; title ESC \\
18//! DCS: ESC P params payload ST               e.g. ESC P + q 524742 ESC \\
19//! APC: ESC _ command payload ST              e.g. ESC _ G ... ESC \\
20//! ```
21//!
22//! Anatomy of a DEC private mode sequence:
23//!
24//! ```text
25//! ESC [  ?  2 0 4 8  h        CSI ? 2048 h  (enable mode 2048)
26//! ──┬── ─┬─ ───┬──── ┬
27//!  CSI  priv  params final
28//! ```
29//!
30//! ## 7-bit and 8-bit controls
31//!
32//! The constants in [`c0`] and [`c1`] name single-byte controls. Parser utilities
33//! recognize both the 7-bit `ESC` spellings and the 8-bit C1 bytes, while writer
34//! functions generally choose explicit 7-bit byte strings.
35//!
36//! ## Mode interaction
37//!
38//! Mode-aware features are represented by [`mode::Mode`]. Enable or disable
39//! modes with [`mode::write_set_mode`] and [`mode::write_reset_mode`] before
40//! expecting mode-controlled reports such as bracketed paste, focus events,
41//! in-band resize, or light/dark notifications.
42//!
43//! ## Example
44//!
45//! ```rust,ignore
46//! use uncurses::ansi::title::write_window_title;
47//!
48//! let mut out = Vec::new();
49//! write_window_title(&mut out, "my app")?; // ESC ] 2 ; my app ESC \\
50//! # Ok::<(), std::io::Error>(())
51//! ```
52
53pub mod ascii;
54pub mod c0;
55pub mod c1;
56pub mod charset;
57pub mod clipboard;
58pub mod color;
59pub mod ctrl;
60pub mod cursor;
61pub mod cwd;
62pub mod drag_drop;
63pub mod finalterm;
64pub mod focus;
65pub mod glyph;
66pub mod graphics;
67pub mod hyperlink;
68pub mod inband;
69pub mod iterm2;
70pub mod keypad;
71pub mod kitty;
72pub mod mode;
73pub mod notification;
74pub mod palette;
75pub mod params;
76pub mod passthrough;
77pub mod paste;
78pub mod program_resume;
79pub mod program_status;
80pub mod progress;
81pub mod screen;
82pub mod sgr;
83pub mod status;
84pub mod strip;
85pub mod termcap;
86pub mod text;
87pub mod text_sizing;
88pub mod title;
89pub mod truncate;
90pub mod urxvt;
91pub mod winop;
92pub mod wrap;
93pub mod xterm;
94
95#[cfg(uncurses_bench)]
96mod bench;
97
98/// The text utilities all reach `from_utf8_unchecked` through their own `bs`,
99/// on the tokenizer's promise that no token ever splits a character.
100///
101/// That promise is checked at the tokenizer, and the `debug_assert!`s in
102/// `wrap::bs`, `truncate::bs`, `strip::bs` and `text::painter` exist to check
103/// it again where it is relied on - but nothing drove them. Every escape
104/// sequence in these modules' tests has an ASCII payload, so reverting the
105/// scanner fix (stepping one byte instead of one character) left all of them
106/// green while `strip` handed ill-formed bytes to `from_utf8_unchecked`. These
107/// inputs put a character that carries a C1 byte inside a sequence, which is
108/// the shape that made it undefined behaviour.
109#[cfg(test)]
110mod utf8_boundaries {
111    use super::{strip::strip, truncate, wrap};
112
113    /// Sequences whose payload contains a character with a C1 continuation
114    /// byte, followed by visible text.
115    ///
116    /// `\u{2705}` is `E2 9C 85` and `\u{dc}` is `C3 9C`.
117    /// Both contain a continuation byte that has the same value as raw ST.
118    const INPUTS: &[&str] = &[
119        "\x1b]0;\u{2705}\x07visible",
120        "\x1b]0;a\u{dc}b\x07visible",
121        "\x1b]0;a\u{9d}b\x07visible",
122        "\x1b]8;;https://example.com/\u{2705}\x07visible\x1b]8;;\x07",
123        "\x1bP1$r\u{2705}\x1b\\visible",
124        "\x1b_G\u{2705}\x1b\\visible",
125        "\x1b^\u{2705}\x1b\\visible",
126        "\x1bX\u{2705}\x1b\\visible",
127        // An intermediate-byte escape whose final byte is non-ASCII, which is
128        // `scan_esc_intermediate`'s half of the same bug.
129        "\x1b#\u{2705}visible",
130        "\x1b\u{2705}visible",
131        "\u{9b}31mvisible\u{9b}m",
132        "\u{9d}0;title\u{9c}visible",
133        // A payload that is not terminated at all: the whole tail is one
134        // escape token, and it still must not stop mid-character.
135        "\x1b]0;caf\u{e9} \u{2705} \u{4e00} \u{1f600}",
136    ];
137
138    #[test]
139    fn the_text_utilities_never_see_a_split_character() {
140        for input in INPUTS {
141            // The assertion is inside the callees: each of these routes every
142            // token through its module's `bs`, which checks the slice is whole
143            // UTF-8 before `from_utf8_unchecked` takes it on trust. A scanner
144            // that stops mid-character makes these panic under
145            // `debug_assertions` and makes them UB without.
146            for limit in [0usize, 1, 3, 7] {
147                wrap::hardwrap(input, limit, false);
148            }
149            for limit in [0usize, 1, 3, 7, 100] {
150                wrap::hardwrap(input, limit, true);
151                wrap::wordwrap(input, limit, wrap::DEFAULT_BREAKPOINTS);
152                wrap::wrap(input, limit, wrap::DEFAULT_BREAKPOINTS);
153                truncate::truncate(input, limit, "…");
154                truncate::truncate_left(input, limit, "…");
155                truncate::cut(input, limit / 2, limit);
156            }
157        }
158        wrap::hardwrap(INPUTS[INPUTS.len() - 1], 100, false);
159        strip(INPUTS[INPUTS.len() - 1]);
160    }
161
162    /// The visible text survives the sequence, which is the user-facing half
163    /// of the same promise: a scanner that stops mid-character leaves the
164    /// remaining bytes of that character outside the escape, where they are
165    /// dropped or painted as garbage.
166    #[test]
167    fn the_text_after_a_utf8_payload_survives() {
168        for input in &INPUTS[..INPUTS.len() - 1] {
169            assert_eq!(
170                strip(input),
171                "visible",
172                "strip lost the text after {input:?}"
173            );
174            assert_eq!(
175                truncate::truncate(input, 7, ""),
176                *input,
177                "truncate at the full width should keep {input:?} intact"
178            );
179            assert_eq!(
180                strip(&wrap::hardwrap(input, 100, false)),
181                "visible",
182                "hardwrap lost the text after {input:?}"
183            );
184        }
185    }
186}
187
188/// A seeded fuzz over the text utilities' public `&str` API.
189///
190/// The tokenizer has its own byte-level fuzz in [`text`], but it stops at the
191/// token stream. What the callers build on top of it - the wrap's decision to
192/// skip a pass, the truncate's running width - is where an invariant can hold
193/// for every token and still be wrong for the string, and none of it was
194/// driven by anything but hand-written cases.
195///
196/// Deliberately a seeded xorshift in an ordinary `#[test]` rather than
197/// `cargo-fuzz`: it needs no nightly, no new dependency and no separate CI
198/// job, so it runs on every `cargo test` instead of whenever somebody
199/// remembers. The ceiling is that it explores a fixed alphabet from a fixed
200/// seed rather than mutating a corpus, so it cannot find a shape that is not
201/// built from these pieces. Reach for `cargo-fuzz` if that stops being enough.
202#[cfg(test)]
203mod fuzz {
204    use super::{
205        strip::strip,
206        text::{WidthMode, string_width},
207        truncate, wrap,
208    };
209
210    /// Text with no escape sequence in it, so a parser has no state to carry.
211    ///
212    /// Words longer than any limit used here are deliberate: they are the only
213    /// thing that makes the word wrap report a line over the limit, so without
214    /// one the hard-wrap path is never reached.
215    const PLAIN: &[&str] = &[
216        "a",
217        "bb",
218        "hello",
219        " ",
220        "  ",
221        "\t",
222        "\n",
223        "-",
224        ",",
225        ".",
226        ";",
227        ":",
228        "supercalifragilistic",
229        "\u{4e00}",
230        "\u{4e00}\u{4e01}\u{4e02}",
231        "\u{1f600}",
232        "\u{1f1fa}\u{1f1f8}",
233        "e\u{301}",
234        "a\u{200d}b",
235        "\u{2705}",
236        "\u{dc}",
237        "\u{dd}",
238    ];
239
240    /// Sequences that terminate and sequences that do not, with payloads that
241    /// carry a C1 byte inside a character.
242    const SEQUENCES: &[&str] = &[
243        "\x07",
244        "\x1b[31m",
245        "\x1b[0m",
246        "\x1b[1;2;3m",
247        "\u{9b}31m",
248        "\u{9b}m",
249        "\u{80}",
250        "\u{9c}",
251        "\u{9d}",
252        "\u{90}",
253        "\u{98}",
254        "\u{9e}",
255        "\u{9f}",
256        "\u{9d}0;title\u{9c}",
257        "\x1b]8;;https://example.com/\u{2705}\x1b\\",
258        "\x1b]0;title\x07",
259        "\x1bP1$r\u{2705}\x1b\\",
260        "\x1b_G\u{2705}\x1b\\",
261        // Unterminated: these carry parser state across a newline, which is
262        // the shape that makes a line-by-line measurement of the output lie.
263        "\x1b]0;unterminated",
264        "\x1b_",
265        "\x1b",
266    ];
267
268    fn next(state: &mut u64) -> u64 {
269        let mut x = *state;
270        x ^= x << 13;
271        x ^= x >> 7;
272        x ^= x << 17;
273        *state = x;
274        x
275    }
276
277    fn build(state: &mut u64, alphabets: &[&[&str]]) -> String {
278        let n = (next(state) % 12) as usize + 1;
279        let mut s = String::new();
280        for _ in 0..n {
281            let a = alphabets[next(state) as usize % alphabets.len()];
282            s.push_str(a[next(state) as usize % a.len()]);
283        }
284        s
285    }
286
287    /// The pre-optimization wrap: word wrap, then hard wrap *every* line.
288    ///
289    /// Only a valid oracle on input with no escape sequence in it. It splits
290    /// the output on newlines and measures each line alone, which restarts the
291    /// ANSI parser; an unterminated control string spanning a newline then
292    /// reads as visible text on the lines after it, and this hard-wraps bytes
293    /// that are inside a sequence and have no width at all. `wrap_mode` no
294    /// longer asks the question that way - the word wrap already measured
295    /// every line it emitted, with the parser state it actually had, and
296    /// reports whether any went over. Without an escape there is no such
297    /// state to lose and the two must agree byte for byte.
298    fn unconditional_wrap(s: &str, limit: usize, mode: WidthMode, eaw_wide: bool) -> String {
299        if limit == 0 {
300            return s.to_string();
301        }
302        let wrapped = wrap::wordwrap_mode(s, limit, wrap::DEFAULT_BREAKPOINTS, mode, eaw_wide);
303        let mut out = String::with_capacity(wrapped.len());
304        for (i, line) in wrapped.split('\n').enumerate() {
305            if i > 0 {
306                out.push('\n');
307            }
308            out.push_str(&wrap::hardwrap_mode(line, limit, false, mode, eaw_wide));
309        }
310        out
311    }
312
313    /// `wrap_mode` skips the whole hard-wrap pass when the word wrap reports
314    /// that no line went over the limit. If that report is ever wrong, `wrap`
315    /// returns lines wider than asked for: nothing panics, nothing is
316    /// ill-formed, and the layout is silently broken. That is the failure this
317    /// exists to catch.
318    #[test]
319    fn skipping_the_hard_wrap_matches_never_skipping_it() {
320        let mut state = 0x9e37_79b9_7f4a_7c15u64;
321        for _ in 0..20_000 {
322            let s = build(&mut state, &[PLAIN]);
323            let limit = (next(&mut state) % 14) as usize;
324            for mode in [WidthMode::Wc, WidthMode::Grapheme] {
325                for eaw_wide in [false, true] {
326                    assert_eq!(
327                        wrap::wrap_mode(&s, limit, wrap::DEFAULT_BREAKPOINTS, mode, eaw_wide),
328                        unconditional_wrap(&s, limit, mode, eaw_wide),
329                        "wrap skipped a hard wrap it needed\n input={s:?}\n limit={limit} mode={mode:?} eaw_wide={eaw_wide}"
330                    );
331                }
332            }
333        }
334    }
335
336    /// Every text utility, over input that mixes sequences into the text.
337    ///
338    /// Under `debug_assertions` this also drives the assertions standing in
339    /// front of each `from_utf8_unchecked` these reach, so a scanner that
340    /// stops mid-character fails here rather than becoming undefined
341    /// behaviour in a release build.
342    #[test]
343    fn the_text_utilities_hold_on_input_containing_sequences() {
344        let mut state = 0x2545_f491_4f6c_dd1du64;
345        for _ in 0..20_000 {
346            let s = build(&mut state, &[PLAIN, SEQUENCES]);
347            let limit = (next(&mut state) % 14) as usize;
348
349            for mode in [WidthMode::Wc, WidthMode::Grapheme] {
350                for eaw_wide in [false, true] {
351                    // Measured over the whole string rather than line by line,
352                    // so this is the parser state the tokenizer actually had.
353                    let cut = truncate::truncate_mode(&s, limit, "", mode, eaw_wide);
354                    assert!(
355                        string_width(cut.as_bytes(), mode, eaw_wide) <= limit,
356                        "truncate exceeded its limit\n input={s:?} -> {cut:?}\n limit={limit} mode={mode:?} eaw_wide={eaw_wide}"
357                    );
358
359                    truncate::truncate_left_mode(&s, limit, "", mode, eaw_wide);
360                    truncate::cut_mode(&s, limit / 2, limit, mode, eaw_wide);
361                    wrap::hardwrap_mode(&s, limit, true, mode, eaw_wide);
362                    wrap::wrap_mode(&s, limit, wrap::DEFAULT_BREAKPOINTS, mode, eaw_wide);
363                    wrap::wordwrap_mode(&s, limit, wrap::DEFAULT_BREAKPOINTS, mode, eaw_wide);
364                }
365            }
366
367            // Stripping drops every sequence, so no introducer survives it.
368            let plain = strip(&s);
369            assert!(
370                !plain.contains('\x1b'),
371                "strip left an escape behind: {s:?} -> {plain:?}"
372            );
373        }
374    }
375}