xref: /DragonOS/kernel/src/libs/lib_ui/font/mod.rs (revision eb49bb993a39964f92494ec3effafed3fb9adfd8)
1 use super::textui::GlyphMapping;
2 
3 pub mod spleen_font;
4 
5 pub use spleen_font::SPLEEN_FONT_8x16 as FONT_8x16;
6 
7 /// Stores the font bitmap and some additional info for each font.
8 #[derive(Clone, Copy)]
9 pub struct BitmapFont<'a> {
10     /// The raw bitmap data for the font.
11     bitmap: RawBitMap<'a>,
12 
13     /// The char to glyph mapping.
14     glyph_mapping: &'a dyn GlyphMapping,
15 
16     /// The size of each character in the raw bitmap data.
17     size: Size,
18 
19     bytes_per_char: usize,
20 }
21 
22 #[allow(dead_code)]
23 impl<'a> BitmapFont<'a> {
24     pub const fn new(
25         bitmap: RawBitMap<'a>,
26         glyph_mapping: &'a dyn GlyphMapping,
27         size: Size,
28     ) -> Self {
29         Self {
30             bitmap,
31             glyph_mapping,
32             size,
33             bytes_per_char: (size.width + 7) / 8 * size.height,
34         }
35     }
36     /// Return the width of each character.
37     pub const fn width(&self) -> u32 {
38         self.size.width as u32
39     }
40 
41     /// Return the height of each character.
42     pub const fn height(&self) -> u32 {
43         self.size.height as u32
44     }
45 
46     #[inline(always)]
47     pub fn char_map(&self, character: char) -> &'a [u8] {
48         //获得ASCII的index
49         let index = self.glyph_mapping.index(character);
50         let pos = index * self.bytes_per_char;
51 
52         return &self.bitmap.data[pos..pos + self.bytes_per_char];
53     }
54 }
55 
56 #[derive(Clone, Copy)]
57 pub struct Size {
58     pub width: usize,
59     pub height: usize,
60 }
61 
62 impl Size {
63     pub const fn new(width: usize, height: usize) -> Self {
64         Self { width, height }
65     }
66 }
67 
68 #[derive(Clone, Copy)]
69 pub struct RawBitMap<'a> {
70     pub data: &'a [u8],
71     pub size: Size,
72 }
73 
74 #[allow(dead_code)]
75 impl RawBitMap<'_> {
76     pub const fn new(data: &'static [u8], width: usize) -> Self {
77         let size = Size {
78             width: 128,
79             height: data.len() / width / 8,
80         };
81         Self { data, size }
82     }
83 
84     pub const fn size(&self) -> Size {
85         self.size
86     }
87 
88     pub const fn len(&self) -> usize {
89         self.data.len()
90     }
91 }
92