croft-software 0.1.942

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
//! SGR span parsing for the rendered ANSI log view (#257).
//!
//! A log file is a stream transcript, not a screen: it has unbounded line
//! width and no cursor. So this parses SGR (colour/attribute) sequences into
//! styled spans over the *stripped* text and discards every other escape —
//! cursor movement, OSC, scroll regions — rather than interpreting them.
//! Driving a real terminal grid instead would impose a fixed width the file
//! does not have.
//!
//! Colours stay symbolic ([`AnsiColor::Indexed`] for the low 16) so the
//! active theme's palette resolves them at paint time and a theme switch
//! recolours the view without reparsing.

/// A colour named by an SGR sequence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnsiColor {
    /// One of the 16 base slots, resolved through the theme's ANSI palette.
    /// Kept symbolic so a theme switch recolours without a reparse.
    Indexed(u8),
    /// A 256-colour cube / greyscale entry (SGR 38;5;n) outside the low 16.
    Palette256(u8),
    /// A 24-bit colour (SGR 38;2;r;g;b).
    Rgb(u8, u8, u8),
}

/// The style in force for a run of characters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AnsiStyle {
    pub fg: Option<AnsiColor>,
    pub bg: Option<AnsiColor>,
    pub bold: bool,
    pub dim: bool,
    pub italic: bool,
    pub underline: bool,
    /// SGR 7. Swapping fg/bg is left to the painter, which knows the
    /// theme's default pair to swap against.
    pub inverse: bool,
    /// SGR 9, cleared by 29.
    pub strikeout: bool,
}

impl AnsiStyle {
    fn reset(&mut self) {
        *self = Self::default();
    }
}

/// A run of characters sharing one style. `start`/`end` are byte offsets into
/// the STRIPPED line text, so a caller can slice the visible string directly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AnsiSpan {
    pub start: usize,
    pub end: usize,
    pub style: AnsiStyle,
}

/// One parsed line: the escape-free text plus the spans that colour it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AnsiLine {
    pub text: String,
    pub spans: Vec<AnsiSpan>,
}

/// Parse one line, carrying `style` in and out so colours persist across
/// lines the way a terminal does (a log that sets red on one line and resets
/// three lines later paints all three red).
pub fn parse_line(raw: &str, style: &mut AnsiStyle) -> AnsiLine {
    let mut out = AnsiLine::default();
    parse_into(raw, style, &mut out);
    out
}

/// [`parse_line`] into a caller-owned line, so a bulk scan can reuse one
/// allocation instead of building a `String` and a span `Vec` per line.
///
/// There is ONE implementation of the stripping rules on purpose: a second
/// "just strip the escapes" copy would be the cheap thing to write and would
/// drift from this one the first time a sequence is handled differently, and
/// the two are compared by everything that trusts `text` (find, copy,
/// `path:line` scanning) to describe the same characters.
pub fn parse_into(raw: &str, style: &mut AnsiStyle, out: &mut AnsiLine) {
    out.text.clear();
    out.spans.clear();
    let mut run_start = 0usize;
    let mut run_style = *style;
    let bytes = raw.as_bytes();
    let mut i = 0usize;

    let close_run = |out: &mut AnsiLine, end: usize, start: usize, st: AnsiStyle| {
        if end > start {
            out.spans.push(AnsiSpan {
                start,
                end,
                style: st,
            });
        }
    };

    while i < bytes.len() {
        if bytes[i] != 0x1b {
            // Copy through to the next ESC in one go; `raw` is valid UTF-8 and
            // ESC never appears inside a multi-byte sequence, so slicing at an
            // ESC boundary is always a char boundary.
            let next = bytes[i..].iter().position(|&b| b == 0x1b);
            let end = next.map(|n| i + n).unwrap_or(bytes.len());
            out.text.push_str(&raw[i..end]);
            i = end;
            continue;
        }
        // An ESC at end-of-line has no sequence to close it: emit it as text
        // rather than swallowing a byte the file really contains.
        let Some(&next) = bytes.get(i + 1) else {
            out.text.push('\u{1b}');
            i += 1;
            continue;
        };
        match next {
            b'[' => {
                // CSI: params until a byte in 0x40..=0x7e ends it.
                let mut j = i + 2;
                while j < bytes.len() && !(0x40..=0x7e).contains(&bytes[j]) {
                    j += 1;
                }
                if j >= bytes.len() {
                    // Truncated sequence (the file ends mid-escape): drop it.
                    i = bytes.len();
                    continue;
                }
                if bytes[j] == b'm' {
                    let params = &raw[i + 2..j];
                    let end = out.text.len();
                    close_run(out, end, run_start, run_style);
                    apply_sgr(params, style);
                    run_start = end;
                    run_style = *style;
                }
                // Every other CSI final byte (cursor movement, erase, …) is
                // dropped: a transcript has no cursor to move.
                i = j + 1;
            }
            b']' => {
                // OSC: ends at BEL or ST (ESC \). Dropped entirely — a title
                // or hyperlink has no meaning in a static buffer.
                let mut j = i + 2;
                while j < bytes.len() {
                    if bytes[j] == 0x07 {
                        j += 1;
                        break;
                    }
                    if bytes[j] == 0x1b && bytes.get(j + 1) == Some(&b'\\') {
                        j += 2;
                        break;
                    }
                    j += 1;
                }
                i = j;
            }
            // Three-byte forms: charset selection (`ESC ( B`) and friends.
            b'(' | b')' | b'*' | b'+' | b'#' => i = next_boundary(raw, i + 3),
            // DCS / SOS / PM / APC carry a payload terminated like OSC, so
            // scanning to ST/BEL is the only way not to leak it as text.
            b'P' | b'X' | b'^' | b'_' => {
                let mut j = i + 2;
                while j < bytes.len() {
                    if bytes[j] == 0x07 {
                        j += 1;
                        break;
                    }
                    if bytes[j] == 0x1b && bytes.get(j + 1) == Some(&b'\\') {
                        j += 2;
                        break;
                    }
                    j += 1;
                }
                i = j;
            }
            // A two-byte escape is `ESC` + one ASCII final byte (RI, NEL,
            // DECSC…). If the byte after ESC is NOT ASCII, this is not an
            // escape at all — it is a stray ESC in the text before a real
            // character. Dropping just the ESC keeps the character, where
            // advancing two bytes would swallow it (and, before the boundary
            // guard, could land mid-character and panic on the next slice).
            _ if next.is_ascii() => i += 2,
            _ => {
                out.text.push('\u{1b}');
                i += 1;
            }
        }
    }
    let end = out.text.len();
    close_run(out, end, run_start, run_style);
}

