f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The advance of a glyph at a size as bi-level rendering gives it, and its device width,
//! from the face's TrueType instructions (`f-office-truetype`). The format crates decide where a target uses it, such
//! as a PDF writer that writes these advances as glyph widths.

use std::sync::Mutex;

use f_office_truetype::{Error, Hinter};

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

/// The most hinters that a face keeps for one grid. A document
/// uses a few sizes of a face; the limit bounds the memory of a database that renders many
/// documents to 8 kept hinters of 15 to 38 KiB for each face and grid.
pub(crate) const MOST_KEPT_HINTERS: usize = 8;

/// Makes a hinter for the face `index` of a font file at a size: `Hinter::new` or
/// `Hinter::device`.
type Build = fn(FontBytes, u32, u16) -> Result<Hinter, Error>;

/// The hinters that a face keeps for one grid, each with its pixels per em, the one put back
/// last at the end; `None` for a size whose font program or control value program failed. A
/// hinter is taken out while it hints a glyph, so that the list's lock is not held through a
/// glyph program and threads that render with one database do not wait for each other. A
/// size may have several hinters, one for each thread that hinted it at once, so that such
/// threads each find one the next time. A hinter is boxed, so that taking it out and putting
/// it back moves a pointer.
#[derive(Debug, Default)]
pub(crate) struct KeptHinters {
    hinters: Vec<(u16, Option<Box<Hinter>>)>,
}

/// What a face's list of kept hinters holds for a size.
enum Kept {
    /// A hinter, now taken out of the list.
    Hinter(Box<Hinter>),
    /// The size's programs failed.
    Failed,
    /// Nothing: the size is new, has left the list, or its hinters are out on other threads.
    Missing,
}

impl KeptHinters {
    /// Takes the hinter of `ppem` put back last out of the list, or says that the size failed
    /// or is missing.
    fn take(&mut self, ppem: u16) -> Kept {
        let Some(at) = self.hinters.iter().rposition(|&(size, _)| size == ppem) else {
            return Kept::Missing;
        };
        match self.hinters.remove(at) {
            (_, Some(hinter)) => Kept::Hinter(hinter),
            failed @ (_, None) => {
                self.hinters.insert(at, failed);
                Kept::Failed
            }
        }
    }

    /// Puts the hinter of `ppem`, or `None` for a size that failed, at the end of the list, and
    /// gives back the hinter that leaves it, so that the caller drops that one after the lock
    /// is released: when the list is full, the one put back longest ago leaves it, and a
    /// failed size that the list holds already is not put twice.
    fn put(&mut self, ppem: u16, hinter: Option<Box<Hinter>>) -> Option<Box<Hinter>> {
        if hinter.is_none()
            && self
                .hinters
                .iter()
                .any(|(size, kept)| *size == ppem && kept.is_none())
        {
            return None;
        }
        self.hinters.push((ppem, hinter));
        if self.hinters.len() > MOST_KEPT_HINTERS {
            return self.hinters.remove(0).1;
        }
        None
    }

    /// The size of each hinter in the list, the one put back last at the end.
    #[cfg(test)]
    pub(crate) fn sizes(&self) -> Vec<u16> {
        self.hinters.iter().map(|&(size, _)| size).collect()
    }
}

impl FontDb {
    /// The advance of `glyph` of face `id` in whole pixels at `ppem` pixels per em, as bi-level
    /// rendering gives it: the linear advance where the face says that the glyph's advance
    /// scales linearly at that size, else the advance that the glyph's instructions hint.
    ///
    /// Returns `None` for an unknown face or glyph, a face without TrueType outlines, or
    /// instructions that fail. The database keeps each answer, and a hinter for each size.
    #[must_use]
    pub fn bi_level_advance(&self, id: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        let face = self.face(id)?;
        let key = (ppem, u16::try_from(glyph).ok()?);
        if let Some(&known) = face.bi_level.lock().ok()?.get(&key) {
            return known;
        }
        let advance = hint(face, &face.bi_level_hinters, Hinter::new, ppem, |hinter| {
            hinter.advance(key.1)
        });
        face.bi_level.lock().ok()?.insert(key, advance);
        advance
    }

