f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The open fonts of Compatifont that the build carries, each behind its own feature (`arimo-cf`,
//! `arimo-narrow-cf`, `tinos-cf`, `celeborn-cf`, `caladea-cf`, `caladea-math-cf`, `intos-cf`,
//! `intos-display-cf`, `curunir-cf`, `gelasio-cf`, `sindar-cf`, `comic-relief-cf`,
//! `noto-symbols-cf`), and their addition to a font database after the caller's own fonts, with
//! their descriptions.

use std::fmt;

pub use compatifont_fonts::{FontFile, OpenFont};

use crate::{Description, FamilyName, FontDb, FontError};

/// Why an open font was not added to a font database.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum OpenFontError {
    /// A font file does not parse.
    Font(FontError),
    /// The description does not read.
    Description(compatifont::Error),
}

impl fmt::Display for OpenFontError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Font(error) => write!(f, "an open font's file does not read: {error}"),
            Self::Description(error) => {
                write!(f, "an open font's description does not read: {error}")
            }
        }
    }
}

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

impl From<FontError> for OpenFontError {
    fn from(error: FontError) -> Self {
        Self::Font(error)
    }
}

impl From<compatifont::Error> for OpenFontError {
    fn from(error: compatifont::Error) -> Self {
        Self::Description(error)
    }
}

/// Adds to `db`, as built-in faces, every open font of this build whose family `db` holds no
/// face of, with its description, and returns the open fonts that it added. A family that the
/// caller's own fonts hold, such as an Arimo CF that the user installed, stays the caller's.
///
/// # Errors
///
/// [`OpenFontError`] when a description does not read or a font file does not parse; the open
/// fonts before it stay added.
pub fn add_missing(db: &mut FontDb) -> Result<Vec<OpenFont>, OpenFontError> {
    add_missing_of(db, OpenFont::all())
}

fn add_missing_of(db: &mut FontDb, fonts: Vec<OpenFont>) -> Result<Vec<OpenFont>, OpenFontError> {
    let mut added = Vec::new();
    for font in fonts {
        let description = Description::from_toml(font.description)?;
        let family = FamilyName::new(description.family_name.as_str());
        if db.faces().any(|(_, info)| family.is(&info.family)) {
            continue;
        }
        for file in &font.files {
            db.add_static(file.bytes)?;
        }
        db.add_description(description);
        added.push(font);
    }
    Ok(added)
}

#[cfg(test)]
mod tests;