/// The next char boundary at or after `i`, clamped to the string's length.
/// Escape-consuming arms advance by a fixed byte count, which can land inside
/// a multi-byte character when a file carries a stray ESC before UTF-8 text;
/// slicing there panics.
fn next_boundary(s: &str, i: usize) -> usize {
    let mut i = i.min(s.len());
    while i < s.len() && !s.is_char_boundary(i) {
        i += 1;
    }
    i
}

/// Apply one SGR parameter string to `style`. Unknown parameters are ignored
/// rather than aborting the sequence, matching what terminals do.
fn apply_sgr(params: &str, style: &mut AnsiStyle) {
    // A bare `ESC[m` means reset, same as `ESC[0m`.
    if params.is_empty() {
        style.reset();
        return;
    }
    let parts: Vec<&str> = params.split(';').collect();
    let mut k = 0usize;
    while k < parts.len() {
        // An empty parameter is a zero (`ESC[;31m` is reset then red).
        let n: u16 = if parts[k].is_empty() {
            0
        } else {
            match parts[k].parse() {
                Ok(v) => v,
                Err(_) => {
                    k += 1;
                    continue;
                }
            }
        };
        match n {
            0 => style.reset(),
            1 => style.bold = true,
            2 => style.dim = true,
            3 => style.italic = true,
            4 => style.underline = true,
            7 => style.inverse = true,
            9 => style.strikeout = true,
            22 => {
                style.bold = false;
                style.dim = false;
            }
            23 => style.italic = false,
            24 => style.underline = false,
            27 => style.inverse = false,
            29 => style.strikeout = false,
            30..=37 => style.fg = Some(AnsiColor::Indexed((n - 30) as u8)),
            39 => style.fg = None,
            40..=47 => style.bg = Some(AnsiColor::Indexed((n - 40) as u8)),
            49 => style.bg = None,
            // Bright aliases occupy palette slots 8..15.
            90..=97 => style.fg = Some(AnsiColor::Indexed((n - 90 + 8) as u8)),
            100..=107 => style.bg = Some(AnsiColor::Indexed((n - 100 + 8) as u8)),
            38 | 48 => {
                let (colour, consumed) = extended_color(&parts[k + 1..]);
                if let Some(c) = colour {
                    if n == 38 {
                        style.fg = Some(c);
                    } else {
                        style.bg = Some(c);
                    }
                }
                k += consumed;
            }
            _ => {}
        }
        k += 1;
    }
}

