termit 0.7.0

Terminal UI over crossterm
Documentation
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
//! ANSI escapes printing

use super::{
    color::Color,
    command::TerminalRequest,
    style::{Style, Stylish},
};
use std::{
    fmt::{Display, Formatter},
    io,
};

/// Controls which features of ANSI output to enable
///
/// The color_* options are not exclusive. If you enable all,
/// we print all the kinds of color sequences. You'd do that
/// to be most compatible without having to detect terminal
/// capabilities.
#[derive(Debug, Clone, Copy)]
pub struct AnsiConfig {
    /// print color in 3 bits (8 colors ANSI palette)
    pub color_3b: bool,
    /// print color in 4 bits (16 colors ANSI palette)
    pub color_4b: bool,
    /// print color in 8 bits (256 colors ANSI palette)
    pub color_8b: bool,
    /// print color in 24 bits (true color RGB)
    pub color_24b: bool,
    /// Add CR (\r) to LF (\n) - useful in raw mode
    pub add_cr_to_lf: bool,
}

/// Takes care of printing to ANSI terminal
///
/// It will escape ESC to prevent abuse.
/// It will print colors for style.
/// It will add CR to LF for text if necessary.
#[derive(Debug, Default, Clone)]
pub struct AnsiPrint<T>(pub T);
impl<T> TerminalRequest for AnsiPrint<T>
where
    AnsiPrint<T>: Display,
    T: std::fmt::Debug,
{
    fn apply(&self, mut write: impl io::Write) -> io::Result<bool> {
        write.write_all(self.to_string().as_bytes()).map(|()| true)
    }
}
impl<T> AnsiPrint<T> {
    pub fn default(self) -> AnsiPrintConfigured<T> {
        AnsiPrintConfigured(self.0, AnsiConfig::default())
    }
    pub fn raw(self, raw: bool) -> AnsiPrintConfigured<T> {
        self.default().raw(raw)
    }

    pub(crate) fn compatible_color(self) -> AnsiPrintConfigured<T> {
        self.default().compatible_color()
    }

    pub(crate) fn true_color(self) -> AnsiPrintConfigured<T> {
        self.default().true_color()
    }
}
/// Takes care of printing to ANSI terminal
///
/// It will escape ESC to prevent abuse.
/// It will print colors for style.
/// It will add CR to LF for text if necessary.
#[derive(Debug, Default, Clone)]
pub struct AnsiPrintConfigured<T>(pub T, pub AnsiConfig);
impl<T> TerminalRequest for AnsiPrintConfigured<T>
where
    AnsiPrintConfigured<T>: Display,
    T: std::fmt::Debug,
{
    fn apply(&self, mut write: impl io::Write) -> io::Result<bool> {
        write.write_all(self.to_string().as_bytes()).map(|()| true)
    }
}
impl<T> AnsiPrintConfigured<T> {
    fn raw(mut self, raw: bool) -> Self {
        self.1.add_cr_to_lf = !raw;
        self
    }
    fn compatible_color(mut self) -> Self {
        self.1.color_4b = true;
        self.1.color_8b = true;
        self.1.color_24b = true;
        self
    }

    fn true_color(mut self) -> Self {
        self.1.color_24b = true;
        self
    }
}

