Skip to main content

sciart_core/
canvas.rs

1use unicode_width::UnicodeWidthChar;
2
3use crate::{Ink, Size};
4
5/// A glyph with a pure-ASCII fallback (GEN-R10).
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct Glyph {
8    pub unicode: char,
9    pub ascii: char,
10}
11
12impl Glyph {
13    pub const fn new(unicode: char, ascii: char) -> Self {
14        Self { unicode, ascii }
15    }
16
17    /// A glyph that is already ASCII in both modes.
18    pub const fn ascii(ch: char) -> Self {
19        Self::new(ch, ch)
20    }
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum GlyphMode {
25    #[default]
26    Unicode,
27    Ascii,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct Cell {
32    pub ch: char,
33    /// Foreground ink of `ch`.
34    pub ink: Ink,
35    /// Background ink; [`Ink::BLANK`] means "no background" (terminal default). Only
36    /// half-block pixels set it (CORE-R40, ADR-0010).
37    pub bg: Ink,
38}
39
40impl Cell {
41    pub const BLANK: Cell = Cell {
42        ch: ' ',
43        ink: Ink::BLANK,
44        bg: Ink::BLANK,
45    };
46}
47
48/// A row-major grid of cells that generators draw into.
49#[derive(Debug, Clone)]
50pub struct Canvas {
51    size: Size,
52    mode: GlyphMode,
53    cells: Vec<Cell>,
54}
55
56impl Canvas {
57    pub fn new(size: Size, mode: GlyphMode) -> Self {
58        Self {
59            size,
60            mode,
61            cells: vec![Cell::BLANK; size.area()],
62        }
63    }
64
65    pub fn size(&self) -> Size {
66        self.size
67    }
68
69    pub fn mode(&self) -> GlyphMode {
70        self.mode
71    }
72
73    pub fn set_mode(&mut self, mode: GlyphMode) {
74        self.mode = mode;
75    }
76
77    pub fn cells(&self) -> &[Cell] {
78        &self.cells
79    }
80
81    /// Reallocate only when the size actually changes; always leaves a blank canvas (CORE-R5).
82    pub fn resize(&mut self, size: Size) {
83        if size != self.size {
84            self.size = size;
85            self.cells = vec![Cell::BLANK; size.area()];
86        } else {
87            self.clear();
88        }
89    }
90
91    pub fn clear(&mut self) {
92        self.cells.fill(Cell::BLANK);
93    }
94
95    fn index(&self, x: i32, y: i32) -> Option<usize> {
96        let (w, h) = (i32::from(self.size.width()), i32::from(self.size.height()));
97        ((0..w).contains(&x) && (0..h).contains(&y))
98            .then(|| y as usize * usize::from(self.size.width()) + x as usize)
99    }
100
101    pub fn get(&self, x: i32, y: i32) -> Option<&Cell> {
102        self.index(x, y).map(|i| &self.cells[i])
103    }
104
105    /// Draw one glyph; out-of-bounds coordinates are ignored (CORE-R3, CORE-R4).
106    ///
107    /// Clears the cell's background, so overdrawing a half-block pixel never leaves a
108    /// stale background colour behind (CORE-R40).
109    pub fn put(&mut self, x: i32, y: i32, glyph: Glyph, ink: Ink) {
110        self.put_bg(x, y, glyph, ink, Ink::BLANK);
111    }
112
113    /// Draw one glyph with a foreground and a background ink, under the same bounds
114    /// and glyph-mode rules as [`put`](Self::put) (CORE-R40).
115    pub fn put_bg(&mut self, x: i32, y: i32, glyph: Glyph, fg: Ink, bg: Ink) {
116        let Some(i) = self.index(x, y) else { return };
117        let ch = match self.mode {
118            GlyphMode::Ascii => glyph.ascii,
119            GlyphMode::Unicode if glyph.unicode.width() == Some(1) => glyph.unicode,
120            GlyphMode::Unicode => glyph.ascii,
121        };
122        self.cells[i] = Cell { ch, ink: fg, bg };
123    }
124
125    /// Draw a string left-to-right; each char is its own ASCII fallback.
126    pub fn text(&mut self, x: i32, y: i32, s: &str, ink: Ink) {
127        for (i, ch) in s.chars().enumerate() {
128            self.put(x.saturating_add(i as i32), y, Glyph::ascii(ch), ink);
129        }
130    }
131
132    /// Exactly `height` lines of exactly `width` chars (CORE-R6).
133    pub fn to_lines(&self) -> Vec<String> {
134        self.cells
135            .chunks(usize::from(self.size.width()))
136            .map(|row| row.iter().map(|c| c.ch).collect())
137            .collect()
138    }
139}