1#![forbid(unsafe_code)]
13
14use std::collections::HashMap;
15use std::fmt;
16
17use ab_glyph::{Font, FontArc, FontVec, GlyphId, PxScale, ScaleFont, point};
18
19pub const BUNDLED_FONT: &[u8] = include_bytes!("../assets/fonts/JetBrainsMono-Regular-subset.ttf");
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum FontError {
37 Invalid,
39 TooManyFonts,
41}
42
43impl fmt::Display for FontError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 Self::Invalid => f.write_str("invalid font data"),
47 Self::TooManyFonts => f.write_str("too many fonts"),
48 }
49 }
50}
51
52impl std::error::Error for FontError {}
53
54#[derive(Clone, Copy, Debug, PartialEq)]
57pub struct LineMetrics {
58 pub ascent: f32,
60 pub descent: f32,
62 pub line_gap: f32,
64}
65
66impl LineMetrics {
67 pub fn height(self) -> f32 {
69 self.ascent + self.descent + self.line_gap
70 }
71
72 fn scaled(self, size: f32) -> Self {
73 Self {
74 ascent: self.ascent * size,
75 descent: self.descent * size,
76 line_gap: self.line_gap * size,
77 }
78 }
79}
80
81struct LoadedFont {
82 font: FontArc,
83 advances: [f32; 128],
85 subscripts: [f32; 10],
87 metrics: LineMetrics,
89}
90
91impl LoadedFont {
92 fn new(font: FontArc) -> Self {
93 let em = em_scale(&font, 1.0);
96 let scaled = font.as_scaled(em);
97 let mut advances = [0.0; 128];
98 for (c, adv) in (0_u8..128).zip(advances.iter_mut()) {
99 *adv = scaled.h_advance(font.glyph_id(char::from(c)));
100 }
101 let mut subscripts = [0.0; 10];
102 for (c, adv) in ('\u{2080}'..='\u{2089}').zip(subscripts.iter_mut()) {
103 *adv = scaled.h_advance(font.glyph_id(c));
104 }
105 let metrics = LineMetrics {
106 ascent: scaled.ascent(),
107 descent: -scaled.descent(),
108 line_gap: scaled.line_gap(),
109 };
110 Self {
111 font,
112 advances,
113 subscripts,
114 metrics,
115 }
116 }
117}
118
119fn subscript_digit(c: char) -> Option<usize> {
121 ('\u{2080}'..='\u{2089}')
122 .contains(&c)
123 .then(|| c as usize - 0x2080)
124}
125
126fn em_scale(font: &FontArc, size: f32) -> PxScale {
128 let upem = font.units_per_em().unwrap_or(1000.0);
129 let height = font.height_unscaled();
130 if height > 0.0 {
131 PxScale::from(size * height / upem)
132 } else {
133 PxScale::from(size)
134 }
135}
136
137#[derive(Clone, Debug, PartialEq)]
139pub struct GlyphBitmap {
140 pub width: u32,
142 pub height: u32,
144 pub left: i32,
146 pub top: i32,
148 pub coverage: Vec<u8>,
150}
151
152pub struct TextEngine {
167 fonts: Vec<LoadedFont>,
168}
169
170impl Default for TextEngine {
171 fn default() -> Self {
172 Self::new()
173 }
174}
175
176impl fmt::Debug for TextEngine {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.debug_struct("TextEngine")
179 .field("fonts", &self.fonts.len())
180 .finish()
181 }
182}
183
184impl TextEngine {
185 pub fn new() -> Self {
187 let fonts = ab_glyph::FontRef::try_from_slice(BUNDLED_FONT)
188 .map(|f| vec![LoadedFont::new(FontArc::new(f))])
189 .unwrap_or_default();
190 Self { fonts }
191 }
192
193 pub fn add_font(&mut self, data: Vec<u8>) -> Result<u16, FontError> {
200 let id = u16::try_from(self.fonts.len()).map_err(|_| FontError::TooManyFonts)?;
201 let font = FontVec::try_from_vec(data).map_err(|_| FontError::Invalid)?;
202 self.fonts.push(LoadedFont::new(FontArc::new(font)));
203 Ok(id)
204 }
205
206 pub fn font_count(&self) -> usize {
208 self.fonts.len()
209 }
210
211 fn font(&self, id: u16) -> Option<&LoadedFont> {
213 self.fonts
214 .get(usize::from(id))
215 .or_else(|| self.fonts.first())
216 }
217
218 pub fn ascii_advances(&self, id: u16) -> &[f32; 128] {
220 static ZERO: [f32; 128] = [0.0; 128];
221 self.font(id).map_or(&ZERO, |f| &f.advances)
222 }
223
224 pub fn subscript_advances(&self, id: u16) -> &[f32; 10] {
227 static ZERO: [f32; 10] = [0.0; 10];
228 self.font(id).map_or(&ZERO, |f| &f.subscripts)
229 }
230
231 pub fn line_metrics(&self, id: u16, size: f32) -> LineMetrics {
233 self.font(id).map_or(
234 LineMetrics {
235 ascent: size,
236 descent: 0.0,
237 line_gap: 0.0,
238 },
239 |f| f.metrics.scaled(size),
240 )
241 }
242
243 pub fn advance(&self, id: u16, c: char, size: f32) -> f32 {
245 let Some(f) = self.font(id) else {
246 return 0.0;
247 };
248 if c.is_ascii() {
249 return f.advances[usize::from(c as u8)] * size;
250 }
251 if let Some(d) = subscript_digit(c) {
252 return f.subscripts[d] * size;
253 }
254 let scaled = f.font.as_scaled(em_scale(&f.font, size));
255 scaled.h_advance(f.font.glyph_id(c))
256 }
257
258 pub fn width(&self, id: u16, text: &str, size: f32) -> f32 {
261 if text.is_ascii() {
262 let table = self.ascii_advances(id);
263 return text.bytes().map(|b| table[usize::from(b)]).sum::<f32>() * size;
264 }
265 text.chars().map(|c| self.advance(id, c, size)).sum()
266 }
267
268 pub fn rasterize(&self, id: u16, c: char, size: f32) -> Option<GlyphBitmap> {
271 let f = self.font(id)?;
272 let glyph = f
273 .font
274 .glyph_id(c)
275 .with_scale_and_position(em_scale(&f.font, size), point(0.0, 0.0));
276 let outlined = f.font.outline_glyph(glyph)?;
277 let bounds = outlined.px_bounds();
278 let width = bounds.width() as u32;
279 let height = bounds.height() as u32;
280 let mut coverage = vec![0_u8; (width as usize) * (height as usize)];
281 outlined.draw(|x, y, v| {
282 let i = (y as usize) * (width as usize) + x as usize;
283 if let Some(px) = coverage.get_mut(i) {
284 *px = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
285 }
286 });
287 Some(GlyphBitmap {
288 width,
289 height,
290 left: bounds.min.x as i32,
291 top: bounds.min.y as i32,
292 coverage,
293 })
294 }
295
296 pub fn glyph_id(&self, id: u16, c: char) -> u16 {
298 self.font(id).map_or(0, |f| {
299 let GlyphId(g) = f.font.glyph_id(c);
300 g
301 })
302 }
303}
304
305#[derive(Debug, Default)]
320pub struct GlyphCache {
321 map: HashMap<(u16, u16, u32), Option<GlyphBitmap>>,
322}
323
324impl GlyphCache {
325 pub fn get(
327 &mut self,
328 engine: &TextEngine,
329 id: u16,
330 c: char,
331 size: f32,
332 ) -> Option<&GlyphBitmap> {
333 let key = (id, engine.glyph_id(id, c), size.to_bits());
334 self.map
335 .entry(key)
336 .or_insert_with(|| engine.rasterize(id, c, size))
337 .as_ref()
338 }
339
340 pub fn len(&self) -> usize {
342 self.map.len()
343 }
344
345 pub fn is_empty(&self) -> bool {
347 self.map.is_empty()
348 }
349
350 pub fn clear(&mut self) {
352 self.map.clear();
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn bundled_font_loads() {
362 let e = TextEngine::new();
363 assert_eq!(e.font_count(), 1);
364 assert!((e.ascii_advances(0)[usize::from(b'5')] - 0.6).abs() < 1e-6);
366 assert!(BUNDLED_FONT.len() < 100 * 1024);
367 }
368
369 #[test]
370 fn bundled_font_has_the_listed_symbols() {
371 let e = TextEngine::new();
372 for c in "\u{a0}°±·×÷–—…₀₁₂₃₄₅₆₇₈₉←↑→↓−≈≠≤≥▲▼".chars()
373 {
374 assert_ne!(e.glyph_id(0, c), 0, "no glyph for {c:?}");
375 if c != '\u{a0}' {
376 assert!(e.rasterize(0, c, 16.0).is_some(), "{c:?} draws nothing");
377 }
378 }
379 assert_eq!(e.glyph_id(0, '€'), 0);
380 }
381
382 #[test]
383 fn width_matches_ascii_sum() {
384 let e = TextEngine::new();
385 let w = e.width(0, "123.45", 11.0);
386 assert!((w - 6.0 * 0.6 * 11.0).abs() < 1e-3);
387 assert!((e.width(7, "123.45", 11.0) - w).abs() < 1e-6);
389 }
390
391 #[test]
392 fn glyphs_sit_on_the_baseline() {
393 let e = TextEngine::new();
394 let g = e.rasterize(0, 'H', 20.0).unwrap();
395 let m = e.line_metrics(0, 20.0);
396 assert!(g.top < 0 && -g.top as f32 <= m.ascent + 1.0);
397 assert!(g.coverage.contains(&255));
398 }
399}