1use unicode_width::UnicodeWidthChar;
2
3use crate::{Ink, Size};
4
5#[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 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 pub ink: Ink,
35 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#[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 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 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 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 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 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}