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()
}
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()
}
fn coverage(glyphs: &[u16]) -> Vec<u8> {
let mut out = words(&[1, len16(glyphs.len())]);
out.extend(words(glyphs));
out
}
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
}
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();
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
}
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
}
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
}
fn lookup(kind: u16, subtable: Vec<u8>) -> Vec<u8> {
with_parts(&[kind, 0, 1], &[subtable])
}
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)
}
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()
}
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)
}
}
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'))])),
]
}
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();
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();
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() {
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);
}