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
//! # onefetch-ascii
//!
//! Provides the ascii template interface for [onefetch](https://github.com/o2sh/onefetch).
//!
//! ```rust,no_run
//! use onefetch_ascii::AsciiArt;
//! use owo_colors::{DynColors, AnsiColors};
//!
//! const ASCII: &str = r#"
//! {2}            .:--::////::--.`
//! {1}        `/yNMMNho{2}////////////:.
//! {1}      `+NMMMMMMMMmy{2}/////////////:`
//! {0}    `-:::{1}ohNMMMMMMMNy{2}/////////////:`
//! {0}   .::::::::{1}odMMMMMMMNy{2}/////////////-
//! {0}  -:::::::::::{1}/hMMMMMMMmo{2}////////////-
//! {0} .::::::::::::::{1}oMMMMMMMMh{2}////////////-
//! {0}`:::::::::::::{1}/dMMMMMMMMMMNo{2}///////////`
//! {0}-::::::::::::{1}sMMMMMMmMMMMMMMy{2}//////////-
//! {0}-::::::::::{1}/dMMMMMMs{0}:{1}+NMMMMMMd{2}/////////:
//! {0}-:::::::::{1}+NMMMMMm/{0}:::{1}/dMMMMMMm+{2}///////:
//! {0}-::::::::{1}sMMMMMMh{0}:::::::{1}dMMMMMMm+{2}//////-
//! {0}`:::::::{1}sMMMMMMy{0}:::::::::{1}dMMMMMMm+{2}/////`
//! {0} .:::::{1}sMMMMMMs{0}:::::::::::{1}mMMMMMMd{2}////-
//! {0}  -:::{1}sMMMMMMy{0}::::::::::::{1}/NMMMMMMh{2}//-
//! {0}   .:{1}+MMMMMMd{0}::::::::::::::{1}oMMMMMMMo{2}-
//! {1}    `yMMMMMN/{0}:::::::::::::::{1}hMMMMMh.
//! {1}      -yMMMo{0}::::::::::::::::{1}/MMMy-
//! {1}        `/s{0}::::::::::::::::::{1}o/`
//! {0}            ``.---::::---..`
//! "#;
//!
//! let colors = vec![
//!     DynColors::Ansi(AnsiColors::Blue),
//!     DynColors::Ansi(AnsiColors::Default),
//!     DynColors::Ansi(AnsiColors::BrightBlue)
//! ];
//!
//! let art = AsciiArt::new(ASCII, colors.as_slice(), true);
//!
//! for line in art {
//!     println!("{line}")
//! }
//! ```
//!

use owo_colors::{AnsiColors, DynColors, OwoColorize, Style};
use std::fmt::Write;

/// Renders an ascii template with the given colors truncated to the correct width.
pub struct AsciiArt<'a> {
    content: Box<dyn 'a + Iterator<Item = &'a str>>,
    colors: &'a [DynColors],
    bold: bool,
    start: usize,
    end: usize,
}
impl<'a> AsciiArt<'a> {
    pub fn new(input: &'a str, colors: &'a [DynColors], bold: bool) -> AsciiArt<'a> {
        let mut lines: Vec<_> = input.lines().skip_while(|line| line.is_empty()).collect();
        while let Some(line) = lines.last() {
            if Tokens(line).is_empty() {
                lines.pop();
            } else {
                break;
            }
        }

        let (start, end) = get_min_start_max_end(&lines);

        AsciiArt {
            content: Box::new(lines.into_iter()),
            colors,
            bold,
            start,
            end,
        }
    }

    pub fn width(&self) -> usize {
        assert!(self.end >= self.start);
        self.end - self.start
    }
}

fn get_min_start_max_end(lines: &[&str]) -> (usize, usize) {
    lines
        .iter()
        .map(|line| {
            let line_start = Tokens(line).leading_spaces();
            let line_end = Tokens(line).true_length();
            (line_start, line_end)
        })
        .fold((usize::MAX, 0), |(acc_s, acc_e), (line_s, line_e)| {
            (acc_s.min(line_s), acc_e.max(line_e))
        })
}

