f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! One font face of the database.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, OnceLock};

use skrifa::ScalerFont;
use skrifa::font::name::{NameId, Names};
use skrifa::font::{Font, Tables};
use skrifa::raw::TableProvider;
use skrifa::raw::tables::head::MacStyle;
use skrifa::raw::tables::os2::SelectionFlags;

use crate::bilevel::KeptHinters;
use crate::file::{FaceOrigin, FaceSource};
use crate::ligature::Lookups;
use crate::script_glyphs::ScriptGlyphs;
use crate::{FamilyName, FontBytes, FontError, FontMetrics};

/// The OpenType weight class of a regular face.
pub(crate) const WEIGHT_REGULAR: u16 = 400;

/// The OpenType weight class of a semi-bold face, the lightest weight that counts as bold.
pub(crate) const WEIGHT_SEMI_BOLD: u16 = 600;

/// The OpenType weight class of a bold face.
pub(crate) const WEIGHT_BOLD: u16 = 700;

const FAMILY_IDS: [NameId; 2] = [NameId::TYPOGRAPHIC_FAMILY_NAME, NameId::FAMILY_NAME];
const SUBFAMILY_IDS: [NameId; 2] = [NameId::TYPOGRAPHIC_SUBFAMILY_NAME, NameId::SUBFAMILY_NAME];

/// The names and style of a face.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FaceInfo {
    /// The typographic family name (name ID 16), or the family name (name ID 1) when the font
    /// has no typographic family name. English is preferred. Empty when the font has neither.
    pub family: String,
    /// The typographic subfamily name (name ID 17), or the subfamily name (name ID 2), chosen in
    /// the same way as [`FaceInfo::family`].
    pub subfamily: String,
    /// Every distinct typographic family name and family name in every language, in table
    /// order. [`crate::FontDb::query`] matches against the family names first and against the
    /// typographic family names last.
    pub family_names: Vec<String>,
    /// `usWeightClass` from `OS/2`. Without `OS/2`, 700 when the bold bit of `macStyle` in
    /// `head` is set and 400 otherwise.
    pub weight: u16,
    /// The italic bit of `fsSelection` in `OS/2`, or of `macStyle` in `head` without `OS/2`.
    pub italic: bool,
    /// The PostScript name (name ID 6), or `None` when the font has none.
    pub postscript_name: Option<String>,
    /// The version string (name ID 5), such as "Version 6.23", or `None` when the font has
    /// none. A target's font environment names each own face by it.
    pub version: Option<String>,
    /// Every distinct full name (name ID 4), such as "Arial Bold", in every language.
    pub full_names: Vec<String>,
    /// The weight of the PANOSE classification in `OS/2`, from 2 (very light) to 11 (extra
    /// black), or 0 or 1 when the font gives none.
    pub panose_weight: u8,
    /// The face's classification in `OS/2`.
    pub classification: FaceClassification,
}

/// What `OS/2` says of a face's kind: its PANOSE numbers and the code pages that it covers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FaceClassification {
    /// The ten numbers of the PANOSE classification, all 0 when the font has no `OS/2`.
    pub panose: [u8; 10],
    /// Whether `ulCodePageRange1` names an East Asian code page: Japanese, simplified Chinese,
    /// Korean Wansung, traditional Chinese or Korean Johab (bits 17 to 21).
    pub east_asian: bool,
}

/// The bits of `ulCodePageRange1` of the East Asian code pages, 17 to 21.
const EAST_ASIAN_CODE_PAGES: u32 = 0b1_1111 << 17;

impl FaceClassification {
    /// Reads the classification of a face from its `OS/2` table, or the default without one.
    fn read(tables: &Tables) -> Self {
        let Ok(os2) = tables.os2() else {
            return Self::default();
        };
        let mut panose = [0; 10];
        for (number, &value) in panose.iter_mut().zip(os2.panose_10()) {
            *number = value;
        }
        let code_pages = os2.ul_code_page_range_1().unwrap_or(0);
        Self {
            panose,
            east_asian: code_pages & EAST_ASIAN_CODE_PAGES != 0,
        }
    }
}

/// The PANOSE weight of a bold face.
const PANOSE_BOLD: u8 = 8;

