f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Heights from the `VDMX` table, as the OpenType specification (`VDMX`) lays it out.

use skrifa::raw::{FontData, TableProvider};
use skrifa::{FontRef, Tag};

use crate::{FontDb, FontId};

impl FontDb {
    /// Returns the largest height above the baseline and the largest depth below it, in
    /// pixels and with the signs that the font stores (`yMax` and `yMin`), that a face's
    /// `VDMX` table gives at `pels` pixels per em on a device with square pixels.
    ///
    /// The OpenType specification (`VDMX`) says how a ratio record matches a device: the
    /// record's ratios, normalized to the device's x resolution, must take in its y
    /// resolution, and a record of zeros matches every device. This reads the group of the
    /// first record that matches the device and that is for the Windows ANSI character set
    /// (`bCharSet` 1), in a table of either version. A group for all glyphs (`bCharSet` 0)
    /// does not count in either version.
    ///
    /// Returns `None` for an unknown face, a face without such a group, or a group that does
    /// not list `pels`.
    #[must_use]
    pub fn device_heights(&self, id: FontId, pels: u16) -> Option<(i16, i16)> {
        let face = self.face(id)?;
        let font = FontRef::from_index(face.data()?, face.index).ok()?;
        let table = font.data_for_tag(Tag::new(b"VDMX"))?;
        heights(table.as_bytes(), pels)
    }
}

/// The heights of [`FontDb::device_heights`] from the bytes of a `VDMX` table.
pub(crate) fn heights(table: &[u8], pels: u16) -> Option<(i16, i16)> {
    let data = FontData::new(table);
    let u16_at = |at: usize| data.read_at::<u16>(at).ok();
    let i16_at = |at: usize| data.read_at::<i16>(at).ok();
    let ratios = usize::from(u16_at(4)?);
    let index = (0..ratios).find(|&index| {
        let Some(&[char_set, x, first, last]) = table.get(6 + 4 * index..10 + 4 * index) else {
            return false;
        };
        let square = (x, first, last) == (0, 0, 0) || (first <= x && x <= last);
        square && char_set == 1
    })?;
    let group = usize::from(u16_at(6 + 4 * ratios + 2 * index)?);
    let count = usize::from(u16_at(group)?);
    (0..count).find_map(|record| {
        let at = group + 4 + 6 * record;
        (u16_at(at)? == pels).then_some(())?;
        Some((i16_at(at + 2)?, i16_at(at + 4)?))
    })
}

#[cfg(test)]
mod tests {
    use super::heights;

    /// A `VDMX` table of `version` with one ratio record (`char_set` and `ratio`) and one
    /// group that lists the pel heights 8 and 48.
    fn table(version: u16, char_set: u8, ratio: [u8; 3]) -> Vec<u8> {
        let mut bytes = Vec::new();
        for value in [version, 1, 1] {
            bytes.extend_from_slice(&value.to_be_bytes());
        }
        bytes.push(char_set);
        bytes.extend_from_slice(&ratio);
        bytes.extend_from_slice(&12_u16.to_be_bytes());
        bytes.extend_from_slice(&[0, 2, 8, 48]);
        for (pels, y_max, y_min) in [(8_u16, 7_i16, -2_i16), (48, 43, -12)] {
            bytes.extend_from_slice(&pels.to_be_bytes());
            bytes.extend_from_slice(&y_max.to_be_bytes());
            bytes.extend_from_slice(&y_min.to_be_bytes());
        }
        bytes
    }

    #[test]
    fn reads_the_heights_of_a_listed_pel_height() {
        let ansi = table(0, 1, [1, 1, 1]);
        assert_eq!(heights(&ansi, 48), Some((43, -12)));
        assert_eq!(heights(&ansi, 8), Some((7, -2)));
        // A pel height that the group does not list.
        assert_eq!(heights(&ansi, 32), None);
        // A record of zeros, and one for 1:1 through 2:1, match square pixels.
        assert_eq!(heights(&table(0, 1, [0, 0, 0]), 48), Some((43, -12)));
        assert_eq!(heights(&table(0, 1, [2, 1, 2]), 48), Some((43, -12)));
    }

    #[test]
    fn ignores_groups_for_other_character_sets_and_devices() {
        // A group for all glyphs, in either version.
        assert_eq!(heights(&table(0, 0, [1, 1, 1]), 48), None);
        assert_eq!(heights(&table(1, 0, [1, 1, 1]), 48), None);
        // A group for the ANSI character set in version 1.
        assert_eq!(heights(&table(1, 1, [1, 1, 1]), 48), Some((43, -12)));
        // The ratio 2:1 only.
        assert_eq!(heights(&table(0, 1, [2, 1, 1]), 48), None);
        // A table cut short.
        assert_eq!(heights(&table(0, 1, [1, 1, 1])[..20], 48), None);
    }

    #[test]
    fn gives_nothing_for_a_face_without_the_table() {
        let mut fonts = crate::FontDb::new();
        let id = fonts.add_font(crate::tests::CARLITO.to_vec()).unwrap()[0];
        assert_eq!(fonts.device_heights(id, 48), None);
        assert_eq!(fonts.device_heights(crate::FontId::from_index(9), 48), None);
    }
}