console_display/pixel/
character_pixel.rs

1use std::fmt::{
2    Debug,
3    Display,
4};
5
6use crate::{
7    constraint,
8    or,
9    pixel::Pixel,
10    widget::DataCell,
11};
12
13use crate::color::{
14    Color,
15    TerminalColor,
16};
17use unicode_width::UnicodeWidthChar;
18
19#[derive(Clone, Copy, Default)]
20pub struct CharacterPixel {
21    data: [CharacterPixelData; 1],
22}
23
24#[derive(Clone, Copy)]
25pub struct CharacterPixelData {
26    character: char,
27    foreground: TerminalColor,
28    background: TerminalColor,
29    copy: bool,
30    width: usize,
31}
32
33impl From<CharacterPixel> for CharacterPixelData {
34    fn from(value: CharacterPixel) -> Self {
35        value.data[0]
36    }
37}
38
39impl Pixel for CharacterPixel {
40    type U = CharacterPixelData;
41
42    const WIDTH: usize = 1;
43
44    const HEIGHT: usize = 1;
45
46    fn pixels(&self) -> &[Self::U; Self::WIDTH * Self::HEIGHT] {
47        &self.data
48    }
49
50    fn pixels_mut(
51        &mut self,
52    ) -> &mut [Self::U; Self::WIDTH * Self::HEIGHT] {
53        &mut self.data
54    }
55
56    fn new(pixels: [Self::U; Self::WIDTH * Self::HEIGHT]) -> Self {
57        Self { data: pixels }
58    }
59}
60
61impl From<CharacterPixel> for DataCell {
62    fn from(val: CharacterPixel) -> Self {
63        Self {
64            character: val.character(),
65            foreground: val.foreground(),
66            background: val.background(),
67        }
68    }
69}
70
71impl CharacterPixel {
72    /// Constructs a character pixel from a char, a foreground and a background color.
73    ///
74    /// # Panics
75    ///
76    /// This function checks for control characters at compile time.
77    /// Panics when the compile time checks miss a control character.
78    /// This should not happen and is a implementation detail that is subject to change.
79    #[must_use]
80    pub fn new<const CHARACTER: char>(
81        foreground: TerminalColor,
82        background: TerminalColor,
83    ) -> Self
84    where
85        constraint!(CHARACTER >= '\u{20}'):, // Exclude C0 control chars
86        constraint!(or!(CHARACTER < '\u{7F}', CHARACTER >= '\u{A0}')):, // Exclude C1 control chars
87    {
88        Self {
89            data: [CharacterPixelData {
90                character: CHARACTER,
91                foreground,
92                background,
93                copy: false,
94                width: UnicodeWidthChar::width(CHARACTER).expect(
95                    "Invariant violated, found control character.",
96                ),
97            }],
98        }
99    }
100
101    /// Constructs a character pixel from a char, a foreground and a background color.
102    ///
103    /// # Errors
104    ///
105    /// Returns an error if the character is a control character.
106    pub fn build(
107        character: char,
108        foreground: TerminalColor,
109        background: TerminalColor,
110    ) -> Result<Self, String> {
111        Ok(Self {
112            data: [CharacterPixelData {
113                character,
114                foreground,
115                background,
116                copy: false,
117                width: match UnicodeWidthChar::width(character) {
118                    Some(val) => val,
119                    None => {
120                        return Err("Control characters are not allowed."
121                            .to_string());
122                    }
123                },
124            }],
125        })
126    }
127
128    #[must_use]
129    pub const fn make_copy(&self) -> Self {
130        let mut clone = *self;
131        clone.set_copy(true);
132        clone
133    }
134
135    #[must_use]
136    pub const fn character(&self) -> char {
137        self.data[0].character
138    }
139
140    #[must_use]
141    pub const fn foreground(&self) -> TerminalColor {
142        self.data[0].foreground
143    }
144
145    #[must_use]
146    pub const fn background(&self) -> TerminalColor {
147        self.data[0].background
148    }
149
150    #[must_use]
151    pub const fn is_copy(&self) -> bool {
152        self.data[0].copy
153    }
154
155    const fn set_copy(&mut self, copy: bool) {
156        self.data[0].copy = copy;
157    }
158
159    #[must_use]
160    pub const fn width(&self) -> usize {
161        self.data[0].width
162    }
163}
164
165impl Display for CharacterPixel {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        write!(
168            f,
169            "{}",
170            TerminalColor::color(
171                self.character().to_string().as_str(),
172                &self.foreground(),
173                &self.background()
174            )
175        )
176    }
177}
178
179impl Debug for CharacterPixel {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        write!(f, "{}", &self.character())
182    }
183}
184
185impl TryFrom<char> for CharacterPixel {
186    type Error = String;
187
188    fn try_from(value: char) -> Result<Self, Self::Error> {
189        Self::build(value, TerminalColor::Default, TerminalColor::Default)
190    }
191}
192
193impl Default for CharacterPixelData {
194    fn default() -> Self {
195        Self {
196            character: ' ',
197            foreground: TerminalColor::default(),
198            background: TerminalColor::default(),
199            copy: false,
200            width: 1,
201        }
202    }
203}