Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #536: Fonts: format, classification and PANOSE of each face, read without keeping fonts loaded

aionggd83de14b7f8c
diff --cc crates/fonts/src/fontdb.rs
index 18043d740,1ccc8d076..5a30675d3
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@@ -123,13 -118,11 +123,15 @@@ pub struct FontFace
/// Basic Multilingual Plane coverage bitset, built on first use.
bmp: std::sync::OnceLock<Box<[u64]>>,
/// The ideographic em box, read on first use.
- em: std::sync::OnceLock<(f64, f64)>,
+ em: std::sync::OnceLock<((f64, f64), bool)>,
+ /// The ideographic character face box, read on first use.
+ icf: std::sync::OnceLock<(f64, f64)>,
/// The font menu group and native family name, read on first use.
group: std::sync::OnceLock<(FontGroup, Option<String>)>,
+ family_aliases: Vec<String>,
+ style_aliases: Vec<String>,
+ /// Format, class and PANOSE numbers (the font menus), read on first use.
+ kind: std::sync::OnceLock<crate::kind::FaceKind>,
}
/// A cheap `Copy` handle to a face. Faces are never unloaded, so the handle lives for the rest of
@@@ -803,10 -736,8 +831,11 @@@ fn make_face(bytes: FontBytes, source:
index,
bmp: std::sync::OnceLock::new(),
em: std::sync::OnceLock::new(),
+ family_aliases,
+ style_aliases,
+ icf: std::sync::OnceLock::new(),
group: std::sync::OnceLock::new(),
+ kind: std::sync::OnceLock::new(),
})
}
@@@ -1626,10 -1306,58 +1655,47 @@@ impl ScopedFonts<'_>
None
}
+ /// `family`'s kind (format, class, PANOSE) and when its file was added, read from its Regular
+ /// face (else its first), for the font menus' filters, which look at every family. A face
+ /// already loaded is asked; an installed family that isn't loaded is read from its file, which
+ /// is then let go rather than kept loaded. None for an unknown family or an unreadable file.
+ pub fn family_kind(&self, family: &str) -> Option<(crate::kind::FaceKind, Option<std::time::SystemTime>)> {
+ let styles = self.styles(family);
+ let style = styles.iter().find(|s| *s == "Regular").or(styles.first())?.clone();
+ if self.own().iter().chain(self.db.read_faces().iter()).any(|f| f.family.eq_ignore_ascii_case(family)) {
+ let f = self.find(family, &style)?;
+ return Some((f.kind(), f.added()));
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let path = {
+ let cat = self.db.read_catalog();
+ let of_family = |c: &&CatalogEntry| c.family.eq_ignore_ascii_case(family);
+ let entry = cat.iter().filter(of_family).find(|c| norm(&c.style) == norm(&style)).or_else(|| cat.iter().find(of_family));
+ entry.map(|c| c.path.clone())?
+ };
+ if std::fs::metadata(&path).ok()?.len() > MAX_DOCUMENT_FONT_BYTES {
+ return None;
+ }
+ let data = Arc::new(std::fs::read(&path).ok()?);
+ let found = enumerate_faces(&data);
+ let pick = found
+ .iter()
+ .find(|(_, f, st, _)| f.eq_ignore_ascii_case(family) && norm(st) == norm(&style))
+ .or_else(|| found.iter().find(|(_, f, _, _)| f.eq_ignore_ascii_case(family)))?
+ .clone();
+ let (index, fam, st, coords) = pick;
+ let face = make_face(FontBytes::Owned(data.clone()), FontSource::Installed(path), index, fam, st, coords)?;
+ Some((face.kind(), face.added()))
+ }
+ #[cfg(target_arch = "wasm32")]
+ None
+ }
+
/// Is `family` available (the document's, loaded, or installed on the system), as named or
- /// without a format suffix (see [`ScopedFonts::face`])?
+ /// without an `$ID/` prefix or a format suffix (see [`ScopedFonts::face`])?
pub fn has_family(&self, family: &str) -> bool {
- self.has_exact_family(family) || without_format_suffix(family).is_some_and(|base| self.has_exact_family(base))
- }
-
- fn has_exact_family(&self, family: &str) -> bool {
- if self.own().iter().any(|f| f.family.eq_ignore_ascii_case(family)) || self.db.is_loaded(family) {
- return true;
- }
- #[cfg(not(target_arch = "wasm32"))]
- if self.db.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {
- return true;
- }
- false
+ self.canonical_family(family).is_some() || plain_family(family).is_some_and(|base| self.canonical_family(base).is_some())
}
/// A variable font's axes: (tag, name, min, default, max), empty for static fonts.
diff --cc crates/fonts/src/lib.rs
index 71f366910,dd4583701..18fd8a56a
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@@ -9,8 -9,7 +9,9 @@@
mod fontdb;
mod group;
+#[cfg(target_os = "macos")]
+mod mac_fonts;
+ mod kind;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
mod vertical;
diff --cc crates/fonts/src/tests_sysfonts.rs
index 3f75eba9e,ca82ad4d7..8a872f4a6
--- a/crates/fonts/src/tests_sysfonts.rs
+++ b/crates/fonts/src/tests_sysfonts.rs
@@@ -184,38 -126,23 +184,55 @@@ fn a_link_back_to_a_parent_folder_ends_
assert_eq!(db.load_system_fonts(), 2);
}
+/// The folder a font service keeps its fonts in, outside the font folders, and the font folder
+/// of [`fonts_the_platform_lists_outside_the_font_folders_are_cataloged_once`].
+fn service_dirs() -> (PathBuf, PathBuf) {
+ let tmp = std::env::temp_dir();
+ let id = std::process::id();
+ (tmp.join(format!("dc-sysfonts-{id}-service")), tmp.join(format!("dc-sysfonts-{id}-platform")))
+}
+
+/// The platform's list: a font service's file without an extension (twice, as for each face of a
+/// collection), a font folder's file by another path, a file gone since and a folder.
+fn service_files() -> Vec<PathBuf> {
+ let (service, folder) = service_dirs();
+ vec![service.join(".r/.12345"), folder.join("Sub/../Sysfont-Regular.ttf"), service.join(".r/.12345"), service.join("gone.otf"), service.clone()]
+}
+
+#[test]
+fn fonts_the_platform_lists_outside_the_font_folders_are_cataloged_once() {
+ let (service, folder) = service_dirs();
+ let dir = font_dir("platform");
+ assert_eq!(dir, folder);
+ let _ = std::fs::remove_dir_all(&service);
+ std::fs::create_dir_all(service.join(".r")).unwrap();
+ std::fs::write(service.join(".r/.12345"), renamed("SourceSans3-It.ttf")).unwrap();
+ let db = FontDb { font_files: service_files, ..FontDb::with_font_dirs(vec![dir]) };
+ assert_eq!(db.styles(FAMILY), ["Regular", "Bold", "Italic"]);
+ assert_eq!(db.load_system_fonts(), 3, "the font folder's Regular listed again isn't cataloged twice");
+ let italic = db.face(FAMILY, "Italic");
+ assert_eq!(italic.style, "Italic");
+ assert_eq!(italic.source.path(), Some(service.join(".r/.12345").as_path()));
+ let _ = std::fs::remove_dir_all(&service);
+}
+
+ #[test]
+ fn a_familys_kind_is_read_without_keeping_it_loaded() {
+ let dir = font_dir("kind");
+ let db = FontDb::with_font_dirs(vec![dir]);
+ db.load_system_fonts();
+ let fonts = db.scoped(0);
+ let (kind, added) = fonts.family_kind(FAMILY).expect("an installed family");
+ assert_eq!(kind.class, crate::kind::FontClass::SansSerif);
+ assert!(added.is_some(), "the file's date");
+ assert!(!db.is_loaded(FAMILY), "the file was read and let go");
+ // A loaded family is asked directly, with the same answer.
+ let _ = fonts.face(FAMILY, "Regular");
+ assert!(db.is_loaded(FAMILY));
+ assert_eq!(fonts.family_kind(FAMILY).map(|(k, _)| k.class), Some(crate::kind::FontClass::SansSerif));
+ assert!(fonts.family_kind("No Such Family").is_none());
+ }
+
#[test]
fn the_scan_reads_names_without_loading_the_font() {
let dir = font_dir("names");