tastty-core 0.1.0

Sans-IO core of the tastty terminal session library: VT parser, screen buffer, and byte encoders.
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Terminal text attributes and SGR color values.

use std::fmt;

/// Terminal color value for foreground, background, or underline color.
#[derive(Eq, PartialEq, Debug, Copy, Clone, Default, Hash)]
pub enum Color {
    /// Use the terminal's current default color for this slot.
    #[default]
    Default,
    /// Indexed ANSI/xterm color palette entry.
    Index(u8),
    /// True-color RGB value.
    Rgb(u8, u8, u8),
}

impl Color {
    /// Return the RGB channels when this is a true-color value.
    #[must_use]
    pub fn as_rgb(self) -> Option<(u8, u8, u8)> {
        match self {
            Color::Rgb(r, g, b) => Some((r, g, b)),
            _ => None,
        }
    }

    /// Return the palette index when this is an indexed color.
    #[must_use]
    pub fn as_index(self) -> Option<u8> {
        match self {
            Color::Index(index) => Some(index),
            _ => None,
        }
    }

    /// Return whether this color uses the terminal default for its slot.
    #[must_use]
    pub fn is_default(self) -> bool {
        matches!(self, Color::Default)
    }

    fn write_fg(&self, out: &mut Vec<u8>) {
        match self {
            Color::Default => out.extend_from_slice(b"39"),
            Color::Index(i) if *i < 8 => {
                out.push(b'3');
                out.push(b'0' + i);
            }
            Color::Index(i) if *i < 16 => {
                out.push(b'9');
                out.push(b'0' + (i - 8));
            }
            Color::Index(i) => {
                out.extend_from_slice(b"38;5;");
                out.extend_from_slice(i.to_string().as_bytes());
            }
            Color::Rgb(r, g, b) => {
                out.extend_from_slice(b"38;2;");
                out.extend_from_slice(r.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(g.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(b.to_string().as_bytes());
            }
        }
    }

    fn write_bg(&self, out: &mut Vec<u8>) {
        match self {
            Color::Default => out.extend_from_slice(b"49"),
            Color::Index(i) if *i < 8 => {
                out.push(b'4');
                out.push(b'0' + i);
            }
            Color::Index(i) if *i < 16 => {
                out.extend_from_slice(b"10");
                out.push(b'0' + (i - 8));
            }
            Color::Index(i) => {
                out.extend_from_slice(b"48;5;");
                out.extend_from_slice(i.to_string().as_bytes());
            }
            Color::Rgb(r, g, b) => {
                out.extend_from_slice(b"48;2;");
                out.extend_from_slice(r.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(g.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(b.to_string().as_bytes());
            }
        }
    }

    fn write_underline(&self, out: &mut Vec<u8>) {
        match self {
            Color::Default => out.extend_from_slice(b"59"),
            Color::Index(i) => {
                out.extend_from_slice(b"58;5;");
                out.extend_from_slice(i.to_string().as_bytes());
            }
            Color::Rgb(r, g, b) => {
                out.extend_from_slice(b"58;2;");
                out.extend_from_slice(r.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(g.to_string().as_bytes());
                out.push(b';');
                out.extend_from_slice(b.to_string().as_bytes());
            }
        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Color::Default => f.write_str("default"),
            Color::Index(index) => write!(f, "color({index})"),
            Color::Rgb(r, g, b) => write!(f, "rgb({r},{g},{b})"),
        }
    }
}

const TEXT_MODE_INTENSITY: u16 = 0b0000_0000_0011;
const TEXT_MODE_BOLD: u16 = 0b0000_0000_0001;
const TEXT_MODE_DIM: u16 = 0b0000_0000_0010;
const TEXT_MODE_ITALIC: u16 = 0b0000_0000_0100;
const TEXT_MODE_INVERSE: u16 = 0b0000_0000_1000;
const TEXT_MODE_STRIKETHROUGH: u16 = 0b0000_0001_0000;
const TEXT_MODE_HIDDEN: u16 = 0b0000_0010_0000;
const TEXT_MODE_OVERLINE: u16 = 0b0010_0000_0000;
const TEXT_MODE_BLINK: u16 = 0b0100_0000_0000;

const UNDERLINE_STYLE_MASK: u16 = 0b0001_1100_0000;
const UNDERLINE_STYLE_SHIFT: u32 = 6;

/// Underline style represented by SGR 4 subparameters.
///
/// # References
///
/// - [ECMA-48 (Control Functions for Coded Character Sets)][ecma48]: SGR 4 / 21 / 24 (single underline, double underline, underline off).
/// - [xterm Control Sequences][xterm-ctlseqs]: SGR 4 subparameters `4:3` (curly), `4:4` (dotted), and `4:5` (dashed).
///
/// [ecma48]: https://ecma-international.org/publications-and-standards/standards/ecma-48/
/// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum UnderlineStyle {
    /// No underline.
    #[default]
    None = 0,
    /// Single underline.
    Single = 1,
    /// Double underline.
    Double = 2,
    /// Curly underline.
    Curly = 3,
    /// Dotted underline.
    Dotted = 4,
    /// Dashed underline.
    Dashed = 5,
}

impl UnderlineStyle {
    fn from_u16(n: u16) -> Self {
        match n {
            1 => Self::Single,
            2 => Self::Double,
            3 => Self::Curly,
            4 => Self::Dotted,
            5 => Self::Dashed,
            _ => Self::None,
        }
    }

    pub(crate) fn from_sgr(n: u16) -> Self {
        match n {
            0 => Self::None,
            1 => Self::Single,
            2 => Self::Double,
            3 => Self::Curly,
            4 => Self::Dotted,
            5 => Self::Dashed,
            _ => Self::Single,
        }
    }
}

/// SGR text attributes for a terminal cell.
///
/// # References
///
/// - [ECMA-48 (Control Functions for Coded Character Sets)][ecma48]: SGR (Select Graphic Rendition) parameters for intensity, italic, underline, blink, inverse, hidden, strikethrough, and the 8-color foreground / background palette.
/// - [xterm Control Sequences][xterm-ctlseqs]: SGR colour extensions used here are 256-color (`38;5;n` / `48;5;n`), true-color (`38;2;r;g;b` / `48;2;r;g;b`), bright 8-color (`90`-`97` / `100`-`107`), underline color (`58` / `59`), and overline (`53`).
///
/// [ecma48]: https://ecma-international.org/publications-and-standards/standards/ecma-48/
/// [xterm-ctlseqs]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[non_exhaustive]
pub struct Attrs {
    /// Foreground color.
    pub fg_color: Color,
    /// Background color.
    pub bg_color: Color,
    /// Underline color.
    pub underline_color: Color,
    pub(crate) mode: u16,
}

macro_rules! flag_accessors {
    ($($getter:ident / $setter:ident => $flag:ident),* $(,)?) => {
        $(
            #[doc = concat!("Return whether the ", stringify!($getter), " attribute is set.")]
            pub fn $getter(&self) -> bool {
                self.mode & $flag != 0
            }

            #[doc = concat!("Set or clear the ", stringify!($getter), " attribute.")]
            pub fn $setter(&mut self, on: bool) {
                if on {
                    self.mode |= $flag;
                } else {
                    self.mode &= !$flag;
                }
            }
        )*
    };
}

impl Attrs {
    /// Return whether bold intensity is set.
    pub fn bold(&self) -> bool {
        self.mode & TEXT_MODE_BOLD != 0
    }

    /// Return whether dim intensity is set.
    pub fn dim(&self) -> bool {
        self.mode & TEXT_MODE_DIM != 0
    }

    /// Set bold intensity, clearing dim if it was set.
    pub fn set_bold(&mut self) {
        self.mode &= !TEXT_MODE_INTENSITY;
        self.mode |= TEXT_MODE_BOLD;
    }

    /// Set dim intensity, clearing bold if it was set.
    pub fn set_dim(&mut self) {
        self.mode &= !TEXT_MODE_INTENSITY;
        self.mode |= TEXT_MODE_DIM;
    }

    /// Clear bold and dim intensity.
    pub fn set_normal_intensity(&mut self) {
        self.mode &= !TEXT_MODE_INTENSITY;
    }

    flag_accessors! {
        italic / set_italic => TEXT_MODE_ITALIC,
        inverse / set_inverse => TEXT_MODE_INVERSE,
        strikethrough / set_strikethrough => TEXT_MODE_STRIKETHROUGH,
        hidden / set_hidden => TEXT_MODE_HIDDEN,
        overline / set_overline => TEXT_MODE_OVERLINE,
        blink / set_blink => TEXT_MODE_BLINK,
    }

    /// Return whether any underline style is active.
    pub fn underline(&self) -> bool {
        self.underline_style() != UnderlineStyle::None
    }

    /// Return the active underline style.
    pub fn underline_style(&self) -> UnderlineStyle {
        let raw = (self.mode & UNDERLINE_STYLE_MASK) >> UNDERLINE_STYLE_SHIFT;
        UnderlineStyle::from_u16(raw)
    }

    /// Enable or disable single underline.
    pub fn set_underline(&mut self, underline: bool) {
        if underline {
            self.set_underline_style(UnderlineStyle::Single);
        } else {
            self.set_underline_style(UnderlineStyle::None);
        }
    }

    /// Set the underline style.
    pub fn set_underline_style(&mut self, style: UnderlineStyle) {
        self.mode &= !UNDERLINE_STYLE_MASK;
        self.mode |= (style as u16) << UNDERLINE_STYLE_SHIFT;
    }

    /// Produce the SGR escape sequence that transitions from `prev` to `self`.
    /// Returns an empty vec when no change is needed.
    #[must_use]
    pub fn to_escape_sequence(&self, prev: &Attrs) -> Vec<u8> {
        if *self == *prev {
            return Vec::new();
        }

        let mut params: Vec<u8> = Vec::new();
        let mut needs_sep = false;

        // When any attribute that was on in prev is off in self, we must
        // emit a full reset first because there is no individual "off"
        // code for most SGR attributes.
        let any_off = (prev.bold() && !self.bold())
            || (prev.dim() && !self.dim())
            || (prev.italic() && !self.italic())
            || (prev.underline() && !self.underline())
            || (prev.inverse() && !self.inverse())
            || (prev.strikethrough() && !self.strikethrough())
            || (prev.hidden() && !self.hidden())
            || (prev.overline() && !self.overline())
            || (prev.blink() && !self.blink());

        let base = if any_off {
            params.push(b'0');
            needs_sep = true;
            &Attrs::default()
        } else {
            prev
        };

        macro_rules! add_param {
            ($param:expr) => {
                if needs_sep {
                    params.push(b';');
                }
                params.extend_from_slice($param);
                needs_sep = true;
            };
        }

        if self.bold() && !base.bold() {
            add_param!(b"1");
        }
        if self.dim() && !base.dim() {
            add_param!(b"2");
        }
        if self.italic() && !base.italic() {
            add_param!(b"3");
        }
        if self.underline() && self.underline_style() != base.underline_style() {
            match self.underline_style() {
                UnderlineStyle::Single => {
                    add_param!(b"4");
                }
                UnderlineStyle::Double => {
                    add_param!(b"4:2");
                }
                UnderlineStyle::Curly => {
                    add_param!(b"4:3");
                }
                UnderlineStyle::Dotted => {
                    add_param!(b"4:4");
                }
                UnderlineStyle::Dashed => {
                    add_param!(b"4:5");
                }
                UnderlineStyle::None => {}
            }
        }
        if self.blink() && !base.blink() {
            add_param!(b"5");
        }
        if self.inverse() && !base.inverse() {
            add_param!(b"7");
        }
        if self.hidden() && !base.hidden() {
            add_param!(b"8");
        }
        if self.strikethrough() && !base.strikethrough() {
            add_param!(b"9");
        }
        if self.overline() && !base.overline() {
            add_param!(b"53");
        }

        if self.fg_color != base.fg_color {
            if needs_sep {
                params.push(b';');
            }
            self.fg_color.write_fg(&mut params);
            needs_sep = true;
        }
        if self.bg_color != base.bg_color {
            if needs_sep {
                params.push(b';');
            }
            self.bg_color.write_bg(&mut params);
            needs_sep = true;
        }
        if self.underline_color != base.underline_color {
            if needs_sep {
                params.push(b';');
            }
            self.underline_color.write_underline(&mut params);
            needs_sep = true;
        }
        let _ = needs_sep;

        if params.is_empty() {
            return Vec::new();
        }
        let mut out = Vec::with_capacity(params.len() + 3);
        out.extend_from_slice(b"\x1b[");
        out.extend_from_slice(&params);
        out.push(b'm');
        out
    }
}

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

    #[test]
    fn default_attrs() {
        let attrs = Attrs::default();
        assert!(!attrs.bold());
        assert!(!attrs.dim());
        assert!(!attrs.italic());
        assert!(!attrs.underline());
        assert!(!attrs.inverse());
        assert!(!attrs.strikethrough());
        assert!(!attrs.hidden());
        assert_eq!(attrs.fg_color, Color::Default);
        assert_eq!(attrs.bg_color, Color::Default);
    }

    #[test]
    fn bold_clears_dim() {
        let mut attrs = Attrs::default();
        attrs.set_dim();
        assert!(attrs.dim());
        attrs.set_bold();
        assert!(attrs.bold());
        assert!(!attrs.dim());
    }

    #[test]
    fn dim_clears_bold() {
        let mut attrs = Attrs::default();
        attrs.set_bold();
        assert!(attrs.bold());
        attrs.set_dim();
        assert!(attrs.dim());
        assert!(!attrs.bold());
    }

    #[test]
    fn normal_intensity_clears_both() {
        let mut attrs = Attrs::default();
        attrs.set_bold();
        attrs.set_normal_intensity();
        assert!(!attrs.bold());
        assert!(!attrs.dim());
    }

    #[test]
    fn toggle_italic() {
        let mut attrs = Attrs::default();
        attrs.set_italic(true);
        assert!(attrs.italic());
        attrs.set_italic(false);
        assert!(!attrs.italic());
    }

    #[test]
    fn underline_style_variants() {
        let mut attrs = Attrs::default();
        assert_eq!(attrs.underline_style(), UnderlineStyle::None);
        assert!(!attrs.underline());

        attrs.set_underline_style(UnderlineStyle::Single);
        assert!(attrs.underline());
        assert_eq!(attrs.underline_style(), UnderlineStyle::Single);

        attrs.set_underline_style(UnderlineStyle::Curly);
        assert!(attrs.underline());
        assert_eq!(attrs.underline_style(), UnderlineStyle::Curly);

        attrs.set_underline_style(UnderlineStyle::Double);
        assert_eq!(attrs.underline_style(), UnderlineStyle::Double);

        attrs.set_underline_style(UnderlineStyle::Dotted);
        assert_eq!(attrs.underline_style(), UnderlineStyle::Dotted);

        attrs.set_underline_style(UnderlineStyle::Dashed);
        assert_eq!(attrs.underline_style(), UnderlineStyle::Dashed);

        attrs.set_underline(false);
        assert_eq!(attrs.underline_style(), UnderlineStyle::None);
    }

    #[test]
    fn set_underline_bool_uses_single() {
        let mut attrs = Attrs::default();
        attrs.set_underline(true);
        assert_eq!(attrs.underline_style(), UnderlineStyle::Single);
    }

    #[test]
    fn underline_color() {
        let mut attrs = Attrs::default();
        assert_eq!(attrs.underline_color, Color::Default);
        attrs.underline_color = Color::Rgb(255, 0, 0);
        assert_eq!(attrs.underline_color, Color::Rgb(255, 0, 0));
    }

    #[test]
    fn toggle_strikethrough() {
        let mut attrs = Attrs::default();
        attrs.set_strikethrough(true);
        assert!(attrs.strikethrough());
        attrs.set_strikethrough(false);
        assert!(!attrs.strikethrough());
    }

    #[test]
    fn toggle_hidden() {
        let mut attrs = Attrs::default();
        attrs.set_hidden(true);
        assert!(attrs.hidden());
        attrs.set_hidden(false);
        assert!(!attrs.hidden());
    }

    #[test]
    fn color_variants() {
        assert_eq!(Color::Default, Color::default());
        assert_ne!(Color::Index(1), Color::Index(2));
        assert_eq!(Color::Rgb(10, 20, 30), Color::Rgb(10, 20, 30));
    }

    #[test]
    fn escape_sequence_bold() {
        let prev = Attrs::default();
        let mut next = Attrs::default();
        next.set_bold();
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[1m");
    }

    #[test]
    fn escape_sequence_reset_bold() {
        let mut prev = Attrs::default();
        prev.set_bold();
        let next = Attrs::default();
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[0m");
    }

    #[test]
    fn escape_sequence_fg_color_idx() {
        let prev = Attrs::default();
        let next = Attrs {
            fg_color: Color::Index(1),
            ..Attrs::default()
        };
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[31m");
    }

    #[test]
    fn escape_sequence_rgb_bg() {
        let prev = Attrs::default();
        let next = Attrs {
            bg_color: Color::Rgb(255, 128, 0),
            ..Attrs::default()
        };
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[48;2;255;128;0m");
    }

    #[test]
    fn escape_sequence_no_change() {
        let attrs = Attrs::default();
        assert!(attrs.to_escape_sequence(&attrs).is_empty());
    }

    #[test]
    fn escape_sequence_bright_fg() {
        let prev = Attrs::default();
        let next = Attrs {
            fg_color: Color::Index(9),
            ..Attrs::default()
        };
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[91m");
    }

    #[test]
    fn escape_sequence_256_color() {
        let prev = Attrs::default();
        let next = Attrs {
            fg_color: Color::Index(200),
            ..Attrs::default()
        };
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[38;5;200m");
    }

    #[test]
    fn escape_sequence_underline_style_transition() {
        // Changing underline style without turning underline off
        let mut prev = Attrs::default();
        prev.set_underline_style(UnderlineStyle::Single);
        let mut next = Attrs::default();
        next.set_underline_style(UnderlineStyle::Curly);
        let seq = next.to_escape_sequence(&prev);
        assert_eq!(seq, b"\x1b[4:3m");
    }

    #[test]
    fn escape_sequence_reset_and_reapply() {
        // prev = bold+red, next = red (bold removed -> needs reset + reapply color)
        let mut prev = Attrs::default();
        prev.set_bold();
        prev.fg_color = Color::Index(1);
        let next = Attrs {
            fg_color: Color::Index(1),
            ..Attrs::default()
        };
        let seq = next.to_escape_sequence(&prev);
        assert_eq!(seq, b"\x1b[0;31m");
    }

    #[test]
    fn escape_sequence_multiple_attrs() {
        // From default to bold+italic+red foreground
        let prev = Attrs::default();
        let mut next = Attrs::default();
        next.set_bold();
        next.set_italic(true);
        next.fg_color = Color::Index(1);
        let seq = next.to_escape_sequence(&prev);
        assert_eq!(seq, b"\x1b[1;3;31m");
    }

    #[test]
    fn to_escape_sequence_emits_underline_color_when_underline_off() {
        // SGR 58/59 (underline color) are independent of SGR 4/24 (underline
        // on/off) per ECMA-48
        // (https://ecma-international.org/publications-and-standards/standards/ecma-48/):
        // a bare `\x1b[58:2::r:g:bm` sets the underline
        // color even with the underline flag off, and an attribute-replay
        // path must round-trip that state.
        let prev = Attrs::default();
        let next = Attrs {
            underline_color: Color::Rgb(170, 170, 170),
            ..Attrs::default()
        };
        assert_eq!(next.to_escape_sequence(&prev), b"\x1b[58;2;170;170;170m");
    }
}