f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Glyph lookup, advances and outlines.

use std::fmt;

use skrifa::raw::TableProvider;
use skrifa::{DrawMemory, GlyphId, PathSink};

use crate::face::Face;
use crate::{FontDb, FontId};

/// A point in font units, with y growing upwards from the baseline.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Point {
    /// Horizontal position from the glyph origin.
    pub x: f32,
    /// Vertical position from the baseline, growing upwards.
    pub y: f32,
}

/// One command of a glyph outline.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PathCommand {
    /// Starts a contour at the point.
    MoveTo(Point),
    /// Draws a line to the point.
    LineTo(Point),
    /// Draws a quadratic curve through the control point to the end point.
    QuadTo(Point, Point),
    /// Draws a cubic curve through two control points to the end point.
    CubicTo(Point, Point, Point),
    /// Closes the contour.
    Close,
}

/// Why [`FontDb::outline`] gives no outline of a glyph. It is ordered, so that a set of the
/// causes, such as the notes of a layout, keeps one order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum OutlineError {
    /// The font database holds no face with the ID.
    UnknownFont,
    /// The font has no glyph with the ID.
    UnknownGlyph,
    /// The font has the glyph but no table of outlines (`glyf`, `CFF ` or `CFF2`), as a font
    /// of bitmaps only has.
    NoOutlines,
    /// The font has the glyph and a table of outlines, but the glyph's outline does not read.
    Unreadable,
}

impl fmt::Display for OutlineError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::UnknownFont => "the font database has no such font",
            Self::UnknownGlyph => "the font has no such glyph",
            Self::NoOutlines => "the font has no glyph outlines",
            Self::Unreadable => "the glyph's outline does not read",
        })
    }
}

impl std::error::Error for OutlineError {}

impl FontDb {
    /// Returns the glyph that the font's character map gives for `ch`.
    ///
    /// The map comes from one `cmap` subtable. A Windows symbol subtable comes first, then full
    /// Unicode, then the Unicode basic plane, then Mac Roman. With a symbol subtable, a
    /// character from U+0000 to U+00FF that the subtable lacks is looked up again at U+F000 to
    /// U+F0FF. Returns `None` for an unknown face or an unmapped character.
    #[must_use]
    pub fn glyph_id(&self, id: FontId, ch: char) -> Option<u32> {
        let glyph = self.face(id)?.font()?.charmap().map_unicode(ch)?;
        Some(glyph.to_u32())
    }

    /// Returns the advance width of a glyph from `hmtx`, in font units and without hinting.
    ///
    /// Returns `None` for an unknown face or a glyph that the font does not have.
    #[must_use]
    pub fn advance(&self, id: FontId, glyph: u32) -> Option<u16> {
        let font = self.face(id)?.font()?;
        if glyph >= font.num_glyphs() {
            return None;
        }
        font.tables().hmtx().ok()?.advance(GlyphId::new(glyph))
    }

    /// Returns the outline of a glyph in font units, without hinting.
    ///
    /// A glyph without contours, such as a space, has an empty outline.
    ///
    /// # Errors
    ///
    /// Returns an [`OutlineError`] that names the cause for an unknown face, a glyph that the
    /// font does not have (the test of [`FontDb::advance`]), a font without a table of
    /// outlines, or an outline that does not read.
    pub fn outline(&self, id: FontId, glyph: u32) -> Result<Vec<PathCommand>, OutlineError> {
        let scaler = self
            .face(id)
            .and_then(Face::scaler)
            .ok_or(OutlineError::UnknownFont)?;
        if glyph >= scaler.font().num_glyphs() {
            return Err(OutlineError::UnknownGlyph);
        }
        let Some(outline) = scaler.outline(GlyphId::new(glyph)) else {
            let outlines = scaler.font().outline_glyphs();
            return Err(if outlines.source().is_none() {
                OutlineError::NoOutlines
            } else {
                OutlineError::Unreadable
            });
        };
        let mut sink = Recorder::default();
        outline
            .draw(DrawMemory::Scratch, &mut sink)
            .map_err(|_| OutlineError::Unreadable)?;
        Ok(sink.commands)
    }
}

/// Records the commands that skrifa draws.
#[derive(Default)]
struct Recorder {
    commands: Vec<PathCommand>,
}

impl PathSink for Recorder {
    fn move_to(&mut self, x: f32, y: f32) {
        self.commands.push(PathCommand::MoveTo(Point { x, y }));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.commands.push(PathCommand::LineTo(Point { x, y }));
    }

    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
        let control = Point { x: cx0, y: cy0 };
        self.commands
            .push(PathCommand::QuadTo(control, Point { x, y }));
    }

    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        let first = Point { x: cx0, y: cy0 };
        let second = Point { x: cx1, y: cy1 };
        self.commands
            .push(PathCommand::CubicTo(first, second, Point { x, y }));
    }

    fn close(&mut self) {
        self.commands.push(PathCommand::Close);
    }
}

#[cfg(test)]
mod tests {
    use skrifa::PathSink;

    use super::{PathCommand, Point, Recorder};

    #[test]
    fn records_every_command() {
        let mut sink = Recorder::default();
        sink.move_to(1.0, 2.0);
        sink.line_to(3.0, 4.0);
        sink.quad_to(5.0, 6.0, 7.0, 8.0);
        sink.curve_to(9.0, 10.0, 11.0, 12.0, 13.0, 14.0);
        sink.close();
        let p = |x, y| Point { x, y };
        assert_eq!(
            sink.commands,
            [
                PathCommand::MoveTo(p(1.0, 2.0)),
                PathCommand::LineTo(p(3.0, 4.0)),
                PathCommand::QuadTo(p(5.0, 6.0), p(7.0, 8.0)),
                PathCommand::CubicTo(p(9.0, 10.0), p(11.0, 12.0), p(13.0, 14.0)),
                PathCommand::Close,
            ]
        );
    }
}