impl FaceInfo {
    /// Whether the face is bold: semi-bold or heavier.
    #[must_use]
    pub const fn bold(&self) -> bool {
        self.weight >= WEIGHT_SEMI_BOLD
    }

    /// Whether both weights of the face, the weight class and the PANOSE weight, say that it
    /// is lighter than bold. An old heavy face whose weight class says 400 while its PANOSE
    /// weight says black is not light.
    #[must_use]
    pub const fn light(&self) -> bool {
        !self.bold() && self.panose_weight < PANOSE_BOLD
    }
}

/// The number of a version string (name ID 5): "7.06.1" of "Version 7.06.1", without the
/// word "Version" and what follows a semicolon.
#[must_use]
pub fn version_number(version: &str) -> &str {
    let version = version.split(';').next().unwrap_or(version).trim();
    version.strip_prefix("Version ").unwrap_or(version)
}

/// What the database reads of a face when it adds it: its names and style, its metrics and
/// its style group, from the tables `head`, `hhea`, `hmtx`, `OS/2`, `post` and `name`.
pub(crate) struct FaceDescription {
    info: FaceInfo,
    metrics: FontMetrics,
    style_group: FamilyName,
    style_group_names: Vec<String>,
}

impl FaceDescription {
    /// Reads the description of the face of `font`, or fails when it lacks a table that the
    /// database needs ([`FontMetrics::read`] and `hmtx`).
    pub(crate) fn read(font: &Font) -> Result<Self, FontError> {
        let metrics = FontMetrics::read(font.tables())?;
        font.tables()
            .hmtx()
            .map_err(|_| FontError::BadTable("hmtx"))?;
        let info = FaceInfo::read(font);
        let names = font.names();
        let style_group = preferred_name(&names, &[NameId::FAMILY_NAME]);
        Ok(Self {
            info,
            metrics,
            style_group: FamilyName::new(style_group.unwrap_or_default()),
            style_group_names: all_names(&names, &[NameId::FAMILY_NAME]),
        })
    }
}

/// A face with everything that the database reads from it.
pub(crate) struct Face {
    pub(crate) info: FaceInfo,
    pub(crate) metrics: FontMetrics,
    /// The family name (name ID 1). The OpenType specification uses it to link up to four
    /// faces, regular, bold, italic and bold italic, as one style group.
    pub(crate) style_group: FamilyName,
    /// Every distinct family name (name ID 1) in every language, by which
    /// [`crate::FontDb::query`] finds the face before it looks at typographic family names.
    pub(crate) style_group_names: Vec<String>,
    /// Where the bytes of the font file or collection that holds the face come from, which
    /// the faces of a collection share.
    pub(crate) source: Arc<FaceSource>,
    /// The index of the face in its file.
    pub(crate) index: u32,
    /// Where the face came from.
    pub(crate) origin: FaceOrigin,
    /// The scaler of the face, made from its file's font at the first read, or `None` when the
    /// file did not load. A read of a glyph then reaches the font in one step, not through the
    /// file.
    pub(crate) scaler: OnceLock<Option<ScalerFont>>,
    /// The standard ligature lookups, read when they are first needed.
    pub(crate) ligatures: OnceLock<Lookups>,
    /// The indices of the `GPOS` lookups of the `kern` feature, read when they are first
    /// needed.
    pub(crate) kern_lookups: OnceLock<Vec<u16>>,
    /// The lookups of the `ssty` feature, read when they are first needed.
    pub(crate) script_glyphs: OnceLock<ScriptGlyphs>,
    /// The lookups of the `flac` feature, read when they are first needed.
    pub(crate) flattened_accents: OnceLock<ScriptGlyphs>,
    /// The lookups of the `dtls` feature, read when they are first needed.
    pub(crate) dotless_forms: OnceLock<ScriptGlyphs>,
    /// The bi-level advances computed so far, by pixels per em and glyph, with `None` where
    /// the face's instructions give none.
    pub(crate) bi_level: Mutex<BTreeMap<(u16, u16), Option<i32>>>,
    /// The device widths computed so far, by pixels per em and glyph, in the same way.
    pub(crate) device: Mutex<BTreeMap<(u16, u16), Option<i32>>>,
    /// The bi-level hinters that the face keeps, for the glyphs that [`Face::bi_level`] lacks.
    pub(crate) bi_level_hinters: Mutex<KeptHinters>,
    /// The hinters in the device-width mode that the face keeps, for the glyphs that
    /// [`Face::device`] lacks.
    pub(crate) device_hinters: Mutex<KeptHinters>,
}