/// The default is on the safe side
impl Default for AnsiConfig {
    fn default() -> Self {
        Self::compatible_color()
    }
}
impl AnsiConfig {
    /// full control
    pub fn new(
        color_3b: bool,
        color_4b: bool,
        color_8b: bool,
        color_24b: bool,
        add_cr_to_lf: bool,
    ) -> Self {
        Self {
            color_3b,
            color_4b,
            color_8b,
            color_24b,
            add_cr_to_lf,
        }
    }
    /// only print RGB and DO add CR to LF
    pub const fn true_color() -> Self {
        Self {
            color_3b: false,
            color_4b: false,
            color_8b: false,
            color_24b: true,
            add_cr_to_lf: true,
        }
    }
    /// only print RGB and do NOT add CR to LF
    pub const fn raw_true_color() -> Self {
        Self {
            color_3b: false,
            color_4b: false,
            color_8b: false,
            color_24b: true,
            add_cr_to_lf: false,
        }
    }
    /// print color in 4b, 8b and true color, and DO add CR to LF
    pub const fn compatible_color() -> Self {
        Self {
            color_3b: false,
            color_4b: true,
            color_8b: true,
            color_24b: true,
            add_cr_to_lf: true,
        }
    }
    /// print color in 4b, 8b and true color, and do NOT add CR to LF
    pub const fn raw_compatible_color() -> Self {
        Self {
            color_3b: false,
            color_4b: true,
            color_8b: true,
            color_24b: true,
            add_cr_to_lf: false,
        }
    }
    /// no color support, but DO add CR to LF
    pub const fn no_color() -> Self {
        Self {
            color_3b: false,
            color_4b: false,
            color_8b: false,
            color_24b: false,
            add_cr_to_lf: true,
        }
    }
    /// no color support and do NOT add CR to LF
    pub const fn raw_no_color() -> Self {
        Self {
            color_3b: false,
            color_4b: false,
            color_8b: false,
            color_24b: false,
            add_cr_to_lf: false,
        }
    }
}
impl<'a, T> Display for AnsiPrint<T>
where
    T: AsRef<str>,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        AnsiPrintConfigured(self.0.as_ref(), AnsiConfig::default()).fmt(f)
    }
}
impl Display for AnsiPrint<Style> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        AnsiPrintConfigured(&self.0, AnsiConfig::default()).fmt(f)
    }
}
/// Print normal text, escaping escape sequences to protect from abuse
/// and adding '\r' on '\n' if in raw mode
impl<T> Display for AnsiPrintConfigured<T>
where
    T: AsRef<str>,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let Self(content, config) = self;
        for line in content.as_ref().split_inclusive(LF) {
            for part in line.split_inclusive(ESC) {
                if part.ends_with(ESC) {
                    // add CR to LF
                    write!(f, "{part}{ESC}")?;
                } else {
                    write!(f, "{part}")?;
                }
            }
            if config.add_cr_to_lf && line.ends_with(LF) && !line.ends_with(CRLF) {
                // add carriage return after line feed
                write!(f, "{CR}")?;
            }
        }
        Ok(())
    }
}

/// Set the given style, always resetting first
impl Display for AnsiPrintConfigured<Style> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let Self(style, config) = self;
        AnsiPrintConfigured(ScreenStyle::from(style), *config).fmt(f)
    }
}

/// Set the given style, always resetting first
impl Display for AnsiPrintConfigured<&'_ Style> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let Self(style, config) = self;
        AnsiPrintConfigured(ScreenStyle::from(*style), *config).fmt(f)
    }
}
/// Set the given style, always resetting first
impl std::fmt::Display for AnsiPrintConfigured<ScreenStyle> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self(style, config) = self;
        AnsiPrintConfigured(style, *config).fmt(f)
    }
}
/// Set the given style, always resetting first
impl std::fmt::Display for AnsiPrintConfigured<&'_ ScreenStyle> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self(style, config) = self;
        // reset attrs not to mix with previous style
        write!(f, "{CSI}m")?;
        if 1 == 1 & (style.flags >> ScreenStyle::FRONT) {
            let mut printed = false;
            if config.color_3b {
                printed = true;
                let code = ansi_color_code_4b(style.front.to_3b(), false);
                write!(f, "{CSI}1;{code}m")?;
            }
            if config.color_4b {
                printed = true;
                let code = ansi_color_code_4b(style.front.to_4b(), false);
                write!(f, "{CSI}1;{code}m")?;
            }
            if config.color_8b {
                printed = true;
                let ansi = style.front.to_8b();
                write!(f, "{CSI}38;5;{ansi}m")?;
            }
            if config.color_24b && (!style.front.is_ansi() || !printed) {
                let (r, g, b) = style.front.to_24b();
                write!(f, "{CSI}38;2;{r};{g};{b}m")?;
            }
        }
        if 1 == 1 & (style.flags >> ScreenStyle::BACK) {
            let mut printed = false;
            if config.color_3b {
                printed = true;
                let code = ansi_color_code_4b(style.back.to_3b(), true);
                write!(f, "{CSI}1;{code}m")?;
            }
            if config.color_4b {
                printed = true;
                let code = ansi_color_code_4b(style.back.to_4b(), true);
                write!(f, "{CSI}1;{code}m")?;
            }
            if config.color_8b {
                printed = true;
                let ansi = style.back.to_8b();
                write!(f, "{CSI}48;5;{ansi}m")?;
            }
            if config.color_24b && (!style.back.is_ansi() || !printed) {
                let (r, g, b) = style.back.to_24b();
                write!(f, "{CSI}48;2;{r};{g};{b}m")?;
            }
        }
        if 1 == 1 & (style.flags >> ScreenStyle::UNDER) {
            write!(f, "{CSI}4m")?;
            if style.under != style.front {
                let mut printed = false;
                if config.color_8b {
                    printed = true;
                    let ansi = style.under.to_8b();
                    write!(f, "{CSI}58;5;{ansi}m")?;
                }
                if config.color_24b && (!style.under.is_ansi() || !printed) {
                    let (r, g, b) = style.under.to_24b();
                    write!(f, "{CSI}58;2;{r};{g};{b}m")?;
                }
            }
        }
        if 1 == 1 & (style.flags >> ScreenStyle::BOLD) {
            write!(f, "{CSI}1m")?;
        }
        if 1 == 1 & (style.flags >> ScreenStyle::ITALIC) {
            write!(f, "{CSI}3m")?;
        }
        if 1 == 1 & (style.flags >> ScreenStyle::BLINK) {
            write!(f, "{CSI}5m")?;
        }
        Ok(())
    }
}

