Skip to main content

embedded_gui/
font.rs

1include!(concat!(env!("OUT_DIR"), "/generated_ascii_3x5.rs"));
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub struct PackedFont {
5    pub first_char: u8,
6    pub advance: u8,
7    pub line_height: u8,
8    pub glyphs: &'static [[u8; 5]],
9}
10
11pub static ASCII_3X5_FONT: PackedFont = PackedFont {
12    first_char: 32,
13    advance: 4,
14    line_height: 6,
15    glyphs: &ASCII_3X5_GLYPHS,
16};
17
18pub static ASCII_4X7_FONT: PackedFont = PackedFont {
19    first_char: 32,
20    advance: 5,
21    line_height: 8,
22    glyphs: &ASCII_4X7_GLYPHS,
23};
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum FontId {
27    Tiny3x5,
28    Medium4x7,
29    Scaled6x10,
30    Custom(&'static PackedFont),
31}
32
33impl FontId {
34    pub const fn advance(self) -> u32 {
35        match self {
36            Self::Tiny3x5 => 4,
37            Self::Medium4x7 => 5,
38            Self::Scaled6x10 => 7,
39            Self::Custom(font) => font.advance as u32,
40        }
41    }
42
43    pub const fn line_height(self) -> u32 {
44        match self {
45            Self::Tiny3x5 => 6,
46            Self::Medium4x7 => 8,
47            Self::Scaled6x10 => 11,
48            Self::Custom(font) => font.line_height as u32,
49        }
50    }
51}
52
53pub const fn packed_font(font: FontId) -> &'static PackedFont {
54    match font {
55        FontId::Tiny3x5 => &ASCII_3X5_FONT,
56        FontId::Medium4x7 => &ASCII_4X7_FONT,
57        FontId::Scaled6x10 => &ASCII_3X5_FONT,
58        FontId::Custom(font) => font,
59    }
60}
61
62pub fn glyph_rows(font: FontId, ch: char) -> [u8; 5] {
63    let packed = packed_font(font);
64    let code = ch as u32;
65    if code >= packed.first_char as u32 {
66        let idx = (code as usize).saturating_sub(packed.first_char as usize);
67        if idx < packed.glyphs.len() {
68            return packed.glyphs[idx];
69        }
70    }
71    let fallback = b'?'.saturating_sub(packed.first_char) as usize;
72    packed.glyphs.get(fallback).copied().unwrap_or([0; 5])
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    static MY_CUSTOM_GLYPHS: [[u8; 5]; 2] = [
80        [0b111, 0b101, 0b111, 0b101, 0b101], // Space / 'A'
81        [0b111, 0b111, 0b111, 0b111, 0b111],
82    ];
83
84    static MY_CUSTOM_FONT: PackedFont = PackedFont {
85        first_char: 32,
86        advance: 8,
87        line_height: 12,
88        glyphs: &MY_CUSTOM_GLYPHS,
89    };
90
91    #[test]
92    fn test_custom_font_id() {
93        let font_id = FontId::Custom(&MY_CUSTOM_FONT);
94        assert_eq!(font_id.advance(), 8);
95        assert_eq!(font_id.line_height(), 12);
96        assert_eq!(packed_font(font_id).first_char, 32);
97        assert_eq!(
98            glyph_rows(font_id, ' '),
99            [0b111, 0b101, 0b111, 0b101, 0b101]
100        );
101    }
102}