f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Font database.
//!
//! This crate loads font files from bytes that the caller passes, indexes them by family and
//! style, and reads their metrics and glyph outlines. Loading from a folder is a helper for
//! native builds only, because a WASM build has no file system: it reads the names, style and
//! metrics of each face at once, and the bytes of a file at the first choice of one of its
//! faces ([`FontDb::load`]). The rules that choose a font for a piece of text belong to the
//! format crates, because each Office app has its own.
//!
//! Every value is in font units, as the font stores it, so that the format crates decide how to
//! scale and round.

#![deny(clippy::float_arithmetic)]

mod bilevel;
pub mod environment;
mod face;
mod family_name;
mod file;
#[cfg(not(target_arch = "wasm32"))]
mod folder;
mod form;
mod glyph;
mod kerning;
mod layout_values;
mod ligature;
mod math;
mod metrics;
#[cfg(feature = "open-fonts")]
pub mod open_fonts;
mod query;
mod script_glyphs;
mod shape;
mod symbol_map;
mod vdmx;

use std::fmt;
use std::ops::Range;
use std::sync::Arc;

pub use compatifont::Description;
pub use f_office_truetype::plain_device_width;
use skrifa::font::{Font, Format};

use crate::face::{Face, FaceDescription};
pub use crate::face::{FaceClassification, FaceInfo, version_number};
pub use crate::family_name::FamilyName;
pub use crate::file::{FaceOrigin, FileNotRead, FontBytes, NotReadCause};
use crate::file::{FaceSource, LoadedFile};
#[cfg(not(target_arch = "wasm32"))]
pub use crate::folder::{FileNotAdded, NotAddedCause, is_font_file};
pub use crate::glyph::{OutlineError, PathCommand, Point};
pub use crate::kerning::KerningSource;
pub use crate::layout_values::{
    Comparison, Difference, KindComparison, LayoutValues, Place, ValueKind, Values,
};
pub use crate::ligature::Ligature;
pub use crate::math::{
    AssemblyPart, HorizontalConstruction, MathAccent, MathBars, MathCorner, MathLimitGaps,
    MathLimits, MathRadical, MathSkewedFraction, MathStretchStack,
};
pub use crate::metrics::{Decoration, FontMetrics, LineMetrics, Os2Metrics, ScriptMetrics};
pub use crate::script_glyphs::ScriptLevel;
pub use crate::shape::{ShapeDirection, ShapeFailure, ShapeRequest, ShapedGlyph, ShapedScript};
pub use crate::symbol_map::SymbolFont;

/// Identifies one font face in the font database.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontId(u32);

impl FontId {
    /// Makes an ID from the index of the face in the database.
    #[must_use]
    pub const fn from_index(index: u32) -> Self {
        Self(index)
    }

    /// Returns the index of the face in the database.
    #[must_use]
    pub const fn index(self) -> u32 {
        self.0
    }
}

/// Why font data could not be added.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontError {
    /// The data is not an OpenType font or font collection.
    NotAFont,
    /// A face lacks a table that the database needs, or the table is malformed. The value is
    /// the table tag.
    BadTable(&'static str),
    /// The database cannot hold more faces.
    TooManyFaces,
}

impl fmt::Display for FontError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAFont => f.write_str("the data is not an OpenType font"),
            Self::BadTable(tag) => write!(f, "the font's {tag} table is missing or malformed"),
            Self::TooManyFaces => f.write_str("the font database is full"),
        }
    }
}

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

/// Font faces loaded from bytes, addressed by [`FontId`].
#[derive(Default)]
pub struct FontDb {
    faces: Vec<Face>,
    descriptions: Vec<Description>,
}

impl fmt::Debug for FontDb {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FontDb")
            .field("faces", &self.faces.len())
            .field("descriptions", &self.descriptions.len())
            .finish_non_exhaustive()
    }
}

impl FontDb {
    /// Makes an empty database.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds every face in an OpenType font or font collection, and returns their IDs in the
    /// order of the faces in the data.
    ///
    /// When built with the `woff2` feature, WOFF2 containers (`wOF2`) are transparently
    /// decompressed to OpenType before indexing. Full-table WOFF2 files preserve exact layout
    /// metrics, while web-subsetted WOFF2 files may omit glyphs or OpenType tables needed for
    /// exact Word line breaks.
    ///
    /// This is the only way to load fonts in a WASM build. When one face fails to load, no
    /// face is added.
    ///
    /// # Errors
    ///
    /// Returns an error when the data is not an OpenType font or collection (or a valid WOFF2
    /// font when `woff2` is enabled), or when a face lacks the `head`, `hhea` or `hmtx` table.
    pub fn add_font(&mut self, data: impl Into<Arc<[u8]>>) -> Result<Vec<FontId>, FontError> {
        let data: Arc<[u8]> = data.into();
        self.add_bytes(data.into(), FaceOrigin::Caller)
    }

    /// Adds every face of an OpenType font or font collection compiled into the program, such
    /// as a built-in font, without a copy of its bytes, and returns their IDs in the order of
    /// the faces in the data. The faces read as the faces of [`FontDb::add_font`] do, also in a
    /// WASM build; of two faces with the same family, style and weight, [`FontDb::query`]
    /// takes the one that the caller added.
    ///
    /// # Errors
    ///
    /// As for [`FontDb::add_font`]; then no face is added.
    pub fn add_static(&mut self, data: &'static [u8]) -> Result<Vec<FontId>, FontError> {
        self.add_bytes(data.into(), FaceOrigin::BuiltIn)
    }

