use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;
use super::is_font_file;
use crate::tests::{CARLITO, collection, collection_after, with_style};
use crate::tests::{with_table_at_offset_zero, without_table};
use crate::{FaceInfo, FamilyName, FileNotRead, FontDb, FontError, FontId, FontMetrics};
use crate::{NotAddedCause, NotReadCause, OutlineError};
struct Folder(PathBuf);
impl Folder {
fn new(test: &str, files: &[(&str, &[u8])]) -> Self {
let name = format!("f-office-fonts-{test}-{}", std::process::id());
let path = std::env::temp_dir().join(name);
fs::create_dir_all(&path).unwrap();
for (name, data) in files {
fs::write(path.join(name), data).unwrap();
}
Self(path)
}
fn file(&self, name: &str) -> PathBuf {
self.0.join(name)
}
fn files(&self) -> Vec<PathBuf> {
let mut files: Vec<PathBuf> = fs::read_dir(&self.0)
.unwrap()
.map(|entry| entry.unwrap().path())
.collect();
files.sort();
files
}
fn database(&self) -> FontDb {
let mut db = FontDb::new();
db.add_files(&self.files()).unwrap();
db
}
}
impl Drop for Folder {
fn drop(&mut self) {
if let Ok(entries) = fs::read_dir(&self.0) {
for entry in entries.flatten() {
let _ = fs::remove_file(entry.path());
}
}
let _ = fs::remove_dir(&self.0);
}
}
fn descriptions(db: &FontDb) -> Vec<(FaceInfo, FontMetrics, String)> {
db.indexed()
.map(|(_, face)| {
let group = face.style_group.as_str().to_owned();
(face.info.clone(), face.metrics, group)
})
.collect()
}
#[test]
fn knows_font_extensions_in_any_case() {
assert!(is_font_file(std::path::Path::new("a/Font.ttf")));
assert!(is_font_file(std::path::Path::new("Font.OTF")));
assert!(is_font_file(std::path::Path::new("Fonts.ttc")));
assert!(is_font_file(std::path::Path::new("Fonts.otc")));
assert!(!is_font_file(std::path::Path::new("OFL.txt")));
assert!(!is_font_file(std::path::Path::new("ttf")));
}
#[test]
fn names_the_first_file_that_it_does_not_add_and_reads_none_after_it() {
let folder = Folder::new(
"not-added",
&[
("broken.ttf", b"not a font"),
("notes.txt", b"not a font"),
("font.ttf", CARLITO),
],
);
let (font, notes, broken) = (
folder.file("font.ttf"),
folder.file("notes.txt"),
folder.file("broken.ttf"),
);
for (bad, cause) in [
(¬es, NotAddedCause::NotAFontFile),
(&broken, NotAddedCause::Font(FontError::NotAFont)),
] {
let mut db = FontDb::new();
let not_added = db
.add_files(&[font.clone(), bad.clone(), font.clone()])
.unwrap_err();
assert_eq!(¬_added.path, bad);
assert_eq!(format!("{:?}", not_added.cause), format!("{cause:?}"));
assert!(not_added.to_string().contains(&bad.display().to_string()));
let source = std::error::Error::source(¬_added).map(ToString::to_string);
let expected = matches!(not_added.cause, NotAddedCause::Font(_))
.then(|| FontError::NotAFont.to_string());
assert_eq!(source, expected);
assert_eq!(db.len(), 1);
}
}
#[test]
fn two_faces_of_equal_style_tie_in_the_order_of_the_files_given() {
let other = with_style(400, false);
assert_ne!(other.as_slice(), CARLITO);
let folder = Folder::new("ties", &[("a.ttf", &other), ("b.ttf", CARLITO)]);
let first = |files: &[PathBuf]| {
let mut db = FontDb::new();
db.add_files(files).unwrap();
let id = db.query(&FamilyName::new("Carlito"), false, false).unwrap();
db.data(id).map(|(data, _)| data.to_vec())
};
let (a, b) = (folder.file("a.ttf"), folder.file("b.ttf"));
assert_eq!(first(&[b.clone(), a.clone()]).as_deref(), Some(CARLITO));
assert_eq!(first(&[a, b]), Some(other));
}
#[test]
fn describes_each_face_as_a_load_of_the_files_bytes_does() {
let first_read = usize::try_from(super::FIRST_READ).unwrap();
let across = u32::try_from(first_read - 100).unwrap();
let files = [
("a.ttf", CARLITO.to_vec()),
("b.ttf", with_style(700, true)),
("c.ttf", without_table(*b"post")),
("d.ttf", without_table(*b"OS/2")),
("e.ttc", collection_after(2, 5000)),
("f.ttc", collection_after(2, across)),
("g.ttf", without_table(*b"hhea")),
("h.otf", b"not a font".to_vec()),
];
let named: Vec<(&str, &[u8])> = files.iter().map(|(n, data)| (*n, &data[..])).collect();
let folder = Folder::new("descriptions", &named);
let mut from_bytes = FontDb::new();
let mut from_folder = FontDb::new();
for (name, data) in &files {
let of_bytes = from_bytes.add_font(data.clone());
let of_file = from_folder
.add_files(&[folder.file(name)])
.map_err(|not_added| match not_added.cause {
NotAddedCause::Font(error) => error,
cause => panic!("{name}: {cause:?}"),
});
assert_eq!(of_file, of_bytes, "{name}");
}
assert_eq!(from_bytes.len(), 8);
assert_eq!(descriptions(&from_folder), descriptions(&from_bytes));
}
#[test]
fn a_table_record_at_offset_zero_reads_as_the_font_of_the_whole_file_reads_it() {
for tag in [*b"OS/2", *b"post"] {
let data = with_table_at_offset_zero(tag);
let folder = Folder::new("offset-zero", &[("a.ttf", &data)]);
let mut from_bytes = FontDb::new();
from_bytes.add_font(data.clone()).unwrap();
let mut without = FontDb::new();
without.add_font(without_table(tag)).unwrap();
assert_ne!(descriptions(&from_bytes), descriptions(&without));
assert_eq!(descriptions(&folder.database()), descriptions(&from_bytes));
}
}
#[test]
fn reads_no_file_whose_faces_are_not_loaded() {
let bold = with_style(700, false);
let folder = Folder::new("unread", &[("a.ttf", CARLITO), ("b.ttf", &bold)]);
let db = folder.database();
fs::remove_file(folder.file("b.ttf")).unwrap();
let regular = db.query(&FamilyName::new("Carlito"), false, false).unwrap();
assert_eq!(regular, FontId::from_index(0));
assert_eq!(db.load(regular), Ok(()));
assert!(db.glyph_id(regular, 'a').is_some());
assert_eq!(
db.query(&FamilyName::new("Carlito"), true, false),
Some(FontId::from_index(1))
);
let missing = NotReadCause::Unreadable(ErrorKind::NotFound);
assert_eq!(
db.load(FontId::from_index(1))
.map_err(|not_read| not_read.cause),
Err(missing)
);
}
#[test]
fn the_faces_of_a_collection_share_one_load() {
let file = collection(2);
let folder = Folder::new("collection", &[("a.ttc", &file)]);
let db = folder.database();
let (first, second) = (FontId::from_index(0), FontId::from_index(1));
assert_eq!(db.load(first), Ok(()));
fs::remove_file(folder.file("a.ttc")).unwrap();
assert_eq!(db.load(second), Ok(()));
let (first_data, first_index) = db.data(first).unwrap();
let (second_data, second_index) = db.data(second).unwrap();
assert!(std::ptr::eq(first_data.as_ptr(), second_data.as_ptr()));
assert_eq!(
(&second_data[..], first_index, second_index),
(&file[..], 0, 1)
);
}
fn assert_described_only(db: &FontDb, id: FontId) {
assert_eq!(db.info(id).unwrap().family, "Carlito");
assert_eq!(db.glyph_id(id, 'a'), None);
assert_eq!(db.advance(id, 3), None);
assert_eq!(db.outline(id, 3).err(), Some(OutlineError::UnknownFont));
assert_eq!(db.data(id), None);
}
#[test]
fn a_file_that_changed_after_its_folder_was_read_does_not_load_and_is_not_read_again() {
let folder = Folder::new("changed", &[("a.ttf", CARLITO)]);
let db = folder.database();
let mut longer = CARLITO.to_vec();
longer.push(0);
fs::write(folder.file("a.ttf"), &longer).unwrap();
let id = FontId::from_index(0);
let not_read = FileNotRead {
file: "a.ttf".to_owned(),
cause: NotReadCause::Changed,
};
assert_eq!(db.load(id), Err(not_read.clone()));
assert_eq!(
not_read.to_string(),
"the font file a.ttf did not load: the file changed after its folder was read"
);
assert_described_only(&db, id);
fs::write(folder.file("a.ttf"), CARLITO).unwrap();
assert_eq!(db.load(id), Err(not_read));
}