lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! External SVG requests use the same host discovery, generic names and
//! admitted file snapshots as native text, but a private asset font database.

use super::{fold_family_name, scalar_presence_map, CanonicalFontCore, FontPreparation};
use crate::Result;
use fontdb::{Database, Family, ID};
use std::collections::HashSet;

/// Match a CSS family spelling with the canonical host family normalization.
pub(crate) fn svg_family_name<'a>(db: &'a Database, name: &str) -> Result<Option<&'a str>> {
    let folded = fold_family_name(name)?;
    for (family, _) in db.faces().flat_map(|face| &face.families) {
        if fold_family_name(family)? == folded {
            return Ok(Some(family));
        }
    }
    Ok(None)
}

pub(crate) struct SvgFontCatalog {
    core: CanonicalFontCore,
    copied: HashSet<ID>,
}

#[cfg(test)]
thread_local! {
    static FIXTURE_FONTS: std::cell::RefCell<Option<Vec<Vec<u8>>>> =
        const { std::cell::RefCell::new(None) };
}

/// Scope the external SVG catalogue to real generated font files for a test.
/// The ordinary renderer and host font inventory are otherwise untouched.
#[cfg(test)]
pub(super) fn with_fixture_fonts<T>(fonts: Vec<Vec<u8>>, test: impl FnOnce() -> T) -> T {
    struct Restore(Option<Vec<Vec<u8>>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            FIXTURE_FONTS.replace(self.0.take());
        }
    }
    let _restore = Restore(FIXTURE_FONTS.replace(Some(fonts)));
    test()
}

impl SvgFontCatalog {
    pub(crate) fn new() -> Result<Self> {
        #[cfg(test)]
        if let Some(fonts) = FIXTURE_FONTS.with_borrow(Clone::clone) {
            return Ok(Self {
                core: CanonicalFontCore::from_generated(
                    fonts,
                    &super::HostGenericNames::default(),
                    FontPreparation::new(),
                    scalar_presence_map()?,
                )?,
                copied: HashSet::new(),
            });
        }
        Ok(Self {
            core: CanonicalFontCore::discover_prepared(
                FontPreparation::new(),
                scalar_presence_map()?,
                None,
            )?,
            copied: HashSet::new(),
        })
    }

    pub(crate) fn load(&mut self, families: &[Family<'_>], db: &mut Database) -> Result<()> {
        for family in [
            Family::Serif,
            Family::SansSerif,
            Family::Monospace,
            Family::Cursive,
            Family::Fantasy,
        ] {
            let name = self.core.database.family_name(&family).to_owned();
            match family {
                Family::Serif => db.set_serif_family(name),
                Family::SansSerif => db.set_sans_serif_family(name),
                Family::Monospace => db.set_monospace_family(name),
                Family::Cursive => db.set_cursive_family(name),
                Family::Fantasy => db.set_fantasy_family(name),
                Family::Name(_) => unreachable!(),
            }
        }
        let names = families
            .iter()
            .map(|family| fold_family_name(self.core.database.family_name(family)))
            .collect::<std::result::Result<Vec<_>, _>>()?;
        self.core.materialize_matching(&names, None)?;
        self.copy_admitted(db);
        Ok(())
    }

    fn copy_admitted(&mut self, db: &mut Database) {
        for info in self.core.database.faces() {
            if self.copied.insert(info.id) {
                db.push_face_info(info.clone());
            }
        }
    }

    pub(crate) fn fallback(&mut self, scalar: char, db: &mut Database) -> Result<Option<ID>> {
        // Host files remain lazy until the shaped text actually needs an
        // unprovided character. Stop as soon as an admitted face covers it.
        for ordinal in 0..self.core.index.len() {
            if !self.core.index[ordinal].pending() {
                continue;
            }
            self.core.materialize_file(ordinal, None)?;
            let mut selected = None;
            for info in self.core.database.faces() {
                if self.copied.insert(info.id) {
                    let id = db.push_face_info(info.clone());
                    if selected.is_none()
                        && db
                            .with_face_data(id, |bytes, index| {
                                ttf_parser::Face::parse(bytes, index)
                                    .is_ok_and(|face| face.glyph_index(scalar).is_some())
                            })
                            .unwrap_or(false)
                    {
                        selected = Some(id);
                    }
                }
            }
            if selected.is_some() {
                return Ok(selected);
            }
        }
        Ok(None)
    }
}