console_display/display/
character_display.rs

1use num_traits::NumCast;
2
3use crate::{
4    console_display::{
5        DynamicConsoleDisplay,
6        StaticConsoleDisplay,
7    },
8    drawing::DynamicCanvas,
9    pixel::{
10        Pixel,
11        character_pixel::{
12            CharacterPixel,
13            CharacterPixelData,
14        },
15    },
16    widget::{
17        DynamicWidget,
18        StaticWidget,
19        StringData,
20    },
21};
22
23pub struct DynamicCharacterDisplay<CharacterPixel> {
24    width: usize,
25    height: usize,
26    data: Box<[CharacterPixel]>,
27}
28
29impl DynamicCharacterDisplay<CharacterPixel> {
30    /// Convenience method to build a blank display struct with specified dimensions
31    ///
32    /// # Panics
33    ///
34    /// This function panics if the data generated from the fill does not match the dimensions of the display.
35    /// This should not happen and is subject to change in the future.
36    #[must_use]
37    pub fn new(width: usize, height: usize, fill: CharacterPixel) -> Self {
38        let character_width = fill.width();
39        let full_columns = width / character_width;
40        let padding = width % character_width;
41        let total_columns = full_columns + padding;
42
43        let mut data: Vec<CharacterPixel> =
44            vec![fill; total_columns * height];
45
46        for i in 0..padding {
47            for y in 0..height {
48                let x = full_columns + i;
49                data[x + y * total_columns] = CharacterPixel::build(' ', fill.foreground(), fill.background())
50                    .expect("Invariant violated. Should not be a control character.");
51            }
52        }
53
54        Self::build_from_data(width, height, &data).expect(
55            "Invariant violated, data does not mach specified dimensions.",
56        )
57    }
58
59    /// Builds a display struct from the given data with the specified dimensions.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error when the length of the data does not match the dimensions of the display.
64    pub fn build_from_data(
65        width: usize,
66        height: usize,
67        data: &[CharacterPixel],
68    ) -> Result<Self, String> {
69        let mut new_data = Vec::with_capacity(data.len());
70        let mut row_length = 0;
71        for i in data {
72            new_data.push(*i);
73            for _ in 1..i.width() {
74                new_data.push(i.make_copy());
75            }
76            row_length += i.width();
77            if row_length > width && row_length - i.width() < width {
78                return Err(
79                    "Data is malformed, character spans multiple rows."
80                        .to_string(),
81                );
82            }
83            if row_length >= width {
84                row_length = 0;
85            }
86        }
87
88        if new_data.len() != width * height {
89            return Err(format!(
90                "Data does not match specified dimensions. Expected length of {}, got {}.",
91                width * height,
92                new_data.len()
93            ));
94        }
95
96        Ok(Self {
97            width,
98            height,
99            data: new_data.into_boxed_slice(),
100        })
101    }
102}
103
104impl DynamicConsoleDisplay<CharacterPixel>
105    for DynamicCharacterDisplay<CharacterPixel>
106{
107    fn width(&self) -> usize {
108        self.width
109    }
110
111    fn height(&self) -> usize {
112        self.height
113    }
114
115    fn data(&self) -> &[CharacterPixel] {
116        &self.data
117    }
118
119    fn data_mut(&mut self) -> &mut Box<[CharacterPixel]> {
120        &mut self.data
121    }
122}
123
124impl DynamicWidget for DynamicCharacterDisplay<CharacterPixel> {
125    fn width_characters(&self) -> usize {
126        self.width / CharacterPixel::WIDTH
127    }
128
129    fn height_characters(&self) -> usize {
130        self.height / CharacterPixel::HEIGHT
131    }
132
133    fn string_data(&self) -> StringData {
134        let mut result = Vec::new();
135        let mut row = Vec::new();
136        let mut width = 0;
137
138        let mut iter = self.data.iter();
139        while let Some(cell) = iter.next() {
140            if width >= self.width_characters() {
141                result.push(row);
142                row = Vec::new();
143                width = 0;
144            }
145
146            if cell.is_copy() {
147                row.push(CharacterPixel::default().into());
148                width += 1;
149                continue;
150            }
151
152            row.push((*cell).into());
153            width += cell.width();
154
155            for _ in 1..cell.width() {
156                iter.next();
157            }
158        }
159
160        if !row.is_empty() {
161            result.push(row);
162        }
163
164        StringData { data: result }
165    }
166}
167
168impl<S: Pixel<U = CharacterPixelData>> DynamicCanvas<S>
169    for DynamicCharacterDisplay<CharacterPixel>
170{
171    type A = usize;
172
173    fn pixel(
174        &self,
175        x: Self::A,
176        y: Self::A,
177    ) -> Result<CharacterPixelData, String>
178    where
179        [(); S::WIDTH * S::HEIGHT]:,
180    {
181        let x: Option<usize> = NumCast::from(x);
182        let y: Option<usize> = NumCast::from(y);
183        if let Some(x) = x &&
184            let Some(y) = y
185        {
186            if x >= self.width() || y >= self.height() {
187                return Err(format!(
188                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
189                ));
190            }
191
192            let block_x: usize = x / S::WIDTH;
193            let block_y: usize = y / S::HEIGHT;
194            let offset_x: usize = x % S::WIDTH;
195            let offset_y: usize = y % S::HEIGHT;
196
197            let pixel =
198                &self.data()[block_x + block_y * self.width_characters()];
199
200            Ok(pixel
201                .subpixel(offset_x, offset_y)
202                .expect("Offset should be 0 or 1."))
203        }
204        else {
205            Err("Coordinates could not be converted to usize.".to_string())
206        }
207    }
208
209    fn set_pixel(
210        &mut self,
211        x: Self::A,
212        y: Self::A,
213        value: S::U,
214    ) -> Result<(), String>
215    where
216        [(); S::WIDTH * S::HEIGHT]:,
217    {
218        let x: Option<usize> = NumCast::from(x);
219        let y: Option<usize> = NumCast::from(y);
220        if let Some(x) = x &&
221            let Some(y) = y
222        {
223            if x >= self.width() || y >= self.height() {
224                return Err(format!(
225                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
226                ));
227            }
228
229            let block_x: usize = x / S::WIDTH;
230            let block_y: usize = y / S::HEIGHT;
231            let offset_x: usize = x % S::WIDTH;
232            let offset_y: usize = y % S::HEIGHT;
233
234            let width_characters = self.width_characters();
235            let pixel =
236                &mut self.data_mut()[block_x + block_y * width_characters];
237            pixel
238                .set_subpixel(offset_x, offset_y, value)
239                .expect("Offset should be 0 or 1.");
240
241            Ok(())
242        }
243        else {
244            Err("Coordinates could not be converted to usize.".to_string())
245        }
246    }
247}
248
249#[derive(Clone)]
250pub struct StaticCharacterDisplay<
251    CharacterPixel,
252    const WIDTH: usize,
253    const HEIGHT: usize,
254> {
255    data: Box<[CharacterPixel]>,
256}
257
258impl<const WIDTH: usize, const HEIGHT: usize>
259    StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
260{
261    /// Convenience method to build a blank display struct with specified dimensions
262    ///
263    /// # Panics
264    ///
265    /// This function panics if the data generated from the fill does not match the dimensions of the display.
266    /// This should not happen and is subject to change in the future.
267    #[must_use]
268    pub fn new(fill: CharacterPixel) -> Self
269    where
270        [(); WIDTH * HEIGHT]:,
271    {
272        let character_width = fill.width();
273        let full_columns = WIDTH / character_width;
274        let padding = WIDTH % character_width;
275        let total_columns = full_columns + padding;
276
277        let mut data: Vec<CharacterPixel> =
278            vec![fill; total_columns * HEIGHT];
279
280        for i in 0..padding {
281            for y in 0..HEIGHT {
282                let x = full_columns + i;
283                data[x + y * total_columns] = CharacterPixel::build(' ', fill.foreground(), fill.background())
284                    .expect("Invariant violated. Should not be a control character.");
285            }
286        }
287
288        Self::build_from_data(&data).expect(
289            "Invariant violated, data does not mach specified dimensions.",
290        )
291    }
292
293    /// Builds a display struct with the specified dimensions from the given data.
294    ///
295    /// # Errors
296    /// Returns an error when the data length does not match the dimensions of the display.
297    /// This also applies if double-width characters, like あ, are used and exceed the dimensions of the display.
298    pub fn build_from_data(
299        data: &[CharacterPixel],
300    ) -> Result<Self, String> {
301        let mut new_data = Vec::with_capacity(data.len());
302        let mut row_length = 0;
303        for i in data {
304            new_data.push(*i);
305            for _ in 1..i.width() {
306                new_data.push(i.make_copy());
307            }
308            row_length += i.width();
309            if row_length > WIDTH && row_length - i.width() < WIDTH {
310                return Err(
311                    "Data is malformed, character spans multiple rows."
312                        .to_string(),
313                );
314            }
315            if row_length >= WIDTH {
316                row_length = 0;
317            }
318        }
319
320        if new_data.len() != WIDTH * HEIGHT {
321            return Err(format!(
322                "Data does not match specified dimensions. Expected length of {}, got {}.",
323                WIDTH * HEIGHT,
324                new_data.len()
325            ));
326        }
327
328        Ok(Self {
329            data: new_data.into_boxed_slice(),
330        })
331    }
332}
333
334impl<const WIDTH: usize, const HEIGHT: usize>
335    StaticConsoleDisplay<CharacterPixel>
336    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
337{
338    const WIDTH: usize = WIDTH;
339
340    const HEIGHT: usize = HEIGHT;
341}
342
343impl<const WIDTH: usize, const HEIGHT: usize>
344    DynamicConsoleDisplay<CharacterPixel>
345    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
346{
347    fn width(&self) -> usize {
348        WIDTH
349    }
350
351    fn height(&self) -> usize {
352        HEIGHT
353    }
354
355    fn data(&self) -> &[CharacterPixel] {
356        &self.data
357    }
358
359    fn data_mut(&mut self) -> &mut Box<[CharacterPixel]> {
360        &mut self.data
361    }
362}
363
364impl<const WIDTH: usize, const HEIGHT: usize> DynamicWidget
365    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
366{
367    fn width_characters(&self) -> usize {
368        WIDTH
369    }
370
371    fn height_characters(&self) -> usize {
372        HEIGHT
373    }
374
375    fn string_data(&self) -> StringData {
376        let mut result = Vec::new();
377        let mut row = Vec::new();
378        let mut width = 0;
379
380        let mut iter = self.data.iter();
381        while let Some(cell) = iter.next() {
382            if width >= Self::WIDTH_CHARACTERS {
383                result.push(row);
384                row = Vec::new();
385                width = 0;
386            }
387
388            if cell.is_copy() {
389                row.push(CharacterPixel::default().into());
390                width += 1;
391                continue;
392            }
393
394            row.push((*cell).into());
395            width += cell.width();
396
397            for _ in 1..cell.width() {
398                iter.next();
399            }
400        }
401
402        if !row.is_empty() {
403            result.push(row);
404        }
405
406        StringData { data: result }
407    }
408}
409
410impl<const WIDTH: usize, const HEIGHT: usize> const StaticWidget
411    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
412{
413    const WIDTH_CHARACTERS: usize = WIDTH;
414
415    const HEIGHT_CHARACTERS: usize = HEIGHT;
416}
417
418impl<const WIDTH: usize, const HEIGHT: usize> DynamicCanvas<CharacterPixel>
419    for StaticCharacterDisplay<CharacterPixel, WIDTH, HEIGHT>
420{
421    type A = usize;
422
423    fn pixel(
424        &self,
425        x: Self::A,
426        y: Self::A,
427    ) -> Result<CharacterPixelData, String>
428    where
429        [(); CharacterPixel::WIDTH * CharacterPixel::HEIGHT]:,
430    {
431        let x: Option<usize> = NumCast::from(x);
432        let y: Option<usize> = NumCast::from(y);
433        if let Some(x) = x &&
434            let Some(y) = y
435        {
436            if x >= self.width() || y >= self.height() {
437                return Err(format!(
438                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
439                ));
440            }
441
442            let block_x: usize = x / CharacterPixel::WIDTH;
443            let block_y: usize = y / CharacterPixel::HEIGHT;
444
445            let pixel =
446                &self.data()[block_x + block_y * self.width_characters()];
447
448            Ok(pixel.subpixel(0, 0).expect("Offset should be 0."))
449        }
450        else {
451            Err("Coordinates could not be converted to usize.".to_string())
452        }
453    }
454
455    fn set_pixel(
456        &mut self,
457        x: Self::A,
458        y: Self::A,
459        value: CharacterPixelData,
460    ) -> Result<(), String>
461    where
462        [(); CharacterPixel::WIDTH * CharacterPixel::HEIGHT]:,
463    {
464        let x: Option<usize> = NumCast::from(x);
465        let y: Option<usize> = NumCast::from(y);
466        if let Some(x) = x &&
467            let Some(y) = y
468        {
469            if x >= self.width() || y >= self.height() {
470                return Err(format!(
471                    "Pixel coordinates out of bounds. Got x = {x}, y = {y}."
472                ));
473            }
474
475            let block_x: usize = x / CharacterPixel::WIDTH;
476            let block_y: usize = y / CharacterPixel::HEIGHT;
477
478            let width_characters = self.width_characters();
479            let pixel =
480                &mut self.data_mut()[block_x + block_y * width_characters];
481            pixel
482                .set_subpixel(0, 0, value)
483                .expect("Offset should be 0.");
484
485            Ok(())
486        }
487        else {
488            Err("Coordinates could not be converted to usize.".to_string())
489        }
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    use crate::color::TerminalColor;
496
497    use super::*;
498
499    #[test]
500    fn build_from_data_success() {
501        let character_display = StaticCharacterDisplay::<
502            CharacterPixel,
503            1,
504            1,
505        >::build_from_data(&[
506            CharacterPixel::build(
507                ' ',
508                TerminalColor::Default,
509                TerminalColor::Default,
510            )
511            .unwrap(),
512        ]);
513        assert!(character_display.is_ok());
514    }
515
516    #[test]
517    fn build_from_data_failure_dimensions() {
518        let character_display = StaticCharacterDisplay::<
519            CharacterPixel,
520            8,
521            10,
522        >::build_from_data(&vec![
523                    CharacterPixel::build(
524                        ' ',
525                        TerminalColor::Default,
526                        TerminalColor::Default,
527                    )
528                    .unwrap();
529                    8 * 10 - 1
530                ]);
531        assert!(character_display.is_err());
532    }
533
534    #[test]
535    fn build_from_data_failure_fit() {
536        let character_display = StaticCharacterDisplay::<
537            CharacterPixel,
538            9,
539            10,
540        >::build_from_data(&vec![
541                    CharacterPixel::build(
542                        'あ',
543                        TerminalColor::Default,
544                        TerminalColor::Default,
545                    )
546                    .unwrap();
547                    9 * 10 / 2
548                ]);
549        assert!(character_display.is_err());
550    }
551}