f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! The glyphs of a text by the font's OpenType layout tables (`GSUB` and `GPOS`).
//!
//! This module is the only place that names the shaping crate. Layout and the outputs see
//! [`ShapeRequest`], [`ShapedGlyph`] and [`ShapeFailure`] only.

use std::fmt;

use harfrust::{Buffer, Direction, Language, Script, ShapeOptions, ShaperFont};

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

/// A script whose text goes through the font's layout tables. The set is closed: a
/// character of no listed script keeps the glyph that the font's character map gives it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ShapedScript {
    /// The Arabic script: its letters and marks in the blocks Arabic, Arabic Supplement,
    /// Arabic Extended-A and the two blocks of presentation forms.
    Arabic,
    /// The Devanagari script: its letters, vowel signs and marks in the blocks Devanagari and
    /// Devanagari Extended, which the font's tables join into conjuncts, half forms and the
    /// reph, and whose vowel signs they move before or over their consonants.
    Devanagari,
}

impl ShapedScript {
    /// The script of a character that goes through the layout tables, or nothing.
    ///
    /// The letters and marks of the Arabic blocks have the script, and so have the zero
    /// width joiner and non-joiner, which change the form of the letters beside them. A
    /// space, a digit (also an Arabic-Indic one), Arabic punctuation and every character of
    /// another block have none: they end a stretch of shaped text, and a letter does not
    /// join over them. The letters, vowel signs and marks of the Devanagari blocks have the
    /// Devanagari script; its dandas, digits and abbreviation sign have none.
    #[must_use]
    pub fn of(ch: char) -> Option<Self> {
        if matches!(ch, '\u{0900}'..='\u{0963}' | '\u{0971}'..='\u{097F}' | '\u{A8E0}'..='\u{A8FF}')
        {
            return Some(Self::Devanagari);
        }
        let arabic = match ch {
            // Punctuation, number signs and digits of the Arabic block.
            '\u{0600}'..='\u{060F}'
            | '\u{061B}'..='\u{061F}'
            | '\u{0660}'..='\u{066D}'
            | '\u{06D4}'
            | '\u{06DD}'
            | '\u{06F0}'..='\u{06F9}' => false,
            '\u{0610}'..='\u{06FF}'
            | '\u{0750}'..='\u{077F}'
            | '\u{08A0}'..='\u{08FF}'
            | '\u{FB50}'..='\u{FDCF}'
            | '\u{FDF0}'..='\u{FDFB}'
            | '\u{FE70}'..='\u{FEFC}'
            | '\u{200C}'
            | '\u{200D}' => true,
            _ => false,
        };
        arabic.then_some(Self::Arabic)
    }

    /// The direction in which text of the script reads.
    #[must_use]
    pub fn direction(self) -> ShapeDirection {
        match self {
            Self::Arabic => ShapeDirection::RightToLeft,
            Self::Devanagari => ShapeDirection::LeftToRight,
        }
    }

    /// The script for the shaping crate.
    fn script(self) -> Script {
        match self {
            Self::Arabic => Script::ARABIC,
            Self::Devanagari => Script::DEVANAGARI,
        }
    }
}

/// The direction in which a shaped text reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShapeDirection {
    /// From left to right.
    LeftToRight,
    /// From right to left.
    RightToLeft,
}

/// A text to shape with one face.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShapeRequest<'a> {
    /// The characters, in the order of the text.
    pub text: &'a str,
    /// The script of the characters.
    pub script: ShapedScript,
    /// The direction in which the text reads.
    pub direction: ShapeDirection,
    /// The language tag of the text, such as `fa-IR`, when it has one. A font can hold
    /// other glyphs for a language.
    pub language: Option<&'a str>,
}

/// One glyph of a shaped text, in font units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShapedGlyph {
    /// The glyph ID in the font.
    pub glyph: u32,
    /// How far the line goes on after the glyph.
    pub advance: i32,
    /// Where the glyph's origin lies from its place in the line: to the right and up.
    pub offset: (i32, i32),
    /// The byte index in [`ShapeRequest::text`] of the first character that the glyph
    /// stands for. Glyphs of one group of characters share the index.
    pub cluster: usize,
}

/// Why a text has no shaped glyphs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ShapeFailure {
    /// The caller has no shaper.
    NoShaper,
    /// The database has no face of that ID.
    UnknownFace,
    /// The shaper refused the text or the face.
    Refused,
}

impl fmt::Display for ShapeFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NoShaper => "no shaper is available",
            Self::UnknownFace => "the face is not in the font database",
            Self::Refused => "the shaper refused the text or the face",
        })
    }
}

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

