f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Tests with copies of Carlito whose `GSUB` table is replaced in memory by one that the tests
//! build, with an `ssty` feature in chosen scripts.

use crate::tests::CARLITO;
use crate::{FontDb, FontId, ScriptLevel};

const ONE: ScriptLevel = ScriptLevel::Script;
const TWO: ScriptLevel = ScriptLevel::ScriptOfScript;

fn u16_at(data: &[u8], at: usize) -> u16 {
    u16::from_be_bytes([data[at], data[at + 1]])
}

fn len16(items: usize) -> u16 {
    u16::try_from(items).unwrap()
}

/// Carlito with its `GSUB` record pointed at `gsub`, which follows the font's data.
fn with_gsub(gsub: &[u8]) -> Vec<u8> {
    let mut data = CARLITO.to_vec();
    data.resize(data.len().next_multiple_of(4), 0);
    let offset = u32::try_from(data.len()).unwrap();
    let record = (0..usize::from(u16_at(&data, 4)))
        .map(|index| 12 + 16 * index)
        .find(|&at| &data[at..at + 4] == b"GSUB")
        .unwrap();
    data[record + 8..record + 12].copy_from_slice(&offset.to_be_bytes());
    data[record + 12..record + 16]
        .copy_from_slice(&u32::try_from(gsub.len()).unwrap().to_be_bytes());
    data.extend(gsub);
    data
}

fn words(values: &[u16]) -> Vec<u8> {
    values.iter().flat_map(|v| v.to_be_bytes()).collect()
}

/// A coverage table of format 1.
fn coverage(glyphs: &[u16]) -> Vec<u8> {
    let mut out = words(&[1, len16(glyphs.len())]);
    out.extend(words(glyphs));
    out
}

/// A table that starts with `head`, a list of offsets from its start to `parts` and the parts.
fn with_parts(head: &[u16], parts: &[Vec<u8>]) -> Vec<u8> {
    let mut at = 2 * (head.len() + parts.len());
    let mut offsets = Vec::new();
    for part in parts {
        offsets.push(len16(at));
        at += part.len();
    }
    let mut out = words(head);
    out.extend(words(&offsets));
    out.extend(parts.concat());
    out
}

/// An alternate substitution of format 1, with the glyphs in order.
fn alternates(sets: &[(u16, &[u16])]) -> Vec<u8> {
    let glyphs: Vec<u16> = sets.iter().map(|(glyph, _)| *glyph).collect();
    let parts: Vec<Vec<u8>> = sets
        .iter()
        .map(|(_, set)| [words(&[len16(set.len())]), words(set)].concat())
        .collect();
    // The coverage table follows the head, the offsets and the alternate sets.
    let at = 6 + 2 * sets.len() + parts.iter().map(Vec::len).sum::<usize>();
    let mut out = with_parts(&[1, len16(at), len16(sets.len())], &parts);
    out.extend(coverage(&glyphs));
    out
}

/// A single substitution of format 2, with the glyphs in order.
fn singles(pairs: &[(u16, u16)]) -> Vec<u8> {
    let glyphs: Vec<u16> = pairs.iter().map(|(glyph, _)| *glyph).collect();
    let substitutes: Vec<u16> = pairs.iter().map(|(_, to)| *to).collect();
    let mut out = words(&[2, len16(6 + 2 * pairs.len()), len16(pairs.len())]);
    out.extend(words(&substitutes));
    out.extend(coverage(&glyphs));
    out
}

/// A single substitution of format 1: each glyph plus `delta`.
fn shifted(glyphs: &[u16], delta: i16) -> Vec<u8> {
    let mut out = words(&[1, 6]);
    out.extend(delta.to_be_bytes());
    out.extend(coverage(glyphs));
    out
}

/// A lookup of `kind` with one subtable.
fn lookup(kind: u16, subtable: Vec<u8>) -> Vec<u8> {
    with_parts(&[kind, 0, 1], &[subtable])
}

/// An extension lookup (type 7) that holds one subtable of `kind`.
fn extension(kind: u16, subtable: &[u8]) -> Vec<u8> {
    let mut inner = words(&[1, kind]);
    inner.extend(8_u32.to_be_bytes());
    inner.extend(subtable);
    lookup(7, inner)
}

/// A `GSUB` table: each script's default language takes the features at its indices, and each
/// feature (all `ssty`) the lookups at its indices.
fn gsub(scripts: &[(&[u8; 4], &[u16])], features: &[&[u16]], lookups: &[Vec<u8>]) -> Vec<u8> {
    let tagged = |tags: Vec<&[u8; 4]>, tables: Vec<Vec<u8>>| {
        let mut at = 2 + 6 * tables.len();
        let mut out = words(&[len16(tables.len())]);
        for (tag, table) in tags.iter().zip(&tables) {
            out.extend(*tag);
            out.extend(words(&[len16(at)]));
            at += table.len();
        }
        out.extend(tables.concat());
        out
    };
    let script_list = tagged(
        scripts.iter().map(|(tag, _)| *tag).collect(),
        scripts
            .iter()
            .map(|(_, features)| {
                words(&[&[4, 0, 0, 0xFFFF, len16(features.len())], *features].concat())
            })
            .collect(),
    );
    let feature_list = tagged(
        features.iter().map(|_| b"ssty").collect(),
        features
            .iter()
            .map(|lookups| words(&[&[0, len16(lookups.len())], *lookups].concat()))
            .collect(),
    );
    let lookup_list = with_parts(&[len16(lookups.len())], lookups);
    let features_at = 10 + script_list.len();
    let lookups_at = features_at + feature_list.len();
    let mut out = words(&[1, 0, 10, len16(features_at), len16(lookups_at)]);
    out.extend([script_list, feature_list, lookup_list].concat());
    out
}

