hyfetch 2.0.5

Neofetch with LGBTQ+ pride flags!
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
use std::io::{self, Write as _};
use std::num::{ParseFloatError, ParseIntError};
use std::str::FromStr;
use std::sync::OnceLock;

use aho_corasick::AhoCorasick;
use ansi_colours::{ansi256_from_grey, rgb_from_ansi256, AsRGB as _};
use anyhow::{anyhow, Context as _, Result};
use deranged::RangedU8;
use palette::color_difference::ImprovedCiede2000 as _;
use palette::{
    FromColor as _, IntoColor as _, IntoColorMut as _, Lab, LinSrgb, Okhsl, Srgb, SrgbLuma,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::types::{AnsiMode, TerminalTheme};

const MINECRAFT_COLORS: [(&str, &str); 30] = [
    // Minecraft formatting codes
    // ==========================
    ("&0", "\x1b[38;5;0m"),
    ("&1", "\x1b[38;5;4m"),
    ("&2", "\x1b[38;5;2m"),
    ("&3", "\x1b[38;5;6m"),
    ("&4", "\x1b[38;5;1m"),
    ("&5", "\x1b[38;5;5m"),
    ("&6", "\x1b[38;5;3m"),
    ("&7", "\x1b[38;5;7m"),
    ("&8", "\x1b[38;5;8m"),
    ("&9", "\x1b[38;5;12m"),
    ("&a", "\x1b[38;5;10m"),
    ("&b", "\x1b[38;5;14m"),
    ("&c", "\x1b[38;5;9m"),
    ("&d", "\x1b[38;5;13m"),
    ("&e", "\x1b[38;5;11m"),
    ("&f", "\x1b[38;5;15m"),
    ("&l", "\x1b[1m"), // Enable bold text
    ("&o", "\x1b[3m"), // Enable italic text
    ("&n", "\x1b[4m"), // Enable underlined text
    ("&k", "\x1b[8m"), // Enable hidden text
    ("&m", "\x1b[9m"), // Enable strikethrough text
    ("&r", "\x1b[0m"), // Reset everything
    // Extended codes (not officially in Minecraft)
    // ============================================
    ("&-", "\n"),       // Line break
    ("&~", "\x1b[39m"), // Reset text color
    ("&*", "\x1b[49m"), // Reset background color
    ("&L", "\x1b[22m"), // Disable bold text
    ("&O", "\x1b[23m"), // Disable italic text
    ("&N", "\x1b[24m"), // Disable underlined text
    ("&K", "\x1b[28m"), // Disable hidden text
    ("&M", "\x1b[29m"), // Disable strikethrough text
];
const RGB_COLOR_PATTERNS: [&str; 2] = ["&gf(", "&gb("];

/// See https://github.com/mina86/ansi_colours/blob/b9feefce10def2ac632b215ecd20830a4fca7836/src/ansi256.rs#L109
const ANSI256_GRAYSCALE_COLORS: [u8; 30] = [
    16, 59, 102, 145, 188, 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,
];

static MINECRAFT_COLORS_AC: OnceLock<(AhoCorasick, Box<[&str; 30]>)> = OnceLock::new();
static RGB_COLORS_AC: OnceLock<AhoCorasick> = OnceLock::new();

/// Represents the lightness component in [`Okhsl`].
///
/// The range of valid values is
/// [`Lightness::MIN`]`..=`[`Lightness::MAX`]
///
/// [`Okhsl`]: palette::Okhsl
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct Lightness(f32);

#[derive(Debug, Error)]
pub enum LightnessError {
    #[error(
        "invalid lightness {0}, expected value between {min} and {max}",
        min = Lightness::MIN,
        max = Lightness::MAX
    )]
    OutOfRange(f32),
}

#[derive(Debug, Error)]
pub enum ParseLightnessError {
    #[error("invalid float")]
    InvalidFloat(#[from] ParseFloatError),
    #[error("invalid lightness")]
    InvalidLightness(#[from] LightnessError),
}

/// An indexed color where the color palette is the set of colors used in
/// neofetch ascii art.
///
/// The range of valid values as supported in neofetch is
/// [`NeofetchAsciiIndexedColor::MIN`]`..=`[`NeofetchAsciiIndexedColor::MAX`]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub struct NeofetchAsciiIndexedColor(
    RangedU8<{ NeofetchAsciiIndexedColor::MIN }, { NeofetchAsciiIndexedColor::MAX }>,
);

/// An indexed color where the color palette is the set of unique colors in a
/// preset.
///
/// The range of valid values depends on the number of unique colors in a
/// certain preset.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub struct PresetIndexedColor(u8);

/// Whether the color is for foreground text or background color.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum ForegroundBackground {
    Foreground,
    Background,
}