impl Face {
    /// The face at `index` in the file of `source`, with its description.
    pub(crate) fn new(
        description: FaceDescription,
        source: Arc<FaceSource>,
        index: u32,
        origin: FaceOrigin,
    ) -> Self {
        let FaceDescription {
            info,
            metrics,
            style_group,
            style_group_names,
        } = description;
        Self {
            info,
            metrics,
            style_group,
            style_group_names,
            source,
            index,
            origin,
            scaler: OnceLock::new(),
            ligatures: OnceLock::new(),
            kern_lookups: OnceLock::new(),
            script_glyphs: OnceLock::new(),
            flattened_accents: OnceLock::new(),
            dotless_forms: OnceLock::new(),
            bi_level: Mutex::default(),
            device: Mutex::default(),
            bi_level_hinters: Mutex::default(),
            device_hinters: Mutex::default(),
        }
    }

    /// The scaler of the face, which draws its outlines in font units without hinting and
    /// holds its font, or `None` when its file did not load. The bytes of a file of a folder
    /// load at the first call of any face of the file, and the face makes its scaler at its own
    /// first call; every later call gives the same answer.
    pub(crate) fn scaler(&self) -> Option<&ScalerFont> {
        self.scaler
            .get_or_init(|| {
                let fonts = &self.source.loaded()?.fonts;
                let font = fonts.get(usize::try_from(self.index).ok()?)?;
                Some(ScalerFont::force_unhinted(font.clone(), None))
            })
            .as_ref()
    }

    /// The font of the face, as [`Face::scaler`] gives it.
    pub(crate) fn font(&self) -> Option<&Font> {
        self.scaler().map(ScalerFont::font)
    }

    /// The bytes of the file that holds the face, as [`Face::scaler`] gives them.
    pub(crate) fn data(&self) -> Option<&FontBytes> {
        self.source.loaded().map(|file| &file.data)
    }
}

impl FaceInfo {
    fn read(font: &Font) -> Self {
        let names = font.names();
        let (weight, italic) = style(font.tables());
        Self {
            family: preferred_name(&names, &FAMILY_IDS).unwrap_or_default(),
            subfamily: preferred_name(&names, &SUBFAMILY_IDS).unwrap_or_default(),
            family_names: all_names(&names, &FAMILY_IDS),
            weight,
            italic,
            postscript_name: preferred_name(&names, &[NameId::POSTSCRIPT_NAME]),
            version: preferred_name(&names, &[NameId::VERSION_STRING]),
            full_names: all_names(&names, &[NameId::FULL_NAME]),
            panose_weight: font
                .tables()
                .os2()
                .ok()
                .and_then(|os2| os2.panose_10().get(2).copied())
                .unwrap_or(0),
            classification: FaceClassification::read(font.tables()),
        }
    }
}

/// Returns the English name for the first of `ids` that the font has.
fn preferred_name(names: &Names<'_>, ids: &[NameId]) -> Option<String> {
    ids.iter()
        .find_map(|id| names.get(*id)?.english_or_first())
        .map(|localized| localized.name().to_string())
}

/// Returns every distinct name for `ids`, in every language.
fn all_names(names: &Names<'_>, ids: &[NameId]) -> Vec<String> {
    let mut found: Vec<String> = Vec::new();
    let localized = ids.iter().filter_map(|id| names.get(*id));
    for name in localized.flat_map(|name| name.iter()) {
        let name = name.name().to_string();
        if !found.contains(&name) {
            found.push(name);
        }
    }
    found
}

/// Returns the weight and the italic flag.
fn style(tables: &Tables) -> (u16, bool) {
    if let Ok(os2) = tables.os2() {
        let italic = os2.fs_selection().contains(SelectionFlags::ITALIC);
        return (os2.us_weight_class(), italic);
    }
    let mac_style = tables.head().map_or_default(|head| head.mac_style());
    let weight = if mac_style.contains(MacStyle::BOLD) {
        WEIGHT_BOLD
    } else {
        WEIGHT_REGULAR
    };
    (weight, mac_style.contains(MacStyle::ITALIC))
}