use std::path::Path;
use write_fonts::FontBuilder;
use write_fonts::read::tables::glyf::CurvePoint;
use write_fonts::tables::cmap::Cmap;
use write_fonts::tables::glyf::{Bbox, Contour, GlyfLocaBuilder, Glyph, SimpleGlyph};
use write_fonts::tables::gpos::{
Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord,
};
use write_fonts::tables::gsub::{
Gsub, Ligature, LigatureSet, LigatureSubstFormat1, SubstitutionLookup, SubstitutionLookupList,
};
use write_fonts::tables::head::{Flags, Head};
use write_fonts::tables::hhea::Hhea;
use write_fonts::tables::hmtx::{Hmtx, LongMetric};
use write_fonts::tables::layout::{
CoverageTable, Feature, FeatureList, FeatureRecord, LangSys, Lookup, LookupFlag, Script,
ScriptList, ScriptRecord,
};
use write_fonts::tables::maxp::Maxp;
use write_fonts::tables::os2::Os2;
use write_fonts::tables::post::Post;
use write_fonts::types::{FWord, GlyphId, GlyphId16, Tag};
use super::{Comparison, LayoutValues, Place, ValueKind};
use crate::FontDb;
#[derive(Clone)]
struct TestGlyph {
character: Option<char>,
advance: u16,
bounds: [i16; 4],
}
const A: usize = 0;
const V: usize = 1;
const F: usize = 2;
const I: usize = 3;
const FI: usize = 4;
#[derive(Clone)]
struct Design {
units_per_em: u16,
ascender: i16,
glyphs: Vec<TestGlyph>,
kerning: i16,
ligature: usize,
order: Vec<usize>,
instructions: Vec<u8>,
}
impl Default for Design {
fn default() -> Self {
let glyph = |character, advance, bounds| TestGlyph {
character,
advance,
bounds,
};
Self {
units_per_em: 1000,
ascender: 800,
glyphs: vec![
glyph(Some('A'), 600, [10, 0, 590, 700]),
glyph(Some('V'), 600, [0, 0, 600, 700]),
glyph(Some('f'), 300, [20, 0, 320, 720]),
glyph(Some('i'), 250, [40, 0, 210, 700]),
glyph(None, 550, [20, 0, 510, 720]),
],
kerning: -50,
ligature: FI,
order: vec![A, V, F, I, FI],
instructions: Vec::new(),
}
}
}
const ONE_PIXEL_WIDER: [u8; 4] = [0xB1, 5, 64, 0x38];
impl Design {
fn id(&self, index: usize) -> GlyphId16 {
let place = self.order.iter().position(|&i| i == index).unwrap_or(0);
GlyphId16::new(u16::try_from(place + 1).unwrap_or(0))
}
fn glyph_count(&self) -> u16 {
u16::try_from(self.order.len() + 1).unwrap_or(0)
}
fn build(&self) -> Vec<u8> {
let mut builder = FontBuilder::new();
let (glyf, loca, format) = self.outlines();
let tables = [
builder.add_table(&self.head(format)).is_ok(),
builder.add_table(&self.hhea()).is_ok(),
builder.add_table(&self.maxp()).is_ok(),
builder.add_table(&self.hmtx()).is_ok(),
builder.add_table(&self.cmap()).is_ok(),
builder.add_table(&glyf).is_ok(),
builder.add_table(&loca).is_ok(),
builder.add_table(&Os2::default()).is_ok(),
builder.add_table(&Post::default()).is_ok(),
builder.add_table(&self.gpos()).is_ok(),
builder.add_table(&self.gsub()).is_ok(),
];
assert!(
tables.iter().all(|&added| added),
"a test table does not build"
);
builder.build()
}
fn head(&self, format: write_fonts::tables::loca::LocaFormat) -> Head {
Head {
flags: Flags::from_bits_truncate(0x001B),
units_per_em: self.units_per_em,
x_min: 0,
y_min: 0,
x_max: 600,
y_max: 720,
index_to_loc_format: i16::from(format == write_fonts::tables::loca::LocaFormat::Long),
..Head::default()
}
}
fn hhea(&self) -> Hhea {
Hhea {
ascender: FWord::new(self.ascender),
descender: FWord::new(-200),
number_of_h_metrics: self.glyph_count(),
..Hhea::default()
}
}
fn maxp(&self) -> Maxp {
Maxp {
max_points: Some(4),
max_contours: Some(1),
max_composite_points: Some(0),
max_composite_contours: Some(0),
max_zones: Some(2),
max_twilight_points: Some(0),
max_storage: Some(0),
max_function_defs: Some(0),
max_instruction_defs: Some(0),
max_stack_elements: Some(16),
max_size_of_instructions: Some(16),
max_component_elements: Some(0),
max_component_depth: Some(0),
..Maxp::new(self.glyph_count())
}
}
fn glyphs_in_order(&self) -> impl Iterator<Item = (usize, &TestGlyph)> {
self.order
.iter()
.filter_map(|&index| Some((index, self.glyphs.get(index)?)))
}
fn hmtx(&self) -> Hmtx {
let notdef = LongMetric {
advance: 500,
side_bearing: 0,
};
let metrics = self.glyphs_in_order().map(|(_, glyph)| LongMetric {
advance: glyph.advance,
side_bearing: glyph.bounds[0],
});
Hmtx::new(std::iter::once(notdef).chain(metrics).collect(), Vec::new())
}
fn cmap(&self) -> Cmap {
let mappings = self
.glyphs_in_order()
.filter_map(|(index, glyph)| Some((glyph.character?, GlyphId::from(self.id(index)))));
let cmap = Cmap::from_mappings(mappings);
assert!(cmap.is_ok(), "the test characters map twice");
cmap.unwrap_or_default()
}
fn outlines(
&self,
) -> (
write_fonts::tables::glyf::Glyf,
write_fonts::tables::loca::Loca,
write_fonts::tables::loca::LocaFormat,
) {
let mut builder = GlyfLocaBuilder::new();
assert!(builder.add_glyph(&Glyph::Empty).is_ok());
for (index, glyph) in self.glyphs_in_order() {
let [x0, y0, x1, y1] = glyph.bounds;
let points = vec![
CurvePoint::on_curve(x0, y0),
CurvePoint::on_curve(x0, y1),
CurvePoint::on_curve(x1, y1),
CurvePoint::on_curve(x1, y0),
];
let instructions = if index == A {
self.instructions.clone()
} else {
Vec::new()
};
let simple = SimpleGlyph {
bbox: Bbox {
x_min: x0,
y_min: y0,
x_max: x1,
y_max: y1,
},
contours: vec![Contour::from(points)],
instructions,
};
assert!(builder.add_glyph(&simple).is_ok());
}
builder.build()
}
fn scripts() -> ScriptList {
let latin = Script::new(Some(LangSys::new(vec![0])), Vec::new());
ScriptList::new(vec![ScriptRecord::new(Tag::new(b"latn"), latin)])
}
fn feature(tag: [u8; 4]) -> FeatureList {
let feature = Feature::new(None, vec![0]);
FeatureList::new(vec![FeatureRecord::new(Tag::new(&tag), feature)])
}
fn gpos(&self) -> Gpos {
let record = PairValueRecord::new(
self.id(V),
ValueRecord::new().with_x_advance(self.kerning),
ValueRecord::new(),
);
let pairs = PairPos::format_1(
CoverageTable::format_1(vec![self.id(A)]),
vec![PairSet::new(vec![record])],
);
let lookup = PositionLookup::Pair(Lookup::new(LookupFlag::empty(), vec![pairs]));
Gpos::new(
Self::scripts(),
Self::feature(*b"kern"),
PositionLookupList::new(vec![lookup]),
)
}
fn gsub(&self) -> Gsub {
let ligature = Ligature::new(self.id(self.ligature), vec![self.id(I)]);
let table = LigatureSubstFormat1::new(
CoverageTable::format_1(vec![self.id(F)]),
vec![LigatureSet::new(vec![ligature])],
);
let lookup = SubstitutionLookup::Ligature(Lookup::new(LookupFlag::empty(), vec![table]));
Gsub::new(
Self::scripts(),
Self::feature(*b"liga"),
SubstitutionLookupList::new(vec![lookup]),
)
}
fn values(&self, sizes: &[u16]) -> LayoutValues {
let mut db = FontDb::new();
let id = db
.add_font(self.build())
.ok()
.and_then(|ids| ids.first().copied());
let values = id.and_then(|id| db.layout_values(id, sizes));
assert!(values.is_some(), "the test face does not load");
values.unwrap_or_default()
}
}
fn compare(left: &Design, right: &Design, sizes: &[u16]) -> Comparison {
Comparison::new(&left.values(sizes), &right.values(sizes), &ValueKind::ALL)
}
fn differences(comparison: &Comparison) -> Vec<(ValueKind, Place)> {
comparison
.kinds()
.iter()
.flat_map(|kind| {
kind.differences
.iter()
.map(move |difference| (kind.kind, difference.place.clone()))
})
.collect()
}
#[test]
fn equal_faces_have_no_difference() {
let comparison = compare(&Design::default(), &Design::default(), &[12, 25]);
assert!(comparison.is_match());
let compared: Vec<(ValueKind, usize)> = comparison
.kinds()
.iter()
.map(|kind| (kind.kind, kind.compared))
.filter(|(kind, _)| *kind != ValueKind::LineValues && *kind != ValueKind::Selection)
.collect();
assert_eq!(
compared,
[
(ValueKind::Characters, 4),
(ValueKind::Advance, 4),
(ValueKind::Box, 4),
(ValueKind::Kerning, 2),
(ValueKind::KernTable, 1),
(ValueKind::PixelHeights, 0),
(ValueKind::BiLevelAdvance, 8),
(ValueKind::DeviceWidth, 8),
(ValueKind::Ligatures, 1),
(ValueKind::Forms, 0),
(ValueKind::Math, 0),
(ValueKind::Shaping, 0),
]
);
}
#[test]
fn reads_the_values_by_character() {
let values = Design::default().values(&[]);
let at = |kind, place: Place| values.of(kind).and_then(|v| v.get(&place)).cloned();
assert_eq!(
at(ValueKind::Advance, Place::Character('V')),
Some(vec![600])
);
assert_eq!(
at(ValueKind::Box, Place::Character('i')),
Some(vec![40, 0, 210, 700])
);
assert_eq!(
at(ValueKind::Kerning, Place::Pair('A', 'V')),
Some(vec![-50])
);
assert_eq!(
at(ValueKind::Ligatures, Place::Sequence(vec!['f', 'i'])),
Some(vec![0, 2, 550, 20, 0, 510, 720])
);
assert_eq!(
at(ValueKind::LineValues, Place::Face("hhea ascender")),
Some(vec![800])
);
}
#[test]
fn one_advance_one_unit_wider_is_one_difference() {
let mut wider = Design::default();
if let Some(glyph) = wider.glyphs.get_mut(V) {
glyph.advance += 1;
}
let comparison = compare(&Design::default(), &wider, &[]);
assert_eq!(
differences(&comparison),
[(ValueKind::Advance, Place::Character('V'))]
);
let largest = comparison.kinds().first().and_then(|kind| kind.largest());
assert_eq!(largest.and_then(|difference| difference.gap), Some(1));
}
#[test]
fn one_kerning_pair_one_unit_less_is_one_difference() {
let other = Design {
kerning: -49,
..Design::default()
};
let comparison = compare(&Design::default(), &other, &[]);
assert_eq!(
differences(&comparison),
[(ValueKind::Kerning, Place::Pair('A', 'V'))]
);
}
#[test]
fn a_pair_that_one_face_does_not_list_has_the_kerning_0() {
let other = Design {
kerning: 0,
..Design::default()
};
let comparison = compare(&Design::default(), &other, &[]);
assert_eq!(comparison.difference_count(), 1);
let largest = comparison.kinds().first().and_then(|kind| kind.largest());
assert_eq!(largest.and_then(|difference| difference.gap), Some(50));
}
#[test]
fn one_line_value_one_unit_higher_is_one_difference() {
let other = Design {
ascender: 801,
..Design::default()
};
let comparison = compare(&Design::default(), &other, &[]);
assert_eq!(
differences(&comparison),
[(ValueKind::LineValues, Place::Face("hhea ascender"))]
);
}
#[test]
fn one_hinted_advance_one_pixel_wider_is_one_difference() {
let wider = Design {
instructions: ONE_PIXEL_WIDER.to_vec(),
..Design::default()
};
let size = 12;
let left = Design::default().values(&[size]);
let right = wider.values(&[size]);
let comparison = Comparison::new(&left, &right, &[ValueKind::DeviceWidth]);
assert_eq!(
differences(&comparison),
[(ValueKind::DeviceWidth, Place::CharacterAt('A', size))]
);
let in_units: Vec<ValueKind> = ValueKind::ALL
.into_iter()
.filter(|kind| !kind.in_pixels())
.collect();
assert!(Comparison::new(&left, &right, &in_units).is_match());
}
#[test]
fn another_ligature_glyph_is_one_difference() {
let other = Design {
ligature: V,
..Design::default()
};
let comparison = compare(&Design::default(), &other, &[]);
assert_eq!(
differences(&comparison),
[(ValueKind::Ligatures, Place::Sequence(vec!['f', 'i']))]
);
}
#[test]
fn another_glyph_order_is_no_difference() {
let renumbered = Design {
order: vec![FI, I, F, V, A],
..Design::default()
};
assert!(compare(&Design::default(), &renumbered, &[12, 25]).is_match());
}
#[test]
fn other_units_per_em_are_one_difference_and_end_the_comparison() {
let other = Design {
units_per_em: 2048,
..Design::default()
};
let comparison = compare(&Design::default(), &other, &[]);
assert_eq!(comparison.units_per_em_differ(), Some((1000, 2048)));
assert_eq!(comparison.difference_count(), 1);
assert_eq!(comparison.kinds(), []);
}
#[test]
fn a_character_of_one_face_is_one_difference_and_its_pairs_are_not_compared() {
let mut fewer = Design::default();
if let Some(glyph) = fewer.glyphs.get_mut(V) {
glyph.character = None;
}
let comparison = compare(&Design::default(), &fewer, &[12]);
assert_eq!(
differences(&comparison),
[(ValueKind::Characters, Place::Character('V'))]
);
}
#[test]
fn keeps_the_characters_of_a_range() {
let mut values = Design::default().values(&[]);
values.keep_characters('a'..='z');
assert_eq!(values.characters().collect::<String>(), "fi");
let kerning = values.of(ValueKind::Kerning);
assert!(kerning.is_some_and(|places| !places.contains_key(&Place::Pair('A', 'V'))));
}
const NOT_LAYOUT_VALUES: [(&str, &str); 16] = [
("new", "makes an empty database"),
(
"add_description",
"adds a font's description, which says what it is compatible with",
),
(
"descriptions",
"lists the descriptions, which say what the fonts are compatible with",
),
("add_font", "adds the faces of a font"),
(
"add_static",
"adds the faces of a font compiled into the program",
),
("add_files", "adds the faces of font files"),
("load", "adds the faces of a folder"),
("len", "counts the faces"),
("is_empty", "counts the faces"),
("faces", "lists the faces"),
("data", "gives the bytes of a face's file"),
("origin", "says where a face came from"),
(
"query",
"finds a face by its names, which an open font has of its own",
),
(
"query_with",
"finds a face by its names, which an open font has of its own",
),
(
"query_typographic_with",
"finds a face by its typographic family name, which an open font has of its own",
),
("layout_values", "reads the layout values"),
];
fn public_methods(source: &str) -> Vec<String> {
let mut methods = Vec::new();
let mut inside = false;
for line in source.lines() {
if line.starts_with("impl FontDb {") {
inside = true;
} else if line.starts_with('}') {
inside = false;
} else if inside && let Some(rest) = line.strip_prefix(" pub fn ") {
let name = rest.split(['(', '<']).next().unwrap_or_default();
methods.push(name.to_owned());
}
}
methods
}
fn uncovered<'a>(methods: &'a [String], reader: &str) -> Vec<&'a str> {
methods
.iter()
.map(String::as_str)
.filter(|name| {
!NOT_LAYOUT_VALUES.iter().any(|(listed, _)| listed == name)
&& !reader.contains(&format!(".{name}("))
})
.collect()
}
fn sources(folder: &Path) -> String {
let mut text = String::new();
let entries = std::fs::read_dir(folder).into_iter().flatten().flatten();
for entry in entries {
let path = entry.path();
if path.is_dir() {
text.push_str(&sources(&path));
} else if path.extension().is_some_and(|e| e == "rs") {
text.push_str(&std::fs::read_to_string(&path).unwrap_or_default());
text.push('\n');
}
}
text
}
#[test]
fn every_public_method_of_the_database_is_a_layout_value_or_named_as_none() {
let folder = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let methods = public_methods(&sources(&folder));
assert!(methods.len() > 30, "found {} methods", methods.len());
let reader = std::fs::read_to_string(folder.join("layout_values.rs")).unwrap_or_default();
assert_eq!(uncovered(&methods, &reader), Vec::<&str>::new());
}
#[test]
fn the_guard_names_a_method_that_the_reader_does_not_call() {
let source = "impl FontDb {\n pub fn advance(&self) {}\n pub fn new_value(&self) {}\n}\n";
let methods = public_methods(source);
assert_eq!(uncovered(&methods, "db.advance(id, glyph)"), ["new_value"]);
}