    fn add_bytes(&mut self, data: FontBytes, origin: FaceOrigin) -> Result<Vec<FontId>, FontError> {
        #[cfg(feature = "woff2")]
        let data = if data.starts_with(b"wOF2") {
            let decoded = wuff::decompress_woff2(&data).map_err(|_| FontError::NotAFont)?;
            FontBytes::from(Arc::<[u8]>::from(decoded))
        } else {
            data
        };
        let Some(Format::Sfnt(count)) = Format::new(&data) else {
            return Err(FontError::NotAFont);
        };
        let mut fonts = Vec::new();
        let mut descriptions = Vec::new();
        for index in 0..count {
            let font = Font::new(data.blob(), index).ok_or(FontError::NotAFont)?;
            descriptions.push(FaceDescription::read(&font)?);
            fonts.push(font);
        }
        let source = FaceSource::Given(LoadedFile::new(data, fonts));
        self.add_faces(source, descriptions, origin)
    }

    /// Adds the faces of the file of `source`, one for each description in the file's order,
    /// and returns their IDs.
    fn add_faces(
        &mut self,
        source: FaceSource,
        descriptions: Vec<FaceDescription>,
        origin: FaceOrigin,
    ) -> Result<Vec<FontId>, FontError> {
        let ids = self.next_ids(descriptions.len())?;
        let source = Arc::new(source);
        let faces = descriptions
            .into_iter()
            .zip(0..)
            .map(|(description, index)| Face::new(description, Arc::clone(&source), index, origin));
        self.faces.extend(faces);
        Ok(ids.map(FontId).collect())
    }

    /// Loads the bytes of the file that holds a face, when they are not loaded yet.
    ///
    /// Only a file that [`FontDb::add_files`] added loads here, at the first call for one of
    /// its faces, and only once: every later call for a face of the file, from any thread,
    /// gives the result of the first. The file's length and modification time must still be
    /// the ones that `add_files` found. Every method that reads a face's bytes loads them in
    /// the same way, and answers for a face whose file did not load as for an unknown face. A
    /// font choice calls this for the face that it chooses, so that such a face counts as
    /// missing and the choice searches again without it.
    ///
    /// # Errors
    ///
    /// Returns the file's name in its folder and the cause when the file did not load. An
    /// unknown face has nothing to load and gives `Ok`.
    pub fn load(&self, id: FontId) -> Result<(), FileNotRead> {
        self.face(id)
            .map_or(Ok(()), |face| face.source.load().map(|_| ()))
    }

    /// Adds the description of a font family in the Compatifont format: its files with their
    /// SHA-256, and the other families that its faces can replace with the values that they
    /// share. The rules of the format crates read it to choose a family that draws a missing
    /// one, and to know a face that lays out as the target's own.
    pub fn add_description(&mut self, description: Description) {
        self.descriptions.push(description);
    }

    /// Returns the descriptions in the order they were added.
    #[must_use]
    pub fn descriptions(&self) -> &[Description] {
        &self.descriptions
    }

    /// Returns the number of faces.
    #[must_use]
    pub fn len(&self) -> usize {
        self.faces.len()
    }

    /// Returns `true` when the database holds no face.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.faces.is_empty()
    }

    /// Returns every face with its ID, in the order they were added.
    pub fn faces(&self) -> impl Iterator<Item = (FontId, &FaceInfo)> {
        self.indexed().map(|(id, face)| (id, &face.info))
    }

    /// Returns the names and style of a face.
    #[must_use]
    pub fn info(&self, id: FontId) -> Option<&FaceInfo> {
        self.face(id).map(|face| &face.info)
    }

    /// Returns where a face came from.
    #[must_use]
    pub fn origin(&self, id: FontId) -> Option<FaceOrigin> {
        self.face(id).map(|face| face.origin)
    }

    /// Returns the font-wide metrics of a face, in font units.
    #[must_use]
    pub fn metrics(&self, id: FontId) -> Option<&FontMetrics> {
        self.face(id).map(|face| &face.metrics)
    }

    /// Returns the bytes of the font file that holds a face, with the index of the face in it.
    ///
    /// The bytes are the ones that [`FontDb::add_font`] or [`FontDb::add_static`] took, or that a
    /// file of a folder held,
    /// so the faces of one collection share them and differ by index. Output crates pass them
    /// on to embed the font. Returns `None` for an unknown face and a face whose file did not
    /// load ([`FontDb::load`]).
    #[must_use]
    pub fn data(&self, id: FontId) -> Option<(&FontBytes, u32)> {
        let face = self.face(id)?;
        Some((face.data()?, face.index))
    }

    fn indexed(&self) -> impl Iterator<Item = (FontId, &Face)> {
        (0..).map(FontId).zip(&self.faces)
    }

    fn face(&self, id: FontId) -> Option<&Face> {
        self.faces.get(usize::try_from(id.0).ok()?)
    }

    fn next_ids(&self, count: usize) -> Result<Range<u32>, FontError> {
        let start = self.faces.len();
        let end = start.checked_add(count).ok_or(FontError::TooManyFaces)?;
        let index = |value: usize| u32::try_from(value).map_err(|_| FontError::TooManyFaces);
        Ok(index(start)?..index(end)?)
    }
}

#[cfg(test)]
mod tests;