use std::fmt::Write as _;
use compatifont::{Description, Item};
use f_office_fonts::environment::{FontEnvironment, Lacking, OwnFace, WordLine};
use f_office_fonts::{
FamilyName, FontDb, FontId, KerningSource, NotReadCause, Os2Metrics, OutlineError,
};
use f_office_fonts::SymbolFont;
use super::{FontChoice, line_descent, sha256};
use crate::profile::Profile;
use crate::quirks::HelveticaLine;
use crate::{Fonts, KerningTable, OutlineCommand, SubstituteLayout};
use f_office_warnings::Name;
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 with_line(line: HelveticaLine) -> Profile {
Profile::base().with_variant(line)
}
fn lines_and_names() -> FontEnvironment {
let base = Profile::base();
let environment = base.font_environment();
FontEnvironment::default()
.with_lines(environment.lines().to_vec())
.with_face_names(environment.face_names().to_vec())
}
fn described(bytes: &[u8], (family, version): (&str, &str), matched: (&str, &str)) -> Description {
let items = Item::all().fold(String::new(), |mut items, item| {
let _ = writeln!(items, "\"{}\" = \"equal\"", item.name());
items
});
let text = format!(
"format = 1\nfamily_name = \"{family}\"\nversion = \"{version}\"\n\n[[fonts]]\n\
filename = \"{family}-Regular.ttf\"\nsubfamily_name = \"Regular\"\n\
full_name = \"{family} Regular\"\npost_script_name = \"{family}-Regular\"\n\
weight = 400\nstyle = \"normal\"\nsha256 = \"{}\"\n\n[[compatible_with]]\n\
family_name = \"{}\"\nversion = \"{}\"\nbasis = \"check\"\n\
reference = \"checks/test.toml\"\nsubfamilies = {{ Regular = \"Regular\" }}\n\n\
[compatible_with.items]\n{items}",
sha256(bytes),
matched.0,
matched.1
);
Description::from_toml(&text).unwrap()
}
fn add_described(
db: &mut FontDb,
(family, version): (&str, &str),
matched: (&str, &str),
) -> FontId {
let bytes = with_names(CARLITO, family, &format!("Version {version}"));
db.add_description(described(&bytes, (family, version), matched));
db.add_font(bytes).unwrap()[0]
}
fn add_arimo_cf(db: &mut FontDb) -> FontId {
add_described(db, ("Arimo CF", "7.06.1"), ("Arial", "7.06"))
}
#[test]
fn takes_pair_kerning_and_ligatures_from_the_font_store() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let glyph = |ch| choice.glyph(carlito, ch).unwrap();
let kerning = |table| choice.kerning(carlito, glyph('A'), glyph('V'), table);
assert_eq!(kerning(KerningTable::FaceSource), -89);
assert_eq!(
kerning(KerningTable::KernTable),
db.kerning_from(carlito, glyph('A'), glyph('V'), KerningSource::KernTable)
);
let fi = [glyph('f'), glyph('i')];
let joined = choice.ligatures(carlito, &fi);
assert_eq!(joined, db.ligatures(carlito, &fi));
assert_eq!(joined.len(), 1);
}
#[test]
fn gives_the_ink_of_a_glyph_none_for_a_space_and_the_cause_of_an_outline_that_does_not_read() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let glyph = |ch| choice.glyph(carlito, ch).unwrap();
let ink = choice.ink(carlito, glyph('x'));
assert!(
matches!(ink, Ok(Some((low, high))) if low <= 0 && high > 0),
"{ink:?}"
);
assert_eq!(choice.ink(carlito, glyph(' ')), Ok(None));
assert_eq!(
choice.ink(carlito, u32::MAX),
Err(OutlineError::UnknownGlyph)
);
let unknown = FontId::from_index(carlito.index() + 1);
assert_eq!(choice.ink(unknown, 0), Err(OutlineError::UnknownFont));
}
#[test]
fn finds_the_families_that_draw_a_family_in_its_place() {
let db = FontDb::new();
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
for (family, first) in [
("calibri", Some("Celeborn CF")),
("Aptos", Some("Intos CF")),
("Courier New", Some("CurunÃr CF")),
("arial narrow", Some("Arimo Narrow CF")),
("Book Antiqua", Some("P052")),
("Bookman Old Style", Some("URW Bookman")),
("Segoe UI", Some("Sindar CF")),
("Comic Sans MS", Some("Comic Relief CF")),
("Cambria Math", Some("Caladea Math CF")),
] {
let drawn = choice.drawn_with(family);
assert_eq!(drawn.first().map(String::as_str), first, "{family}");
}
}
#[test]
fn draws_the_families_of_its_own_rule_with_their_compatible_fonts() {
let db = FontDb::new();
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let arial = ["Arial", "Arimo CF", "Arimo", "Liberation Sans"];
assert_eq!(choice.drawn_with("Helvetica"), arial);
assert_eq!(choice.drawn_with("Symbol"), Vec::<String>::new());
assert_eq!(
choice.drawn_with("Times"),
["Times New Roman", "Tinos CF", "Liberation Serif", "Tinos"]
);
}
#[test]
fn takes_words_line_of_a_family_from_the_base_environment() {
let base = Profile::base();
let line = |family| {
base.font_environment()
.line(family)
.map(|l| (l.ascent, l.descent))
};
assert_eq!(line("Calibri"), None);
assert_eq!(line("Cambria"), Some((960, 212)));
}
#[test]
fn draws_a_family_with_the_family_that_the_configuration_names_and_its_compatible_fonts() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let target = crate::Target::all().next().unwrap();
let mut configuration = crate::Configuration::of(target);
for (family, uses) in [
("Aptos", "Calibri"),
("Symbol", "Aptos"),
("Calibri", "Symbol"),
] {
configuration
.fonts
.uses
.insert(family.to_owned(), uses.to_owned());
}
let profile = Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap();
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &profile);
assert_eq!(choice.drawn_with("Aptos"), ["Calibri", "Symbol"]);
assert_eq!(
choice.drawn_with("Symbol"),
["Aptos", "Calibri", "Celeborn CF", "Carlito"]
);
let aptos = choice.face(&FamilyName::from_static("Aptos"), false, false);
assert_eq!(aptos.map(|chosen| chosen.font), None);
let symbol = choice.face(&FamilyName::from_static("Symbol"), false, false);
assert_eq!(symbol.map(|chosen| chosen.font), Some(carlito));
}
#[test]
fn keeps_measured_line_metrics_over_the_own_file_only_for_named_fonts() {
let mut db = FontDb::new();
let helvetica = db
.add_font(with_names(CARLITO, "Helvetica", "Version 1.0"))
.unwrap()[0];
let symbol = db
.add_font(with_names(CARLITO, "Symbol", "Version 1.0"))
.unwrap()[0];
let environment = lines_and_names();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let metrics = |family, named| {
let family = FamilyName::from_static(family);
let chosen = if named {
choice.face(&family, false, false)
} else {
choice.substitute(&family, false, false)
};
chosen.map(|chosen| chosen.metrics)
};
let own = choice.metrics(helvetica);
assert_ne!(metrics("Helvetica", true), own);
assert_eq!(metrics("Helvetica", false), own);
assert_eq!(metrics("Symbol", true), choice.metrics(symbol));
}
#[test]
fn gives_helvetica_the_line_of_its_face_where_the_target_says_so() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = lines_and_names();
let metrics = |helvetica_line| {
let choice = FontChoice::new(&db, &environment, &with_line(helvetica_line));
let own = choice.metrics(carlito);
let drawn_with = ["Carlito".to_owned()];
let drawn = choice.draw_stand_in("Helvetica", &drawn_with, (false, false), &[]);
(drawn.map(|chosen| chosen.metrics), own)
};
let (face, own) = metrics(HelveticaLine::TakesFaceLine);
assert_eq!(face, own);
let (mac, own) = metrics(HelveticaLine::TwelveTenthsEm);
assert_ne!(mac, own);
let lines = with_line(HelveticaLine::TakesFaceLine).stand_in_lines();
assert!(lines.of_family("Symbol"));
}
#[test]
fn treats_a_family_that_the_target_lacks_as_missing() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
let lacking = Lacking {
drawn_with: None,
family: FamilyName::from_static("Carlito"),
};
let environment = FontEnvironment::default().with_lacking(vec![lacking]);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let carlito = FamilyName::from_static("Carlito");
assert!(choice.face(&carlito, false, false).is_none());
assert!(choice.substitute(&carlito, true, false).is_none());
let lower = FamilyName::from_static("carlito");
assert!(choice.face(&lower, false, false).is_none());
}
#[test]
fn a_target_listing_blocks_local_names_before_stand_ins() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
let environment =
FontEnvironment::default().with_available(vec![FamilyName::from_static("Calibri")]);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let face = |family| choice.face(&FamilyName::from_static(family), false, false);
assert!(face("Carlito").is_none());
assert!(
choice
.substitute(&FamilyName::from_static("Carlito"), false, false)
.is_none()
);
assert!(face("Calibri").is_some());
assert!(face("CALIBRI").is_some());
}
fn with_installed(target: crate::Target, family: &str) -> Profile {
let mut configuration = crate::Configuration::of(target);
configuration
.fonts
.installed
.insert(family.to_owned(), true);
Profile::resolve(&configuration, &crate::profile::Overrides::default()).unwrap()
}
fn listed(target: crate::Target) -> bool {
!Profile::of(target)
.unwrap()
.font_environment()
.available()
.is_empty()
}
fn takes_carlito(db: &FontDb, profile: &Profile) -> bool {
FontChoice::new(db, profile.font_environment(), profile)
.face(&FamilyName::from_static("Carlito"), false, false)
.is_some()
}
#[test]
fn a_family_that_the_configuration_installs_counts_as_listed() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
let targets: Vec<_> = crate::Target::all()
.filter(|target| listed(*target))
.collect();
assert_ne!(targets.len(), 0, "a target has a full font listing");
for target in targets {
assert!(
!takes_carlito(&db, &Profile::of(target).unwrap()),
"{target}"
);
let added = with_installed(target, "Carlito");
assert!(takes_carlito(&db, &added), "{target}");
assert!(added.font_environment().permits("carlito"), "{target}");
assert_eq!(
added.origin("configuration.fonts.installed.Carlito"),
Some("configuration")
);
assert!(
!takes_carlito(&db, &with_installed(target, "Lato")),
"{target}"
);
}
}
#[test]
fn a_target_without_a_full_listing_takes_an_added_family_as_every_other() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
for target in crate::Target::all().filter(|target| !listed(*target)) {
let added = with_installed(target, "Carlito");
assert!(added.font_environment().available().is_empty(), "{target}");
assert!(takes_carlito(&db, &added), "{target}");
}
}
#[test]
fn a_reference_stand_in_needs_the_targets_family_style_and_version() {
let mut db = FontDb::new();
let id = db.add_font(CARLITO.to_vec()).unwrap()[0];
let mut info = db.info(id).unwrap().clone();
info.family = "Helvetica".to_owned();
let environment = FontEnvironment::new(vec![OwnFace {
family: "Helvetica".to_owned(),
style: info.subfamily.clone(),
version: info.version.clone().unwrap(),
kerning: None,
}])
.with_available(vec![FamilyName::from_static("Arial")]);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TakesFaceLine));
assert!(choice.permits_face(&info));
info.version = Some("another version".to_owned());
assert!(!choice.permits_face(&info));
}
#[test]
fn names_a_face_only_when_it_is_the_targets_own() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let info = db.info(carlito).unwrap();
let (name, version) = (
info.postscript_name.clone().unwrap(),
info.version.clone().unwrap(),
);
let (family, style) = (info.family.clone(), info.subfamily.clone());
let own = |style: &str, version: &str| {
FontEnvironment::new(vec![OwnFace {
family: family.clone(),
style: style.to_owned(),
version: version.to_owned(),
kerning: None,
}])
};
let named = |environment: &FontEnvironment| {
let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
choice.target_face(carlito)
};
assert_eq!(
named(&own(&style, &version)),
Some((name.clone(), version.clone()))
);
assert_eq!(named(&own(&style, "Version 0.1")), None);
assert_eq!(named(&own("Other", &version)), None);
assert_eq!(named(&FontEnvironment::default()), None);
}
#[test]
fn takes_the_recorded_kerning_source_of_the_targets_file_over_its_own() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let info = db.info(carlito).unwrap();
let (family, style, version) = (
info.family.clone(),
info.subfamily.clone(),
info.version.clone().unwrap(),
);
let own = db.kerning_source(carlito);
let other = match own {
KerningSource::Gpos => KerningSource::KernTable,
KerningSource::KernTable => KerningSource::Gpos,
};
let own_face = |version: &str, kerning| {
FontEnvironment::new(vec![OwnFace {
family: family.clone(),
style: style.clone(),
version: version.to_owned(),
kerning,
}])
};
let source = |environment: &FontEnvironment| {
let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
(
choice.kerning_source(carlito),
choice.kerning_source(carlito),
)
};
assert_eq!(source(&own_face(&version, Some(other))), (other, other));
assert_eq!(source(&own_face(&version, None)), (own, own));
assert_eq!(source(&own_face("Version 0.1", Some(other))), (own, own));
assert_eq!(source(&FontEnvironment::default()), (own, own));
}
fn with_names(font: &[u8], family: &str, version: &str) -> Vec<u8> {
with_name_table(font, ®ular_names(family, version))
}
fn regular_names(family: &str, version: &str) -> Vec<(u16, String)> {
vec![
(1, family.to_owned()),
(2, "Regular".to_owned()),
(4, format!("{family} Regular")),
(5, version.to_owned()),
(6, format!("{family}-Regular")),
]
}
fn with_name_table(font: &[u8], names: &[(u16, String)]) -> Vec<u8> {
let short = |n: usize| u16::try_from(n).unwrap();
let mut strings = Vec::new();
let mut table = Vec::new();
table.extend_from_slice(&0_u16.to_be_bytes());
table.extend_from_slice(&short(names.len()).to_be_bytes());
table.extend_from_slice(&short(6 + 12 * names.len()).to_be_bytes());
for (id, text) in names {
let utf16: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
for value in [
3_u16,
1,
0x409,
*id,
short(utf16.len()),
short(strings.len()),
] {
table.extend_from_slice(&value.to_be_bytes());
}
strings.extend(utf16);
}
table.extend(strings);
let mut bytes = font.to_vec();
while !bytes.len().is_multiple_of(4) {
bytes.push(0);
}
let count = usize::from(u16::from_be_bytes([bytes[4], bytes[5]]));
let record = (0..count)
.map(|index| 12 + 16 * index)
.find(|&at| &bytes[at..at + 4] == b"name")
.unwrap();
let (offset, length) = (
u32::try_from(bytes.len()).unwrap(),
u32::try_from(table.len()).unwrap(),
);
bytes[record + 8..record + 12].copy_from_slice(&offset.to_be_bytes());
bytes[record + 12..record + 16].copy_from_slice(&length.to_be_bytes());
bytes.extend(table);
bytes
}
fn own_regular(family: &str, version: &str, kerning: Option<KerningSource>) -> FontEnvironment {
FontEnvironment::new(vec![OwnFace {
family: family.to_owned(),
style: "Regular".to_owned(),
version: version.to_owned(),
kerning,
}])
}
#[test]
fn lays_out_a_described_face_as_the_targets_own_face_of_the_same_version() {
let mut db = FontDb::new();
let arimo_cf = add_arimo_cf(&mut db);
let arimo = db
.add_font(with_names(CARLITO, "Arimo", "Version 7.06.1"))
.unwrap()[0];
let tinos_cf = add_described(&mut db, ("Tinos CF", "7.12.1"), ("Times New Roman", "7.12"));
let changed = db
.add_font(with_weight(
&with_names(CARLITO, "Arimo CF", "Version 7.06.1"),
500,
))
.unwrap()[0];
let own = db.kerning_source(arimo_cf);
let other = match own {
KerningSource::Gpos => KerningSource::KernTable,
KerningSource::KernTable => KerningSource::Gpos,
};
let answers = |environment: &FontEnvironment, font| {
let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
(choice.target_face(font), choice.kerning_source(font))
};
let arial = own_regular("Arial", "Version 7.06", Some(other));
let as_own = Some(("Arimo CF-Regular".to_owned(), "Version 7.06.1".to_owned()));
assert_eq!(answers(&arial, arimo_cf), (as_own, other));
for environment in [
own_regular("Arial", "Version 5.01", Some(other)),
own_regular("Arial", "Version 7.0", Some(other)),
own_regular("Arial", "Version 7.06.1", None),
FontEnvironment::default(),
] {
assert_eq!(answers(&environment, arimo_cf), (None, own));
}
assert_eq!(answers(&arial, arimo), (None, own));
assert_eq!(answers(&arial, tinos_cf), (None, own));
assert_eq!(answers(&arial, changed).0, None);
}
#[test]
fn says_whether_a_described_face_has_the_layout_of_the_targets_face() {
let mut db = FontDb::new();
let arimo_cf = add_arimo_cf(&mut db);
let sans = db
.add_font(with_names(CARLITO, "Liberation Sans", "Version 2.1"))
.unwrap()[0];
let answers = |environment: &FontEnvironment, font| {
let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
(choice.face_version(font), choice.substitute_layout(font))
};
let version = |text: &str| Some(text.to_owned());
let windows = own_regular("Arial", "Version 7.06", None);
let mac = own_regular("Arial", "Version 5.01.2x", None);
assert_eq!(
answers(&windows, arimo_cf),
(version("7.06.1"), SubstituteLayout::Exact)
);
let other = SubstituteLayout::OtherVersion {
family: Name::new("Arial"),
made_for: Name::new("7.06"),
target: Name::new("5.01.2x"),
};
assert_eq!(answers(&mac, arimo_cf), (version("7.06.1"), other));
let nothing = FontEnvironment::default();
assert_eq!(
answers(¬hing, arimo_cf),
(version("7.06.1"), SubstituteLayout::Widths)
);
assert_eq!(
answers(&windows, sans),
(version("2.1"), SubstituteLayout::Widths)
);
}
#[test]
fn draws_arial_and_times_new_roman_with_the_fonts_of_their_layout_first() {
let environment = FontEnvironment::default();
let mut db = FontDb::new();
let sans = db
.add_font(with_names(CARLITO, "Liberation Sans", "Version 2.1"))
.unwrap()[0];
let serif = db
.add_font(with_names(CARLITO, "Liberation Serif", "Version 2.1"))
.unwrap()[0];
let fonts = |db: &FontDb| {
let choice = FontChoice::new(db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
["Arial", "Times New Roman", "Helvetica", "Times"].map(|family| {
let chosen = choice
.face(&FamilyName::from_static(family), false, false)
.unwrap();
assert!(chosen.stands_in, "{family}");
chosen.font
})
};
assert_eq!(fonts(&db), [sans, serif, sans, serif]);
let arimo_cf = add_arimo_cf(&mut db);
let tinos_cf = add_described(&mut db, ("Tinos CF", "7.12.1"), ("Times New Roman", "7.12"));
assert_eq!(fonts(&db), [arimo_cf, tinos_cf, arimo_cf, tinos_cf]);
}
#[test]
fn draws_a_missing_family_with_its_compatible_font_before_a_face_of_its_typographic_family() {
let environment = FontEnvironment::default();
let mut names = regular_names("Arial Narrow", "Version 2.40");
names.push((16, "Arial".to_owned()));
let mut db = FontDb::new();
let narrow = db.add_font(with_name_table(CARLITO, &names)).unwrap()[0];
let arial = |db: &FontDb| {
let choice = FontChoice::new(db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let chosen = choice
.face(&FamilyName::from_static("Arial"), false, false)
.unwrap();
(chosen.font, chosen.stands_in)
};
assert_eq!(arial(&db), (narrow, false));
let arimo_cf = add_arimo_cf(&mut db);
assert_eq!(arial(&db), (arimo_cf, true));
let own = db
.add_font(with_names(CARLITO, "Arial", "Version 7.06"))
.unwrap()[0];
assert_eq!(arial(&db), (own, false));
}
#[test]
fn draws_a_target_face_named_by_its_full_or_postscript_name_with_its_compatible_font() {
let environment = lines_and_names();
let mut db = FontDb::new();
let arimo_cf = add_arimo_cf(&mut db);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let chosen = |name, bold| {
let chosen = choice
.face(&FamilyName::from_static(name), bold, false)
.unwrap();
(chosen.font, chosen.stands_in, chosen.synthetic_bold)
};
assert_eq!(chosen("Arial Bold", false), (arimo_cf, true, false));
assert_eq!(chosen("ArialMT", false), (arimo_cf, true, false));
assert_eq!(chosen("Arial-ItalicMT", true), (arimo_cf, true, true));
assert!(
choice
.face(&FamilyName::from_static("TimesNewRomanPSMT"), false, false)
.is_none()
);
let nameless = FontEnvironment::default();
let choice = FontChoice::new(&db, &nameless, &with_line(HelveticaLine::TwelveTenthsEm));
assert!(
choice
.face(&FamilyName::from_static("ArialMT"), false, false)
.is_none()
);
}
#[test]
fn a_described_face_lays_out_as_the_family_of_the_targets_face() {
let mut db = FontDb::new();
let arimo_cf = add_arimo_cf(&mut db);
let family = |environment: &FontEnvironment| {
let choice = FontChoice::new(&db, environment, &with_line(HelveticaLine::TwelveTenthsEm));
(choice.family_name(arimo_cf), choice.layout_family(arimo_cf))
};
let named = |name: &str| Some(name.to_owned());
assert_eq!(
family(&own_regular("Arial", "Version 7.06", None)),
(named("Arimo CF"), named("Arial"))
);
assert_eq!(
family(&own_regular("Arial", "Version 5.01", None)),
(named("Arimo CF"), named("Arimo CF"))
);
}
#[test]
fn finds_faces_by_family_and_through_stand_ins() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let font = |family| {
choice
.face(&FamilyName::from_static(family), false, false)
.map(|f| f.font)
};
assert_eq!(font("Carlito"), Some(carlito));
assert_eq!(font("Calibri"), Some(carlito));
assert_eq!(font("Aptos"), None);
let chosen = choice
.face(&FamilyName::from_static("Calibri"), false, false)
.unwrap();
assert_eq!(Some(chosen.metrics), choice.metrics(carlito));
assert_eq!(font("Symbol"), None);
}
#[test]
fn finds_one_face_for_a_family_in_any_case_of_ascii_letters() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
for family in ["Calibri", "CALIBRI", "Carlito", "carlito"] {
let face = choice.face(&FamilyName::from_static(family), false, false);
assert_eq!(face.map(|f| f.font), Some(carlito), "{family}");
}
assert_eq!(choice.chosen.borrow().len(), 2);
}
#[test]
fn finds_older_builds_by_names_without_mt_or_ms() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let font = |family| {
choice
.face(&FamilyName::from_static(family), false, false)
.map(|f| f.font)
};
assert_eq!(font("Carlito-RegularMT"), Some(carlito));
assert_eq!(font("Carlito MS"), Some(carlito));
assert_eq!(font("MT"), None);
assert_eq!(font(" MS"), None);
}
#[test]
fn keeps_the_answer_of_each_family_and_request_and_gives_it_again() {
let mut db = FontDb::new();
db.add_font(CARLITO.to_vec()).unwrap();
let environment =
FontEnvironment::default().with_available(vec![FamilyName::from_static("Calibri")]);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let families = ["Calibri", "Carlito", "Aptos", "Symbol", "Carlito MS"];
let requests = (0..8_u8).map(|bits| (bits & 1 != 0, bits & 2 != 0, bits & 4 != 0));
for (family, (bold, italic, named)) in families
.iter()
.flat_map(|family| requests.clone().map(move |request| (*family, request)))
{
let family = FamilyName::from_static(family);
let anew = choice.choose_anew(&family, bold, italic, named, &[]);
let first = choice.choose(&family, bold, italic, named);
let again = choice.choose(&family, bold, italic, named);
assert_eq!((first, again), (anew, anew), "{}", family.as_str());
}
let chosen = choice.chosen.borrow();
assert_eq!(chosen.len(), families.len());
assert!(chosen.values().all(|answers| answers.len() == 8));
}
#[test]
fn draws_a_missing_symbol_font_with_its_measured_metrics() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let environment = FontEnvironment::default().with_lines(vec![WordLine {
family: FamilyName::from_static("Test Symbols"),
ascent: 1005,
descent: 215,
over_own_file: false,
}]);
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let drawn_with = |families: &[&str]| -> Vec<String> {
families.iter().map(|family| (*family).to_owned()).collect()
};
let draw = |family, families: &[&str], bold| {
choice.draw_stand_in(family, &drawn_with(families), (bold, false), &[])
};
let chosen = draw("Test Symbols", &["Missing", "Carlito"], true).unwrap();
assert_eq!(chosen.font, carlito);
let m = chosen.metrics;
assert_eq!((m.units_per_em, m.hhea_line_gap), (2048, 0));
assert_eq!(
(m.hhea_ascender, m.hhea_descender, m.descent),
(2058, -440, 440)
);
let own = choice.metrics(carlito).unwrap();
assert_eq!(m.underline_position, own.underline_position);
assert!(draw("Test Symbols", &["Missing"], false).is_none());
let chosen = draw("Other Symbols", &["Carlito"], false).unwrap();
assert_eq!(Some(chosen.metrics), choice.metrics(carlito));
}
#[test]
fn takes_the_typo_descent_only_from_fonts_that_ask_for_typo_metrics() {
let mut db = FontDb::new();
let carlito = db.add_font(CARLITO.to_vec()).unwrap()[0];
let os2 = db.metrics(carlito).unwrap().os2.unwrap();
let with = |use_typo_metrics, descender| Os2Metrics {
use_typo_metrics,
typo: f_office_fonts::LineMetrics {
descender,
..os2.typo
},
win_descent: 550,
..os2
};
assert_eq!(line_descent(&with(false, -400)), 550);
assert_eq!(line_descent(&with(true, -400)), 400);
assert_eq!(line_descent(&with(true, -600)), 600);
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
assert_eq!(choice.metrics(carlito).unwrap().descent, line_descent(&os2));
}
fn files_not_read(choice: &FontChoice<'_>) -> Vec<(String, NotReadCause)> {
let files = choice.files_not_read().into_iter();
files.map(|file| (file.file, file.cause)).collect()
}
#[test]
fn a_face_whose_file_does_not_load_counts_as_missing_and_its_file_is_named_once() {
let name = format!("f-office-docx-choice-{}", std::process::id());
let folder = std::env::temp_dir().join(name);
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
let mut db = FontDb::new();
db.add_files(&[folder.join("carlito.ttf")]).unwrap();
std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
std::fs::remove_dir(&folder).unwrap();
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
assert_eq!(choice.files_not_read(), []);
assert_eq!(choice.face(&FamilyName::new("Carlito"), false, false), None);
assert_eq!(choice.face(&FamilyName::new("Calibri"), false, false), None);
let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
assert_eq!(files_not_read(&choice), [("carlito.ttf".to_owned(), gone)]);
}
fn renamed(font: &[u8], from: &str, to: &str) -> Vec<u8> {
assert_eq!(from.len(), to.len());
let utf16 =
|name: &str| -> Vec<u8> { name.encode_utf16().flat_map(u16::to_be_bytes).collect() };
let mut bytes = font.to_vec();
for (from, to) in [
(from.as_bytes().to_vec(), to.as_bytes().to_vec()),
(utf16(from), utf16(to)),
] {
let mut start = 0;
while let Some(found) = bytes[start..].windows(from.len()).position(|w| w == from) {
let at = start + found;
bytes[at..at + to.len()].copy_from_slice(&to);
start = at + to.len();
}
}
bytes
}
#[test]
fn the_search_goes_on_past_a_face_whose_file_does_not_load_to_the_stand_in() {
let name = format!("f-office-docx-choice-search-{}", std::process::id());
let folder = std::env::temp_dir().join(name);
std::fs::create_dir_all(&folder).unwrap();
let calibri_file = renamed(CARLITO, "Carlito", "Calibri");
std::fs::write(folder.join("calibri.ttf"), calibri_file).unwrap();
std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
let mut db = FontDb::new();
db.add_files(&[folder.join("calibri.ttf"), folder.join("carlito.ttf")])
.unwrap();
std::fs::remove_file(folder.join("calibri.ttf")).unwrap();
let calibri = FamilyName::new("Calibri");
let own = db.query(&calibri, false, false).unwrap();
assert_eq!(db.info(own).unwrap().family, "Calibri");
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let chosen = choice.face(&calibri, false, false).unwrap();
assert!(chosen.stands_in);
assert_eq!(db.info(chosen.font).unwrap().family, "Carlito");
assert_eq!(choice.face(&calibri, false, false), Some(chosen));
std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
std::fs::remove_dir(&folder).unwrap();
let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
assert_eq!(files_not_read(&choice), [("calibri.ttf".to_owned(), gone)]);
}
fn with_weight(font: &[u8], weight: u16) -> Vec<u8> {
let number = |at: usize, len: usize| {
font[at..at + len]
.iter()
.fold(0_usize, |value, byte| value << 8 | usize::from(*byte))
};
let os2 = (0..number(4, 2))
.map(|index| 12 + 16 * index)
.find(|&at| &font[at..at + 4] == b"OS/2")
.unwrap();
let table = number(os2 + 8, 4);
let mut bytes = font.to_vec();
bytes[table + 4..table + 6].copy_from_slice(&weight.to_be_bytes());
bytes
}
#[test]
fn a_bold_face_whose_file_does_not_load_gives_the_regular_face_of_its_family() {
let name = format!("f-office-docx-choice-bold-{}", std::process::id());
let folder = std::env::temp_dir().join(name);
std::fs::create_dir_all(&folder).unwrap();
std::fs::write(folder.join("carlito-bold.ttf"), with_weight(CARLITO, 700)).unwrap();
std::fs::write(folder.join("carlito.ttf"), CARLITO).unwrap();
let mut db = FontDb::new();
db.add_files(&[folder.join("carlito-bold.ttf"), folder.join("carlito.ttf")])
.unwrap();
std::fs::remove_file(folder.join("carlito-bold.ttf")).unwrap();
let carlito = FamilyName::new("Carlito");
let bold = db.query(&carlito, true, false).unwrap();
assert_eq!(db.info(bold).unwrap().weight, 700);
let environment = FontEnvironment::default();
let choice = FontChoice::new(&db, &environment, &with_line(HelveticaLine::TwelveTenthsEm));
let chosen = choice.face(&carlito, true, false).unwrap();
std::fs::remove_file(folder.join("carlito.ttf")).unwrap();
std::fs::remove_dir(&folder).unwrap();
let mut regular_only = FontDb::new();
let regular = regular_only.add_font(CARLITO.to_vec()).unwrap()[0];
let alone = FontChoice::new(
®ular_only,
&environment,
&with_line(HelveticaLine::TwelveTenthsEm),
);
let expected = alone.face(&carlito, true, false).unwrap();
assert_eq!(db.info(chosen.font), regular_only.info(regular));
assert_eq!(
(chosen.metrics, chosen.synthetic_bold, chosen.stands_in),
(expected.metrics, expected.synthetic_bold, false)
);
let italic = alone.face(&carlito, false, true).unwrap();
assert_eq!(regular_only.info(italic.font), regular_only.info(regular));
assert!(italic.synthetic_italic && !expected.synthetic_italic);
let gone = NotReadCause::Unreadable(std::io::ErrorKind::NotFound);
assert_eq!(
files_not_read(&choice),
[("carlito-bold.ttf".to_owned(), gone)]
);
}
#[test]
fn gives_the_metafile_face_of_the_font_environment() {
use f_office_fonts::environment::MetafileFaces;
let db = FontDb::new();
let environment = FontEnvironment::default()
.with_available(vec![FamilyName::from_static("Calibri")])
.with_metafile_faces(vec![MetafileFaces {
charset: 255,
faces: (0..18).map(|index| format!("Face {index}")).collect(),
}]);
let profile = with_line(HelveticaLine::TwelveTenthsEm);
let choice = FontChoice::new(&db, &environment, &profile);
let mapped = |family| choice.metafile_face(&FamilyName::new(family), 255, 0x31);
assert_eq!(mapped("Missing"), Some(FamilyName::new("Face 10")));
assert_eq!(mapped("Calibri"), None);
}
fn open_fonts() -> (FontDb, FontId) {
let mut db = FontDb::new();
f_office_fonts::open_fonts::add_missing(&mut db).expect("the open fonts read");
let family = FamilyName::from_static(SymbolFont::DRAWING_FAMILY);
let noto = db
.query(&family, false, false)
.expect("the build holds Noto Symbols CF");
(db, noto)
}
fn with_symbol_widths(font: SymbolFont, code: u32) -> Vec<(crate::Target, Profile, u16, u16, i32)> {
let profiles: Vec<_> = (crate::Target::all())
.filter_map(|target| {
let profile = Profile::of(target).ok()?;
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(font)?;
let numbers = (
widths.units_per_em(),
widths.advance(code)?,
widths.device_width(code, 100)?,
);
Some((target, profile.clone(), numbers.0, numbers.1, numbers.2))
})
.collect();
assert!(
!profiles.is_empty(),
"a target holds Word's numbers of {font:?}"
);
profiles
}
fn stand_in(choice: &FontChoice<'_>, family: &'static str) -> FontId {
choice
.substitute(&FamilyName::from_static(family), false, false)
.expect("a stand-in face")
.font
}
fn placed(
outline: Vec<OutlineCommand>,
place: impl Fn([i32; 2]) -> [i32; 2],
) -> Vec<OutlineCommand> {
(outline.into_iter())
.map(|command| match command {
OutlineCommand::MoveTo(p) => OutlineCommand::MoveTo(place(p)),
OutlineCommand::LineTo(p) => OutlineCommand::LineTo(place(p)),
OutlineCommand::QuadTo(c, p) => OutlineCommand::QuadTo(place(c), place(p)),
OutlineCommand::CubicTo(c, d, p) => {
OutlineCommand::CubicTo(place(c), place(d), place(p))
}
OutlineCommand::Close => OutlineCommand::Close,
})
.collect()
}
#[test]
fn gives_a_missing_symbol_font_a_stand_in_face_with_the_metrics_of_its_file() {
let (db, _) = open_fonts();
let first = u32::try_from(db.len()).unwrap();
let wingdings = FamilyName::from_static("Wingdings");
for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
let choice = FontChoice::of(&db, &profile);
let chosen = (choice.substitute(&wingdings, true, true)).expect("a stand-in face");
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
let flags = (
chosen.stands_in,
chosen.synthetic_bold,
chosen.synthetic_italic,
);
assert_eq!(
(chosen.font.index() >= first, flags),
(true, (true, true, true))
);
assert_eq!(chosen.metrics, super::metrics_of(&widths.metrics));
assert_eq!(choice.substitute(&wingdings, true, true), Some(chosen));
}
}
#[test]
fn gives_the_stand_in_face_of_a_symbol_font_to_the_postscript_name_of_its_file() {
let (db, _) = open_fonts();
for (_, profile, ..) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
let choice = FontChoice::of(&db, &profile);
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(SymbolFont::Symbol).unwrap();
let postscript = FamilyName::new(&widths.postscript_name);
let chosen = choice
.face(&postscript, false, false)
.map(|chosen| chosen.font);
assert_eq!(chosen, Some(stand_in(&choice, "Symbol")));
}
}
#[test]
fn gives_the_codes_of_a_symbol_stand_in_face_the_widths_of_words_file() {
let (db, _) = open_fonts();
for (_, profile, _, advance, device_width) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Wingdings");
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
let glyphs = ['\u{F0FC}', '\u{FC}', '\u{2713}'].map(|ch| choice.glyph(font, ch));
assert_eq!(glyphs, [Some(0xFC), Some(0xFC), None]);
let numbers = (
choice.advance(font, 0xFC),
choice.device_width(font, 0xFC, 100),
choice.bi_level_advance(font, 0xFC, 1000),
choice.device_heights(font, 8),
);
let expected = (
Some(advance),
Some(device_width),
widths.written(0xFC).map(i32::from),
widths.heights(8),
);
assert_eq!(numbers, expected);
let joins = (
choice.kerning(font, 0xFC, 0xFC, KerningTable::FaceSource),
choice.ligatures(font, &[0xFC, 0xFC]).len(),
);
assert_eq!(joins, (0, 0));
}
}
#[test]
fn lays_out_a_symbol_stand_in_face_as_its_font_and_names_the_face_that_draws_it() {
let (db, noto) = open_fonts();
for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Wingdings");
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(SymbolFont::Wingdings).unwrap();
let family = choice.layout_family(font);
let layout = (
family.as_deref(),
choice.substitute_layout(font),
choice.classification(font),
);
let expected = (
Some("Wingdings"),
SubstituteLayout::Exact,
Some(widths.classification),
);
assert_eq!(layout, expected);
let names = (choice.family_name(font), choice.face_version(font));
assert_eq!(names, (choice.family_name(noto), choice.face_version(noto)));
}
}
#[test]
fn steps_a_symbol_stand_in_face_as_an_own_face_only_where_the_file_of_its_font_is_one() {
let (db, _) = open_fonts();
for (_, profile, ..) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
let choice = FontChoice::of(&db, &profile);
let fonts = profile.symbol_fonts();
let environment = profile.font_environment();
let own: Vec<_> = (SymbolFont::ALL.into_iter())
.filter_map(|font| {
let (_, widths) = fonts.get(font)?;
let file = environment.is_target_file(font.family(), "Regular", &widths.version);
let face = choice.target_face(stand_in(&choice, font.family()));
Some((font, face.is_some(), file))
})
.collect();
assert!(own.iter().all(|(_, face, file)| face == file), "{own:?}");
}
}
#[test]
fn gives_the_missing_glyph_of_a_symbol_stand_in_face_the_widths_of_the_files_missing_glyph() {
use f_office_fonts::{ShapeDirection, ShapeRequest, ShapedScript};
let (db, _) = open_fonts();
for (_, profile, _, advance, device_width) in with_symbol_widths(SymbolFont::Symbol, 0) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Symbol");
let fonts = profile.symbol_fonts();
let (_, widths) = fonts.get(SymbolFont::Symbol).unwrap();
let code = (0x20..=0xFF)
.find(|&code| widths.advance(code).is_none())
.expect("a code that the file does not map");
let text = char::from_u32(0xF000 + code).unwrap().to_string();
let request = ShapeRequest {
text: &text,
script: ShapedScript::Arabic,
direction: ShapeDirection::LeftToRight,
language: None,
};
let shaped = choice.shape(font, &request).unwrap();
let glyphs: Vec<_> = shaped.iter().map(|g| (g.glyph, g.advance)).collect();
assert_eq!(glyphs, [(0, i32::from(advance))]);
assert_eq!(choice.device_width(font, 0, 100), Some(device_width));
}
}
#[test]
fn gives_no_stand_in_face_without_the_face_that_draws_it() {
let db = FontDb::new();
for (_, profile, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
let choice = FontChoice::of(&db, &profile);
let wingdings = FamilyName::from_static("Wingdings");
assert_eq!(choice.substitute(&wingdings, false, false), None);
}
}
#[test]
fn shapes_the_codes_of_a_symbol_stand_in_face_without_substitutions() {
use f_office_fonts::{ShapeDirection, ShapeRequest, ShapedScript};
let (db, _) = open_fonts();
for (_, profile, _, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Symbol");
let request = ShapeRequest {
text: "a\u{F062}",
script: ShapedScript::Arabic,
direction: ShapeDirection::RightToLeft,
language: None,
};
let shaped = choice.shape(font, &request).unwrap();
let glyphs: Vec<_> = (shaped.iter())
.map(|g| (g.glyph, g.cluster, g.offset))
.collect();
assert_eq!(glyphs, [(0x62, 1, (0, 0)), (0x61, 0, (0, 0))]);
assert_eq!(shaped.last().map(|g| g.advance), Some(i32::from(advance)));
}
}
#[test]
fn outlines_a_code_of_a_symbol_stand_in_face_with_the_drawing_faces_glyph_in_its_middle() {
let (db, noto) = open_fonts();
for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Symbol");
let alpha = db.glyph_id(noto, '\u{3B1}').unwrap();
let drawn = i64::from(db.advance(noto, alpha).unwrap());
let noto_em = i64::from(db.metrics(noto).unwrap().units_per_em);
let (em, advance) = (i64::from(em), i64::from(advance));
let height =
|y: i32| i32::try_from(f_office_units::div_round(i64::from(y) * em, noto_em)).unwrap();
let place = |[x, y]: [i32; 2]| {
let twice = 2 * i64::from(x) * em + advance * noto_em - drawn * em;
let x = f_office_units::div_round(twice, 2 * noto_em);
[i32::try_from(x).unwrap(), height(y)]
};
let expected = placed(choice.outline(noto, alpha).unwrap(), place);
assert_eq!(choice.outline(font, 0x61).unwrap(), expected);
let ink = choice.ink(noto, alpha).unwrap();
let expected = ink.map(|(low, high)| (height(low), height(high)));
assert_eq!(choice.ink(font, 0x61).unwrap(), expected);
}
}
fn drawn_run(
choice: &FontChoice<'_>,
font: FontId,
id: u32,
) -> (f_office_paint::GlyphRun, f_office_paint::GlyphRun) {
use f_office_paint::{DisplayList, Glyph, GlyphRun, Item, Orientation, Page, Rgb};
use f_office_units::Length;
let size = Length::from_units(12 * Length::UNITS_PER_POINT);
let x = Length::from_units(72 * Length::UNITS_PER_POINT);
let run = GlyphRun {
font,
size,
color: Rgb { r: 0, g: 0, b: 0 },
text: "\u{3B1}".to_owned(),
glyphs: vec![Glyph {
id,
x,
y: x,
text_start: 0,
text_end: 2,
}],
outline: None,
filled: true,
effect: false,
turn: None,
};
let page = Page::new(
size,
size,
Orientation::Portrait,
vec![Item::Glyphs(run.clone())],
);
let list = choice.draw_symbol_stand_ins(DisplayList::new(vec![page]));
let [page] = list.pages() else {
panic!("one page");
};
let [Item::Glyphs(drawn)] = page.items() else {
panic!("one glyph run");
};
(run, drawn.clone())
}
fn glyph_places(
run: &f_office_paint::GlyphRun,
) -> Vec<(u32, f_office_units::Length, f_office_units::Length)> {
run.glyphs.iter().map(|g| (g.id, g.x, g.y)).collect()
}
fn middle_shift(
db: &FontDb,
noto: FontId,
(advance, em): (u16, u16),
drawn: u16,
run: &f_office_paint::GlyphRun,
) -> f_office_units::Length {
let noto_em = i64::from(db.metrics(noto).unwrap().units_per_em);
let (em, advance, drawn) = (i64::from(em), i64::from(advance), i64::from(drawn));
f_office_units::Length::from_units(f_office_units::div_round(
(advance * noto_em - drawn * em) * run.size.units(),
2 * em * noto_em,
))
}
#[test]
fn draws_the_runs_of_a_symbol_stand_in_face_with_its_drawing_face_in_the_middle_of_each_width() {
let (db, noto) = open_fonts();
for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0x61) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Symbol");
let (run, drawn) = drawn_run(&choice, font, 0x61);
let alpha = db.glyph_id(noto, '\u{3B1}').unwrap();
let noto_advance = db.advance(noto, alpha).unwrap();
let shift = middle_shift(&db, noto, (advance, em), noto_advance, &run);
assert_eq!((drawn.font, &drawn.text), (noto, &run.text));
let [(_, x, y)] = glyph_places(&run)[..] else {
panic!("one glyph");
};
assert_eq!(glyph_places(&drawn), [(alpha, x + shift, y)]);
}
}
#[test]
fn draws_the_missing_glyph_of_a_symbol_stand_in_face_with_the_drawing_faces_missing_glyph() {
let (db, noto) = open_fonts();
for (_, profile, em, advance, _) in with_symbol_widths(SymbolFont::Symbol, 0) {
let choice = FontChoice::of(&db, &profile);
let font = stand_in(&choice, "Symbol");
let (run, drawn) = drawn_run(&choice, font, 0);
let shift = middle_shift(&db, noto, (advance, em), db.advance(noto, 0).unwrap(), &run);
let [(_, x, y)] = glyph_places(&run)[..] else {
panic!("one glyph");
};
assert_eq!(glyph_places(&drawn), [(0, x + shift, y)]);
}
}
#[test]
fn lays_out_a_missing_symbol_font_with_its_stand_in_and_draws_it_with_its_drawing_face() {
use crate::testing::WordParts as _;
use f_office_paint::Item;
let (db, noto) = open_fonts();
let first = u32::try_from(db.len()).unwrap();
let body = r#"<w:p><w:r><w:sym w:font="Wingdings" w:char="F0FC"/><w:sym w:font="Wingdings" w:char="F0FC"/></w:r></w:p>"#;
let bytes = crate::testing::docx(body).plain_styles().zip().unwrap();
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
let check = SymbolFont::Wingdings.character('\u{F0FC}').unwrap();
let tick = db.glyph_id(noto, check).unwrap();
for (target, ..) in with_symbol_widths(SymbolFont::Wingdings, 0xFC) {
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let laid_out = crate::layout_lines(&package, (&db, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let runs: Vec<_> = (laid_out.list.pages().iter())
.flat_map(f_office_paint::Page::items)
.filter_map(|item| match item {
Item::Glyphs(run) => Some(run),
_ => None,
})
.collect();
assert!(runs.iter().all(|run| run.font.index() < first));
let ticks: Vec<u32> = (runs.iter())
.filter(|run| run.font == noto)
.flat_map(|run| run.glyphs.iter().map(|glyph| glyph.id))
.collect();
assert_eq!(ticks, [tick, tick]);
}
}
const OPEN_FONTS_OF_FAMILIES: [(&str, &str, &str); 9] = [
("Cambria", "Caladea CF", "Cambria"),
("Cambria Math", "Caladea Math CF", "CambriaMath"),
("Aptos", "Intos CF", "Aptos"),
("Aptos Display", "Intos Display CF", "AptosDisplay"),
("Arial Narrow", "Arimo Narrow CF", "ArialNarrow"),
("Courier New", "CurunÃr CF", "CourierNewPSMT"),
("Georgia", "Gelasio CF", "Georgia"),
("Segoe UI", "Sindar CF", "SegoeUI"),
("Comic Sans MS", "Comic Relief CF", "ComicSansMS"),
];
fn family_of(db: &FontDb, font: FontId) -> Option<String> {
(db.faces()).find_map(|(id, face)| (id == font).then(|| face.family.clone()))
}
fn styled_face(db: &FontDb, family: &str, (bold, italic): (bool, bool)) -> Option<FontId> {
(db.faces()).find_map(|(id, face)| {
(face.family == family && face.bold() == bold && face.italic == italic).then_some(id)
})
}
#[test]
fn draws_a_missing_family_with_the_open_font_that_carries_its_layout() {
let (db, _) = open_fonts();
let styles = [(false, false), (true, false), (false, true), (true, true)];
for target in crate::Target::all() {
let profile = Profile::of(target).unwrap();
let choice = FontChoice::of(&db, &profile);
for ((closed, open, _), (bold, italic)) in
(OPEN_FONTS_OF_FAMILIES.iter()).flat_map(|font| styles.map(|style| (font, style)))
{
let family = FamilyName::from_static(closed);
let chosen = (choice.face(&family, bold, italic))
.or_else(|| choice.substitute(&family, bold, italic))
.expect("an open font");
let asked = format!("{target:?} {closed} bold {bold} italic {italic}");
assert_eq!(
family_of(&db, chosen.font).as_deref(),
Some(*open),
"{asked}"
);
if let Some(face) = styled_face(&db, open, (bold, italic)) {
let synthetic = (chosen.synthetic_bold, chosen.synthetic_italic);
assert_eq!((chosen.font, synthetic), (face, (false, false)), "{asked}");
}
}
}
}
#[test]
fn draws_a_family_that_the_fonts_hold_with_its_own_file_and_not_with_its_open_font() {
let mut db = FontDb::new();
let own: Vec<FontId> = (OPEN_FONTS_OF_FAMILIES.iter())
.map(|(closed, _, postscript_name)| {
let mut names = regular_names(closed, "Version 0.01");
names[4].1 = (*postscript_name).to_owned();
db.add_font(with_name_table(CARLITO, &names)).unwrap()[0]
})
.collect();
f_office_fonts::open_fonts::add_missing(&mut db).expect("the open fonts read");
for target in crate::Target::all() {
let profile = Profile::of(target).unwrap();
let choice = FontChoice::of(&db, &profile);
for ((closed, ..), &font) in OPEN_FONTS_OF_FAMILIES.iter().zip(&own) {
let family = FamilyName::from_static(closed);
let chosen = choice.face(&family, false, false).map(|chosen| chosen.font);
assert_eq!(chosen, Some(font), "{target:?} {closed}");
}
}
}
#[test]
fn lays_out_an_equation_with_the_math_table_of_caladea_math_cf_where_cambria_math_is_missing() {
use crate::testing::WordParts as _;
use f_office_paint::Item;
use f_office_units::Length;
let (db, _) = open_fonts();
let query = |family| db.query(&FamilyName::from_static(family), false, false);
let caladea_math = query("Caladea Math CF").expect("the build holds Caladea Math CF");
assert!(db.math_bars(caladea_math).is_some());
assert_eq!(db.math_bars(query("Caladea CF").unwrap()), None);
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let body = format!(
r#"<w:p><m:oMath xmlns:m="{math}"><m:bar><m:barPr><m:pos m:val="top"/></m:barPr><m:e><m:r><m:t>x</m:t></m:r></m:e></m:bar></m:oMath></w:p>"#
);
let bytes = crate::testing::docx(&body).plain_styles().zip().unwrap();
let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
for target in crate::Target::all() {
let options = crate::Options {
configuration: crate::Configuration::of(target),
..crate::Options::default()
};
let laid_out = crate::layout_lines(&package, (&db, &crate::ArtPictures::new()), &options)
.unwrap()
.value;
let items: Vec<_> = (laid_out.list.pages().iter())
.flat_map(f_office_paint::Page::items)
.collect();
let fonts: Vec<FontId> = (items.iter())
.filter_map(|item| match item {
Item::Glyphs(run) => Some(run.font),
_ => None,
})
.collect();
assert!(!fonts.is_empty(), "{target:?}");
assert!(fonts.iter().all(|&font| font == caladea_math), "{target:?}");
let rects: Vec<_> = (items.iter())
.filter_map(|item| match item {
Item::Rect(rect) => Some((rect.width, rect.height)),
_ => None,
})
.collect();
let [(width, height)] = rects[..] else {
panic!("{target:?} {rects:?}");
};
assert!(width > Length::ZERO && height > Length::ZERO, "{target:?}");
}
}
#[test]
fn reads_skewed_fraction_gaps_from_caladea_math_cf() {
let (db, _) = open_fonts();
let query = |family| db.query(&FamilyName::from_static(family), false, false);
let caladea_math = query("Caladea Math CF").expect("the build holds Caladea Math CF");
let gaps = db
.math_skewed_fraction(caladea_math)
.expect("Caladea Math CF has MATH skewed fraction gaps");
assert!(gaps.horizontal_gap > 0 && gaps.vertical_gap > 0, "{gaps:?}");
assert_eq!(db.math_skewed_fraction(query("Caladea CF").unwrap()), None);
}