croft-software 0.2.182

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! The terminal's colour depth, and the pass that fits a frame to it
//! (#1433). Themes, syntax colours and terminal panes all paint
//! `Color::Rgb`, which ratatui writes as 24-bit SGR (`38;2;r;g;b`). A
//! terminal that only knows the 256-colour palette (Terminal.app before
//! macOS 26, `screen`, PuTTY's defaults) or the 16 ANSI colours (the Linux
//! console) draws those wrong or not at all, so below truecolor every
//! `Rgb` in the frame is mapped to the nearest colour the terminal has.
//!
//! The same pass drops underline colours where the terminal cannot read
//! them (#2661): see [`underline_colors_supported`].

use ratatui::buffer::Buffer;
use ratatui::style::Color;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorDepth {
    TrueColor,
    Ansi256,
    Ansi16,
}

impl ColorDepth {
    /// The `color_depth` setting's value, when it names a depth.
    pub fn from_setting(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "truecolor" | "24bit" => Some(Self::TrueColor),
            "256" => Some(Self::Ansi256),
            "16" => Some(Self::Ansi16),
            _ => None,
        }
    }

    /// The depth the terminal advertises through its environment. Truecolor
    /// when `COLORTERM` says so, for a terminal known to draw 24-bit colour
    /// (by `TERM_PROGRAM` or `TERM`, which outlive an SSH hop where
    /// `COLORTERM` often does not), and inside tmux, which converts colours
    /// for the terminal outside it. Otherwise 256 colours for a `256color`
    /// `TERM`, and 16 for anything else.
    pub fn detect(env: impl Fn(&str) -> Option<String>) -> Self {
        let var = |name: &str| env(name).unwrap_or_default().to_ascii_lowercase();
        let colorterm = var("COLORTERM");
        if colorterm == "truecolor" || colorterm == "24bit" {
            return Self::TrueColor;
        }
        const TRUECOLOR_PROGRAMS: &[&str] = &[
            "iterm.app",
            "wezterm",
            "ghostty",
            "vscode",
            "tmux",
            "hyper",
            "tabby",
            "warpterminal",
            "rio",
        ];
        if TRUECOLOR_PROGRAMS.contains(&var("TERM_PROGRAM").as_str()) {
            return Self::TrueColor;
        }
        // Windows Terminal names itself only through this variable.
        if env("WT_SESSION").is_some_and(|s| !s.is_empty()) {
            return Self::TrueColor;
        }
        let term = var("TERM");
        const TRUECOLOR_TERMS: &[&str] = &[
            "kitty",
            "ghostty",
            "alacritty",
            "wezterm",
            "foot",
            "contour",
            "rio",
            "direct",
            "truecolor",
            "24bit",
        ];
        if TRUECOLOR_TERMS.iter().any(|t| term.contains(t)) {
            return Self::TrueColor;
        }
        if term.contains("256color") {
            return Self::Ansi256;
        }
        Self::Ansi16
    }

    /// `color` as this depth can show it. Named and indexed colours pass
    /// through, except a 256-palette index on a 16-colour terminal.
    pub fn fit(self, color: Color) -> Color {
        match (self, color) {
            (Self::TrueColor, c) => c,
            (Self::Ansi256, Color::Rgb(r, g, b)) => Color::Indexed(nearest_256(r, g, b)),
            (Self::Ansi16, Color::Rgb(r, g, b)) => nearest_16(r, g, b),
            (Self::Ansi16, Color::Indexed(i)) if i >= 16 => {
                let (r, g, b) = palette_256(i);
                nearest_16(r, g, b)
            }
            (_, c) => c,
        }
    }

    /// Fit every colour of a finished frame to this depth, before ratatui
    /// writes it out. One pass covers the chrome, syntax colours and the
    /// cells terminal panes copied from their programs.
    pub fn fit_buffer(self, buffer: &mut Buffer) {
        if self == Self::TrueColor {
            return;
        }
        for cell in &mut buffer.content {
            cell.fg = self.fit(cell.fg);
            cell.bg = self.fit(cell.bg);
            cell.underline_color = self.fit(cell.underline_color);
        }
    }
}

