Skip to main content

f_office_fonts/
glyph.rs

1//! Glyph lookup, advances and outlines.
2
3use std::fmt;
4
5use skrifa::raw::TableProvider;
6use skrifa::{DrawMemory, GlyphId, PathSink};
7
8use crate::face::Face;
9use crate::{FontDb, FontId};
10
11/// A point in font units, with y growing upwards from the baseline.
12#[derive(Clone, Copy, Debug, Default, PartialEq)]
13pub struct Point {
14    /// Horizontal position from the glyph origin.
15    pub x: f32,
16    /// Vertical position from the baseline, growing upwards.
17    pub y: f32,
18}
19
20/// One command of a glyph outline.
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub enum PathCommand {
23    /// Starts a contour at the point.
24    MoveTo(Point),
25    /// Draws a line to the point.
26    LineTo(Point),
27    /// Draws a quadratic curve through the control point to the end point.
28    QuadTo(Point, Point),
29    /// Draws a cubic curve through two control points to the end point.
30    CubicTo(Point, Point, Point),
31    /// Closes the contour.
32    Close,
33}
34
35/// Why [`FontDb::outline`] gives no outline of a glyph. It is ordered, so that a set of the
36/// causes, such as the notes of a layout, keeps one order.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
38#[non_exhaustive]
39pub enum OutlineError {
40    /// The font database holds no face with the ID.
41    UnknownFont,
42    /// The font has no glyph with the ID.
43    UnknownGlyph,
44    /// The font has the glyph but no table of outlines (`glyf`, `CFF ` or `CFF2`), as a font
45    /// of bitmaps only has.
46    NoOutlines,
47    /// The font has the glyph and a table of outlines, but the glyph's outline does not read.
48    Unreadable,
49}
50
51impl fmt::Display for OutlineError {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.write_str(match self {
54            Self::UnknownFont => "the font database has no such font",
55            Self::UnknownGlyph => "the font has no such glyph",
56            Self::NoOutlines => "the font has no glyph outlines",
57            Self::Unreadable => "the glyph's outline does not read",
58        })
59    }
60}
61
62impl std::error::Error for OutlineError {}
63
64impl FontDb {
65    /// Returns the glyph that the font's character map gives for `ch`.
66    ///
67    /// The map comes from one `cmap` subtable. A Windows symbol subtable comes first, then full
68    /// Unicode, then the Unicode basic plane, then Mac Roman. With a symbol subtable, a
69    /// character from U+0000 to U+00FF that the subtable lacks is looked up again at U+F000 to
70    /// U+F0FF. Returns `None` for an unknown face or an unmapped character.
71    #[must_use]
72    pub fn glyph_id(&self, id: FontId, ch: char) -> Option<u32> {
73        let glyph = self.face(id)?.font()?.charmap().map_unicode(ch)?;
74        Some(glyph.to_u32())
75    }
76
77    /// Returns the advance width of a glyph from `hmtx`, in font units and without hinting.
78    ///
79    /// Returns `None` for an unknown face or a glyph that the font does not have.
80    #[must_use]
81    pub fn advance(&self, id: FontId, glyph: u32) -> Option<u16> {
82        let font = self.face(id)?.font()?;
83        if glyph >= font.num_glyphs() {
84            return None;
85        }
86        font.tables().hmtx().ok()?.advance(GlyphId::new(glyph))
87    }
88
89    /// Returns the outline of a glyph in font units, without hinting.
90    ///
91    /// A glyph without contours, such as a space, has an empty outline.
92    ///
93    /// # Errors
94    ///
95    /// Returns an [`OutlineError`] that names the cause for an unknown face, a glyph that the
96    /// font does not have (the test of [`FontDb::advance`]), a font without a table of
97    /// outlines, or an outline that does not read.
98    pub fn outline(&self, id: FontId, glyph: u32) -> Result<Vec<PathCommand>, OutlineError> {
99        let scaler = self
100            .face(id)
101            .and_then(Face::scaler)
102            .ok_or(OutlineError::UnknownFont)?;
103        if glyph >= scaler.font().num_glyphs() {
104            return Err(OutlineError::UnknownGlyph);
105        }
106        let Some(outline) = scaler.outline(GlyphId::new(glyph)) else {
107            let outlines = scaler.font().outline_glyphs();
108            return Err(if outlines.source().is_none() {
109                OutlineError::NoOutlines
110            } else {
111                OutlineError::Unreadable
112            });
113        };
114        let mut sink = Recorder::default();
115        outline
116            .draw(DrawMemory::Scratch, &mut sink)
117            .map_err(|_| OutlineError::Unreadable)?;
118        Ok(sink.commands)
119    }
120}
121
122/// Records the commands that skrifa draws.
123#[derive(Default)]
124struct Recorder {
125    commands: Vec<PathCommand>,
126}
127
128impl PathSink for Recorder {
129    fn move_to(&mut self, x: f32, y: f32) {
130        self.commands.push(PathCommand::MoveTo(Point { x, y }));
131    }
132
133    fn line_to(&mut self, x: f32, y: f32) {
134        self.commands.push(PathCommand::LineTo(Point { x, y }));
135    }
136
137    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
138        let control = Point { x: cx0, y: cy0 };
139        self.commands
140            .push(PathCommand::QuadTo(control, Point { x, y }));
141    }
142
143    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
144        let first = Point { x: cx0, y: cy0 };
145        let second = Point { x: cx1, y: cy1 };
146        self.commands
147            .push(PathCommand::CubicTo(first, second, Point { x, y }));
148    }
149
150    fn close(&mut self) {
151        self.commands.push(PathCommand::Close);
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use skrifa::PathSink;
158
159    use super::{PathCommand, Point, Recorder};
160
161    #[test]
162    fn records_every_command() {
163        let mut sink = Recorder::default();
164        sink.move_to(1.0, 2.0);
165        sink.line_to(3.0, 4.0);
166        sink.quad_to(5.0, 6.0, 7.0, 8.0);
167        sink.curve_to(9.0, 10.0, 11.0, 12.0, 13.0, 14.0);
168        sink.close();
169        let p = |x, y| Point { x, y };
170        assert_eq!(
171            sink.commands,
172            [
173                PathCommand::MoveTo(p(1.0, 2.0)),
174                PathCommand::LineTo(p(3.0, 4.0)),
175                PathCommand::QuadTo(p(5.0, 6.0), p(7.0, 8.0)),
176                PathCommand::CubicTo(p(9.0, 10.0), p(11.0, 12.0), p(13.0, 14.0)),
177                PathCommand::Close,
178            ]
179        );
180    }
181}