Skip to content

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

Merge #548: SVG text: find fonts by PostScript name (#430)

aionggad33ff95d4fe
diff --cc crates/fonts/src/fontdb.rs
index 5a30675d3,1a400e9fe..8edb9fb49
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@@ -123,15 -118,11 +123,17 @@@ 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>,
+ /// The PostScript name, read on first use.
+ postscript: std::sync::OnceLock<Option<String>>,
}
/// A cheap `Copy` handle to a face. Faces are never unloaded, so the handle lives for the rest of
@@@ -360,7 -313,7 +369,8 @@@ struct CatalogEntry
/// The font menu group and native family name, read by the scan.
group: FontGroup,
native: Option<String>,
+ aliases: Vec<String>,
+ postscript: Option<String>,
}
/// What the scan reads of one face in a font file: its names and font menu group.
@@@ -371,7 -324,7 +381,8 @@@ struct ScannedFace
style: String,
group: FontGroup,
native: Option<String>,
+ aliases: Vec<String>,
+ postscript: Option<String>,
}
/// Process-wide font database: the fonts every document shares (bundled, installed, added), and
@@@ -648,7 -578,8 +659,15 @@@ fn file_face_names(path: &std::path::Pa
crate::group::classify(&skrifa::FontRef::new(&font).ok()?, &family)
}
};
- Some(ScannedFace { family, style, group, native, aliases: aliases(&f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME]) })
+ let postscript = name(&f, &[StringId::POSTSCRIPT_NAME]);
- Some(ScannedFace { family, style, group, native, postscript })
++ Some(ScannedFace {
++ family,
++ style,
++ group,
++ native,
++ aliases: aliases(&f, &[StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME]),
++ postscript,
++ })
})
.collect()
}
@@@ -831,11 -720,8 +850,12 @@@ 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(),
+ postscript: std::sync::OnceLock::new(),
})
}
@@@ -1147,18 -944,11 +1167,27 @@@ impl FontDb
path: p.clone(),
group: f.group,
native: f.native,
+ aliases: f.aliases,
+ postscript: f.postscript,
});
}
}
}
+ // Font services name their files as they like (no extension, say): the face names read
+ // decide what is a font.
+ for p in unscanned_font_files((self.font_files)(), &mut scanned) {
+ for f in file_face_names(&p) {
- found.push(CatalogEntry { family: f.family, style: f.style, path: p.clone(), group: f.group, native: f.native, aliases: f.aliases });
++ found.push(CatalogEntry {
++ family: f.family,
++ style: f.style,
++ path: p.clone(),
++ group: f.group,
++ native: f.native,
++ aliases: f.aliases,
++ postscript: f.postscript,
++ });
+ }
+ }
let n = found.len();
log::debug!("cataloged {n} system font faces");
*self.catalog.write().unwrap_or_else(|e| e.into_inner()) = found;
@@@ -1655,47 -1302,36 +1689,62 @@@ impl ScopedFonts<'_>
None
}
- /// Is `family` available (the document's, loaded, or installed on the system), as named or
- /// without 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))
+ /// `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
}
+ /// The family and style of the face whose PostScript name is `name`, ignoring case (the
+ /// document's, loaded, or installed on the system, not loading it). SVGs exported from
+ /// Illustrator name fonts this way (`font-family="'MyriadPro-Regular'"`).
+ pub fn postscript_face(&self, name: &str) -> Option<(String, String)> {
+ let named = |ps: Option<&str>| ps.is_some_and(|ps| ps.eq_ignore_ascii_case(name));
+ if let Some(f) = self.own().iter().chain(self.db.read_faces().iter()).find(|f| named(f.postscript_name())) {
+ return Some((f.family.clone(), f.style.clone()));
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(c) = self.db.read_catalog().iter().find(|c| named(c.postscript.as_deref())) {
+ return Some((c.family.clone(), c.style.clone()));
+ }
+ None
+ }
+
- 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
+ /// Is `family` available (the document's, loaded, or installed on the system), as named or
+ /// without an `$ID/` prefix or a format suffix (see [`ScopedFonts::face`])?
+ pub fn has_family(&self, family: &str) -> bool {
+ 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/tests_sysfonts.rs
index 8a872f4a6,f10088705..cf75772ba
--- a/crates/fonts/src/tests_sysfonts.rs
+++ b/crates/fonts/src/tests_sysfonts.rs
@@@ -272,81 -165,22 +272,101 @@@ fn font_menus_group_installed_and_loade
let _ = std::fs::remove_dir_all(&dir);
}
+#[test]
+fn rescanning_retries_missing_glyphs_and_absent_fallback_families() {
+ use crate::testing::font_with;
+ let dir = font_dir("rescan-fallback-ttf");
+ // Only synthetic TTF files in this folder are scanned. Keep the loaded Latin fallback
+ // alone so optional craft-fonts cannot provide the characters used by this fixture.
+ let db = FontDb::with_font_dirs(vec![dir.clone()]);
+ db.faces.write().unwrap().retain(|f| f.family == FALLBACK_FAMILY);
+ let c = '\u{1e900}';
+ assert!(db.fallback_for(c, 0, None).is_none());
+ // A loaded non-chain face supplies Hangul while all installed Korean chain faces are absent.
+ db.add_font(font_with("Earlier Korean Fallback", &['가']).unwrap());
+ let chain_family = "Noto Serif CJK KR";
+ assert!(!db.has_family(chain_family));
+ assert_eq!(db.fallback_for('가', 0, Some("ko")).unwrap().family, "Earlier Korean Fallback");
+ let family = "Installed After Glyph Miss";
+ std::fs::write(dir.join("Later.ttf"), font_with(family, &[c]).unwrap()).unwrap();
+ std::fs::write(dir.join("LaterKorean.ttf"), font_with(chain_family, &['가']).unwrap()).unwrap();
+ // Before an explicit rescan, both fallbacks still use the previous catalog.
+ assert!(db.fallback_for(c, 0, None).is_none());
+ assert_eq!(db.fallback_for('가', 0, Some("ko")).unwrap().family, "Earlier Korean Fallback");
+ assert_eq!(db.load_system_fonts(), 4);
+ assert!(db.has_family(family) && db.has_family(chain_family));
+ assert_eq!(db.fallback_for(c, 0, None).unwrap().family, family);
+ assert_eq!(db.fallback_for('가', 0, Some("ko")).unwrap().family, chain_family);
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+fn a_rescan_does_not_cache_an_older_in_flight_glyph_miss() {
+ use crate::testing::font_with;
+ use std::sync::{Barrier, mpsc};
+ use std::time::Duration;
+
+ let dir = font_dir("rescan-in-flight-ttf");
+ let db = Arc::new(FontDb::with_font_dirs(vec![dir.clone()]));
+ // Optional craft-fonts must not supply the test glyph from an already loaded face.
+ db.faces.write().unwrap().retain(|f| f.family == FALLBACK_FAMILY);
+ let c = '\u{1e900}';
+ let family = "Installed During Glyph Lookup";
+ let font = font_with(family, &[c]).unwrap();
+ assert!(db.read_faces().iter().all(|f| !f.covers(c)));
+ assert_eq!(db.load_system_fonts(), 2);
+
+ let deadline = Duration::from_secs(10);
+ let (reached_tx, reached_rx) = mpsc::sync_channel(1);
+ let resume = Arc::new(Barrier::new(2));
+ *db.fallback_snapshot_hook.lock().unwrap() = Some(FallbackSnapshotHook { reached: reached_tx, resume: resume.clone() });
+ let (lookup_tx, lookup_rx) = mpsc::sync_channel(1);
+ let lookup_db = db.clone();
+ let lookup = std::thread::spawn(move || {
+ let face = lookup_db.fallback_for(c, 0, None).map(|f| f.family.clone());
+ let _ = lookup_tx.send(face);
+ });
+ reached_rx.recv_timeout(deadline).expect("the lookup must reach its old catalog snapshot");
+
+ // Finish the rescan while the old lookup is paused. A timeout also detects accidentally
+ // holding sys/catalog locks at the hook; release the lookup before reporting that failure.
+ let (scan_tx, scan_rx) = mpsc::sync_channel(1);
+ let scan_db = db.clone();
+ let scan = std::thread::spawn(move || {
+ let result = std::fs::write(dir.join("Later.ttf"), font).map(|()| scan_db.load_system_fonts());
+ let _ = scan_tx.send(result);
+ });
+ let scanned = scan_rx.recv_timeout(deadline);
+ resume.wait();
+ let old_face = lookup_rx.recv_timeout(deadline).expect("the old lookup must finish after release");
+ lookup.join().unwrap();
+ assert_eq!(scanned.expect("the rescan must finish before releasing the old lookup").unwrap(), 3);
+ scan.join().unwrap();
+ assert!(old_face.is_none(), "the paused lookup only searched the old paths");
+ assert!(db.has_family(family));
+ assert!(!db.is_loaded(family), "a rescan catalogs the font without loading it");
+ // The old miss must not hide the new catalog entry; no second rescan is performed.
+ assert_eq!(db.fallback_for(c, 0, None).unwrap().family, family);
+ std::fs::remove_dir_all(db.font_dirs.first().unwrap()).unwrap();
+}
++
+ #[test]
+ fn installed_and_loaded_fonts_are_found_by_postscript_name() {
+ let dir = std::env::temp_dir().join(format!("dc-sysfonts-postscript-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("ps.ttf"), crate::testing::font_with("DC Test PS Installed", &['a']).unwrap()).unwrap();
+ let db = FontDb::with_font_dirs(vec![dir]);
+ let found = Some(("DC Test PS Installed".to_string(), "Regular".to_string()));
+ // From the catalog, without loading the font; case doesn't matter.
+ assert_eq!(db.postscript_face("dctestpsinstalled-regular"), found);
+ assert!(!db.is_loaded("DC Test PS Installed"));
+ // Bundled and added (loaded) faces.
+ assert_eq!(db.postscript_face("SourceSerif4-Semibold"), Some(("Source Serif 4".to_string(), "Semibold".to_string())));
+ db.add_font(crate::testing::font_with("DC Test PS Added", &['a']).unwrap());
+ assert_eq!(db.postscript_face("DCTestPSAdded-Regular"), Some(("DC Test PS Added".to_string(), "Regular".to_string())));
+ // A family name isn't a PostScript name.
+ assert_eq!(db.postscript_face("Source Serif 4"), None);
+ assert_eq!(db.postscript_face("NoSuchFont-Regular"), None);
+ }
diff --cc crates/images/src/lib.rs
index 1f5c064ab,4f507f486..3bea7a3b3
--- a/crates/images/src/lib.rs
+++ b/crates/images/src/lib.rs
@@@ -73,68 -73,54 +73,93 @@@ fn svg_options() -> &'static usvg::Opti
}
/// A family the SVG names that isn't bundled comes from the shared fonts (installed ones too),
- /// as it would in a text frame, and matches in any case, as it does there.
-/// as it would in a text frame. A name that is no family's but a face's PostScript name (as
-/// Illustrator's SVG export writes them: `font-family="'MyriadPro-Regular'"`) sets the text in
-/// that face, whatever font-weight and font-style say: the name already picks the weight and
-/// style, and a family's other faces would contradict it. Families listed before it come first.
++/// as it would in a text frame, and matches in any case, as it does there. A name that is no
++/// family's but a face's PostScript name (as Illustrator's SVG export writes them:
++/// `font-family="'MyriadPro-Regular'"`) sets the text in that face, whatever font-weight and
++/// font-style say: the name already picks the weight and style, and a family's other faces would
++/// contradict it. Families listed before it come first.
fn select_font() -> usvg::FontSelectionFn<'static> {
- let bundled = usvg::FontResolver::default_font_selector();
+ use usvg::fontdb::{Family, Query, Stretch, Style, Weight};
Box::new(move |font, db| {
let fonts = designcraft_fonts::FontDb::global();
+ let spelled = |db: &usvg::fontdb::Database, name: &str| {
+ db.faces().flat_map(|f| &f.families).find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(n, _)| n.clone())
+ };
for family in font.families() {
if let usvg::FontFamily::Named(name) = family
- && !has_family(db, name)
+ && spelled(db, name).is_none()
- && fonts.has_family(name)
{
- for style in fonts.styles(name) {
- add_face(db, fonts.face(name, &style));
+ if fonts.has_family(name) {
+ for style in fonts.styles(name) {
+ add_face(db, fonts.face(name, &style));
+ }
+ } else if postscript_face(db, name).is_none()
+ && let Some((family, style)) = fonts.postscript_face(name)
+ {
+ add_face(db, fonts.face(&family, &style));
}
}
}
+ for family in font.families() {
+ match family {
- usvg::FontFamily::Named(name) if !has_family(db, name) => {
++ usvg::FontFamily::Named(name) if spelled(db, name).is_none() => {
+ if let Some(id) = postscript_face(db, name) {
+ return Some(id);
+ }
+ }
+ // A family (or generic family) that matches: usvg's own selection.
+ _ => break,
+ }
+ }
- bundled(font, db)
+ // usvg's default query, but with each named family spelled as the database spells it:
+ // fontdb compares names exactly, so "DeJaVu SaNs" would quietly fall to the serif.
+ let names: Vec<Option<String>> = font
+ .families()
+ .iter()
+ .map(|f| match f {
+ usvg::FontFamily::Named(name) => Some(spelled(db, name).unwrap_or_else(|| name.clone())),
+ _ => None,
+ })
+ .collect();
+ let mut families: Vec<Family> = font
+ .families()
+ .iter()
+ .zip(&names)
+ .map(|(f, name)| match f {
+ usvg::FontFamily::Serif => Family::Serif,
+ usvg::FontFamily::SansSerif => Family::SansSerif,
+ usvg::FontFamily::Cursive => Family::Cursive,
+ usvg::FontFamily::Fantasy => Family::Fantasy,
+ usvg::FontFamily::Monospace => Family::Monospace,
+ usvg::FontFamily::Named(_) => Family::Name(name.as_deref().unwrap_or_default()),
+ })
+ .collect();
+ families.push(Family::Serif);
+ let stretch = match font.stretch() {
+ usvg::FontStretch::UltraCondensed => Stretch::UltraCondensed,
+ usvg::FontStretch::ExtraCondensed => Stretch::ExtraCondensed,
+ usvg::FontStretch::Condensed => Stretch::Condensed,
+ usvg::FontStretch::SemiCondensed => Stretch::SemiCondensed,
+ usvg::FontStretch::Normal => Stretch::Normal,
+ usvg::FontStretch::SemiExpanded => Stretch::SemiExpanded,
+ usvg::FontStretch::Expanded => Stretch::Expanded,
+ usvg::FontStretch::ExtraExpanded => Stretch::ExtraExpanded,
+ usvg::FontStretch::UltraExpanded => Stretch::UltraExpanded,
+ };
+ let style = match font.style() {
+ usvg::FontStyle::Normal => Style::Normal,
+ usvg::FontStyle::Italic => Style::Italic,
+ usvg::FontStyle::Oblique => Style::Oblique,
+ };
+ db.query(&Query { families: &families, weight: Weight(font.weight()), stretch, style })
})
}
-/// Does a face in the SVG's font database have family `name` (ignoring case)?
-fn has_family(db: &usvg::fontdb::Database, name: &str) -> bool {
- db.faces().any(|f| f.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)))
-}
-
+ /// The face in the SVG's font database with PostScript name `name` (ignoring case).
+ fn postscript_face(db: &usvg::fontdb::Database, name: &str) -> Option<usvg::fontdb::ID> {
+ db.faces().find(|f| f.post_script_name.eq_ignore_ascii_case(name)).map(|f| f.id)
+ }
+
/// Characters the chosen fonts lack (Korean, Arabic…) fall back to a shared face that has them.
fn select_fallback() -> usvg::FallbackSelectionFn<'static> {
let loaded = usvg::FontResolver::default_fallback_selector();
@@@ -385,27 -371,45 +410,66 @@@ mod tests
assert!(set.len() == 2 && set.iter().all(|(f, gid)| f != "Source Sans 3" && *gid != 0), "{set:?}");
}
+ #[test]
+ fn svg_family_names_match_in_any_case() {
+ let font = designcraft_fonts::testing::font_with("DC Test SVG Casing", &['A', 'b']).unwrap();
+ designcraft_fonts::FontDb::global().add_font(font);
+ let text = |family: &str, attrs: &str| {
+ format!(
+ r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"><text y="30" font-size="20" font-family="{family}"{attrs}>Ab</text></svg>"#
+ )
+ };
+ for family in ["DC Test SVG Casing", "dc test svg casing", "DC TEST svg Casing", "Nope, dc test SVG casing, serif"] {
+ let set = glyph_families(&text(family, ""));
+ assert!(set.len() == 2 && set.iter().all(|(f, gid)| f == "DC Test SVG Casing" && *gid != 0), "{family}: {set:?}");
+ }
+ // Weight and style still reach the query: there's only a regular face, so it sets the text.
+ let set = glyph_families(&text("dc test svg casing", r#" font-weight="700" font-style="italic""#));
+ assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "DC Test SVG Casing"), "{set:?}");
+ // A family nobody has still falls to the bundled serif.
+ let set = glyph_families(&text("DC Test SVG Nobody", ""));
+ assert!(set.len() == 2 && set.iter().all(|(f, _)| f == "Source Serif 4"), "{set:?}");
+ }
+
+ /// The PostScript name of the face that sets the text of `svg` (one face for all of it).
+ fn text_face(svg_attrs: &str) -> String {
+ let svg =
+ format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"><text y="30" font-size="20"{svg_attrs}>ab</text></svg>"#);
+ let tree = svg_tree(svg.as_bytes()).unwrap();
+ let mut faces = Vec::new();
+ for n in tree.root().children() {
+ if let usvg::Node::Text(t) = n {
+ for g in t.layouted().iter().flat_map(|s| &s.positioned_glyphs) {
+ faces.extend(tree.fontdb().face(g.font).map(|f| f.post_script_name.clone()));
+ }
+ }
+ }
+ faces.dedup();
+ assert_eq!(faces.len(), 1, "{faces:?}");
+ faces.remove(0)
+ }
+
+ #[test]
+ fn svg_text_finds_fonts_by_postscript_name() {
+ // Bundled, as Illustrator's SVG export names it; any case.
+ assert_eq!(text_face(r#" font-family="'SourceSerif4-Semibold'""#), "SourceSerif4-Semibold");
+ assert_eq!(text_face(r#" font-family="sourceserif4-semibold""#), "SourceSerif4-Semibold");
+ // A shared font (as an installed one would be).
+ let font = designcraft_fonts::testing::font_with("DC Test SVG PostScript", &['a', 'b']).unwrap();
+ designcraft_fonts::FontDb::global().add_font(font);
+ assert_eq!(text_face(r#" font-family="DCTestSVGPostScript-Regular""#), "DCTestSVGPostScript-Regular");
+ // The name picks that face: font-weight and font-style don't change it.
+ assert_eq!(text_face(r#" font-family="SourceSerif4-Semibold" font-weight="bold" font-style="italic""#), "SourceSerif4-Semibold");
+ // A family listed before it still comes first; one after it is a fallback.
+ assert_eq!(text_face(r#" font-family="'Source Sans 3', SourceSerif4-Bold""#), "SourceSans3-Regular");
+ assert_eq!(text_face(r#" font-family="NoSuch-Font, SourceSerif4-Bold, 'Source Sans 3'""#), "SourceSerif4-Bold");
+ // Family names work as before.
+ assert_eq!(text_face(r#" font-family="'Source Serif 4'" font-weight="bold""#), "SourceSerif4-Bold");
+ // An unknown name falls back as before (the serif default).
+ assert_eq!(text_face(r#" font-family="NoSuch-Font""#), text_face(r#" font-family="No Such Font""#));
+ assert_eq!(text_face(r#" font-family="NoSuch-Font""#), "SourceSerif4-Regular");
+ }
+
/// A minimal Photoshop file: 2×1 RGB, no layers, raw merged image.
fn tiny_psd() -> Vec<u8> {
let mut b = Vec::new();