pub trait ToAnsiString {
    /// Converts RGB to ANSI escape code.
    fn to_ansi_string(&self, mode: AnsiMode, foreground_background: ForegroundBackground)
        -> String;
}

pub trait Theme {
    fn theme(&self) -> TerminalTheme;
}

pub trait ContrastGrayscale {
    /// Calculates the grayscale foreground color which provides the highest
    /// contrast against this background color.
    ///
    /// The returned color is one of the ANSI 256 (8-bit) grayscale colors.
    ///
    /// See <https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg>
    fn contrast_grayscale(&self) -> SrgbLuma<u8>;
}

impl Lightness {
    pub const MAX: f32 = 1.0f32;
    pub const MIN: f32 = 0.0f32;

    pub fn new(value: f32) -> Result<Self, LightnessError> {
        if !(Self::MIN..=Self::MAX).contains(&value) {
            return Err(LightnessError::OutOfRange(value));
        }

        Ok(Self(value))
    }
}

impl TryFrom<f32> for Lightness {
    type Error = LightnessError;

    fn try_from(value: f32) -> Result<Self, Self::Error> {
        Lightness::new(value)
    }
}

impl FromStr for Lightness {
    type Err = ParseLightnessError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Lightness::new(s.parse()?)?)
    }
}

impl From<Lightness> for f32 {
    fn from(value: Lightness) -> Self {
        value.0
    }
}

impl NeofetchAsciiIndexedColor {
    pub const MAX: u8 = 6;
    pub const MIN: u8 = 1;
}

impl TryFrom<u8> for NeofetchAsciiIndexedColor {
    type Error = deranged::TryFromIntError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        Ok(Self(value.try_into()?))
    }
}

impl FromStr for NeofetchAsciiIndexedColor {
    type Err = deranged::ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.parse()?))
    }
}

impl From<NeofetchAsciiIndexedColor> for u8 {
    fn from(value: NeofetchAsciiIndexedColor) -> Self {
        value.0.get()
    }
}

impl From<u8> for PresetIndexedColor {
    fn from(value: u8) -> Self {
        Self(value)
    }
}

impl FromStr for PresetIndexedColor {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(s.parse()?))
    }
}

impl From<PresetIndexedColor> for u8 {
    fn from(value: PresetIndexedColor) -> Self {
        value.0
    }
}

impl ToAnsiString for Srgb<u8> {
    fn to_ansi_string(
        &self,
        mode: AnsiMode,
        foreground_background: ForegroundBackground,
    ) -> String {
        let c: u8 = match foreground_background {
            ForegroundBackground::Foreground => 38,
            ForegroundBackground::Background => 48,
        };
        match mode {
            AnsiMode::Rgb => {
                let [r, g, b]: [u8; 3] = (*self).into();
                format!("\x1b[{c};2;{r};{g};{b}m")
            },
            AnsiMode::Ansi256 => {
                let rgb: [u8; 3] = (*self).into();
                let indexed = rgb.to_ansi256();
                format!("\x1b[{c};5;{indexed}m")
            },
            AnsiMode::Ansi16 => {
                unimplemented!();
            },
        }
    }
}

impl ToAnsiString for SrgbLuma<u8> {
    fn to_ansi_string(
        &self,
        mode: AnsiMode,
        foreground_background: ForegroundBackground,
    ) -> String {
        let c: u8 = match foreground_background {
            ForegroundBackground::Foreground => 38,
            ForegroundBackground::Background => 48,
        };
        match mode {
            AnsiMode::Rgb => {
                let rgb_f32_color: LinSrgb = self.into_linear().into_color();
                let [r, g, b]: [u8; 3] = Srgb::<u8>::from_linear(rgb_f32_color).into();
                format!("\x1b[{c};2;{r};{g};{b}m")
            },
            AnsiMode::Ansi256 => {
                let indexed = ansi256_from_grey(self.luma);
                format!("\x1b[{c};5;{indexed}m")
            },
            AnsiMode::Ansi16 => {
                unimplemented!();
            },
        }
    }
}

impl Theme for Srgb<u8> {
    fn theme(&self) -> TerminalTheme {
        let mut rgb_f32_color: LinSrgb = self.into_linear();

        {
            let okhsl_f32_color: &mut Okhsl = &mut rgb_f32_color.into_color_mut();

            if okhsl_f32_color.lightness > 0.5 {
                TerminalTheme::Light
            } else {
                TerminalTheme::Dark
            }
        }
    }
}

