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(crate) 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 /// The distance from the baseline to the top of the highest glyph
51 pub fn ascender(&self) -> f32 {
52 self.ascender
53 }
54
55 /// 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 pub fn height(&self) -> f32 {
61 self.height.round()
62 }
63
64 pub fn regular(&self) -> bool {
65 self.regular
66 }
67
68 pub fn italic(&self) -> bool {
69 self.italic
70 }
71
72 pub fn bold(&self) -> bool {
73 self.bold
74 }
75
76 pub fn oblique(&self) -> bool {
77 self.oblique
78 }
79
80 pub fn variable(&self) -> bool {
81 self.variable
82 }
83
84 pub fn weight(&self) -> u16 {
85 self.weight
86 }
87
88 pub fn width(&self) -> u16 {
89 self.width
90 }
91}
92
93pub(crate) struct Font {
94 data: Box<dyn AsRef<[u8]>>,
95 face_index: u32,
96 units_per_em: u16,
97 metrics: FontMetrics,
98 glyphs: RefCell<FnvHashMap<u16, Glyph>>,
99}
100
101impl Font {
102 pub fn new_with_data<T: AsRef<[u8]> + 'static>(data: T, face_index: u32) -> Result<Self, ErrorKind> {
103 let ttf_font = TtfFont::parse(data.as_ref(), face_index).map_err(|_| ErrorKind::FontParseError)?;
104
105 let units_per_em = ttf_font.units_per_em();
106
107 let metrics = FontMetrics {
108 ascender: ttf_font.ascender() as f32,
109 descender: ttf_font.descender() as f32,
110 height: ttf_font.height() as f32,
111 regular: ttf_font.is_regular(),
112 italic: ttf_font.is_italic(),
113 bold: ttf_font.is_bold(),
114 oblique: ttf_font.is_oblique(),
115 variable: ttf_font.is_variable(),
116 width: ttf_font.width().to_number(),
117 weight: ttf_font.weight().to_number(),
118 };
119
120 Ok(Self {
121 data: Box::new(data),
122 face_index,
123 units_per_em,
124 metrics,
125 glyphs: Default::default(),
126 })
127 }
128
129 pub fn face_ref(&self) -> rustybuzz::Face<'_> {
130 rustybuzz::Face::from_slice(self.data.as_ref().as_ref(), self.face_index).unwrap()
131 }
132
133 pub fn metrics(&self, size: f32) -> FontMetrics {
134 let mut metrics = self.metrics;
135
136 metrics.scale(self.scale(size));
137
138 metrics
139 }
140
141 pub fn scale(&self, size: f32) -> f32 {
142 size / self.units_per_em as f32
143 }
144
145 pub fn glyph(&self, face: &rustybuzz::Face<'_>, codepoint: u16) -> Option<Ref<'_, Glyph>> {
146 if let Entry::Vacant(entry) = self.glyphs.borrow_mut().entry(codepoint) {
147 let mut path = Path::new();
148
149 let id = GlyphId(codepoint);
150
151 let maybe_glyph = if let Some(image) = face
152 .glyph_raster_image(id, std::u16::MAX)
153 .filter(|img| img.format == ttf_parser::RasterImageFormat::PNG)
154 {
155 let scale = if image.pixels_per_em != 0 {
156 self.units_per_em as f32 / image.pixels_per_em as f32
157 } else {
158 1.0
159 };
160 Some(Glyph {
161 path: None,
162 metrics: GlyphMetrics {
163 width: image.width as f32 * scale,
164 height: image.height as f32 * scale,
165 bearing_x: image.x as f32 * scale,
166 bearing_y: (image.y as f32 + image.height as f32) * scale,
167 },
168 })
169 } else {
170 face.outline_glyph(id, &mut path).map(|bbox| Glyph {
171 path: Some(path),
172 metrics: GlyphMetrics {
173 width: bbox.width() as f32,
174 height: bbox.height() as f32,
175 bearing_x: bbox.x_min as f32,
176 bearing_y: bbox.y_max as f32,
177 },
178 })
179 };
180
181 if let Some(glyph) = maybe_glyph {
182 entry.insert(glyph);
183 }
184 }
185
186 Ref::filter_map(self.glyphs.borrow(), |glyphs| glyphs.get(&codepoint)).ok()
187 }
188
189 pub fn glyph_rendering_representation(
190 &self,
191 face: &rustybuzz::Face<'_>,
192 codepoint: u16,
193 _pixels_per_em: u16,
194 ) -> Option<GlyphRendering> {
195 #[cfg(feature = "image-loading")]
196 if let Some(image) =
197 face.glyph_raster_image(GlyphId(codepoint), _pixels_per_em)
198 .and_then(|raster_glyph_image| {
199 image::load_from_memory_with_format(raster_glyph_image.data, image::ImageFormat::Png).ok()
200 })
201 {
202 return Some(GlyphRendering::RenderAsImage(image));
203 };
204
205 self.glyph(face, codepoint).and_then(|glyph| {
206 Ref::filter_map(glyph, |glyph| glyph.path.as_ref())
207 .ok()
208 .map(GlyphRendering::RenderAsPath)
209 })
210 }
211}
212