noonoo-engine 0.21.0

Noonoo's orchestration: a parsed, styled, laid-out engine over a DOM document.
Documentation
//! `@font-face`: faces fetched through the host's loader and handed to the
//! host to register.
//!
//! The engine keeps no parsed font store (a `FontSet` borrows its fonts, so
//! the host owns it). It keeps each face's *bytes* (validated by parsing
//! them once) or, for `local()`, the host's own name, under the declared
//! family, weight and style: [`Engine::loaded_fonts`]. A host builds its
//! `FontSet` from that list whenever [`Engine::poll_resources`] says
//! something changed. Until a face arrives, text uses whatever the host's
//! set offers for the family (font-display `swap`).

use std::collections::HashMap;
use std::sync::Arc;

use noonoo_css::FontSource;
use noonoo_net::RequestId;

use crate::Engine;

/// The most faces one engine tracks.
const MAX_FACES: usize = 64;
/// The largest font file it keeps, in bytes.
const MAX_FONT_BYTES: usize = 16 * 1024 * 1024;

/// What a loaded face is made of.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum FontData {
    /// The font file (TrueType or OpenType, parsed once to check it).
    Bytes(Arc<[u8]>),
    /// A face the host already has, by the `local()` name that matched.
    Local(String),
}

/// A `@font-face` the host should register.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LoadedFont {
    /// The declared `font-family`.
    pub family: String,
    /// The declared `font-weight` (a range registers at its first value).
    pub weight: u16,
    /// Whether the face is italic or oblique.
    pub italic: bool,
    /// The font.
    pub data: FontData,
}

struct Face {
    family: String,
    weight: u16,
    italic: bool,
    sources: Vec<FontSource>,
    next: usize,
}

type LocalFonts = Box<dyn Fn(&str) -> bool + Send + Sync>;

#[derive(Default)]
pub(crate) struct Fonts {
    faces: Vec<Face>,
    loaded: Vec<LoadedFont>,
    pending: HashMap<RequestId, usize>,
    local: Option<LocalFonts>,
}

impl Fonts {
    pub(crate) fn owns(&self, id: RequestId) -> bool {
        self.pending.contains_key(&id)
    }
}

/// Whether a `format()` hint names something `noonoo-ttf` reads.
fn supported(format: Option<&str>) -> bool {
    matches!(
        format,
        None | Some("truetype" | "opentype" | "ttf" | "otf" | "collection")
    )
}

impl Engine {
    /// The faces loaded from `@font-face` rules so far, for the host to
    /// register (each under its family, weight and style).
    pub fn loaded_fonts(&self) -> &[LoadedFont] {
        &self.resources.fonts.loaded
    }

    /// How the engine asks the host whether a `local()` name is a face it
    /// has (for instance, `FontSet::select(name, ..).is_some()`). Without
    /// one, `local()` sources are skipped.
    pub fn set_local_fonts(&mut self, has: impl Fn(&str) -> bool + Send + Sync + 'static) {
        self.resources.fonts.local = Some(Box::new(has));
    }

    /// Start loading the `@font-face` rules not seen before; returns the
    /// number of requests started.
    pub(crate) fn load_fonts(&mut self) -> usize {
        if self.resources.loader.is_none() {
            return 0;
        }
        let mut started = 0;
        for face in self.font_faces() {
            if self.resources.fonts.faces.len() >= MAX_FACES {
                break;
            }
            let known = self.resources.fonts.faces.iter().any(|f| {
                f.family == face.family
                    && f.weight == face.weight
                    && f.italic == face.italic
                    && f.sources == face.sources
            });
            if known {
                continue;
            }
            self.resources.fonts.faces.push(Face {
                family: face.family,
                weight: face.weight,
                italic: face.italic,
                sources: face.sources,
                next: 0,
            });
            let index = self.resources.fonts.faces.len() - 1;
            if self.advance_face(index) {
                started += 1;
            }
        }
        started
    }

    /// Move face `index` to its next usable source: a `local()` the host
    /// has completes it; a supported `url()` is requested (true). False
    /// when nothing is left to fetch.
    fn advance_face(&mut self, index: usize) -> bool {
        loop {
            let fonts = &mut self.resources.fonts;
            let face = &mut fonts.faces[index];
            let Some(source) = face.sources.get(face.next).cloned() else {
                return false;
            };
            face.next += 1;
            match source {
                FontSource::Local(name) => {
                    if fonts.local.as_ref().is_some_and(|has| has(&name)) {
                        let face = &fonts.faces[index];
                        fonts.loaded.push(LoadedFont {
                            family: face.family.clone(),
                            weight: face.weight,
                            italic: face.italic,
                            data: FontData::Local(name),
                        });
                        return false;
                    }
                }
                FontSource::Url { url, format } => {
                    if !supported(format.as_deref()) {
                        continue;
                    }
                    let url = match &self.resources.base_url {
                        Some(base) => noonoo_net::resolve(base, &url),
                        None => url,
                    };
                    let Some(loader) = &self.resources.loader else {
                        return false;
                    };
                    let (request, completion) = self.resources.completions.request(url);
                    self.resources.fonts.pending.insert(request.id, index);
                    loader.start(request, completion);
                    return true;
                }
            }
        }
    }

    /// Take in a finished font load. True when a face was added.
    pub(crate) fn font_arrived(
        &mut self,
        id: RequestId,
        result: Result<Vec<u8>, noonoo_net::LoadError>,
    ) -> bool {
        let Some(index) = self.resources.fonts.pending.remove(&id) else {
            return false;
        };
        let usable = result
            .ok()
            .filter(|bytes| bytes.len() <= MAX_FONT_BYTES)
            .filter(|bytes| noonoo_ttf::Font::parse(bytes).is_ok());
        match usable {
            Some(bytes) => {
                let face = &self.resources.fonts.faces[index];
                let font = LoadedFont {
                    family: face.family.clone(),
                    weight: face.weight,
                    italic: face.italic,
                    data: FontData::Bytes(bytes.into()),
                };
                self.resources.fonts.loaded.push(font);
                true
            }
            None => {
                // Try the next source; a `local()` that matches counts.
                let before = self.resources.fonts.loaded.len();
                self.advance_face(index);
                self.resources.fonts.loaded.len() > before
            }
        }
    }
}