/// Produces a series of lines which have been automatically truncated to the
/// correct width
impl<'a> Iterator for AsciiArt<'a> {
    type Item = String;
    fn next(&mut self) -> Option<String> {
        self.content
            .next()
            .map(|line| Tokens(line).render(self.colors, self.start, self.end, self.bold))
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum Token {
    Color(u32),
    Char(char),
    Space,
}
impl std::fmt::Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Token::Color(c) => write!(f, "{{{c}}}"),
            Token::Char(c) => write!(f, "{c}"),
            Token::Space => write!(f, " "),
        }
    }
}
impl Token {
    fn is_solid(&self) -> bool {
        matches!(*self, Token::Char(_))
    }
    fn is_space(&self) -> bool {
        matches!(*self, Token::Space)
    }
    fn has_zero_width(&self) -> bool {
        matches!(*self, Token::Color(_))
    }
}

/// An iterator over tokens found within the *.ascii format.
#[derive(Clone, Debug)]
struct Tokens<'a>(&'a str);
impl<'a> Iterator for Tokens<'a> {
    type Item = Token;
    fn next(&mut self) -> Option<Token> {
        let (s, tok) = color_token(self.0)
            .or_else(|| space_token(self.0))
            .or_else(|| char_token(self.0))?;

        self.0 = s;
        Some(tok)
    }
}

impl<'a> Tokens<'a> {
    fn is_empty(&mut self) -> bool {
        for token in self {
            if token.is_solid() {
                return false;
            }
        }
        true
    }
    fn true_length(&mut self) -> usize {
        let mut last_non_space = 0;
        let mut last = 0;
        for token in self {
            if token.has_zero_width() {
                continue;
            }
            last += 1;
            if !token.is_space() {
                last_non_space = last;
            }
        }
        last_non_space
    }
    fn leading_spaces(&mut self) -> usize {
        self.take_while(|token| !token.is_solid())
            .filter(Token::is_space)
            .count()
    }
    fn truncate(self, mut start: usize, end: usize) -> impl 'a + Iterator<Item = Token> {
        assert!(start <= end);
        let mut width = end - start;

        self.filter(move |token| {
            if start > 0 && !token.has_zero_width() {
                start -= 1;
                return false;
            }
            true
        })
        .take_while(move |token| {
            if width == 0 {
                return false;
            }
            if !token.has_zero_width() {
                width -= 1;
            }
            true
        })
    }
    /// render a truncated line of tokens.
    fn render(self, colors: &[DynColors], start: usize, end: usize, bold: bool) -> String {
        assert!(start <= end);
        let mut width = end - start;
        let mut colored_segment = String::new();
        let mut whole_string = String::new();
        let mut color = &DynColors::Ansi(AnsiColors::Default);

        self.truncate(start, end).for_each(|token| {
            match token {
                Token::Char(chr) => {
                    width = width.saturating_sub(1);
                    colored_segment.push(chr);
                }
                Token::Color(col) => {
                    add_styled_segment(&mut whole_string, &colored_segment, *color, bold);
                    colored_segment = String::new();
                    color = colors
                        .get(col as usize)
                        .unwrap_or(&DynColors::Ansi(AnsiColors::Default));
                }
                Token::Space => {
                    width = width.saturating_sub(1);
                    colored_segment.push(' ')
                }
            };
        });

        add_styled_segment(&mut whole_string, &colored_segment, *color, bold);
        (0..width).for_each(|_| whole_string.push(' '));
        whole_string
    }
}

// Utility functions

fn succeed_when<I>(predicate: impl FnOnce(I) -> bool) -> impl FnOnce(I) -> Option<()> {
    |input| {
        if predicate(input) {
            Some(())
        } else {
            None
        }
    }
}

fn add_styled_segment(base: &mut String, segment: &str, color: DynColors, bold: bool) {
    let mut style = Style::new().color(color);
    if bold {
        style = style.bold();
    }
    let formatted_segment = segment.style(style);
    let _ = write!(base, "{formatted_segment}");
}

// Basic combinators

type ParseResult<'a, R> = Option<(&'a str, R)>;

fn token<R>(s: &str, predicate: impl FnOnce(char) -> Option<R>) -> ParseResult<R> {
    let mut chars = s.chars();
    let token = chars.next()?;
    let result = predicate(token)?;
    Some((chars.as_str(), result))
}

// Parsers

/// Parses a color indicator of the format `{n}` where `n` is a digit.
fn color_token(s: &str) -> ParseResult<Token> {
    let (s, _) = token(s, succeed_when(|c| c == '{'))?;
    let (s, color_index) = token(s, |c| c.to_digit(10))?;
    let (s, _) = token(s, succeed_when(|c| c == '}'))?;
    Some((s, Token::Color(color_index)))
}

