valo-text 0.27.0

Fonts, shaping and glyph raster for valo: font collections and fallback, harfrust shaping, glyph masks, SDF, COLR
Documentation
//! The faces parsed so far, each with its fonts, so a face asked for again answers the
//! same fonts and is not parsed again: Skia's `SkTypefaceCache`
//! (`src/core/SkTypefaceCache.cpp`), which hands back the typeface it already has of a
//! font and lets go of the ones nobody else holds once it is full.
//!
//! A face is its data, by allocation, at an index, with the remote id it was parsed
//! with: the same bytes in another allocation are another face, which only misses.
//!
//! The invariant: a face stays while anything outside the cache holds one of its fonts,
//! so two holders of one face always hold the same fonts, with the same identifiers.

use std::sync::{Arc, Mutex, PoisonError};

use crate::font::{Font, FontData};

/// How many faces the cache holds before it lets go of those nobody else holds. Skia's
/// `TYPEFACE_CACHE_LIMIT` is 1024 typefaces, which read their tables as they are asked
/// for; a face here holds its character map and shaping data from the start, so fewer
/// are kept.
const FACE_CACHE_LIMIT: usize = 64;

/// Every face parsed in this process.
static FACES: Mutex<FaceCache> = Mutex::new(FaceCache { faces: Vec::new() });

/// The fonts of the face at `face_index` of `data`, parsed with `remote_id`, where the
/// cache has it.
pub(crate) fn find(data: &FontData, face_index: u32, remote_id: Option<u64>) -> Option<Vec<Font>> {
    faces().find(data, face_index, remote_id)
}

/// Keeps `instances` as the fonts of the face at `face_index` of `data`, parsed with
/// `remote_id`.
pub(crate) fn add(data: FontData, face_index: u32, remote_id: Option<u64>, instances: Vec<Font>) {
    faces().add(CachedFace {
        data,
        face_index,
        remote_id,
        instances,
    });
}

fn faces() -> std::sync::MutexGuard<'static, FaceCache> {
    FACES.lock().unwrap_or_else(PoisonError::into_inner)
}

/// One parsed face and its fonts.
struct CachedFace {
    data: FontData,
    face_index: u32,
    remote_id: Option<u64>,
    instances: Vec<Font>,
}

impl CachedFace {
    fn is(&self, data: &FontData, face_index: u32, remote_id: Option<u64>) -> bool {
        self.face_index == face_index
            && self.remote_id == remote_id
            && std::ptr::addr_eq(Arc::as_ptr(&self.data), Arc::as_ptr(data))
    }

    /// Whether only the cache holds the face's fonts: Skia's `SkTypeface::unique`.
    fn is_unique(&self) -> bool {
        self.instances
            .iter()
            .all(|font| !font.is_held_beyond(self.instances.len()))
    }
}

#[derive(Default)]
struct FaceCache {
    faces: Vec<CachedFace>,
}

impl FaceCache {
    fn find(&self, data: &FontData, face_index: u32, remote_id: Option<u64>) -> Option<Vec<Font>> {
        let known = self
            .faces
            .iter()
            .find(|face| face.is(data, face_index, remote_id))?;
        Some(known.instances.clone())
    }

    /// Skia's `SkTypefaceCache::add`: a full cache first lets go of a quarter of its limit.
    fn add(&mut self, face: CachedFace) {
        if self.faces.len() >= FACE_CACHE_LIMIT {
            self.purge(FACE_CACHE_LIMIT >> 2);
        }
        self.faces.push(face);
    }

    /// Skia's `SkTypefaceCache::purge`: lets go of up to `count` faces nobody else holds.
    fn purge(&mut self, count: usize) {
        let mut left = count;
        self.faces.retain(|face| {
            let goes = left > 0 && face.is_unique();
            left -= usize::from(goes);
            !goes
        });
    }
}

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

    fn fira() -> FontData {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../assets/fonts/fira_sans.ttf"
        );
        Arc::new(std::fs::read(path).unwrap())
    }

    /// A face of `data` in a cache of the test's own, with the fonts parsed for it, which
    /// the process's cache never sees.
    fn kept_in(cache: &mut FaceCache, data: FontData) -> Vec<Font> {
        let instances = Font::parsed_instances(Arc::clone(&data), 0, None);
        cache.add(CachedFace {
            data,
            face_index: 0,
            remote_id: None,
            instances: instances.clone(),
        });
        instances
    }

    #[test]
    fn a_face_asked_for_again_answers_the_same_fonts() {
        let data = fira();
        let first = Font::instances_from_data(Arc::clone(&data), 0);
        let again = Font::instances_from_data(data, 0);
        assert_eq!(first.len(), 1);
        assert_eq!(first[0].uid(), again[0].uid());
    }

    #[test]
    fn the_same_bytes_in_another_allocation_are_another_face() {
        let first = Font::instances_from_data(fira(), 0);
        let other = Font::instances_from_data(fira(), 0);
        assert_ne!(first[0].uid(), other[0].uid());
    }

    #[test]
    fn a_purge_lets_go_of_the_faces_nobody_else_holds() {
        let mut cache = FaceCache::default();
        let held = kept_in(&mut cache, fira());
        drop(kept_in(&mut cache, fira()));
        cache.purge(2);
        assert_eq!(cache.faces.len(), 1);
        assert_eq!(cache.faces[0].instances[0].uid(), held[0].uid());
    }

    #[test]
    fn a_full_cache_makes_room_for_the_next_face() {
        let mut cache = FaceCache::default();
        let data = fira();
        for _ in 0..FACE_CACHE_LIMIT {
            drop(kept_in(&mut cache, Arc::clone(&data)));
        }
        drop(kept_in(&mut cache, data));
        assert_eq!(
            cache.faces.len(),
            FACE_CACHE_LIMIT - (FACE_CACHE_LIMIT >> 2) + 1
        );
    }
}