/// Parse the tail of a `38`/`48` sequence: `5;n` (palette) or `2;r;g;b`
/// (truecolor). Returns the colour and how many extra parameters it ate, so a
/// malformed sequence consumes what it can instead of desynchronising the
/// rest of the parameter list.
fn extended_color(rest: &[&str]) -> (Option<AnsiColor>, usize) {
    let num = |s: &str| s.parse::<u16>().ok();
    match rest.first().and_then(|s| num(s)) {
        Some(5) => match rest.get(1).and_then(|s| num(s)) {
            Some(v) if v < 256 => {
                let v = v as u8;
                // The low 16 stay symbolic so the theme palette owns them.
                let c = if v < 16 {
                    AnsiColor::Indexed(v)
                } else {
                    AnsiColor::Palette256(v)
                };
                (Some(c), 2)
            }
            _ => (None, 1),
        },
        Some(2) => {
            let r = rest.get(1).and_then(|s| num(s));
            let g = rest.get(2).and_then(|s| num(s));
            let b = rest.get(3).and_then(|s| num(s));
            match (r, g, b) {
                (Some(r), Some(g), Some(b)) if r < 256 && g < 256 && b < 256 => {
                    (Some(AnsiColor::Rgb(r as u8, g as u8, b as u8)), 4)
                }
                _ => (None, 1),
            }
        }
        _ => (None, 0),
    }
}