/// Parses a space.
fn space_token(s: &str) -> ParseResult<Token> {
    token(s, succeed_when(|c| c == ' ')).map(|(s, _)| (s, Token::Space))
}

/// Parses any arbitrary character. This cannot fail.
fn char_token(s: &str) -> ParseResult<Token> {
    token(s, |c| Some(Token::Char(c)))
}

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

    #[test]
    fn test_get_min_start_max_end() {
        let lines = [
            "                     xxx",
            "   xxx",
            "         oo",
            "     o",
            "                           xx",
        ];
        assert_eq!(get_min_start_max_end(&lines), (3, 29));
    }

    #[test]
    fn space_parses() {
        assert_eq!(space_token(" "), Some(("", Token::Space)));
        assert_eq!(space_token(" hello"), Some(("hello", Token::Space)));
        assert_eq!(space_token("      "), Some(("     ", Token::Space)));
        assert_eq!(space_token(" {1}{2}"), Some(("{1}{2}", Token::Space)));
    }

    #[test]
    fn color_indicator_parses() {
        assert_eq!(color_token("{1}"), Some(("", Token::Color(1))));
        assert_eq!(color_token("{9} "), Some((" ", Token::Color(9))));
    }

    #[test]
    fn leading_spaces_counts_correctly() {
        assert_eq!(Tokens("").leading_spaces(), 0);
        assert_eq!(Tokens("     ").leading_spaces(), 5);
        assert_eq!(Tokens("     a;lksjf;a").leading_spaces(), 5);
        assert_eq!(Tokens("  {1} {5}  {9} a").leading_spaces(), 6);
    }

    #[test]
    fn render() {
        let colors_shim = Vec::new();

        assert_eq!(
            Tokens("").render(&colors_shim, 0, 0, true),
            "\u{1b}[39;1m\u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 0, true),
            "\u{1b}[39;1m\u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 5, true),
            "\u{1b}[39;1m     \u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 1, 5, true),
            "\u{1b}[39;1m    \u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 3, 5, true),
            "\u{1b}[39;1m  \u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 4, true),
            "\u{1b}[39;1m    \u{1b}[0m"
        );

        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 3, true),
            "\u{1b}[39;1m   \u{1b}[0m"
        );

        // https://github.com/o2sh/onefetch/issues/935
        assert_eq!(
            Tokens("███").render(Vec::new().as_slice(), 0, 3, true),
            "\u{1b}[39;1m███\u{1b}[0m"
        );

        assert_eq!(
            Tokens("  {1} {5}  {9} a").render(&colors_shim, 4, 10, true),
            "\u{1b}[39;1m\u{1b}[0m\u{1b}[39;1m\u{1b}[0m\u{1b}[39;1m \u{1b}[0m\u{1b}[39;1m a\u{1b}[0m   "
        );

        // Tests for bold disabled
        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 0, false),
            "\u{1b}[39m\u{1b}[0m"
        );
        assert_eq!(
            Tokens("     ").render(&colors_shim, 0, 5, false),
            "\u{1b}[39m     \u{1b}[0m"
        );
    }

    #[test]
    fn truncate() {
        assert_eq!(
            Tokens("").truncate(0, 0).collect::<Vec<_>>(),
            Tokens("").collect::<Vec<_>>()
        );

        assert_eq!(
            Tokens("     ").truncate(0, 0).collect::<Vec<_>>(),
            Tokens("").collect::<Vec<_>>()
        );
        assert_eq!(
            Tokens("     ").truncate(0, 5).collect::<Vec<_>>(),
            Tokens("     ").collect::<Vec<_>>()
        );
        assert_eq!(
            Tokens("     ").truncate(1, 5).collect::<Vec<_>>(),
            Tokens("    ").collect::<Vec<_>>()
        );
        assert_eq!(
            Tokens("     ").truncate(3, 5).collect::<Vec<_>>(),
            Tokens("  ").collect::<Vec<_>>()
        );
        assert_eq!(
            Tokens("     ").truncate(0, 4).collect::<Vec<_>>(),
            Tokens("    ").collect::<Vec<_>>()
        );
        assert_eq!(
            Tokens("     ").truncate(0, 3).collect::<Vec<_>>(),
            Tokens("   ").collect::<Vec<_>>()
        );

        assert_eq!(
            Tokens("  {1} {5}  {9} a")
                .truncate(4, 10)
                .collect::<Vec<_>>(),
            Tokens("{1}{5} {9} a").collect::<Vec<_>>()
        );
    }
}