Retype: grown font files and drawn glyphs count toward the search limits

- A font file that grew past the limits after the installed fonts were
  listed counts as skipped, and the bytes read from it count toward the
  2 GiB a search reads. A suitcase font's resource fork is read the same
  way, no further than one byte past the limit.
- The 500,000-glyph budget counts the glyphs an index draws (each
  matched glyph once), not the face's mapped characters.
- The Retype panel's background search hands the command the loaded
  fonts that match as well as the installed fonts it found, so a loaded
  font that matched stays listed after the fonts found are loaded.
- A shape that no glyph's key fits (more than 48 contours) no longer
  keeps type.retype reading installed files after the other shapes
  have matched.
This commit is contained in:
dotCooCoo committed 2026-11-20 03:40:22 -08:00
1 parent 5200e3c54b
commit ee464025ad
9 files changed
+206 -43

No files matched your search

+5
View File
@@ -50,6 +50,11 @@ pub(super) struct Ranked {
}
impl Ranked {
/// The font.
pub(super) fn face(&self) -> &Arc<FontFace> {
&self.face
}
fn mean(&self) -> f64 {
self.residual / self.matched.max(1) as f64
}
+21 -10
View File
@@ -114,7 +114,8 @@ type File = (std::path::PathBuf, u64, Vec<(String, String)>);
/// [`search`] within `limits`, keeping in its faces only those `listed` accepts.
fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
let mut out = Installed::default();
let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s)).collect();
// A shape without a glyph's key matches no face: the search does not wait for it.
let shapes: Vec<&BezPath> = shapes.iter().copied().filter(|s| !is_plain(s) && shape_key(s).is_some()).collect();
let keys: BTreeSet<u64> = shapes.iter().filter_map(|s| shape_key(s)).collect();
if keys.is_empty() {
return Ok(out);
@@ -144,15 +145,15 @@ fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits,
continue;
}
// A file that grew since the scan is read only within what is left.
let faces = db.read_unloaded_file(path, limits.file.min(bytes_left));
// The bytes read: the file's fonts (a collection's faces share one), or its length then.
let mut datas: Vec<(usize, usize)> = faces.iter().map(|f| (f.file_data().as_ptr() as usize, f.file_data().len())).collect();
datas.sort_unstable();
datas.dedup();
let read = datas.iter().map(|d| d.1 as u64).sum::<u64>().max(*len);
bytes_left = bytes_left.saturating_sub(read);
let file = db.read_unloaded_file(path, limits.file.min(bytes_left));
// The bytes read, those of a file that grew past the limits too.
bytes_left = bytes_left.saturating_sub(file.bytes);
if file.too_long {
out.skipped += styles.len();
continue;
}
let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style));
let faces: Vec<Arc<FontFace>> = faces.into_iter().filter(|f| wanted(f)).collect();
let faces: Vec<Arc<FontFace>> = file.faces.into_iter().filter(|f| wanted(f)).collect();
for (j, face) in faces.iter().enumerate() {
if out.faces.len() >= limits.faces {
// The faces not compared past the cap: the rest of this file's and the later files'.
@@ -391,7 +392,17 @@ impl RetypeSearch {
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
let shapes: Vec<&BezPath> = self.shapes.iter().collect();
let installed = if self.command == "type.retypeFonts" {
super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?.1
let (ranked, mut found) = super::fonts::rank_fonts(db, self.faces.clone(), &shapes, true, None)?;
// The loaded faces that match are handed in too, ahead of the installed ones found:
// loading those can move a loaded face past the 96 the command lists.
let mut faces: Vec<Arc<FontFace>> = ranked.iter().map(|r| r.face().clone()).collect();
for f in std::mem::take(&mut found.faces) {
if !faces.iter().any(|k| k.id() == f.id()) {
faces.push(f);
}
}
found.faces = faces;
found
} else {
let keys: BTreeSet<u64> = shapes.iter().filter_map(|sh| shape_key(sh)).collect();
let index = RetypeIndex::build(db, self.faces.iter().cloned(), &keys);
@@ -98,7 +98,7 @@ fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() {
let dir = vectorcraft_testkit::temp_dir("retype-installed-twin");
let path = dir.join("RetypeTwin-Regular.ttf");
std::fs::write(&path, named_copy(false, names).unwrap()).unwrap();
let read = db.read_unloaded_file(&path, u64::MAX).into_iter().next().unwrap();
let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap();
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let keys = keys(&shapes);
@@ -140,6 +140,22 @@ fn plain_shapes_alone_read_no_installed_font() {
assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1);
}
#[test]
fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() {
let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]);
let mut shapes = glyphs(&db, "k");
// More contours than any glyph's key counts: no face can match it.
let mut dots = BezPath::new();
for i in 0..49 {
dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1));
}
assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots));
shapes.push(dots);
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read");
}
#[test]
fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() {
let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]);
@@ -180,6 +196,63 @@ fn faces_past_the_limits_are_skipped_and_counted() {
assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1));
}
#[test]
fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() {
let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// The order the search reads them in: smallest first.
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
let (first, second) = (len(&files[0]), len(&files[1]));
let grown = files[0].clone();
// The first file grows past the limit for one file as its reading starts, after the listing.
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
if done == 0 {
let mut data = std::fs::read(&grown).unwrap();
data.resize(data.len() + second as usize + 1, 0);
std::fs::write(&grown, data).unwrap();
}
});
// Bytes for both files as listed: the grown file's reading takes one more than the limit for
// one file, which leaves too little for the second.
let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX };
let token = vectorcraft_doc::cancel::CancelToken::new();
let all = |_: &vectorcraft_text::FontFace| true;
let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0));
}
#[test]
fn the_glyph_budget_counts_the_glyphs_drawn() {
let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
let mapped = face.mapped_chars().len();
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
assert!(drawn < mapped, "{drawn} of {mapped}");
// A budget below the face's characters and at the glyphs drawn: the face is compared.
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
let found = search_within(&db, &refs, true, open, &|_| true).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1));
}
#[test]
fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() {
let (db, _) = installed("list-run", &["Retype Copy List"]);
db.add_font(
vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(),
);
let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect();
let search = super::RetypeSearch { command: "type.retypeFonts", doc: 1, shapes: glyphs(&db, "Rx"), faces: loaded.clone() };
let found = search.run_in(&db).unwrap();
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
// The loaded face first, then the installed one, each once.
assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]);
assert_eq!((found.installed.read, found.installed.skipped), (1, 0));
}
#[test]
fn faces_a_list_turns_down_are_loaded_and_take_no_place() {
let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]);
@@ -244,7 +317,11 @@ fn a_run_away_from_the_command_loads_the_faces_it_finds() {
assert!(run.current(&s));
let found = run.run_in(&db).unwrap();
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
assert_eq!(found.installed.faces.iter().map(|f| f.family.as_str()).collect::<Vec<_>>(), ["Retype Copy X"]);
// The loaded faces that match are handed in with it, ahead of it.
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}");
assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}");
assert!(families.contains(&"Source Sans 3"), "{families:?}");
assert!(!unloaded(&db, "Retype Copy X"));
// A change of selection or content: it no longer applies.
s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap();
+1 -1
View File
@@ -60,7 +60,7 @@ pub(crate) use face::PathAlignHeights;
pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat};
pub(crate) use glyph_pen::FlipPen;
pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind};
pub use installed::InstalledFace;
pub use installed::{InstalledFace, UnloadedFile};
#[cfg(not(target_arch = "wasm32"))]
use names::SysFallback;
#[cfg(test)]
+44 -20
View File
@@ -54,39 +54,55 @@ impl FontDb {
}
/// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one
/// search and not added to the database: none when the file, or the fork, is longer than
/// `max_len` bytes or holds no font. Each face read has an id of its own, which no loaded face
/// has, and its path is `path`. Empty on wasm.
pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> Vec<Arc<FontFace>> {
/// search and not added to the database, with the bytes read: no faces when the file, or the
/// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face
/// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm.
pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile {
#[cfg(not(target_arch = "wasm32"))]
{
let files = if crate::suitcase::is_suitcase(path) {
if crate::suitcase::fork_len(path) > max_len {
return vec![];
let (files, bytes) = if crate::suitcase::is_suitcase(path) {
match crate::suitcase::read_fonts_within(path, max_len) {
(_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() },
(fonts, n, false) => (fonts, n),
}
crate::suitcase::read_fonts(path)
} else {
read_within(path, max_len).into_iter().collect()
match read_within(path, max_len) {
Some((data, n)) if n <= max_len => (vec![data], n),
Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() },
None => return UnloadedFile::default(),
}
};
let mut out = vec![];
let mut faces = vec![];
for data in files {
let data = Arc::new(data);
for (i, spec) in enumerate_faces(&data) {
if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) {
out.push(Arc::new(f));
faces.push(Arc::new(f));
}
}
}
out
UnloadedFile { faces, bytes, too_long: false }
}
#[cfg(target_arch = "wasm32")]
{
let _ = (path, max_len);
vec![]
UnloadedFile::default()
}
}
}
/// What [`FontDb::read_unloaded_file`] read from one font file.
#[derive(Default)]
pub struct UnloadedFile {
/// The faces read, not loaded.
pub faces: Vec<Arc<FontFace>>,
/// The bytes read from the file, those of a file longer than the limit included (at most one
/// past it).
pub bytes: u64,
/// The file, or the fork, is longer than the limit: no face was read.
pub too_long: bool,
}
impl FontDb {
/// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or
/// the family's other files: it joins the loaded faces, unless a face of its family, style and
@@ -116,13 +132,15 @@ fn file_len(path: &Path) -> u64 {
}
}
/// The file at `path`, when it is at most `max_len` bytes long (read no further than one byte past).
/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than
/// `max_len` when the file is longer. None when it cannot be read.
#[cfg(not(target_arch = "wasm32"))]
fn read_within(path: &Path, max_len: u64) -> Option<Vec<u8>> {
fn read_within(path: &Path, max_len: u64) -> Option<(Vec<u8>, u64)> {
use std::io::Read;
let mut data = Vec::new();
std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?;
(data.len() as u64 <= max_len).then_some(data)
let n = data.len() as u64;
Some((data, n))
}
#[cfg(test)]
@@ -150,16 +168,22 @@ mod tests {
let regular = inter.iter().find(|f| f.style == "Regular").unwrap();
assert_eq!(regular.len, std::fs::metadata(&regular.path).unwrap().len());
let before = db.loaded_faces().len();
let read = db.read_unloaded_file(&regular.path, regular.len);
let file = db.read_unloaded_file(&regular.path, regular.len);
assert_eq!((file.bytes, file.too_long), (regular.len, false));
let read = file.faces;
assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read");
assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path())));
// Read for the search only: the database does not hold it, and no loaded face has its id.
assert_eq!(db.loaded_faces().len(), before);
assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none()));
assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded");
// A file longer than the limit is not read.
assert!(db.read_unloaded_file(&regular.path, regular.len - 1).is_empty());
assert!(db.read_unloaded_file(&regular.path.with_extension("missing"), u64::MAX).is_empty());
// A file longer than the limit is not read past one byte over it, and says so.
let long = db.read_unloaded_file(&regular.path, regular.len - 1);
assert!(long.faces.is_empty());
assert_eq!((long.bytes, long.too_long), (regular.len, true));
let missing = db.read_unloaded_file(&regular.path.with_extension("missing"), u64::MAX);
assert!(missing.faces.is_empty());
assert_eq!((missing.bytes, missing.too_long), (0, false));
// Once loaded, the family is no longer listed.
assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter"));
assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular"));
+3 -3
View File
@@ -44,9 +44,9 @@ pub use features::{
pub use fontdb::{
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate,
GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles,
RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file,
is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight,
system_font_dirs, user_font_dirs,
RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, app_font_dir,
is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined,
style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
pub use layout::{envelope_ink, layout_inputs, register_envelope_ink};
+8 -6
View File
@@ -355,10 +355,10 @@ fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> {
gids
}
/// How many glyphs of `face` an index draws to read their keys: at most [`MAX_GLYPHS_PER_FACE`].
/// Reads the face's cmap only.
/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once,
/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only.
pub fn encoded_glyphs(face: &FontFace) -> usize {
face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)
matched_glyphs(face).len()
}
/// [`FaceKeys`] of `face`, each matched glyph drawn once, past the outline cache.
@@ -1026,17 +1026,19 @@ mod tests {
}
/// A face read from an installed file and not loaded is indexed as a loaded one is, and the
/// count of glyphs its index draws comes from its cmap.
/// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_unloaded_face_is_indexed_as_a_loaded_one() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts");
let db = FontDb::with_font_dirs(vec![]);
let loaded = db.face("Source Sans 3", "Regular").unwrap();
let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX);
let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces;
let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap();
assert_ne!(face.id(), loaded.id());
assert_eq!(encoded_glyphs(&face), face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE));
assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len());
// Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters.
assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE));
let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g'));
let keys: BTreeSet<u64> = std::iter::once(shape_key(&shape).unwrap()).collect();
let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys);
+25 -1
View File
@@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec<Vec<u8>> {
sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect()
}
/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest
/// fork read), with the bytes read: no fonts, and true, when the fork is longer.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec<Vec<u8>>, u64, bool) {
let max_len = max_len.min(MAX_FORK);
let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) };
let n = fork.len() as u64;
if n > max_len {
return (vec![], n, true);
}
(sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false)
}
/// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its
/// resource fork.
pub(crate) fn is_suitcase(path: &Path) -> bool {
@@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 {
#[cfg(target_os = "macos")]
fn read_fork(path: &Path) -> Option<Vec<u8>> {
read_fork_within(path, MAX_FORK)
}
/// The first `max` bytes of the resource fork of the file at `path`.
#[cfg(target_os = "macos")]
fn read_fork_within(path: &Path, max: u64) -> Option<Vec<u8>> {
use std::io::Read;
let mut fork = Vec::new();
std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?;
std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?;
Some(fork)
}
@@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option<Vec<u8>> {
None
}
#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))]
fn read_fork_within(_: &Path, _: u64) -> Option<Vec<u8>> {
None
}
/// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as
/// a font utility writes them.
#[cfg(test)]
+20
View File
@@ -800,6 +800,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A suitcase font read for one search (Retype) is read no further than one byte past the limit,
/// and the bytes read are counted.
#[cfg(target_os = "macos")]
#[test]
fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let suitcase = dir.join("Sysfont Sans3");
std::fs::write(&suitcase, b"").unwrap();
let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]);
let len = fork.len() as u64;
std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap();
let db = FontDb::with_font_dirs(vec![]);
let file = db.read_unloaded_file(&suitcase, len);
assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false));
let long = db.read_unloaded_file(&suitcase, len - 1);
assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn font_files_are_told_by_their_extension() {
for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] {