/// Whether `sample` looks like ANSI-coloured output: an SGR sequence in the
/// sniffed prefix. Deliberately narrower than "contains ESC" — a file full of
/// cursor movement is a terminal recording, not a colour log, and rendering
/// it as if the escapes were decoration would mislead.
pub fn looks_like_ansi(sample: &str) -> bool {
    let b = sample.as_bytes();
    for i in 0..b.len() {
        if b[i] != 0x1b || b.get(i + 1) != Some(&b'[') {
            continue;
        }
        let mut j = i + 2;
        while j < b.len() && !(0x40..=0x7e).contains(&b[j]) {
            j += 1;
        }
        if b.get(j) == Some(&b'm') {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    /// SGR 9 and 29 round-trip like the other attributes: a pane's
    /// struck-through cells come back struck through in the rendered log.
    #[test]
    fn strikeout_is_set_by_9_and_cleared_by_29() {
        let mut style = AnsiStyle::default();
        let line = parse_line("\x1b[9mgone\x1b[29m kept", &mut style);
        assert_eq!(line.text, "gone kept");
        let gone = line
            .spans
            .iter()
            .find(|s| s.start == 0)
            .expect("a span for the struck run");
        assert!(
            gone.style.strikeout,
            "SGR 9 sets strikeout: {:?}",
            line.spans
        );
        let kept = line.spans.iter().find(|s| s.start >= 4);
        assert!(
            kept.is_none_or(|s| !s.style.strikeout),
            "SGR 29 clears it: {:?}",
            line.spans
        );
    }

    fn parse(raw: &str) -> AnsiLine {
        let mut st = AnsiStyle::default();
        parse_line(raw, &mut st)
    }

    #[test]
    fn plain_text_yields_one_unstyled_span() {
        let l = parse("hello");
        assert_eq!(l.text, "hello");
        assert_eq!(l.spans.len(), 1);
        assert_eq!(l.spans[0].style, AnsiStyle::default());
    }

    #[test]
    fn basic_colors_map_to_palette_slots_and_text_is_stripped() {
        let l = parse("\u{1b}[31mred\u{1b}[0m plain");
        assert_eq!(l.text, "red plain", "escapes never reach the text");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(1)));
        assert_eq!(&l.text[l.spans[0].start..l.spans[0].end], "red");
        assert_eq!(l.spans[1].style, AnsiStyle::default());
    }

    #[test]
    fn bright_aliases_land_in_the_upper_palette_half() {
        let l = parse("\u{1b}[91mbright\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(9)));
        let l = parse("\u{1b}[103mbg\u{1b}[0m");
        assert_eq!(l.spans[0].style.bg, Some(AnsiColor::Indexed(11)));
    }

    #[test]
    fn palette_and_truecolor_parse_with_their_parameters_consumed() {
        let l = parse("\u{1b}[38;5;208morange\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Palette256(208)));
        let l = parse("\u{1b}[38;2;10;20;30mrgb\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Rgb(10, 20, 30)));
        // The low 16 stay symbolic even when spelled the 256-colour way, so
        // the theme palette still owns them.
        let l = parse("\u{1b}[38;5;3myellow\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Indexed(3)));
    }

    #[test]
    fn a_truecolor_sequence_does_not_swallow_following_attributes() {
        // The r;g;b parameters must be consumed, or the `1` below would be
        // read as a colour component and bold would be lost.
        let l = parse("\u{1b}[38;2;1;2;3;1mx\u{1b}[0m");
        assert_eq!(l.spans[0].style.fg, Some(AnsiColor::Rgb(1, 2, 3)));
        assert!(l.spans[0].style.bold, "the trailing 1 is still bold");
    }

    #[test]
    fn attributes_set_and_clear_independently() {
        let l = parse("\u{1b}[1;3;4ma\u{1b}[23mb\u{1b}[24mc\u{1b}[22md");
        assert!(l.spans[0].style.bold && l.spans[0].style.italic && l.spans[0].style.underline);
        assert!(!l.spans[1].style.italic && l.spans[1].style.underline);
        assert!(!l.spans[2].style.underline && l.spans[2].style.bold);
        assert!(!l.spans[3].style.bold);
    }

    #[test]
    fn non_sgr_escapes_are_stripped_not_rendered() {
        // Cursor movement, erase-line, and OSC titles carry no meaning in a
        // static buffer; none of them may leak into the text.
        let l = parse("\u{1b}[2Ka\u{1b}[10;20Hb\u{1b}]0;title\u{7}c");
        assert_eq!(l.text, "abc");
        let l = parse("\u{1b}]8;;https://example.com\u{1b}\\link\u{1b}]8;;\u{1b}\\");
        assert_eq!(l.text, "link", "OSC-8 hyperlinks strip to their label");
    }

    #[test]
    fn style_carries_across_lines_like_a_terminal() {
        let mut st = AnsiStyle::default();
        let a = parse_line("\u{1b}[31mred starts", &mut st);
        let b = parse_line("still red", &mut st);
        assert_eq!(a.spans[0].style.fg, Some(AnsiColor::Indexed(1)));
        assert_eq!(
            b.spans[0].style.fg,
            Some(AnsiColor::Indexed(1)),
            "no reset means the next line stays red"
        );
        let c = parse_line("\u{1b}[0mplain", &mut st);
        assert_eq!(c.spans[0].style.fg, None);
    }

    #[test]
    fn malformed_and_truncated_sequences_do_not_panic_or_eat_text() {
        assert_eq!(parse("\u{1b}[999999999999m x").text, " x");
        assert_eq!(parse("\u{1b}[38;5mtruncated").text, "truncated");
        assert_eq!(parse("\u{1b}[38;2;1;2mshort").text, "short");
        // A trailing ESC is real content, not the start of a sequence.
        assert_eq!(parse("tail\u{1b}").text, "tail\u{1b}");
        // Unterminated CSI at EOF: dropped, and nothing after it exists.
        assert_eq!(parse("head\u{1b}[31").text, "head");
    }

    #[test]
    fn multibyte_text_survives_slicing_at_escape_boundaries() {
        let l = parse("héllo \u{1b}[31mwörld 🙂\u{1b}[0m ok");
        assert_eq!(l.text, "héllo wörld 🙂 ok");
        // Spans are byte offsets into the stripped text, so slicing them must
        // land on char boundaries.
        for s in &l.spans {
            assert!(l.text.is_char_boundary(s.start) && l.text.is_char_boundary(s.end));
        }
        assert_eq!(&l.text[l.spans[1].start..l.spans[1].end], "wörld 🙂");
    }

    #[test]
    fn bare_and_empty_sgr_parameters_reset() {
        let mut st = AnsiStyle {
            bold: true,
            fg: Some(AnsiColor::Indexed(2)),
            ..Default::default()
        };
        parse_line("\u{1b}[mx", &mut st);
        assert_eq!(st, AnsiStyle::default(), "ESC[m is a reset");
        let l = parse("\u{1b}[1m\u{1b}[;31mx");
        assert_eq!(
            l.spans.last().unwrap().style.fg,
            Some(AnsiColor::Indexed(1))
        );
        assert!(
            !l.spans.last().unwrap().style.bold,
            "the empty parameter reset bold before red applied"
        );
    }

    #[test]
    fn sniffing_requires_an_sgr_sequence_not_just_an_escape() {
        assert!(looks_like_ansi("plain \u{1b}[31mred"));
        assert!(looks_like_ansi("\u{1b}[1;32mok"));
        assert!(
            !looks_like_ansi("\u{1b}[2J\u{1b}[10;1H"),
            "a screen recording is not a colour log"
        );
        assert!(!looks_like_ansi("no escapes here"));
        assert!(!looks_like_ansi("\u{1b}[31"), "truncated is not a match");
    }

    #[test]
    fn an_escape_before_a_multibyte_char_does_not_panic() {
        // The two-byte-escape arm advanced past ESC + one byte
        // unconditionally, landing inside a multi-byte character and
        // panicking on the next slice.
        // ESC before a non-ASCII byte is not an escape sequence at all, so
        // the ESC is kept as content (same rule as a trailing ESC) and the
        // character survives — the old code swallowed it, or panicked.
        assert_eq!(parse("\u{1b}\u{e9} tail").text, "\u{1b}\u{e9} tail");
        assert_eq!(parse("\u{1b}\u{1F642} tail").text, "\u{1b}\u{1F642} tail");
        // A real two-byte escape still disappears.
        assert_eq!(parse("\u{1b}7saved").text, "saved");
    }
}