impl ContrastGrayscale for Srgb<u8> {
    fn contrast_grayscale(&self) -> SrgbLuma<u8> {
        let self_lab_f32: Lab = self.into_linear().into_color();

        let mut best_contrast = None;
        for indexed in ANSI256_GRAYSCALE_COLORS {
            let rgb_u8_color: Srgb<u8> = rgb_from_ansi256(indexed).into();
            let lab_f32_color: Lab = rgb_u8_color.into_linear().into_color();
            let diff = lab_f32_color.improved_difference(self_lab_f32);
            best_contrast = match best_contrast {
                Some((_, best_diff)) if diff > best_diff => Some((lab_f32_color, diff)),
                None => Some((lab_f32_color, diff)),
                best => best,
            };
        }
        let (best_lab_f32, _) = best_contrast.expect("`best_contrast` should not be `None`");
        SrgbLuma::from_color(best_lab_f32).into_format()
    }
}

/// Replaces extended minecraft color codes in message.
///
/// Returns message with escape codes.
pub fn color<S>(msg: S, mode: AnsiMode) -> Result<String>
where
    S: AsRef<str>,
{
    let msg = msg.as_ref();

    let msg = {
        let (ac, escape_codes) = MINECRAFT_COLORS_AC.get_or_init(|| {
            let (color_codes, escape_codes): (Vec<_>, Vec<_>) =
                MINECRAFT_COLORS.into_iter().unzip();
            let ac = AhoCorasick::new(color_codes).unwrap();
            (
                ac,
                escape_codes.try_into().expect(
                    "`MINECRAFT_COLORS` should have the same number of elements as \
                     `MINECRAFT_COLORS_AC.get_or_init(...).1`",
                ),
            )
        });
        ac.replace_all(msg, &escape_codes[..])
    };

    let ac = RGB_COLORS_AC.get_or_init(|| AhoCorasick::new(RGB_COLOR_PATTERNS).unwrap());
    let mut dst = String::new();
    let mut ret_err = None;
    ac.replace_all_with(&msg, &mut dst, |m, _, dst| {
        let start = m.end();
        let end = msg[start..]
            .find(')')
            .context("missing closing brace for color code");
        let end = match end {
            Ok(end) => end,
            Err(err) => {
                ret_err = Some(err);
                return false;
            },
        };
        let code = &msg[start..end];
        let foreground_background = if m.pattern().as_usize() == 0 {
            ForegroundBackground::Foreground
        } else {
            ForegroundBackground::Background
        };

        let rgb: Srgb<u8> = if code.starts_with('#') {
            let rgb = code.parse().context("failed to parse hex color");
            match rgb {
                Ok(rgb) => rgb,
                Err(err) => {
                    ret_err = Some(err);
                    return false;
                },
            }
        } else {
            let rgb: Result<[&str; 3], _> = code
                .split(&[',', ';', ' '])
                .filter(|x| x.is_empty())
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| anyhow!("wrong number of rgb components"));
            let rgb = match rgb {
                Ok(rgb) => rgb,
                Err(err) => {
                    ret_err = Some(err);
                    return false;
                },
            };
            let rgb = rgb
                .into_iter()
                .map(u8::from_str)
                .collect::<Result<Vec<_>, _>>()
                .context("failed to parse rgb components");
            let rgb: [u8; 3] = match rgb {
                Ok(rgb) => rgb.try_into().unwrap(),
                Err(err) => {
                    ret_err = Some(err);
                    return false;
                },
            };
            rgb.into()
        };

        dst.push_str(&rgb.to_ansi_string(mode, foreground_background));

        true
    });
    if let Some(err) = ret_err {
        return Err(err);
    }

    Ok(dst)
}

#[macro_export]
macro_rules! printc {
    ($($arg:tt)*) => {
        println!("{}", color(format!("{}&r", format!($($arg)*)), AnsiMode::Rgb).expect("failed to color message"));
    };
}

/// Prints with color.
pub fn printc<S>(msg: S, mode: AnsiMode) -> Result<()>
where
    S: AsRef<str>,
{
    println!("{msg}", msg = color(format!("{msg}&r", msg = msg.as_ref()), mode).context("failed to color message")?);
    Ok(())
}

/// Clears screen using ANSI escape codes.
pub fn clear_screen(title: Option<&str>, mode: AnsiMode, debug_mode: bool) -> Result<()> {
    if !debug_mode {
        write!(io::stdout(), "\x1b[2J\x1b[H")
            .and_then(|_| io::stdout().flush())
            .context("failed to write clear screen sequence to stdout")?;
    }

    if let Some(title) = title {
        printc(format!("\n{title}\n"), mode).context("failed to print title")?;
    }

    Ok(())
}