impl FontDb {
    /// Returns the glyphs of a text by the layout tables of a face, in the order of the
    /// text: the first glyph stands for the first characters, also in a text that reads
    /// from right to left. The caller orders a line.
    ///
    /// # Errors
    ///
    /// Returns the cause when the face is unknown or when the shaper refuses the text or the
    /// face. The caller then draws the characters with the glyphs of the font's character
    /// map. A face without a `GSUB` and a `GPOS` table is no failure: the shaper then gives
    /// an Arabic letter the glyph of its presentation-form character, when the font has it.
    pub fn shape(
        &self,
        id: FontId,
        request: &ShapeRequest<'_>,
    ) -> Result<Vec<ShapedGlyph>, ShapeFailure> {
        let font = self
            .face(id)
            .and_then(Face::font)
            .ok_or(ShapeFailure::UnknownFace)?;
        let font = ShaperFont::new(font);
        let mut buffer = Buffer::new();
        buffer.push_str(request.text);
        buffer.set_direction(match request.direction {
            ShapeDirection::LeftToRight => Direction::LeftToRight,
            ShapeDirection::RightToLeft => Direction::RightToLeft,
        });
        buffer.set_script(Some(request.script.script()));
        buffer.set_language(request.language.and_then(Language::new));
        harfrust::shape(&font, &mut buffer, ShapeOptions::new())
            .map_err(|_| ShapeFailure::Refused)?;
        if !buffer.allocation_successful() {
            return Err(ShapeFailure::Refused);
        }
        let mut glyphs: Vec<ShapedGlyph> = buffer
            .glyph_infos()
            .iter()
            .zip(buffer.glyph_positions())
            .map(|(info, position)| ShapedGlyph {
                glyph: info.glyph_id,
                advance: position.x_advance,
                offset: (position.x_offset, position.y_offset),
                cluster: usize::try_from(info.cluster).unwrap_or(usize::MAX),
            })
            .collect();
        // The shaper gives a right-to-left text from the left of the line.
        if request.direction == ShapeDirection::RightToLeft {
            glyphs.reverse();
        }
        Ok(glyphs)
    }
}

#[cfg(test)]
mod tests {
    use super::{ShapeDirection, ShapeFailure, ShapeRequest, ShapedScript};
    use crate::tests::CARLITO;
    use crate::{FontDb, FontId};

    fn request(text: &str, direction: ShapeDirection) -> ShapeRequest<'_> {
        ShapeRequest {
            text,
            script: ShapedScript::Arabic,
            direction,
            language: None,
        }
    }

    /// Carlito with the tables of `tags` renamed, so that the font seems to lack them.
    fn without_tables(tags: &[&[u8; 4]]) -> Vec<u8> {
        let mut data = CARLITO.to_vec();
        let count = usize::from(u16::from_be_bytes([data[4], data[5]]));
        for record in 0..count {
            let at = 12 + record * 16;
            if tags.iter().any(|tag| data[at..at + 4] == tag[..]) {
                data[at..at + 4].copy_from_slice(b"zzzz");
            }
        }
        data
    }

    #[test]
    fn only_letters_and_marks_of_the_arabic_and_devanagari_blocks_have_a_shaped_script() {
        for ch in [
            'ب', 'ـ', '\u{064E}', 'پ', '\u{FE8F}', '\u{200D}', '\u{200C}',
        ] {
            assert_eq!(ShapedScript::of(ch), Some(ShapedScript::Arabic), "{ch:?}");
        }
        for ch in [
            ' ', '7', '٧', '۷', '،', '؟', 'a', 'א', '-', '\u{200F}', '।', '१',
        ] {
            assert_eq!(ShapedScript::of(ch), None, "{ch:?}");
        }
        for ch in ['क', '\u{094D}', '\u{093F}', '\u{0902}', 'ॐ', '\u{A8E0}'] {
            assert_eq!(
                ShapedScript::of(ch),
                Some(ShapedScript::Devanagari),
                "{ch:?}"
            );
        }
    }

    #[test]
    fn gives_the_glyphs_in_the_order_of_the_text_in_both_directions() {
        let mut db = FontDb::new();
        let id = db.add_font(CARLITO.to_vec()).unwrap()[0];
        let ids = ['o', 'x'].map(|ch| db.glyph_id(id, ch).unwrap());
        for direction in [ShapeDirection::LeftToRight, ShapeDirection::RightToLeft] {
            let glyphs = db.shape(id, &request("ox", direction)).unwrap();
            assert_eq!(glyphs.iter().map(|g| g.glyph).collect::<Vec<_>>(), ids);
            assert_eq!(glyphs.iter().map(|g| g.cluster).collect::<Vec<_>>(), [0, 1]);
            assert!(glyphs.iter().all(|g| g.advance > 0 && g.offset == (0, 0)));
        }
    }

    #[test]
    fn shapes_a_face_without_layout_tables_by_its_character_map() {
        let mut db = FontDb::new();
        let bare = db.add_font(without_tables(&[b"GSUB", b"GPOS"])).unwrap()[0];
        let ids = ['o', 'x'].map(|ch| db.glyph_id(bare, ch).unwrap());
        let glyphs = db
            .shape(bare, &request("ox", ShapeDirection::RightToLeft))
            .unwrap();
        assert_eq!(glyphs.iter().map(|g| g.glyph).collect::<Vec<_>>(), ids);
    }

    #[test]
    fn says_why_a_text_has_no_shaped_glyphs() {
        let db = FontDb::new();
        let text = request("ox", ShapeDirection::LeftToRight);
        let unknown = FontId::from_index(7);
        assert_eq!(db.shape(unknown, &text), Err(ShapeFailure::UnknownFace));
        assert_eq!(
            ShapeFailure::UnknownFace.to_string(),
            "the face is not in the font database"
        );
    }
}