pub(crate) fn ansi_color_code_4b(mut c: u8, background: bool) -> u8 {
    if c >= 8 {
        c += 52
    }
    if background {
        c += 10
    }
    c += 30;
    assert!(
        (30..38).contains(&c)
            || (40..48).contains(&c)
            || (90..98).contains(&c)
            || (100..108).contains(&c),
        "correct ansi escape code param"
    );
    c
}
pub const CRLF: &str = "\r\n";
pub const LF: char = '\n';
pub const CR: char = '\r';
pub const ESC: char = '\x1b';
pub const CSI: &str = "\x1b[";

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenStyle {
    flags: u8,
    front: Color,
    back: Color,
    under: Color,
}
impl ScreenStyle {
    pub const DEFAULT: ScreenStyle = ScreenStyle {
        flags: 0,
        front: Color::grey(true),
        back: Color::black(),
        under: Color::grey(true),
    };
    pub fn front_color(&self) -> Option<Color> {
        if 1 == 1 & (self.flags >> Self::FRONT) {
            Some(self.front)
        } else {
            None
        }
    }
    pub fn back_color(&self) -> Option<Color> {
        if 1 == 1 & (self.flags >> Self::BACK) {
            Some(self.back)
        } else {
            None
        }
    }
}
impl ScreenStyle {
    const FRONT: u8 = 0;
    const BACK: u8 = 1;
    const UNDER: u8 = 2;
    const BOLD: u8 = 3;
    const ITALIC: u8 = 4;
    const BLINK: u8 = 5;
}

impl<T> From<&T> for ScreenStyle
where
    T: Stylish,
{
    fn from(stylish: &T) -> Self {
        let style = stylish.style();
        let front = style.front_color.unwrap_or(Color::grey(true));
        let back = style.back_color.unwrap_or(Color::black());
        let under = style.frame_color.unwrap_or(front);
        let flags = (((style.frame_color.is_some() && style.underlined.unwrap_or_default()) as u8)
            << Self::UNDER)
            | ((style.front_color.is_some() as u8) << Self::FRONT)
            | ((style.back_color.is_some() as u8) << Self::BACK)
            | ((style.bold.unwrap_or_default() as u8) << Self::BOLD)
            | ((style.italic.unwrap_or_default() as u8) << Self::ITALIC)
            | ((style.blink.unwrap_or_default() as u8) << Self::BLINK);
        Self {
            flags,
            front,
            back,
            under,
        }
    }
}

#[test]
fn print_new_lines() {
    assert_eq!(
        AnsiPrintConfigured("a\n b\r\n c", AnsiConfig::no_color()).to_string(),
        "a\n\r b\r\n c"
    );
}

#[test]
fn print_esc_esc() {
    assert_eq!(
        AnsiPrintConfigured("a \x1b[0m b", AnsiConfig::default()).to_string(),
        "a \x1b\x1b[0m b"
    );
}

#[test]
fn print_compatible_colors() {
    use crate::output::style::Stylist;
    assert_eq!(
        AnsiPrintConfigured(
            crate::output::style::Style::DEFAULT
                .front(crate::output::color::Color::rgb(1, 99, 222)),
            AnsiConfig::compatible_color()
        )
        .to_string(),
        "\x1b[m\x1b[1;96m\x1b[38;5;26m\x1b[38;2;1;99;222m"
    );
}