/// The variable that carries [`underline_colors_supported`]'s answer to a
/// croft that draws into the same terminal from elsewhere: over SSH or in a
/// dev container, where the terminal's own variables do not follow. `1` or
/// `0`; a user may also set it for a terminal the list below leaves out.
pub const UNDERLINE_COLORS_ENV: &str = "CROFT_UNDERLINE_COLORS";

/// Whether the terminal reads underline colours (SGR 58, #2661). One that
/// does not skips the 58 and reads the numbers after it as codes of its own:
/// in xterm `58;5;8` turns on blink and hides the text (code 8) for the rest
/// of the frame. So underline colours go only to terminals known to read
/// them: [`UNDERLINE_COLORS_ENV`] when set, then `TERM_PROGRAM` or `TERM`,
/// tmux (which converts them for the terminal outside it), and VTE 0.52 or
/// newer (GNOME Terminal and others). `COLORTERM` says nothing here: xterm
/// draws 24-bit colour but not underline colours.
pub fn underline_colors_supported(env: impl Fn(&str) -> Option<String>) -> bool {
    match env(UNDERLINE_COLORS_ENV).as_deref().map(str::trim) {
        Some("1") => return true,
        Some("0") => return false,
        _ => {}
    }
    let var = |name: &str| env(name).unwrap_or_default().to_ascii_lowercase();
    const PROGRAMS: &[&str] = &[
        "iterm.app",
        "wezterm",
        "ghostty",
        "vscode",
        "tmux",
        "rio",
        "croft",
    ];
    if PROGRAMS.contains(&var("TERM_PROGRAM").as_str()) {
        return true;
    }
    const TERMS: &[&str] = &[
        "kitty",
        "ghostty",
        "alacritty",
        "wezterm",
        "foot",
        "contour",
        "rio",
        "tmux",
    ];
    let term = var("TERM");
    if TERMS.iter().any(|t| term.contains(t)) {
        return true;
    }
    var("VTE_VERSION").parse::<u32>().is_ok_and(|v| v >= 5200)
}

/// Clear every underline colour in a finished frame, for a terminal that
/// cannot read them: the underline stays, in the text's own colour.
pub fn drop_underline_colors(buffer: &mut Buffer) {
    for cell in &mut buffer.content {
        cell.underline_color = Color::Reset;
    }
}

/// Removes underline colours (SGR 58) from a byte stream on its way to a
/// terminal that cannot read them (#2661), for the bytes croft does not draw
/// itself: a persistent session's output, shared by every attached client,
/// is filtered per client. Only `ESC [ … m` sequences change; everything
/// else, pictures and OSC strings included, passes through byte for byte.
/// A sequence split across two writes is held until its end arrives.
#[derive(Default)]
pub struct UnderlineColorFilter {
    pending: Vec<u8>,
}

impl UnderlineColorFilter {
    /// A sequence longer than this without its final byte is not one croft
    /// writes; it is passed on as it came.
    const LONGEST: usize = 256;

    /// Append `input` to `out` with every underline colour removed.
    pub fn feed(&mut self, input: &[u8], out: &mut Vec<u8>) {
        let joined;
        let data: &[u8] = if self.pending.is_empty() {
            input
        } else {
            self.pending.extend_from_slice(input);
            joined = std::mem::take(&mut self.pending);
            &joined
        };
        let mut at = 0;
        while let Some(found) = memchr::memchr(0x1b, &data[at..]) {
            let esc = at + found;
            out.extend_from_slice(&data[at..esc]);
            if esc + 1 == data.len() {
                self.pending.extend_from_slice(&data[esc..]);
                return;
            }
            if data[esc + 1] != b'[' {
                out.push(0x1b);
                at = esc + 1;
                continue;
            }
            let body = esc + 2;
            let Some(end) = data[body..].iter().position(|b| (0x40..=0x7e).contains(b)) else {
                if data.len() - esc > Self::LONGEST {
                    out.extend_from_slice(&data[esc..]);
                } else {
                    self.pending.extend_from_slice(&data[esc..]);
                }
                return;
            };
            let fin = body + end;
            let params = &data[body..fin];
            match (data[fin], without_underline_color(params)) {
                (b'm', Some(kept)) if kept.is_empty() => {}
                (b'm', Some(kept)) => {
                    out.extend_from_slice(b"\x1b[");
                    out.extend_from_slice(&kept);
                    out.push(b'm');
                }
                _ => out.extend_from_slice(&data[esc..=fin]),
            }
            at = fin + 1;
        }
        out.extend_from_slice(&data[at..]);
    }
}

