Skip to main content

ferrochart_text/
lib.rs

1//! Font loading, text measurement and glyph rasterization shared by the FerroChart
2//! backends.
3//!
4//! The crate does not depend on `ferrochart-core`: backends adapt [`TextEngine`]
5//! to the core's `TextMeasurer` trait. All metrics are reported both
6//! em-normalized (per 1 px of font size, as the core's ASCII fast path expects)
7//! and in pixels for a given size.
8//!
9//! A subset of JetBrains Mono Regular (SIL Open Font License 1.1, ASCII plus a few
10//! symbols, about 11 KB) is bundled and always available as font 0.
11//!
12#![forbid(unsafe_code)]
13
14use std::collections::HashMap;
15use std::fmt;
16
17use ab_glyph::{Font, FontArc, FontVec, GlyphId, PxScale, ScaleFont, point};
18
19/// The bundled font: JetBrains Mono Regular, subset to ASCII and
20/// `\u{a0} ° ± · × ÷ – — … ₀-₉ ← ↑ → ↓ − ≈ ≠ ≤ ≥ ▲ ▼`.
21/// License: `assets/fonts/OFL.txt`.
22pub const BUNDLED_FONT: &[u8] = include_bytes!("../assets/fonts/JetBrainsMono-Regular-subset.ttf");
23
24/// Error from loading a font.
25///
26/// # Examples
27///
28/// ```
29/// use ferrochart_text::{FontError, TextEngine};
30///
31/// let mut engine = TextEngine::new();
32/// assert_eq!(engine.add_font(vec![0, 1, 2]), Err(FontError::Invalid));
33/// ```
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum FontError {
37    /// The data is not a font `ab_glyph` can read.
38    Invalid,
39    /// More than `u16::MAX` fonts.
40    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/// Vertical metrics of a font at some size (pixels, y down: `descent` is
55/// positive below the baseline).
56#[derive(Clone, Copy, Debug, PartialEq)]
57pub struct LineMetrics {
58    /// Distance from the top of the line box to the baseline.
59    pub ascent: f32,
60    /// Distance from the baseline to the bottom of the line box.
61    pub descent: f32,
62    /// Extra space between lines.
63    pub line_gap: f32,
64}
65
66impl LineMetrics {
67    /// Height of a line box: ascent + descent + line gap.
68    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 of ASCII characters at a font size of 1 px.
84    advances: [f32; 128],
85    /// Advances of the subscript digits U+2080..=U+2089 at 1 px.
86    subscripts: [f32; 10],
87    /// Line metrics at a font size of 1 px.
88    metrics: LineMetrics,
89}
90
91impl LoadedFont {
92    fn new(font: FontArc) -> Self {
93        // `PxScale` is the line height (ascent - descent), not the em size. Scaling
94        // by `units_per_em / height` gives an em size of exactly 1 px.
95        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
119/// `0..=9` for the subscript digits `₀`..=`₉`.
120fn subscript_digit(c: char) -> Option<usize> {
121    ('\u{2080}'..='\u{2089}')
122        .contains(&c)
123        .then(|| c as usize - 0x2080)
124}
125
126/// The `PxScale` that gives an em size of `size` pixels.
127fn 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/// A rasterized glyph: 8-bit coverage, row-major, `width × height`.
138#[derive(Clone, Debug, PartialEq)]
139pub struct GlyphBitmap {
140    /// Width in pixels.
141    pub width: u32,
142    /// Height in pixels.
143    pub height: u32,
144    /// Offset of the bitmap's left edge from the pen position.
145    pub left: i32,
146    /// Offset of the bitmap's top edge from the baseline (negative = above).
147    pub top: i32,
148    /// Coverage, 0..=255.
149    pub coverage: Vec<u8>,
150}
151
152/// Fonts and metrics.
153///
154/// # Examples
155///
156/// ```
157/// use ferrochart_text::TextEngine;
158///
159/// let engine = TextEngine::new();
160/// // The bundled font is monospaced: every digit has the same advance.
161/// let adv = engine.ascii_advances(0);
162/// assert!(adv[b'0' as usize] > 0.0);
163/// assert_eq!(adv[b'1' as usize], adv[b'8' as usize]);
164/// assert!(engine.line_metrics(0, 12.0).height() > 12.0);
165/// ```
166pub 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    /// An engine with the bundled font as font 0.
186    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    /// Adds a font (TTF/OTF data) and returns its index.
194    ///
195    /// # Errors
196    ///
197    /// [`FontError::Invalid`] if the data cannot be parsed,
198    /// [`FontError::TooManyFonts`] beyond `u16::MAX` fonts.
199    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    /// Number of loaded fonts.
207    pub fn font_count(&self) -> usize {
208        self.fonts.len()
209    }
210
211    /// Font `id`, falling back to font 0 for unknown ids.
212    fn font(&self, id: u16) -> Option<&LoadedFont> {
213        self.fonts
214            .get(usize::from(id))
215            .or_else(|| self.fonts.first())
216    }
217
218    /// ASCII advances of font `id` at a font size of 1 px. Unknown ids use font 0.
219    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    /// Advances of the subscript digits `₀`..=`₉` (U+2080..=U+2089) of font
225    /// `id` at a font size of 1 px. Unknown ids use font 0.
226    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    /// Line metrics of font `id` at `size` px.
232    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    /// Advance of `c` at `size` px.
244    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    /// Width of `text` at `size` px: the sum of the advances, without kerning,
259    /// exactly as the core's ASCII fast path measures it.
260    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    /// Rasterizes `c` at `size` px with the pen on an integer pixel. `None` for
269    /// glyphs without an outline (space).
270    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    /// The glyph id of `c` (for cache keys).
297    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/// Cache of rasterized glyphs, keyed by font, glyph and size.
306///
307/// # Examples
308///
309/// ```
310/// use ferrochart_text::{GlyphCache, TextEngine};
311///
312/// let engine = TextEngine::new();
313/// let mut cache = GlyphCache::default();
314/// let w = cache.get(&engine, 0, 'A', 12.0).map(|g| g.width);
315/// assert!(w.is_some_and(|w| w > 0));
316/// assert!(cache.get(&engine, 0, ' ', 12.0).is_none());
317/// assert_eq!(cache.len(), 2);
318/// ```
319#[derive(Debug, Default)]
320pub struct GlyphCache {
321    map: HashMap<(u16, u16, u32), Option<GlyphBitmap>>,
322}
323
324impl GlyphCache {
325    /// The bitmap of `c`, rasterizing it on first use.
326    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    /// Number of cached entries (including empty glyphs).
341    pub fn len(&self) -> usize {
342        self.map.len()
343    }
344
345    /// Whether the cache is empty.
346    pub fn is_empty(&self) -> bool {
347        self.map.is_empty()
348    }
349
350    /// Drops all cached glyphs.
351    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        // JetBrains Mono advances are 600/1000 em.
365        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        // Unknown font ids fall back to font 0.
388        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}