Skip to content

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

FONT7: validate replacement coverage and reject placeholder font fallbacks

Shao Wenbinaf43dd88c9fb
diff --git a/ROADMAP.md b/ROADMAP.md
index 70d566d90..d9ae42fe9 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,5 +1,7 @@
# DesignCraft roadmap
+- FONT7: replacement recommendations check the characters actually used; placeholder LastResort fonts and glyph-zero mappings cannot masquerade as glyph coverage or suppress missing-glyph diagnostics.
+
- FONT6: localized and legacy family/style names share canonical resolution across shaping, inventory and replacement. Known compatible and script-based substitutes retain missing status; Find Font shows the resolved face and offers it as the replacement, while preflight reports unavailable styles.
- FONT5: missing-glyph preflight inspects rendered characters in generated labels, including zero-length continuation glyphs, and identifies the owning page frame for nested text.
diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs
index 111444251..83acd685b 100644
--- a/crates/engine/src/cmd/fonts.rs
+++ b/crates/engine/src/cmd/fonts.rs
@@ -13,7 +13,7 @@ use crate::{Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
- cmd!(query "font.list", "Fonts in Document", [], None, "{} → [{family, style, characters, missing, styleMissing, source: bundled|installed|document|added (null when missing), matchStatus: exact|styleSubstitute|missing, resolvedFamily, resolvedStyle}] (missing first)", has_doc, |s, _| {
+ cmd!(query "font.list", "Fonts in Document", [], None, "{} → [{family, style, characters, missing, styleMissing, source: bundled|installed|document|added (null when missing), matchStatus: exact|styleSubstitute|missing, resolvedFamily, resolvedStyle, replacementFamily, replacementStyle}] (missing first)", has_doc, |s, _| {
Ok(Value::Array(list(&s.doc()?.doc)))
}),
cmd!(
@@ -51,6 +51,8 @@ pub(super) struct UsedFont {
pub match_status: &'static str,
pub resolved_family: String,
pub resolved_style: String,
+ pub replacement_family: String,
+ pub replacement_style: String,
}
fn list(d: &Document) -> Vec<Value> {
@@ -59,7 +61,7 @@ fn list(d: &Document) -> Vec<Value> {
pub(super) fn used_fonts(d: &Document) -> Vec<UsedFont> {
let db = designcraft_fonts::FontDb::global().scoped(d.font_scope);
- let mut used: BTreeMap<(String, String), usize> = BTreeMap::new();
+ let mut used: BTreeMap<(String, String), (usize, std::collections::BTreeSet<char>)> = BTreeMap::new();
for_each_story(d, &mut |st| {
let ranges = st.para_ranges();
for (pi, r) in ranges.iter().enumerate() {
@@ -74,21 +76,27 @@ pub(super) fn used_fonts(d: &Document) -> Vec<UsedFont> {
let text = st.text.get(rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))).unwrap_or("");
for c in text.chars() {
if let Some(e) = f.entry(c) {
- *used.entry((e.family.clone(), e.style.clone())).or_default() += 1;
+ let entry = used.entry((e.family.clone(), e.style.clone())).or_default();
+ entry.0 += 1;
+ entry.1.insert(c);
}
}
} else {
- *used.entry((p.font_family, p.font_style)).or_default() += n;
+ let entry = used.entry((p.font_family, p.font_style)).or_default();
+ entry.0 += n;
+ entry.1.extend(st.text.get(rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))).unwrap_or("").chars());
}
}
}
});
let mut out: Vec<UsedFont> = used
.into_iter()
- .map(|((family, style), n)| {
+ .map(|((family, style), (n, characters))| {
let missing = !db.has_family(&family);
let style_missing = !missing && !db.has_style(&family, &style);
let resolved = db.face(&family, &style);
+ let characters: Vec<char> = characters.into_iter().filter(|c| !('\u{E000}'..='\u{E1FF}').contains(c)).collect();
+ let replacement = db.replacement_face(&family, &style, &characters);
let source = (!missing).then(|| match db.face(&family, &style).source {
FontSource::Bundled => "bundled",
FontSource::Installed(_) => "installed",
@@ -111,6 +119,8 @@ pub(super) fn used_fonts(d: &Document) -> Vec<UsedFont> {
},
resolved_family: resolved.family.clone(),
resolved_style: resolved.style.clone(),
+ replacement_family: replacement.family.clone(),
+ replacement_style: replacement.style.clone(),
}
})
.collect();
@@ -147,6 +157,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("font.replace", "Choose an available replacement font style"));
}
let resolved = db.face(&to_family, to_style.as_deref().or(style.as_deref()).unwrap_or("Regular"));
+ if resolved.is_placeholder() {
+ return Err(bad("font.replace", "A placeholder font cannot replace document text"));
+ }
let to_family = resolved.family.clone();
let to_style = (to_style.is_some() || style.is_some()).then(|| resolved.style.clone());
let styles_too = p.get("redefineStyles").and_then(Value::as_bool).unwrap_or(true);
diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs
index 028edd555..d02fc1cd5 100644
--- a/crates/engine/src/cmd/preflight.rs
+++ b/crates/engine/src/cmd/preflight.rs
@@ -51,7 +51,7 @@ fn missing_glyphs(
}
for f in &cs.frames {
let owner = owner.unwrap_or(f.frame);
- for g in f.lines.iter().flat_map(|l| &l.glyphs).filter(|g| g.visible && g.gid == 0) {
+ for g in f.lines.iter().flat_map(|l| &l.glyphs).filter(|g| g.visible && (g.gid == 0 || g.face.is_placeholder())) {
let c = g.rendered_char;
if c.is_control() || c.is_whitespace() || ('\u{E000}'..='\u{E1FF}').contains(&c) {
continue;
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index 169756221..2bc2b00ed 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -209,15 +209,23 @@ impl FontFace {
pub fn id(&self) -> u32 {
self.id
}
- /// Does the face map `c` to a glyph?
+ /// System placeholder fonts draw generic boxes rather than the requested character.
+ pub fn is_placeholder(&self) -> bool {
+ matches!(norm(self.family.trim_start_matches('.')).as_str(), "lastresort")
+ }
+
+ /// Does the face map `c` to a real glyph?
pub fn covers(&self, c: char) -> bool {
+ if self.is_placeholder() {
+ return false;
+ }
let cp = c as u32;
if cp < 0x1_0000 {
let bits = self.bmp.get_or_init(|| {
let mut b = vec![0u64; 1024].into_boxed_slice();
if let Some(f) = self.skrifa() {
- for (cp, _) in f.charmap().mappings() {
- if cp < 0x1_0000 {
+ for (cp, gid) in f.charmap().mappings() {
+ if cp < 0x1_0000 && gid.to_u32() != 0 {
b[(cp / 64) as usize] |= 1 << (cp % 64);
}
}
@@ -226,7 +234,7 @@ impl FontFace {
});
return bits[(cp / 64) as usize] & (1 << (cp % 64)) != 0;
}
- self.skrifa().is_some_and(|f| f.charmap().map(c).is_some())
+ self.skrifa().is_some_and(|f| f.charmap().map(c).is_some_and(|gid| gid.to_u32() != 0))
}
/// Units per em.
pub fn units_per_em(&self) -> f64 {
@@ -1262,6 +1270,36 @@ impl ScopedFonts<'_> {
candidates.iter().find_map(|name| self.canonical_family(name)).unwrap_or_else(|| FALLBACK_FAMILY.to_string())
}
+ /// A replacement suggestion must cover the text being replaced, not just its main script.
+ /// Ties retain the preferred substitute; this does not install or redefine any font.
+ pub fn replacement_face(&self, family: &str, style: &str, characters: &[char]) -> Arc<FontFace> {
+ let mut best = self.face(family, style);
+ let coverage = |face: &FontFace| characters.iter().filter(|&&c| c.is_whitespace() || c.is_control() || face.covers(c)).count();
+ let mut score = coverage(&best);
+ let candidates: &[&str] = if characters.iter().any(|c| ('\u{0600}'..='\u{08ff}').contains(c)) {
+ &["Amiri", "Noto Naskh Arabic", "Al Bayan", "Damascus", "Geeza Pro", "Arial"]
+ } else if characters.iter().any(|c| ('\u{3400}'..='\u{9fff}').contains(c)) {
+ &["Songti SC", "Kaiti SC", "Noto Serif CJK SC", "PingFang SC", "Noto Sans CJK SC"]
+ } else {
+ &["Source Serif 4", "Source Sans 3", "Inter"]
+ };
+ for candidate in candidates {
+ if score == characters.len() {
+ break;
+ }
+ if !self.has_family(candidate) {
+ continue;
+ }
+ let face = self.face(candidate, style);
+ let next = coverage(&face);
+ if next > score {
+ best = face;
+ score = next;
+ }
+ }
+ best
+ }
+
/// Family names available (the document's, loaded and cataloged system fonts), sorted and
/// deduplicated.
pub fn families(&self) -> Vec<String> {
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 01b8e3bc4..60a474b3b 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -563,3 +563,29 @@ mod resolution_tests {
assert_eq!(scope.face("An Unavailable Original Family", "Regular").family, FALLBACK_FAMILY);
}
}
+
+#[cfg(test)]
+mod coverage_recommendation_tests {
+ use super::*;
+
+ #[test]
+ fn placeholder_fonts_do_not_satisfy_glyph_coverage() {
+ let db = FontDb::with_font_dirs(Vec::new());
+ db.add_font(testing::font_with(".LastResort", &['\u{10fffd}']).unwrap());
+ let face = db.face(".LastResort", "Regular");
+ assert!(face.is_placeholder());
+ assert!(!face.covers('\u{10fffd}'));
+ assert!(db.fallback_for('\u{10fffd}', u32::MAX, None).is_none());
+ }
+
+ #[test]
+ fn arabic_replacement_also_covers_surrounding_punctuation() {
+ let db = FontDb::with_font_dirs(Vec::new());
+ db.add_font(testing::font_with("Geeza Pro", &['ع']).unwrap());
+ db.add_font(testing::font_with("Al Bayan", &['ع', '“']).unwrap());
+ let scope = db.scoped(0);
+ assert_eq!(scope.face("Traditional Arabic", "Regular").family, "Geeza Pro");
+ assert_eq!(scope.replacement_face("Traditional Arabic", "Regular", &['ع', '“']).family, "Al Bayan");
+ assert!(!scope.has_family("Traditional Arabic"));
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 7545d44c2..2ef15a776 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -2611,13 +2611,13 @@ fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
d.fields.insert("_fonts".into(), list);
}
let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();
- if d.s("family").is_empty()
+ if !fonts.iter().any(|font| font["family"] == d.s("family") && font["style"] == d.s("style"))
&& let Some(font) = fonts.first()
{
d.fields.insert("family".into(), font["family"].clone());
d.fields.insert("style".into(), font["style"].clone());
}
- if d.b("onOpen") {
+ if d.b("onOpen") && fonts.iter().any(|f| f["missing"] == true || f["styleMissing"] == true) {
crate::rtl::label(
ui,
crate::i18n::tr(
@@ -2656,8 +2656,8 @@ fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
if let Some(font) = fonts.iter().find(|f| f["family"] == d.s("family") && f["style"] == d.s("style")) {
if d.s("_fontKey") != key {
d.fields.insert("_fontKey".into(), json!(key));
- d.fields.insert("toFamily".into(), font["resolvedFamily"].clone());
- d.fields.insert("toStyle".into(), font["resolvedStyle"].clone());
+ d.fields.insert("toFamily".into(), font["replacementFamily"].clone());
+ d.fields.insert("toStyle".into(), font["replacementStyle"].clone());
}
crate::rtl::label(
ui,