/// `params` of an SGR sequence with its underline colours removed, or `None`
/// when it holds none (or is not plain SGR parameters). `58;5;n` and
/// `58;2;r;g;b` take their arguments with them; `38` and `48` keep theirs, so
/// a `58` that is a colour index (`38;5;58`) stays.
fn without_underline_color(params: &[u8]) -> Option<Vec<u8>> {
    if !params
        .iter()
        .all(|b| b.is_ascii_digit() || *b == b';' || *b == b':')
    {
        return None;
    }
    let fields: Vec<&[u8]> = params.split(|b| *b == b';').collect();
    let mut kept: Vec<&[u8]> = Vec::with_capacity(fields.len());
    let mut changed = false;
    let mut i = 0;
    while i < fields.len() {
        let field = fields[i];
        let head = field.split(|b| *b == b':').next().unwrap_or_default();
        let span = if field.contains(&b':') {
            1
        } else {
            match (head, fields.get(i + 1).copied()) {
                (b"38" | b"48" | b"58", Some(b"5")) => 3,
                (b"38" | b"48" | b"58", Some(b"2")) => 5,
                _ => 1,
            }
        };
        let group = &fields[i..(i + span).min(fields.len())];
        if head == b"58" {
            changed = true;
        } else {
            kept.extend_from_slice(group);
        }
        i += span;
    }
    changed.then(|| kept.join(&b';'))
}

/// The xterm colour cube's six levels per channel.
const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255];

fn distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> u32 {
    let d = |x: u8, y: u8| (i32::from(x) - i32::from(y)).pow(2) as u32;
    d(a.0, b.0) + d(a.1, b.1) + d(a.2, b.2)
}

/// The index of the closest colour among the 6×6×6 cube (16-231) and the
/// grey ramp (232-255). The 16 system colours are left out: terminals
/// theme them, so their RGB is not known.
fn nearest_256(r: u8, g: u8, b: u8) -> u8 {
    let level = |v: u8| {
        (0..6)
            .min_by_key(|&i| (i32::from(CUBE[i]) - i32::from(v)).abs())
            .unwrap_or(0)
    };
    let (ri, gi, bi) = (level(r), level(g), level(b));
    let cube_index = 16 + 36 * ri + 6 * gi + bi;
    let cube = (CUBE[ri], CUBE[gi], CUBE[bi]);
    let avg = (u32::from(r) + u32::from(g) + u32::from(b)) / 3;
    let grey_step = ((avg.saturating_sub(8) + 5) / 10).min(23) as u8;
    let grey_level = 8 + 10 * grey_step;
    let grey = (grey_level, grey_level, grey_level);
    if distance((r, g, b), grey) < distance((r, g, b), cube) {
        232 + grey_step
    } else {
        cube_index as u8
    }
}

/// The RGB of a 256-palette index from 16 up.
fn palette_256(i: u8) -> (u8, u8, u8) {
    if i >= 232 {
        let v = 8 + 10 * (i - 232);
        return (v, v, v);
    }
    let i = i.saturating_sub(16) as usize;
    (CUBE[i / 36], CUBE[(i / 6) % 6], CUBE[i % 6])
}

/// The closest of the 16 ANSI colours, by xterm's default values for them.
fn nearest_16(r: u8, g: u8, b: u8) -> Color {
    const ANSI: [(Color, (u8, u8, u8)); 16] = [
        (Color::Black, (0, 0, 0)),
        (Color::Red, (205, 0, 0)),
        (Color::Green, (0, 205, 0)),
        (Color::Yellow, (205, 205, 0)),
        (Color::Blue, (0, 0, 238)),
        (Color::Magenta, (205, 0, 205)),
        (Color::Cyan, (0, 205, 205)),
        (Color::Gray, (229, 229, 229)),
        (Color::DarkGray, (127, 127, 127)),
        (Color::LightRed, (255, 0, 0)),
        (Color::LightGreen, (0, 255, 0)),
        (Color::LightYellow, (255, 255, 0)),
        (Color::LightBlue, (92, 92, 255)),
        (Color::LightMagenta, (255, 0, 255)),
        (Color::LightCyan, (0, 255, 255)),
        (Color::White, (255, 255, 255)),
    ];
    ANSI.iter()
        .min_by_key(|(_, rgb)| distance((r, g, b), *rgb))
        .map_or(Color::Reset, |(c, _)| *c)
}

