use std::path::Path;
use super::{
Decoration, FaceOrigin, FamilyName, FontDb, FontError, FontId, FontMetrics, KerningSource,
LineMetrics, Os2Metrics, OutlineError, PathCommand, ScriptMetrics, version_number,
};
pub(crate) const CARLITO: &[u8] = include_bytes!(concat!(
env!(
"F_OFFICE_UNIT_TEST_FONTS",
"set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
),
"/Carlito-Regular.ttf"
));
fn name(name: &str) -> FamilyName {
FamilyName::new(name)
}
fn fonts_folder() -> &'static Path {
Path::new(env!(
"F_OFFICE_UNIT_TEST_FONTS",
"set F_OFFICE_UNIT_TEST_FONTS to the folder of the test fonts, which holds Carlito-Regular.ttf"
))
}
fn read_u16(data: &[u8], at: usize) -> u16 {
u16::from_be_bytes([data[at], data[at + 1]])
}
fn read_u32(data: &[u8], at: usize) -> u32 {
u32::from_be_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]])
}
fn table_record(data: &[u8], tag: [u8; 4]) -> usize {
let count = usize::from(read_u16(data, 4));
(0..count)
.map(|index| 12 + 16 * index)
.find(|&at| data[at..at + 4] == tag)
.unwrap()
}
fn table_offset(data: &[u8], tag: [u8; 4]) -> usize {
read_u32(data, table_record(data, tag) + 8) as usize
}
fn write_u16(data: &mut [u8], at: usize, value: u16) {
data[at..at + 2].copy_from_slice(&value.to_be_bytes());
}
pub(crate) fn without_table(tag: [u8; 4]) -> Vec<u8> {
let mut data = CARLITO.to_vec();
let at = table_record(&data, tag);
data[at..at + 4].copy_from_slice(b"zzzz");
data
}
pub(crate) fn with_table_at_offset_zero(tag: [u8; 4]) -> Vec<u8> {
let mut data = CARLITO.to_vec();
let at = table_record(&data, tag) + 8;
data[at..at + 4].copy_from_slice(&0_u32.to_be_bytes());
data
}
pub(crate) fn with_style(weight: u16, italic: bool) -> Vec<u8> {
let mut data = CARLITO.to_vec();
let os2 = table_offset(&data, *b"OS/2");
write_u16(&mut data, os2 + 4, weight);
write_u16(&mut data, os2 + 62, u16::from(italic));
data
}
pub(crate) fn collection(count: u32) -> Vec<u8> {
collection_after(count, 0)
}
pub(crate) fn collection_after(count: u32, gap: u32) -> Vec<u8> {
let header_len = 12 + 4 * count + gap;
let mut data = b"ttcf".to_vec();
data.extend(0x0001_0000_u32.to_be_bytes());
data.extend(count.to_be_bytes());
for _ in 0..count {
data.extend(header_len.to_be_bytes());
}
data.extend(vec![0; usize::try_from(gap).unwrap()]);
let mut font = CARLITO.to_vec();
for index in 0..usize::from(read_u16(&font, 4)) {
let at = 12 + 16 * index + 8;
let offset = read_u32(&font, at) + header_len;
font[at..at + 4].copy_from_slice(&offset.to_be_bytes());
}
data.extend(font);
data
}
pub(crate) fn with_kern(pairs: &[(u16, u16, i16)]) -> Vec<u8> {
let subtable = |coverage: u16, pairs: &[(u16, u16, i16)]| {
let mut out = Vec::new();
let count = u16::try_from(pairs.len()).unwrap();
out.extend(0_u16.to_be_bytes());
out.extend((14 + 6 * count).to_be_bytes());
out.extend(coverage.to_be_bytes());
out.extend(count.to_be_bytes());
out.extend([0_u8; 6]);
for (left, right, value) in pairs {
out.extend(left.to_be_bytes());
out.extend(right.to_be_bytes());
out.extend(value.to_be_bytes());
}
out
};
let mut kern = vec![0, 0, 0, 2];
kern.extend(subtable(0x0001, pairs));
let cross: Vec<(u16, u16, i16)> = pairs.iter().map(|(l, r, _)| (*l, *r, 1000)).collect();
kern.extend(subtable(0x0005, &cross));
let font = CARLITO;
let count = usize::from(read_u16(font, 4));
let mut records: Vec<Vec<u8>> = (0..count)
.map(|index| {
let at = 12 + 16 * index;
let mut record = font[at..at + 16].to_vec();
let offset = read_u32(font, at + 8) + 16;
record[8..12].copy_from_slice(&offset.to_be_bytes());
record
})
.collect();
let body = &font[12 + 16 * count..];
let padding = (4 - body.len() % 4) % 4;
let kern_offset = u32::try_from(12 + 16 * (count + 1) + body.len() + padding).unwrap();
let mut record = b"kern".to_vec();
record.extend(0_u32.to_be_bytes());
record.extend(kern_offset.to_be_bytes());
record.extend(u32::try_from(kern.len()).unwrap().to_be_bytes());
records.push(record);
records.sort_by(|a, b| a[..4].cmp(&b[..4]));
let mut data = font[..4].to_vec();
data.extend(u16::try_from(count + 1).unwrap().to_be_bytes());
data.extend(&font[6..12]);
data.extend(records.concat());
data.extend(body);
data.extend(vec![0; padding]);
data.extend(kern);
data
}
fn database(fonts: &[Vec<u8>]) -> FontDb {
let mut db = FontDb::new();
for font in fonts {
db.add_font(font.clone()).unwrap();
}
db
}
#[test]
fn adds_one_face_and_counts_it() {
let mut db = FontDb::new();
assert!(db.is_empty());
assert_eq!(db.len(), 0);
assert_eq!(
db.add_font(CARLITO.to_vec()),
Ok(vec![FontId::from_index(0)])
);
assert!(!db.is_empty());
assert_eq!(db.len(), 1);
}
#[test]
fn ids_continue_across_fonts() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
let data: std::sync::Arc<[u8]> = CARLITO.into();
assert_eq!(db.add_font(data), Ok(vec![FontId::from_index(1)]));
let ids: Vec<u32> = db.faces().map(|(id, _)| id.index()).collect();
assert_eq!(ids, [0, 1]);
}
#[test]
fn index_round_trips() {
assert_eq!(FontId::from_index(7).index(), 7);
}
#[test]
fn a_font_without_a_math_table_has_no_limits_and_no_display_variants() {
let db = database(&[CARLITO.to_vec()]);
for font in [FontId::from_index(0), FontId::from_index(5)] {
assert_eq!(db.math_limits(font), None);
assert_eq!(db.math_radical(font), None);
assert_eq!(db.display_variant(font, 3), None);
assert_eq!(db.italic_correction(font, 3), None);
}
}
#[test]
fn a_face_is_light_only_when_both_of_its_weights_are_below_bold() {
let mut black = with_style(400, false);
let os2 = table_offset(&black, *b"OS/2");
if let Some(byte) = black.get_mut(os2 + 34) {
*byte = 10;
}
let db = database(&[CARLITO.to_vec(), with_style(700, false), black]);
let light = |index| db.info(FontId::from_index(index)).unwrap().light();
assert!(light(0));
assert!(!light(1));
assert!(!light(2));
assert_eq!(db.info(FontId::from_index(2)).unwrap().panose_weight, 10);
}
#[test]
fn reads_the_number_of_a_version_string() {
assert_eq!(version_number("Version 7.06.1"), "7.06.1");
assert_eq!(version_number("Version 7.12.1; F-Office"), "7.12.1");
}
#[test]
fn reads_names_and_style() {
let db = database(&[CARLITO.to_vec()]);
let info = db.info(FontId::from_index(0)).unwrap();
assert_eq!(info.family, "Carlito");
assert_eq!(info.subfamily, "Regular");
assert_eq!(info.family_names, ["Carlito"]);
assert_eq!(info.weight, 400);
assert!(!info.italic);
}
#[test]
fn reads_metrics_as_stored() {
let db = database(&[CARLITO.to_vec()]);
let expected = FontMetrics {
units_per_em: 2048,
hhea: LineMetrics {
ascender: 1950,
descender: -550,
line_gap: 0,
},
os2: Some(Os2Metrics {
average_width: 1048,
typo: LineMetrics {
ascender: 1536,
descender: -512,
line_gap: 452,
},
win_ascent: 1950,
win_descent: 550,
use_typo_metrics: false,
x_height: Some(978),
cap_height: Some(1314),
strikeout: Decoration {
position: 512,
thickness: 134,
},
subscript: ScriptMetrics {
x_size: 1433,
y_size: 1331,
x_offset: 0,
y_offset: 286,
},
superscript: ScriptMetrics {
x_size: 1433,
y_size: 1331,
x_offset: 0,
y_offset: 976,
},
east_asian: false,
}),
underline: Some(Decoration {
position: -103,
thickness: 194,
}),
};
assert_eq!(db.metrics(FontId::from_index(0)), Some(&expected));
}
#[test]
fn reads_the_use_typo_metrics_bit() {
let mut data = CARLITO.to_vec();
let os2 = table_offset(&data, *b"OS/2");
write_u16(&mut data, os2 + 62, 1 << 7);
let db = database(&[data]);
let os2 = db.metrics(FontId::from_index(0)).unwrap().os2.unwrap();
assert!(os2.use_typo_metrics);
}
#[test]
fn unknown_ids_return_none() {
let db = database(&[CARLITO.to_vec()]);
assert_eq!(db.info(FontId::from_index(1)), None);
assert_eq!(db.metrics(FontId::from_index(1)), None);
}
#[test]
fn rejects_data_that_is_not_a_font() {
let mut db = FontDb::new();
assert_eq!(
db.add_font(b"not a font".to_vec()),
Err(FontError::NotAFont)
);
assert!(db.is_empty());
}
#[test]
fn rejects_faces_without_the_tables_it_needs() {
let mut db = FontDb::new();
assert_eq!(
db.add_font(without_table(*b"hhea")),
Err(FontError::BadTable("hhea"))
);
assert_eq!(
db.add_font(without_table(*b"hmtx")),
Err(FontError::BadTable("hmtx"))
);
assert!(db.add_font(without_table(*b"head")).is_err());
assert!(db.is_empty());
}
#[test]
fn rejects_zero_units_per_em() {
let mut data = CARLITO.to_vec();
let head = table_offset(&data, *b"head");
write_u16(&mut data, head + 18, 0);
let mut db = FontDb::new();
assert_eq!(db.add_font(data), Err(FontError::BadTable("head")));
}
#[test]
fn adds_every_face_of_a_collection() {
let mut db = FontDb::new();
let ids = db.add_font(collection(2)).unwrap();
assert_eq!(ids, [FontId::from_index(0), FontId::from_index(1)]);
assert_eq!(db.info(ids[1]).unwrap().family, "Carlito");
}
#[test]
fn returns_the_file_bytes_and_index_of_each_face() {
let mut db = FontDb::new();
let file = collection(2);
let ids = db.add_font(file.clone()).unwrap();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let (first, first_index) = db.data(ids[0]).unwrap();
let (second, second_index) = db.data(ids[1]).unwrap();
assert_eq!((&first[..], first_index), (&file[..], 0));
assert_eq!(second_index, 1);
assert!(std::ptr::eq(first.as_ptr(), second.as_ptr()));
assert_eq!(
db.data(carlito).map(|(data, index)| (&data[..], index)),
Some((CARLITO, 0))
);
assert_eq!(db.data(FontId::from_index(3)), None);
}
#[test]
fn reads_built_in_bytes_as_given_bytes_without_a_copy() {
let mut db = FontDb::new();
let built_in = db.add_static(CARLITO).unwrap()[0];
let given = db.add_font(CARLITO.to_vec()).unwrap()[0];
assert_eq!(db.info(built_in), db.info(given));
assert_eq!(db.metrics(built_in), db.metrics(given));
assert_eq!(db.origin(built_in), Some(FaceOrigin::BuiltIn));
assert_eq!(db.origin(given), Some(FaceOrigin::Caller));
let (data, index) = db.data(built_in).unwrap();
assert!(std::ptr::eq(data.as_ptr(), CARLITO.as_ptr()) && index == 0);
assert_eq!(
db.device_width(built_in, 0x21, 13),
db.device_width(given, 0x21, 13)
);
}
#[test]
fn adds_no_built_in_face_of_bytes_that_are_no_font() {
let mut db = FontDb::new();
assert!(db.add_static(&CARLITO[..100]).is_err());
assert_eq!(db.len(), 0);
}
#[test]
fn takes_the_callers_face_over_an_equal_built_in_face() {
let mut db = FontDb::new();
let built_in = db.add_static(CARLITO).unwrap()[0];
assert_eq!(db.query(&name("Carlito"), false, false), Some(built_in));
let given = db.add_font(CARLITO.to_vec()).unwrap()[0];
let info = db.info(given).unwrap().clone();
let postscript = info.postscript_name.unwrap();
for family in ["Carlito", &postscript, &info.full_names[0]] {
assert_eq!(
db.query(&name(family), false, false),
Some(given),
"{family}"
);
}
}
#[test]
fn reads_style_from_head_without_os2() {
let mut data = without_table(*b"OS/2");
let db = database(std::slice::from_ref(&data));
let id = FontId::from_index(0);
assert_eq!(db.metrics(id).unwrap().os2, None);
assert_eq!(db.info(id).unwrap().weight, 400);
assert!(!db.info(id).unwrap().italic);
let head = table_offset(&data, *b"head");
write_u16(&mut data, head + 44, 0b11);
let db = database(&[data]);
assert_eq!(db.info(id).unwrap().weight, 700);
assert!(db.info(id).unwrap().italic);
}
#[test]
fn has_no_underline_without_post() {
let db = database(&[without_table(*b"post")]);
assert_eq!(db.metrics(FontId::from_index(0)).unwrap().underline, None);
}
#[test]
fn query_ignores_case_and_never_substitutes() {
let db = database(&[CARLITO.to_vec()]);
let id = Some(FontId::from_index(0));
assert_eq!(db.query(&name("carlito"), false, false), id);
assert_eq!(db.query(&name("CARLITO"), true, true), id);
assert_eq!(db.query(&name("Calibri"), false, false), None);
assert_eq!(db.query(&name("Carlit"), false, false), None);
}
#[test]
fn query_prefers_the_exact_style() {
let db = database(&[
with_style(400, false),
with_style(700, false),
with_style(400, true),
with_style(700, true),
]);
let id = |index| Some(FontId::from_index(index));
assert_eq!(db.query(&name("Carlito"), false, false), id(0));
assert_eq!(db.query(&name("Carlito"), true, false), id(1));
assert_eq!(db.query(&name("Carlito"), false, true), id(2));
assert_eq!(db.query(&name("Carlito"), true, true), id(3));
}
#[test]
fn query_filters_faces_before_it_selects_a_style_or_a_name() {
let db = database(&[with_style(400, false), with_style(700, false)]);
let regular = Some(FontId::from_index(0));
assert_eq!(
db.query_with(&name("Carlito"), true, false, |_, face| face.weight == 400),
regular
);
assert_eq!(
db.query_with(&name("Carlito"), true, false, |_, _| false),
None
);
assert_eq!(
db.query_with(&name("Carlito-Regular"), true, false, |_, face| face.weight
== 400),
regular
);
assert_eq!(
db.query_with(&name("Carlito-Regular"), false, false, |_, _| false),
None
);
}
#[test]
fn query_prefers_italic_then_the_closest_weight_then_the_first_face() {
let db = database(&[
with_style(600, false),
with_style(300, false),
with_style(300, true),
with_style(300, false),
]);
let id = |index| Some(FontId::from_index(index));
assert_eq!(db.query(&name("Carlito"), true, false), id(0));
assert_eq!(db.query(&name("Carlito"), false, false), id(1));
assert_eq!(db.query(&name("Carlito"), true, true), id(2));
}
#[test]
fn adds_the_fonts_of_files() {
let mut db = FontDb::new();
let ids = db
.add_files(&[fonts_folder().join("Carlito-Regular.ttf")])
.unwrap();
assert_eq!(ids, [FontId::from_index(0)]);
assert_eq!(db.info(ids[0]).unwrap().family, "Carlito");
}
#[test]
fn names_a_file_that_is_not_a_font_file() {
let mut db = FontDb::new();
let license = fonts_folder().join("Carlito-OFL.txt");
let not_added = db.add_files(std::slice::from_ref(&license)).unwrap_err();
assert_eq!(not_added.path, license);
assert!(matches!(
not_added.cause,
crate::NotAddedCause::NotAFontFile
));
assert!(not_added.to_string().contains("Carlito-OFL.txt"));
assert!(std::error::Error::source(¬_added).is_none());
assert_eq!(
std::io::Error::from(not_added).kind(),
std::io::ErrorKind::InvalidData
);
assert_eq!(db.len(), 0);
}
#[test]
fn names_a_font_file_that_cannot_be_read() {
let missing = fonts_folder().join("missing.ttf");
let not_added = FontDb::new()
.add_files(std::slice::from_ref(&missing))
.unwrap_err();
assert!(matches!(
¬_added.cause,
crate::NotAddedCause::Unreadable(error) if error.kind() == std::io::ErrorKind::NotFound
));
assert!(not_added.to_string().contains("missing.ttf cannot be read"));
assert!(std::error::Error::source(¬_added).is_some());
assert_eq!(
std::io::Error::from(not_added).kind(),
std::io::ErrorKind::NotFound
);
}
#[test]
fn errors_and_the_database_print() {
assert_eq!(
FontError::NotAFont.to_string(),
"the data is not an OpenType font"
);
assert_eq!(
FontError::BadTable("hhea").to_string(),
"the font's hhea table is missing or malformed"
);
assert_eq!(
FontError::TooManyFaces.to_string(),
"the font database is full"
);
let outline_errors = [
OutlineError::UnknownFont,
OutlineError::UnknownGlyph,
OutlineError::NoOutlines,
OutlineError::Unreadable,
];
assert_eq!(
outline_errors.map(|error| error.to_string()),
[
"the font database has no such font",
"the font has no such glyph",
"the font has no glyph outlines",
"the glyph's outline does not read",
]
);
let db = database(&[CARLITO.to_vec()]);
assert_eq!(
format!("{db:?}"),
"FontDb { faces: 1, descriptions: 0, .. }"
);
}
fn bounds(commands: &[PathCommand]) -> (f32, f32, f32, f32) {
let points = commands.iter().flat_map(|command| match *command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => vec![p],
PathCommand::QuadTo(c, p) => vec![c, p],
PathCommand::CubicTo(c0, c1, p) => vec![c0, c1, p],
PathCommand::Close => vec![],
});
points.fold(
(f32::MAX, f32::MAX, f32::MIN, f32::MIN),
|(x0, y0, x1, y1), p| (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)),
)
}
fn contours(commands: &[PathCommand]) -> usize {
commands
.iter()
.filter(|command| **command == PathCommand::Close)
.count()
}
#[test]
fn maps_characters_to_glyphs() {
let db = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let glyphs: Vec<Option<u32>> = ['A', 'H', ' ', 'g', 'é']
.into_iter()
.map(|ch| db.glyph_id(id, ch))
.collect();
assert_eq!(glyphs, [Some(3), Some(15), Some(2), Some(93), Some(2007)]);
assert_eq!(db.glyph_id(id, '\u{10FFFD}'), None);
assert_eq!(db.glyph_id(FontId::from_index(1), 'A'), None);
}
#[test]
fn reads_advances_from_hmtx() {
let db = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
assert_eq!(db.advance(id, 3), Some(1185));
assert_eq!(db.advance(id, 15), Some(1276));
assert_eq!(db.advance(id, 2), Some(463));
assert_eq!(db.advance(id, 2782), Some(463));
assert_eq!(db.advance(id, 2783), None);
assert_eq!(db.advance(FontId::from_index(1), 3), None);
}
fn carlito_outline(glyph: u32) -> Vec<PathCommand> {
database(&[CARLITO.to_vec()])
.outline(FontId::from_index(0), glyph)
.unwrap()
}
#[test]
fn draws_outlines_in_font_units() {
let h = carlito_outline(15);
assert!(matches!(h.first(), Some(PathCommand::MoveTo(_))));
assert_eq!(h.last(), Some(&PathCommand::Close));
assert_eq!(contours(&h), 1);
assert_eq!(bounds(&h), (140.0, 0.0, 1136.0, 1314.0));
}
#[test]
fn draws_every_contour() {
let a = carlito_outline(3);
assert_eq!(contours(&a), 2);
assert_eq!(bounds(&a), (8.0, 0.0, 1178.0, 1314.0));
}
#[test]
fn draws_curves_and_descenders() {
let g = carlito_outline(93);
assert!(
g.iter()
.any(|command| matches!(command, PathCommand::QuadTo(..)))
);
assert_eq!(bounds(&g), (64.0, -352.0, 928.0, 994.0));
}
#[test]
fn draws_composite_glyphs() {
assert_eq!(bounds(&carlito_outline(2007)), (75.0, -14.0, 945.0, 1399.0));
}
fn with_unreadable_glyph(glyph: usize) -> Vec<u8> {
let mut data = CARLITO.to_vec();
let head = table_offset(&data, *b"head");
let loca = table_offset(&data, *b"loca");
let past_glyf = read_u32(&data, table_record(&data, *b"glyf") + 12) + 4;
if read_u16(&data, head + 50) == 1 {
let at = loca + 4 * (glyph + 1);
data[at..at + 4].copy_from_slice(&past_glyf.to_be_bytes());
} else {
let halves = u16::try_from(past_glyf / 2).unwrap();
write_u16(&mut data, loca + 2 * (glyph + 1), halves);
}
data
}
#[test]
fn names_why_a_glyph_that_the_font_has_has_no_outline() {
let db = database(&[without_table(*b"glyf"), with_unreadable_glyph(15)]);
let (bare, broken) = (FontId::from_index(0), FontId::from_index(1));
assert_eq!(db.outline(bare, 15), Err(OutlineError::NoOutlines));
assert_eq!(db.outline(broken, 15), Err(OutlineError::Unreadable));
assert_eq!(
db.outline(broken, 3).map(|outline| contours(&outline)),
Ok(2)
);
}
#[test]
fn outlines_of_empty_and_missing_glyphs() {
let db = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
assert_eq!(db.outline(id, 2), Ok(vec![]));
assert_eq!(db.outline(id, 2783), Err(OutlineError::UnknownGlyph));
assert_eq!(
db.outline(FontId::from_index(1), 15),
Err(OutlineError::UnknownFont)
);
}
fn rename(data: &mut [u8], name_id: u16, name: &str) {
let table = table_offset(data, *b"name");
let count = usize::from(read_u16(data, table + 2));
let storage = table + usize::from(read_u16(data, table + 4));
let encoded: Vec<u8> = name.encode_utf16().flat_map(u16::to_be_bytes).collect();
for record in (0..count).map(|index| table + 6 + 12 * index) {
if read_u16(data, record + 6) == name_id {
assert!(encoded.len() <= usize::from(read_u16(data, record + 8)));
let at = storage + usize::from(read_u16(data, record + 10));
data[at..at + encoded.len()].copy_from_slice(&encoded);
write_u16(data, record + 8, u16::try_from(encoded.len()).unwrap());
}
}
}
fn named(weight: u16, italic: bool, family: Option<&str>, postscript: &str) -> Vec<u8> {
let mut data = with_style(weight, italic);
rename(&mut data, 6, postscript);
if let Some(family) = family {
rename(&mut data, 1, family);
}
data
}
#[test]
fn reads_the_postscript_name() {
let db = database(&[
CARLITO.to_vec(),
named(700, false, Some("Xarlito"), "X-Bold"),
]);
let info = |index| db.info(FontId::from_index(index)).unwrap();
assert_eq!(info(0).postscript_name.as_deref(), Some("Carlito-Regular"));
assert_eq!(info(1).postscript_name.as_deref(), Some("X-Bold"));
assert_eq!(info(1).family, "Xarlito");
}
#[test]
fn a_face_without_names_has_empty_names() {
let db = database(&[without_table(*b"name")]);
let info = db.info(FontId::from_index(0)).unwrap();
assert_eq!(info.family, "");
assert_eq!(info.subfamily, "");
assert_eq!(info.family_names, [] as [String; 0]);
assert_eq!(info.postscript_name, None);
assert_eq!(db.query(&name("Carlito-Regular"), false, false), None);
}
#[test]
fn query_finds_a_face_by_its_postscript_name() {
let db = database(&[
named(400, false, None, "Carlito-Regular"),
named(700, false, None, "Carlito-Bold"),
]);
let id = |index| Some(FontId::from_index(index));
assert_eq!(db.query(&name("carlito-regular"), false, false), id(0));
assert_eq!(db.query(&name("CARLITO-BOLD"), true, false), id(1));
assert_eq!(db.query(&name("Carlito-Book"), false, false), None);
}
#[test]
fn query_by_postscript_name_prefers_the_requested_style_in_the_style_group() {
let db = database(&[
named(400, false, None, "Carlito-Regular"),
named(700, false, None, "Carlito-Bold"),
named(400, true, Some("Xarlito"), "Xarlito-Italic"),
]);
let id = |index| Some(FontId::from_index(index));
assert_eq!(db.query(&name("Carlito-Regular"), true, false), id(1));
assert_eq!(db.query(&name("Carlito-Bold"), false, false), id(0));
assert_eq!(db.query(&name("Carlito-Regular"), false, true), id(0));
assert_eq!(db.query(&name("Carlito-Bold"), true, true), id(1));
}
#[test]
fn query_finds_a_face_by_its_full_name_whatever_the_style() {
let mut bold = named(700, false, Some("Xarlito"), "Xarlito-Bold");
rename(&mut bold, 4, "Xarlito Bold");
let db = database(&[named(400, false, Some("Xarlito"), "Xarlito"), bold]);
let id = |index| Some(FontId::from_index(index));
assert!(
db.info(FontId::from_index(1))
.unwrap()
.full_names
.contains(&"Xarlito Bold".to_owned())
);
assert_eq!(db.query(&name("Xarlito"), false, false), id(0));
assert_eq!(db.query(&name("xarlito bold"), false, false), id(1));
assert_eq!(db.query(&name("Xarlito Bold"), true, true), id(1));
assert_eq!(db.query(&name("Xarlito Black"), false, false), None);
}
#[test]
fn query_by_postscript_name_counts_bold_from_weight_600() {
let semi_bold = database(&[
named(400, false, None, "Carlito-Regular"),
named(600, false, None, "Carlito-Semi"),
]);
assert_eq!(
semi_bold.query(&name("Carlito-Regular"), true, false),
Some(FontId::from_index(1))
);
let medium = database(&[
named(400, false, None, "Carlito-Regular"),
named(599, false, None, "Carlito-Semi"),
]);
assert_eq!(
medium.query(&name("Carlito-Regular"), true, false),
Some(FontId::from_index(0))
);
assert_eq!(
medium.query(&name("Carlito-Semi"), false, false),
Some(FontId::from_index(0))
);
}
fn in_typographic_family() -> Vec<u8> {
let mut data = CARLITO.to_vec();
rename(&mut data, 1, "Carlit");
let table = table_offset(&data, *b"name");
let count = usize::from(read_u16(&data, table + 2));
for record in (0..count).map(|index| table + 6 + 12 * index) {
if read_u16(&data, record + 6) == 4 {
write_u16(&mut data, record + 6, 16);
}
}
rename(&mut data, 16, "Carlito");
data
}
#[test]
fn query_prefers_the_face_whose_family_name_is_the_requested_one() {
let db = database(&[in_typographic_family(), CARLITO.to_vec()]);
assert!(
db.info(FontId::from_index(0))
.unwrap()
.family_names
.contains(&"Carlito".to_owned())
);
assert_eq!(
db.query(&name("Carlito"), false, false),
Some(FontId::from_index(1))
);
assert_eq!(
db.query(&name("Carlit"), false, false),
Some(FontId::from_index(0))
);
let alone = database(&[in_typographic_family()]);
assert_eq!(
alone.query(&name("Carlito"), false, false),
Some(FontId::from_index(0))
);
assert_eq!(
alone.query_with(&name("Carlito"), false, false, |_, _| true),
None
);
assert_eq!(
alone.query_typographic_with(&name("Carlito"), false, false, |_, _| true),
Some(FontId::from_index(0))
);
assert_eq!(
db.query_typographic_with(&name("Carlito"), false, false, |_, _| true),
Some(FontId::from_index(1))
);
}
#[test]
fn query_matches_family_names_before_postscript_names() {
let db = database(&[
named(700, false, Some("Xarlito"), "Carlito"),
CARLITO.to_vec(),
]);
assert_eq!(
db.query(&name("Carlito"), true, false),
Some(FontId::from_index(1))
);
assert_eq!(
db.query(&name("Xarlito"), false, false),
Some(FontId::from_index(0))
);
}
fn renamed_table(font: &[u8], from: [u8; 4], to: [u8; 4]) -> Vec<u8> {
let mut data = font.to_vec();
let count = usize::from(read_u16(font, 4));
for index in 0..count {
let at = 12 + 16 * index;
if data[at..at + 4] == from {
data[at..at + 4].copy_from_slice(&to);
}
}
data
}
#[test]
fn kerning_reads_the_kern_feature_of_gpos_before_the_kern_table() {
let fonts = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let glyph = |c| fonts.glyph_id(id, c).unwrap();
let kern = |fonts: &FontDb, pair: &str| {
let mut chars = pair.chars();
let (left, right) = (chars.next().unwrap(), chars.next().unwrap());
fonts.kerning(id, glyph(left), glyph(right))
};
assert_eq!(kern(&fonts, "AV"), -89);
assert_eq!(kern(&fonts, "VA"), -96);
assert_eq!(kern(&fonts, "To"), -182);
assert_eq!(kern(&fonts, " "), 0);
let pair = (
u16::try_from(glyph('A')).unwrap(),
u16::try_from(glyph('V')).unwrap(),
-120,
);
let both = database(&[with_kern(&[pair])]);
assert_eq!(kern(&both, "AV"), -89);
assert_eq!(fonts.kerning_source(id), KerningSource::Gpos);
assert_eq!(both.kerning_source(id), KerningSource::Gpos);
}
#[test]
fn kerning_sums_horizontal_pairs_from_the_kern_table() {
let plain = database(&[renamed_table(CARLITO, *b"GPOS", *b"GPOT")]);
let id = FontId::from_index(0);
let a = plain.glyph_id(id, 'A').unwrap();
let v = plain.glyph_id(id, 'V').unwrap();
assert_eq!(plain.kerning(id, a, v), 0);
let pair = (u16::try_from(a).unwrap(), u16::try_from(v).unwrap(), -120);
let kerned = database(&[renamed_table(&with_kern(&[pair]), *b"GPOS", *b"GPOT")]);
assert_eq!(kerned.kerning(id, a, v), -120);
assert_eq!(kerned.kerning(id, v, a), 0);
assert_eq!(kerned.kerning(FontId::from_index(7), a, v), 0);
assert_eq!(kerned.advance(id, a), plain.advance(id, a));
}
#[test]
fn a_face_without_the_kern_feature_of_gpos_takes_its_kerning_from_the_kern_table() {
let id = FontId::from_index(0);
let plain = database(&[renamed_table(CARLITO, *b"GPOS", *b"GPOT")]);
let kerned = database(&[renamed_table(
&with_kern(&[(1, 2, -120)]),
*b"GPOS",
*b"GPOT",
)]);
assert_eq!(kerned.kerning_source(id), KerningSource::KernTable);
assert_eq!(plain.kerning_source(id), KerningSource::KernTable);
let unknown = FontId::from_index(7);
assert_eq!(kerned.kerning_source(unknown), KerningSource::KernTable);
}
fn kerning_sources() -> ((u32, u32), [FontDb; 3]) {
let gpos_only = database(&[CARLITO.to_vec()]);
let glyph = |c| gpos_only.glyph_id(FontId::from_index(0), c).unwrap();
let (a, v) = (glyph('A'), glyph('V'));
let pair = (u16::try_from(a).unwrap(), u16::try_from(v).unwrap(), -120);
let both = database(&[with_kern(&[pair])]);
let table_only = database(&[renamed_table(&with_kern(&[pair]), *b"GPOS", *b"GPOT")]);
((a, v), [gpos_only, both, table_only])
}
#[test]
fn reads_each_kerning_source_of_a_face_on_its_own() {
let ((a, v), [gpos_only, both, table_only]) = kerning_sources();
let kerning = |fonts: &FontDb, source| fonts.kerning_from(FontId::from_index(0), a, v, source);
assert_eq!(kerning(&both, KerningSource::Gpos), -89);
assert_eq!(kerning(&both, KerningSource::KernTable), -120);
assert_eq!(kerning(&gpos_only, KerningSource::KernTable), 0);
assert_eq!(kerning(&table_only, KerningSource::Gpos), 0);
assert_eq!(kerning(&table_only, KerningSource::KernTable), -120);
}
#[test]
fn tells_whether_a_face_has_a_kern_table_whatever_its_gpos_holds() {
let (_, [gpos_only, both, table_only]) = kerning_sources();
let id = FontId::from_index(0);
assert!(both.has_kern_table(id));
assert!(table_only.has_kern_table(id));
assert!(!gpos_only.has_kern_table(id));
assert!(!both.has_kern_table(FontId::from_index(7)));
}
fn carlito_ligatures(fonts: &FontDb, text: &str) -> Vec<(usize, usize, Option<u16>)> {
let id = FontId::from_index(0);
let glyphs: Vec<u32> = text
.chars()
.map(|c| fonts.glyph_id(id, c).unwrap())
.collect();
fonts
.ligatures(id, &glyphs)
.iter()
.map(|l| (l.start, l.len, fonts.advance(id, l.glyph)))
.collect()
}
#[test]
fn joins_standard_ligatures_with_the_longest_first() {
let fonts = database(&[CARLITO.to_vec()]);
assert_eq!(
carlito_ligatures(&fonts, "office"),
vec![(1, 3, Some(1654))]
);
assert_eq!(carlito_ligatures(&fonts, "off"), vec![(1, 2, Some(1195))]);
assert_eq!(
carlito_ligatures(&fonts, "fit flat"),
vec![(0, 2, Some(1084)), (4, 2, Some(1084))]
);
assert_eq!(carlito_ligatures(&fonts, "abc"), vec![]);
assert_eq!(carlito_ligatures(&fonts, "f"), vec![]);
assert_eq!(fonts.ligatures(FontId::from_index(3), &[1, 2]), vec![]);
}
#[test]
fn a_font_without_a_gsub_table_has_no_ligatures() {
let mut data = CARLITO.to_vec();
let at = table_record(&data, *b"GSUB");
data[at..at + 4].copy_from_slice(b"XSUB");
let fonts = database(&[data]);
assert_eq!(carlito_ligatures(&fonts, "office"), vec![]);
}
fn assert_kept(
store: &std::sync::Mutex<std::collections::BTreeMap<(u16, u16), Option<i32>>>,
key: (u16, u16),
own: Option<i32>,
answer: impl Fn() -> Option<i32>,
) {
assert_eq!(store.lock().unwrap().get(&key), Some(&own), "{key:?}");
let other = own.map(|value| value + 1);
store.lock().unwrap().insert(key, other);
assert_eq!(answer(), other, "{key:?}");
}
#[test]
fn gives_the_bi_level_advance_of_the_faces_instructions() {
let fonts = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let mut hinter = f_office_truetype::Hinter::new(CARLITO, 0, 1000).unwrap();
for ch in ['i', 'm', 'W'] {
let glyph = fonts.glyph_id(id, ch).unwrap();
let own = hinter.advance(u16::try_from(glyph).unwrap()).ok();
assert_eq!(fonts.bi_level_advance(id, glyph, 1000), own, "{ch}");
let key = (1000, u16::try_from(glyph).unwrap());
assert_kept(&fonts.face(id).unwrap().bi_level, key, own, || {
fonts.bi_level_advance(id, glyph, 1000)
});
}
assert_eq!(fonts.bi_level_advance(id, 60_000, 1000), None);
assert_eq!(fonts.bi_level_advance(id, 70_000, 1000), None);
assert_eq!(fonts.bi_level_advance(FontId::from_index(5), 1, 1000), None);
}
#[test]
fn keeps_a_hinter_for_each_of_the_last_sizes_with_the_answers_of_a_new_hinter() {
use crate::bilevel::MOST_KEPT_HINTERS;
use f_office_truetype::Hinter;
let fonts = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let more = u16::try_from(MOST_KEPT_HINTERS).unwrap() + 2;
let sizes: Vec<u16> = (10..10 + more).collect();
for ch in ['i', 'm', 'W'] {
let glyph = fonts.glyph_id(id, ch).unwrap();
let short = u16::try_from(glyph).unwrap();
for &ppem in &sizes {
let advance = Hinter::new(CARLITO, 0, ppem).unwrap().advance(short);
assert_eq!(
fonts.bi_level_advance(id, glyph, ppem),
advance.ok(),
"{ch} {ppem}"
);
let width = Hinter::device(CARLITO, 0, ppem)
.unwrap()
.device_width(short);
assert_eq!(
fonts.device_width(id, glyph, ppem),
width.ok(),
"{ch} {ppem}"
);
}
}
let face = fonts.face(id).unwrap();
let last = sizes
.get(sizes.len() - MOST_KEPT_HINTERS..)
.unwrap()
.to_vec();
assert_eq!(face.bi_level_hinters.lock().unwrap().sizes(), last);
assert_eq!(face.device_hinters.lock().unwrap().sizes(), last);
}
#[test]
fn hints_one_size_on_several_threads_with_the_answers_of_a_new_hinter() {
use crate::bilevel::MOST_KEPT_HINTERS;
use f_office_truetype::Hinter;
let fonts = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let ppem = 17;
let mut fresh = Hinter::device(CARLITO, 0, ppem).unwrap();
let glyphs: Vec<u32> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.chars()
.map(|ch| fonts.glyph_id(id, ch).unwrap())
.collect();
let expected: Vec<Option<i32>> = glyphs
.iter()
.map(|&glyph| fresh.device_width(u16::try_from(glyph).unwrap()).ok())
.collect();
std::thread::scope(|scope| {
for first in 0..4 {
let (fonts, glyphs, expected) = (&fonts, &glyphs, &expected);
scope.spawn(move || {
for (glyph, want) in glyphs.iter().zip(expected).skip(first).step_by(4) {
assert_eq!(fonts.device_width(id, *glyph, ppem), *want, "{glyph}");
}
});
}
});
let sizes = fonts
.face(id)
.unwrap()
.device_hinters
.lock()
.unwrap()
.sizes();
assert!(
!sizes.is_empty() && sizes.len() <= MOST_KEPT_HINTERS.min(4),
"{sizes:?}"
);
assert!(sizes.iter().all(|&size| size == ppem), "{sizes:?}");
}
#[test]
fn gives_the_device_width_of_the_faces_instructions() {
let fonts = database(&[CARLITO.to_vec()]);
let id = FontId::from_index(0);
let mut hinter = f_office_truetype::Hinter::device(CARLITO, 0, 44).unwrap();
for ch in ['i', 'm', 'W'] {
let glyph = fonts.glyph_id(id, ch).unwrap();
let own = hinter.device_width(u16::try_from(glyph).unwrap()).ok();
assert!(own.is_some_and(|width| width > 0), "{ch}");
assert_eq!(fonts.device_width(id, glyph, 44), own, "{ch}");
let key = (44, u16::try_from(glyph).unwrap());
assert_kept(&fonts.face(id).unwrap().device, key, own, || {
fonts.device_width(id, glyph, 44)
});
}
assert_eq!(fonts.device_width(id, 60_000, 44), None);
assert_eq!(fonts.device_width(id, 70_000, 44), None);
assert_eq!(fonts.device_width(FontId::from_index(5), 1, 44), None);
}
#[cfg(feature = "woff2")]
mod woff2_tests {
use super::{CARLITO, FontDb, FontError, read_u16, read_u32};
fn push_base128(out: &mut Vec<u8>, mut value: u32) {
let mut buf = [0u8; 5];
let mut len = 0;
loop {
buf[len] = (value & 0x7f) as u8;
value >>= 7;
len += 1;
if value == 0 {
break;
}
}
for i in (0..len).rev() {
let byte = buf[i] | if i > 0 { 0x80 } else { 0 };
out.push(byte);
}
}
struct BitWriter {
bytes: Vec<u8>,
acc: u64,
bits: u32,
}
impl BitWriter {
fn new() -> Self {
Self {
bytes: Vec::new(),
acc: 0,
bits: 0,
}
}
fn push(&mut self, value: u64, count: u32) {
self.acc |= (value & ((1u64 << count) - 1)) << self.bits;
self.bits += count;
while self.bits >= 8 {
self.bytes.push((self.acc & 0xff) as u8);
self.acc >>= 8;
self.bits -= 8;
}
}
fn align_byte(&mut self) {
if self.bits > 0 {
self.bytes.push((self.acc & 0xff) as u8);
self.acc = 0;
self.bits = 0;
}
}
}
fn brotli_uncompressed(data: &[u8]) -> Vec<u8> {
let mut bits = BitWriter::new();
bits.push(0, 1); for chunk in data.chunks(65_536) {
let mlen_minus_1 = u64::try_from(chunk.len() - 1).unwrap();
bits.push(0, 1); bits.push(0, 2); bits.push(mlen_minus_1, 16);
bits.push(1, 1); bits.align_byte();
bits.bytes.extend_from_slice(chunk);
}
bits.push(1, 1); bits.push(1, 1); bits.align_byte();
bits.bytes
}
fn wrap_sfnt_as_woff2(sfnt: &[u8]) -> Vec<u8> {
let num_tables = read_u16(sfnt, 4);
let mut directory = Vec::new();
let mut raw_stream = Vec::new();
let mut sfnt_size = 12u32 + 16u32 * u32::from(num_tables);
for i in 0..usize::from(num_tables) {
let rec = 12 + i * 16;
let tag = &sfnt[rec..rec + 4];
let offset = read_u32(sfnt, rec + 8) as usize;
let length = read_u32(sfnt, rec + 12);
let is_glyf_or_loca = tag == b"glyf" || tag == b"loca";
let flags = if is_glyf_or_loca { 0xc0 | 63 } else { 63 };
directory.push(flags);
directory.extend_from_slice(tag);
push_base128(&mut directory, length);
raw_stream.extend_from_slice(&sfnt[offset..offset + length as usize]);
sfnt_size += (length + 3) & !3;
}
let compressed = brotli_uncompressed(&raw_stream);
let total_len = (48 + directory.len() + compressed.len() + 3) & !3;
let mut out = Vec::with_capacity(total_len);
out.extend_from_slice(b"wOF2");
out.extend_from_slice(&sfnt[0..4]);
out.extend_from_slice(&u32::try_from(total_len).unwrap().to_be_bytes());
out.extend_from_slice(&num_tables.to_be_bytes());
out.extend_from_slice(&0u16.to_be_bytes());
out.extend_from_slice(&sfnt_size.to_be_bytes());
out.extend_from_slice(&u32::try_from(compressed.len()).unwrap().to_be_bytes());
out.extend_from_slice(&[0u8; 24]); out.extend_from_slice(&directory);
out.extend_from_slice(&compressed);
while out.len() < total_len {
out.push(0);
}
out
}
#[test]
fn loads_woff2_with_identical_metrics_and_advances() {
let woff2 = wrap_sfnt_as_woff2(CARLITO);
assert!(woff2.starts_with(b"wOF2"));
let mut raw_db = FontDb::new();
let raw_ids = raw_db.add_font(CARLITO).unwrap();
let mut woff2_db = FontDb::new();
let woff2_ids = woff2_db.add_font(woff2).unwrap();
assert_eq!(woff2_ids.len(), raw_ids.len());
assert_eq!(woff2_db.info(woff2_ids[0]), raw_db.info(raw_ids[0]));
assert_eq!(woff2_db.metrics(woff2_ids[0]), raw_db.metrics(raw_ids[0]));
for ch in ['A', 'g', 'W', '0'] {
let g_raw = raw_db.glyph_id(raw_ids[0], ch).unwrap();
let g_woff2 = woff2_db.glyph_id(woff2_ids[0], ch).unwrap();
assert_eq!(g_woff2, g_raw, "glyph_id mismatch for {ch}");
assert_eq!(
woff2_db.advance(woff2_ids[0], g_woff2),
raw_db.advance(raw_ids[0], g_raw),
"advance mismatch for {ch}"
);
}
}
#[test]
fn rejects_corrupt_woff2_as_not_a_font() {
let mut db = FontDb::new();
assert_eq!(
db.add_font(b"wOF2corrupt".as_slice()),
Err(FontError::NotAFont)
);
assert!(db.is_empty());
}
}