1use fnv::FnvHashMap;
2use rustybuzz::ttf_parser;
3use rustybuzz::ttf_parser::{Face as TtfFont, GlyphId};
4use std::cell::{Ref, RefCell};
5use std::collections::hash_map::Entry;
6
7use crate::{ErrorKind, Path};
8
9pub struct GlyphMetrics {
10 pub width: f32,
11 pub height: f32,
12 pub bearing_x: f32,
13 pub bearing_y: f32,
14}
15
16pub struct Glyph {
17 pub path: Option<Path>, // None means render as image
18 pub metrics: GlyphMetrics,
19}
20
21pub enum GlyphRendering<'a> {
22 RenderAsPath(Ref<'a, Path>),
23 #[cfg(feature = "image-loading")]
24 RenderAsImage(image::DynamicImage),
25}
26
27/// Information about a font.
28// TODO: underline, strikeout, subscript, superscript metrics
29#[derive(Copy, Clone, Default, Debug)]
30pub struct FontMetrics {
31 ascender: f32,
32 descender: f32,
33 height: f32,
34 regular: bool,
35 italic: bool,
36 bold: bool,
37 oblique: bool,
38 variable: bool,
39 weight: u16,
40 width: u16,
41}
42
43impl FontMetrics {
44 fn scale(&mut self, scale: f32) {
45 self.ascender *= scale;
46 self.descender *= scale;
47 self.height *= scale;
48 }
49
50 /// Returns the distance from the baseline to the top of the highest glyph.
51 pub fn ascender(&self) -> f32 {
52 self.ascender
53 }
54
55 /// Returns the distance from the baseline to the bottom of the lowest descenders on the glyphs.
56 pub fn descender(&self) -> f32 {
57 self.descender
58 }
59
60 /// Returns the height of the font.
61 pub fn height(&self) -> f32 {
62 self.height.round()
63 }
64
65 /// Returns if the font is regular.
66 pub fn regular(&self) -> bool {
67 self.regular
68 }
69
70 /// Returns if the font is italic.
71 pub fn italic(&self) -> bool {
72 self.italic
73 }
74
75 /// Returns if the font is bold.
76 pub fn bold(&self) -> bool {
77 self.bold
78 }
79
80 /// Returns if the font is oblique.
81 pub fn oblique(&self) -> bool {
82 self.oblique
83 }
84
85 /// Returns if the font is a variable font.
86 pub fn variable(&self) -> bool {
87 self.variable
88 }
89
90 /// Returns the weight of the font.
91 pub fn weight(&self) -> u16 {
92 self.weight
93 }
94
95 /// Returns the width of the font.
96 pub fn width(&self) -> u16 {
97 self.width
98 }
99}
100
101pub struct Font {
102 data: Box<dyn AsRef<[u8]>>,
103 face_index: u32,
104 units_per_em: u16,
105 metrics: FontMetrics,
106 glyphs: RefCell<FnvHashMap<u16, Glyph>>,
107}
108
109impl Font {
110 pub fn new_with_data<T: AsRef<[u8]> + 'static>(data: T, face_index: u32) -> Result<Self, ErrorKind> {
111 let ttf_font = TtfFont::parse(data.as_ref(), face_index).map_err(|_| ErrorKind::FontParseError)?;
112
113 let units_per_em = ttf_font.units_per_em();
114
115 let metrics = FontMetrics {
116 ascender: ttf_font.ascender() as f32,
117 descender: ttf_font.descender() as f32,
118 height: ttf_font.height() as f32,
119 regular: ttf_font.is_regular(),
120 italic: ttf_font.is_italic(),
121 bold: ttf_font.is_bold(),
122 oblique: ttf_font.is_oblique(),
123 variable: ttf_font.is_variable(),
124 width: ttf_font.width().to_number(),
125 weight: ttf_font.weight().to_number(),
126 };
127
128 Ok(Self {
129 data: Box::new(data),
130 face_index,
131 units_per_em,
132 metrics,
133 glyphs: Default::default(),
134 })
135 }
136
137 pub fn face_ref(&self) -> rustybuzz::Face<'_> {
138 rustybuzz::Face::from_slice(self.data.as_ref().as_ref(), self.face_index).unwrap()
139 }
140
141 pub fn metrics(&self, size: f32) -> FontMetrics {
142 let mut metrics = self.metrics;
143
144 metrics.scale(self.scale(size));
145
146 metrics
147 }
148
149 pub fn scale(&self, size: f32) -> f32 {
150 size / self.units_per_em as f32
151 }
152
153 pub fn glyph(&self, face: &rustybuzz::Face<'_>, codepoint: u16) -> Option<Ref<'_, Glyph>> {
154 if let Entry::Vacant(entry) = self.glyphs.borrow_mut().entry(codepoint) {
155 let mut path = Path::new();
156
157 let id = GlyphId(codepoint);
158
159 let maybe_glyph = if let Some(image) = face
160 .glyph_raster_image(id, u16::MAX)
161 .filter(|img| img.format == ttf_parser::RasterImageFormat::PNG)
162 {
163 let scale = if image.pixels_per_em != 0 {
164 self.units_per_em as f32 / image.pixels_per_em as f32
165 } else {
166 1.0
167 };
168 Some(Glyph {
169 path: None,
170 metrics: GlyphMetrics {
171 width: image.width as f32 * scale,
172 height: image.height as f32 * scale,
173 bearing_x: image.x as f32 * scale,
174 bearing_y: (image.y as f32 + image.height as f32) * scale,
175 },
176 })
177 } else {
178 face.outline_glyph(id, &mut path).map(|bbox| Glyph {
179 path: Some(path),
180 metrics: GlyphMetrics {
181 width: bbox.width() as f32,
182 height: bbox.height() as f32,
183 bearing_x: bbox.x_min as f32,
184 bearing_y: bbox.y_max as f32,
185 },
186 })
187 };
188
189 if let Some(glyph) = maybe_glyph {
190 entry.insert(glyph);
191 }
192 }
193
194 Ref::filter_map(self.glyphs.borrow(), |glyphs| glyphs.get(&codepoint)).ok()
195 }
196
197 pub fn glyph_rendering_representation(
198 &self,
199 face: &rustybuzz::Face<'_>,
200 codepoint: u16,
201 #[allow(unused_variables)] pixels_per_em: u16,
202 ) -> Option<GlyphRendering> {
203 #[cfg(feature = "image-loading")]
204 if let Some(image) = face
205 .glyph_raster_image(GlyphId(codepoint), pixels_per_em)
206 .and_then(|raster_glyph_image| {
207 image::load_from_memory_with_format(raster_glyph_image.data, image::ImageFormat::Png).ok()
208 })
209 {
210 return Some(GlyphRendering::RenderAsImage(image));
211 };
212
213 self.glyph(face, codepoint).and_then(|glyph| {
214 Ref::filter_map(glyph, |glyph| glyph.path.as_ref())
215 .ok()
216 .map(GlyphRendering::RenderAsPath)
217 })
218 }
219}
220