f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The file that holds faces of the database: its bytes and the font of each of its faces,
//! loaded at once for bytes that the caller gives, and at the first choice of one of its faces
//! for a file of a folder.

use std::fmt;
use std::io;
use std::ops::Deref;
use std::sync::Arc;

use skrifa::font::{Blob, Font};

/// The bytes of a font file or collection of the database: bytes compiled into the program,
/// which the database never copies, or bytes that it shares with its callers.
#[derive(Clone)]
pub struct FontBytes(Bytes);

#[derive(Clone)]
enum Bytes {
    Static(&'static [u8]),
    Shared(Arc<[u8]>),
}

impl FontBytes {
    /// The bytes as a blob of the font reader, which shares them without a copy.
    pub(crate) fn blob(&self) -> Blob {
        match &self.0 {
            Bytes::Static(bytes) => Blob::Static(bytes),
            Bytes::Shared(bytes) => Blob::Shared(Arc::new(Arc::clone(bytes))),
        }
    }
}

impl From<&'static [u8]> for FontBytes {
    fn from(bytes: &'static [u8]) -> Self {
        Self(Bytes::Static(bytes))
    }
}

impl From<Arc<[u8]>> for FontBytes {
    fn from(bytes: Arc<[u8]>) -> Self {
        Self(Bytes::Shared(bytes))
    }
}

impl Deref for FontBytes {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        match &self.0 {
            Bytes::Static(bytes) => bytes,
            Bytes::Shared(bytes) => bytes,
        }
    }
}

impl AsRef<[u8]> for FontBytes {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl PartialEq for FontBytes {
    fn eq(&self, other: &Self) -> bool {
        **self == **other
    }
}

impl Eq for FontBytes {}

impl fmt::Debug for FontBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "FontBytes({} bytes)", self.len())
    }
}

/// Where a face of the database came from. Of two faces with the same family, style and
/// weight, [`FontDb::query`](crate::FontDb::query) takes the caller's.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FaceOrigin {
    /// Bytes or a font folder that the caller added ([`FontDb::add_font`](crate::FontDb::add_font),
    /// `FontDb::add_files`).
    Caller,
    /// Bytes compiled into the program
    /// ([`FontDb::add_static`](crate::FontDb::add_static)).
    BuiltIn,
}

/// The bytes of a font file or collection, with the font of each of its faces.
pub(crate) struct LoadedFile {
    /// The bytes of the file.
    pub(crate) data: FontBytes,
    /// The font of each face of the file, in the file's order, which a face makes its scaler
    /// from at its first read ([`crate::face::Face::scaler`]).
    pub(crate) fonts: Box<[Font]>,
}

impl LoadedFile {
    /// The file with `data` and `fonts`, the faces of the file in order.
    pub(crate) fn new(data: FontBytes, fonts: Vec<Font>) -> Self {
        Self {
            data,
            fonts: fonts.into(),
        }
    }
}

/// Where the bytes of faces of the database come from: bytes that the caller gave or that the
/// program holds, or a file of a folder. The faces of one file or collection share it.
pub(crate) enum FaceSource {
    /// Bytes that the caller gave or that the program holds, loaded when they were added.
    Given(LoadedFile),
    /// A file of a folder, whose bytes load at the first call of [`FaceSource::load`].
    #[cfg(not(target_arch = "wasm32"))]
    Folder(crate::folder::FolderFile),
}

impl FaceSource {
    /// The loaded file. A file of a folder loads at the first call, and every later call gives
    /// the result of the first, so that a file that did not load is never read again.
    ///
    /// # Errors
    ///
    /// Returns the file's name and the cause when a file of a folder did not load.
    pub(crate) fn load(&self) -> Result<&LoadedFile, FileNotRead> {
        match self {
            Self::Given(file) => Ok(file),
            #[cfg(not(target_arch = "wasm32"))]
            Self::Folder(file) => file.load(),
        }
    }

    /// The loaded file as [`FaceSource::load`] gives it, or `None` for a file that did not load.
    pub(crate) fn loaded(&self) -> Option<&LoadedFile> {
        match self {
            Self::Given(file) => Some(file),
            #[cfg(not(target_arch = "wasm32"))]
            Self::Folder(file) => file.loaded().ok(),
        }
    }
}

/// A font file of a folder whose bytes did not load at the first choice of one of its faces,
/// so that its faces count as missing.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct FileNotRead {
    /// The file's name, without its folder, which
    /// [`FontDb::add_files`](crate::FontDb::add_files) took from its path.
    pub file: String,
    /// Why the file did not load.
    pub cause: NotReadCause,
}

/// Why a font file of a folder did not load.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum NotReadCause {
    /// The file's length or modification time differs from the one that
    /// [`FontDb::add_files`](crate::FontDb::add_files) found, or its bytes no longer hold
    /// the faces that it read.
    Changed,
    /// The file could not be opened or read, with the kind of the error.
    Unreadable(io::ErrorKind),
}

impl fmt::Display for NotReadCause {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Changed => f.write_str("the file changed after its folder was read"),
            Self::Unreadable(kind) => write!(f, "the file could not be read ({kind})"),
        }
    }
}

impl fmt::Display for FileNotRead {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the font file {} did not load: {}",
            self.file, self.cause
        )
    }
}

impl std::error::Error for FileNotRead {}