#[cfg(test)]
mod tests {
    use super::ColorDepth;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    use ratatui::style::Color;

    fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
        move |name| {
            vars.iter()
                .find(|(k, _)| *k == name)
                .map(|(_, v)| v.to_string())
        }
    }

    #[test]
    fn colorterm_truecolor_is_truecolor() {
        for value in ["truecolor", "24bit", "TrueColor"] {
            assert_eq!(
                ColorDepth::detect(env(&[("COLORTERM", value), ("TERM", "xterm-256color")])),
                ColorDepth::TrueColor,
                "{value}"
            );
        }
    }

    #[test]
    fn a_256color_term_without_colorterm_is_256() {
        assert_eq!(
            ColorDepth::detect(env(&[("TERM", "xterm-256color")])),
            ColorDepth::Ansi256
        );
        assert_eq!(
            ColorDepth::detect(env(&[
                ("TERM", "xterm-256color"),
                ("TERM_PROGRAM", "Apple_Terminal")
            ])),
            ColorDepth::Ansi256
        );
        assert_eq!(
            ColorDepth::detect(env(&[("TERM", "screen-256color")])),
            ColorDepth::Ansi256
        );
    }

    #[test]
    fn the_linux_console_and_unknown_terms_are_16() {
        assert_eq!(
            ColorDepth::detect(env(&[("TERM", "linux")])),
            ColorDepth::Ansi16
        );
        assert_eq!(ColorDepth::detect(env(&[])), ColorDepth::Ansi16);
    }

    /// Negative: terminals that draw 24-bit colour but do not set
    /// `COLORTERM` (it is often lost over SSH) keep truecolor, and so does
    /// tmux, which converts colours itself.
    #[test]
    fn known_truecolor_terminals_keep_truecolor_without_colorterm() {
        for vars in [
            [("TERM", "xterm-ghostty"), ("TERM_PROGRAM", "")],
            [("TERM", "xterm-kitty"), ("TERM_PROGRAM", "")],
            [("TERM", "alacritty"), ("TERM_PROGRAM", "")],
            [("TERM", "xterm-256color"), ("TERM_PROGRAM", "iTerm.app")],
            [("TERM", "xterm-256color"), ("TERM_PROGRAM", "WezTerm")],
            [("TERM", "xterm-256color"), ("TERM_PROGRAM", "vscode")],
            [("TERM", "tmux-256color"), ("TERM_PROGRAM", "tmux")],
            [("TERM", "xterm-256color"), ("WT_SESSION", "abc")],
        ] {
            assert_eq!(
                ColorDepth::detect(env(&vars)),
                ColorDepth::TrueColor,
                "{vars:?}"
            );
        }
    }

    #[test]
    fn the_setting_names_a_depth() {
        assert_eq!(
            ColorDepth::from_setting("truecolor"),
            Some(ColorDepth::TrueColor)
        );
        assert_eq!(ColorDepth::from_setting("256"), Some(ColorDepth::Ansi256));
        assert_eq!(ColorDepth::from_setting("16"), Some(ColorDepth::Ansi16));
        assert_eq!(ColorDepth::from_setting("auto"), None);
        assert_eq!(ColorDepth::from_setting("88"), None);
    }

    /// The issue's cases: the editor greys land on the grey ramp and black
    /// on the cube's black.
    #[test]
    fn at_256_colours_rgb_maps_to_the_nearest_palette_index() {
        let d = ColorDepth::Ansi256;
        assert_eq!(d.fit(Color::Rgb(0x1e, 0x1e, 0x1e)), Color::Indexed(234));
        assert_eq!(d.fit(Color::Rgb(0, 0, 0)), Color::Indexed(16));
        assert_eq!(d.fit(Color::Rgb(255, 255, 255)), Color::Indexed(231));
        assert_eq!(d.fit(Color::Rgb(255, 0, 0)), Color::Indexed(196));
        assert_eq!(d.fit(Color::Rgb(0x56, 0x9c, 0xd6)), Color::Indexed(74));
    }

    #[test]
    fn at_16_colours_rgb_and_high_indexes_map_to_ansi_names() {
        let d = ColorDepth::Ansi16;
        assert_eq!(d.fit(Color::Rgb(0x1e, 0x1e, 0x1e)), Color::Black);
        assert_eq!(d.fit(Color::Rgb(250, 10, 10)), Color::LightRed);
        assert_eq!(d.fit(Color::Indexed(231)), Color::White);
        assert_eq!(d.fit(Color::Indexed(1)), Color::Indexed(1));
    }

    /// Negative: named, indexed and reset colours are what the terminal
    /// already has, so they pass through untouched.
    #[test]
    fn named_and_reset_colours_pass_through() {
        for d in [ColorDepth::Ansi256, ColorDepth::Ansi16] {
            for c in [Color::Reset, Color::Red, Color::Indexed(7)] {
                assert_eq!(d.fit(c), c, "{d:?} {c:?}");
            }
        }
        assert_eq!(
            ColorDepth::Ansi256.fit(Color::Indexed(200)),
            Color::Indexed(200)
        );
    }

    #[test]
    fn a_frame_below_truecolor_holds_no_rgb() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 3, 1));
        for cell in &mut buf.content {
            cell.fg = Color::Rgb(0x1e, 0x1e, 0x1e);
            cell.bg = Color::Rgb(0, 0, 0);
            cell.underline_color = Color::Rgb(255, 0, 0);
        }
        ColorDepth::Ansi256.fit_buffer(&mut buf);
        for cell in &buf.content {
            assert_eq!(cell.fg, Color::Indexed(234));
            assert_eq!(cell.bg, Color::Indexed(16));
            assert_eq!(cell.underline_color, Color::Indexed(196));
        }
    }

    #[test]
    fn underline_colours_go_only_to_terminals_that_read_them() {
        use super::underline_colors_supported as reads;
        // xterm, whatever its depth: 24-bit colour is not underline colour.
        assert!(!reads(env(&[("TERM", "xterm")])));
        assert!(!reads(env(&[
            ("TERM", "xterm-256color"),
            ("COLORTERM", "truecolor")
        ])));
        assert!(!reads(env(&[("TERM", "linux")])));
        assert!(!reads(env(&[("TERM", "screen-256color")])));
        assert!(!reads(env(&[
            ("TERM_PROGRAM", "Apple_Terminal"),
            ("TERM", "xterm-256color")
        ])));
        assert!(!reads(env(&[])));
        for (k, v) in [
            ("TERM_PROGRAM", "iTerm.app"),
            ("TERM_PROGRAM", "WezTerm"),
            ("TERM_PROGRAM", "ghostty"),
            ("TERM_PROGRAM", "vscode"),
            ("TERM_PROGRAM", "tmux"),
            ("TERM_PROGRAM", "croft"),
            ("TERM", "xterm-kitty"),
            ("TERM", "alacritty"),
            ("TERM", "foot"),
            ("TERM", "tmux-256color"),
        ] {
            assert!(reads(env(&[(k, v)])), "{k}={v}");
        }
        assert!(reads(env(&[
            ("TERM", "xterm-256color"),
            ("VTE_VERSION", "7600")
        ])));
        assert!(!reads(env(&[
            ("TERM", "xterm-256color"),
            ("VTE_VERSION", "5000")
        ])));
    }

    /// The answer carried from another croft wins both ways.
    #[test]
    fn the_carried_answer_wins() {
        use super::{UNDERLINE_COLORS_ENV, underline_colors_supported as reads};
        assert!(reads(env(&[
            ("TERM", "xterm"),
            (UNDERLINE_COLORS_ENV, "1")
        ])));
        assert!(!reads(env(&[
            ("TERM_PROGRAM", "ghostty"),
            (UNDERLINE_COLORS_ENV, "0")
        ])));
        assert!(reads(env(&[
            ("TERM_PROGRAM", "ghostty"),
            (UNDERLINE_COLORS_ENV, "maybe")
        ])));
    }

    #[test]
    fn dropping_underline_colours_keeps_the_underline() {
        use ratatui::style::Modifier;
        let mut buf = Buffer::empty(Rect::new(0, 0, 2, 1));
        buf.content[0].underline_color = Color::Rgb(0x4f, 0xb1, 0xa6);
        buf.content[0].modifier = Modifier::UNDERLINED;
        buf.content[0].fg = Color::Rgb(1, 2, 3);
        super::drop_underline_colors(&mut buf);
        assert_eq!(buf.content[0].underline_color, Color::Reset);
        assert_eq!(buf.content[0].modifier, Modifier::UNDERLINED);
        assert_eq!(buf.content[0].fg, Color::Rgb(1, 2, 3));
    }

    fn filtered(chunks: &[&[u8]]) -> Vec<u8> {
        let mut filter = super::UnderlineColorFilter::default();
        let mut out = Vec::new();
        for chunk in chunks {
            filter.feed(chunk, &mut out);
        }
        out
    }

    #[test]
    fn the_filter_removes_underline_colours_and_nothing_else() {
        let cases: &[(&[u8], &[u8])] = &[
            (b"a\x1b[58;5;8mb", b"ab"),
            (b"a\x1b[58;2;1;2;3mb", b"ab"),
            (b"a\x1b[58:2::1:2:3mb", b"ab"),
            (b"\x1b[4;58;5;8mx", b"\x1b[4mx"),
            (b"\x1b[1;58;2;9;9;9;3mx", b"\x1b[1;3mx"),
            // A colour index of 58 is a colour, not code 58.
            (b"\x1b[38;5;58mx", b"\x1b[38;5;58mx"),
            (b"\x1b[48;2;58;58;58mx", b"\x1b[48;2;58;58;58mx"),
            // Resetting the underline colour, a reset and other sequences.
            (b"\x1b[59m\x1b[m\x1b[0m", b"\x1b[59m\x1b[m\x1b[0m"),
            (b"\x1b[58;5H\x1b[?2026h", b"\x1b[58;5H\x1b[?2026h"),
            // Pictures and OSC strings pass byte for byte.
            (
                b"\x1bP0;1;0q#58;2;1;2;3~\x1b\\",
                b"\x1bP0;1;0q#58;2;1;2;3~\x1b\\",
            ),
            (
                b"\x1b]1337;File=inline=1:AAAA\x07",
                b"\x1b]1337;File=inline=1:AAAA\x07",
            ),
            (
                "caf\u{e9} \u{2014}".as_bytes(),
                "caf\u{e9} \u{2014}".as_bytes(),
            ),
        ];
        for (input, want) in cases {
            assert_eq!(
                filtered(&[input]),
                want.to_vec(),
                "{}",
                String::from_utf8_lossy(input)
            );
        }
    }

    /// A write may end anywhere, even inside a sequence: the result is the
    /// same however the stream is cut.
    #[test]
    fn the_filter_gives_the_same_bytes_however_the_stream_is_cut() {
        let stream: &[u8] =
            b"tab \x1b[3m\x1b[4m\x1b[58;5;8mname\x1b[24m\x1b[59m rest\x1b[38;5;58m!\x1b[0m\x1b";
        let whole = filtered(&[stream]);
        assert!(
            !String::from_utf8_lossy(&whole).contains("[58;"),
            "{whole:?}"
        );
        for cut in 0..=stream.len() {
            let (a, b) = stream.split_at(cut);
            assert_eq!(filtered(&[a, b]), whole, "cut at {cut}");
        }
        let bytes: Vec<&[u8]> = stream.chunks(1).collect();
        assert_eq!(filtered(&bytes), whole, "one byte at a time");
    }

    /// Negative: at truecolor the frame is left exactly as drawn.
    #[test]
    fn a_truecolor_frame_is_unchanged() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 2, 1));
        buf.content[0].fg = Color::Rgb(1, 2, 3);
        let before = buf.clone();
        ColorDepth::TrueColor.fit_buffer(&mut buf);
        assert_eq!(buf, before);
    }
}