gemini_engine/core/colchar/
modifier.rs

1use super::Colour;
2use std::fmt::Display;
3
4/// The [`Modifier`] enum is used for adding modifications to text such as colour, bold/italic/underline and others. `Modifier` should be used through [`ColChar`](super::ColChar).
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub enum Modifier {
7    /// `Coded(u8)` unwraps to `\x1b[{x}m`, where `x` is the code.
8    ///
9    /// For example, `Coded(0)` (available as `Modifier::END`) clears all previously applied modifiers. When displayed, `Modifier::Coded(31)` writes `\x1b[31m`.
10    ///
11    /// See <https://prirai.github.io/blogs/ansi-esc/#colors-graphics-mode> for a guide to available code
12    Coded(u8),
13    /// `Colour(`[`Colour`](Colour)`)` unwraps to `\x1b[38;2;{r};{g};{b}m`, where `(r, g, b)` together represent a 24 bit RGB value
14    ///
15    /// Not all terminals support RGB ANSI escape codes, in which case you will have to resort to `Modifier::Coded` for colours. Some `Coded` colours are available as constants, e.g. [`Modifier::RED`]
16    Colour(Colour),
17    /// `None` unwraps to nothing. It does not change the current applied modifiers.
18    #[default]
19    None,
20}
21
22impl Modifier {
23    /// An END code, which clears all previously applied modifiers. You should never have to use this yourself as `View` makes use of it between pixels where necessary
24    pub const END: Self = Self::Coded(0);
25    /// A red ANSI escape code
26    pub const RED: Self = Self::Coded(31);
27    /// A green ANSI escape code
28    pub const GREEN: Self = Self::Coded(32);
29    /// A yellow ANSI escape code
30    pub const YELLOW: Self = Self::Coded(33);
31    /// A blue ANSI escape code
32    pub const BLUE: Self = Self::Coded(34);
33    /// A purple ANSI escape code
34    pub const PURPLE: Self = Self::Coded(35);
35    /// A cyan ANSI escape code
36    pub const CYAN: Self = Self::Coded(36);
37
38    /// Create a `Modifier::Colour` from an RGB value
39    #[must_use]
40    pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
41        Self::Colour(Colour::rgb(r, g, b))
42    }
43
44    /// Create a `Modifier::Colour` from an HSV value
45    #[must_use]
46    pub fn from_hsv(h: u8, s: u8, v: u8) -> Self {
47        Self::Colour(Colour::hsv(h, s, v))
48    }
49}
50
51impl Display for Modifier {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            Self::Coded(code) => write!(f, "\x1b[{code}m"),
55            Self::Colour(c) => write!(f, "\x1b[38;2;{};{};{}m", c.r, c.g, c.b),
56            Self::None => Ok(()),
57        }
58    }
59}