struct Glyphs(FontDb);

impl Glyphs {
    fn new(gsub: &[u8]) -> Self {
        let mut fonts = FontDb::new();
        fonts.add_font(with_gsub(gsub)).unwrap();
        Self(fonts)
    }

    fn id(&self, ch: char) -> u16 {
        u16::try_from(self.0.glyph_id(FontId::from_index(0), ch).unwrap()).unwrap()
    }

    /// The character whose glyph the feature puts in place of `ch`'s at `level`.
    fn at(&self, ch: char, level: ScriptLevel) -> Option<char> {
        let glyph = self
            .0
            .script_glyph(FontId::from_index(0), u32::from(self.id(ch)), level)?;
        ('a'..='z').find(|&c| u32::from(self.id(c)) == glyph)
    }
}

/// The lookups of the tests: alternates of `a` and `x`, `c` to `d` through an extension, `m`
/// to `n` by a delta, and `z` to `q`.
fn lookups(font: &Glyphs) -> Vec<Vec<u8>> {
    let g = |ch| font.id(ch);
    let mut sets = [(g('a'), vec![g('b'), g('c')]), (g('x'), vec![g('y')])];
    sets.sort_unstable();
    let sets: Vec<(u16, &[u16])> = sets
        .iter()
        .map(|(glyph, set)| (*glyph, set.as_slice()))
        .collect();
    let delta = i16::try_from(i32::from(g('n')) - i32::from(g('m'))).unwrap();
    vec![
        lookup(3, alternates(&sets)),
        extension(1, &singles(&[(g('c'), g('d'))])),
        lookup(1, shifted(&[g('m')], delta)),
        lookup(1, singles(&[(g('z'), g('q'))])),
    ]
}

/// A font whose `math` script takes lookups 0 to 2 and whose `latn` script takes lookup 3.
fn math_font() -> Glyphs {
    let plain = Glyphs::new(&gsub(&[], &[], &[]));
    Glyphs::new(&gsub(
        &[(b"latn", &[1]), (b"math", &[0])],
        &[&[0, 1, 2], &[3]],
        &lookups(&plain),
    ))
}

#[test]
fn takes_the_alternate_of_the_level_after_each_lookup_in_turn() {
    let font = math_font();
    let cases = [('a', ONE), ('a', TWO), ('c', ONE), ('x', ONE), ('x', TWO)];
    let found: Vec<Option<char>> = cases
        .iter()
        .map(|&(ch, level)| font.at(ch, level))
        .collect();
    // The second alternate of `a` is `c`, which the extension's single substitution then
    // changes to `d`; a set with fewer alternates than the level changes nothing.
    assert_eq!(found, [Some('b'), Some('d'), Some('d'), Some('y'), None]);
}

#[test]
fn gives_a_single_substitution_at_every_level() {
    let font = math_font();
    let cases = [('m', ONE), ('m', TWO), ('e', ONE), ('z', ONE)];
    let found: Vec<Option<char>> = cases
        .iter()
        .map(|&(ch, level)| font.at(ch, level))
        .collect();
    // `e` is in no lookup, and `z` only in the Latin script's feature, which a font with a
    // `math` script does not read.
    assert_eq!(found, [Some('n'), Some('n'), None, None]);
    assert_eq!(font.0.script_glyph(FontId::from_index(4), 1, ONE), None);
}

#[test]
fn reads_the_default_script_without_a_math_script() {
    let plain = Glyphs::new(&gsub(&[], &[], &[]));
    let font = Glyphs::new(&gsub(&[(b"DFLT", &[0])], &[&[3]], &lookups(&plain)));
    assert_eq!(font.at('z', ONE), Some('q'));
    assert_eq!(font.at('a', ONE), None);
    let latin = Glyphs::new(&gsub(&[(b"latn", &[0])], &[&[3]], &lookups(&plain)));
    assert_eq!(latin.at('z', ONE), None);
}

#[test]
fn a_font_without_the_feature_or_with_a_broken_table_has_no_script_glyphs() {
    // Carlito's own `GSUB` table has no `ssty` feature.
    let mut fonts = FontDb::new();
    let id = fonts.add_font(CARLITO.to_vec()).unwrap()[0];
    let a = fonts.glyph_id(id, 'a').unwrap();
    assert_eq!(fonts.script_glyph(id, a, ONE), None);
    let broken = Glyphs::new(&[0, 1, 0]);
    assert_eq!(broken.at('a', ONE), None);
}