    /// The device width of `glyph` of face `id` in whole pixels at `ppem` pixels per em: the
    /// advance point after the glyph's instructions in the interpreter's device-width mode,
    /// rounded, which is the width that Word's device steps a glyph by.
    ///
    /// Returns `None` for an unknown face or glyph, a face without TrueType outlines, or
    /// instructions that fail. The database keeps each answer, and a hinter for each size.
    #[must_use]
    pub fn device_width(&self, id: FontId, glyph: u32, ppem: u16) -> Option<i32> {
        let face = self.face(id)?;
        let key = (ppem, u16::try_from(glyph).ok()?);
        if let Some(&known) = face.device.lock().ok()?.get(&key) {
            return known;
        }
        let width = hint(face, &face.device_hinters, Hinter::device, ppem, |hinter| {
            hinter.device_width(key.1)
        });
        face.device.lock().ok()?.insert(key, width);
        width
    }
}

/// Hints one glyph of the face at `ppem` with `glyph`, by a hinter that `kept` holds for the
/// size or by a new one from `build`, which runs the face's font program and control value
/// program, and puts the hinter back. The list's lock is held only to take and to put, and a
/// hinter that leaves the list is dropped after the lock is released.
fn hint(
    face: &Face,
    kept: &Mutex<KeptHinters>,
    build: Build,
    ppem: u16,
    glyph: impl FnOnce(&mut Hinter) -> Result<i32, Error>,
) -> Option<i32> {
    let taken = kept
        .lock()
        .map_or(Kept::Missing, |mut list| list.take(ppem));
    let mut hinter = match taken {
        Kept::Hinter(hinter) => hinter,
        Kept::Failed => return None,
        Kept::Missing => {
            let made = face
                .data()
                .and_then(|data| build(data.clone(), face.index, ppem).ok());
            let Some(hinter) = made else {
                let left = kept.lock().ok().and_then(|mut list| list.put(ppem, None));
                drop(left);
                return None;
            };
            Box::new(hinter)
        }
    };
    let answer = glyph(&mut hinter).ok();
    let left = kept
        .lock()
        .ok()
        .and_then(|mut list| list.put(ppem, Some(hinter)));
    drop(left);
    answer
}

#[cfg(test)]
mod tests {
    use super::{Kept, KeptHinters, MOST_KEPT_HINTERS};
    use f_office_truetype::Hinter;

    fn hinter() -> Box<Hinter> {
        Box::new(Hinter::new(crate::tests::CARLITO, 0, 12).unwrap())
    }

    /// What `take` gave, by name.
    fn named(kept: &Kept) -> &'static str {
        match kept {
            Kept::Hinter(_) => "hinter",
            Kept::Failed => "failed",
            Kept::Missing => "missing",
        }
    }

    #[test]
    fn takes_a_hinter_out_and_keeps_a_failed_size_once() {
        let mut list = KeptHinters::default();
        let left = [
            list.put(10, None),
            list.put(10, None),
            list.put(12, Some(hinter())),
        ];
        assert!(left.iter().all(Option::is_none));
        // After the hinter is out, a second thread finds none and builds one.
        let taken = [list.take(10), list.take(12), list.take(12)];
        assert_eq!(taken.each_ref().map(named), ["failed", "hinter", "missing"]);
        assert_eq!(list.sizes(), [10]);
    }

    #[test]
    fn keeps_a_hinter_for_each_thread_that_hinted_a_size_at_once() {
        let mut list = KeptHinters::default();
        let left = [list.put(12, Some(hinter())), list.put(12, Some(hinter()))];
        assert!(left.iter().all(Option::is_none));
        assert_eq!(list.sizes(), [12, 12]);
        let taken = [list.take(12), list.take(12), list.take(12)];
        assert_eq!(taken.each_ref().map(named), ["hinter", "hinter", "missing"]);
    }

    #[test]
    fn gives_back_the_hinter_put_back_longest_ago_when_full() {
        let mut list = KeptHinters::default();
        let most = u16::try_from(MOST_KEPT_HINTERS).unwrap();
        let left: Vec<bool> = (1..=most)
            .map(|ppem| list.put(ppem, Some(hinter())).is_some())
            .collect();
        assert!(!left.contains(&true));
        // Size 1 is taken out and put back, so size 2 is the one put back longest ago.
        let Kept::Hinter(one) = list.take(1) else {
            unreachable!("size 1 is kept");
        };
        let left = [list.put(1, Some(one)), list.put(99, Some(hinter()))];
        assert_eq!(left.each_ref().map(Option::is_some), [false, true]);
        let mut expected: Vec<u16> = (3..=most).collect();
        expected.extend([1, 99]);
        assert_eq!(list.sizes(), expected);
    }
}