Skip to content

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

Text: missing glyphs show as boxes

aiongg1ef187ad0227
diff --git a/ROADMAP.md b/ROADMAP.md
index f195feb27..508f711b5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -30,6 +30,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Ruler guides: drag out of the rulers (page guides, or spread guides on the pasteboard), drag to move, drop on a ruler to delete; Layout › Create Guides (rows/columns with gutters, fit to margins or page); Delete All Guides on Spread; `guide.*` commands.
- Links panel: every placed graphic with status (OK / Modified / Missing / Embedded, checked against the file on disk), page and effective PPI (low resolution flagged); Relink…, Go To, Update, Embed; `links.*` commands.
- Missing fonts: highlighted pink on screen (never in output), listed by Preflight; Type › Find/Replace Font (fonts in the document, missing first; replace in text, cells, footnotes and styles); `font.list` / `font.replace`.
+- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts.
- Damage-region repaint: after an edit the canvas re-renders only the frames whose composed text (or the items that) changed and patches its texture — pixel-identical to a full render; typing in a frame repaints in under a millisecond instead of a full-viewport render (22 ms measured on the sample).
- Crash recovery: unsaved documents are written to the recovery folder every 30 s and reopened (unsaved, remembering their files) after a crash; File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.
- Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).
@@ -87,7 +88,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Edit ▸ Menus (`window.hideMenuItem`): hide menu items; menus with hidden items end in Show All Menu Items.
- View ▸ Separations Preview (`view.separations`): one process plate as ink density, or areas over an ink limit in red (a GCR preview of the rendered view; spot plates and the flattener preview aren't there).
- Separations Preview plates now come from each object's own colour (CMYK as authored; RGB and images through the colour settings, images via a cached 17³ table), so pure black shows only on the black plate.
-- Language (Character panel ▸ Language, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks: Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; Chinese, Japanese and Korean are recognised in their common spellings and locale codes ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`, `ja_JP`, `ko-KR`). Hyphenation dictionaries for other languages aren't bundled yet.
+- Language (Character panel ▸ Language, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; Chinese, Japanese and Korean are recognised in their common spellings and locale codes ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`, `ja_JP`, `ko-KR`). Hyphenation dictionaries for other languages aren't bundled yet.
- Books (`book.new/open/add/remove/list/styleSource/paginate/syncStyles/exportPdf`, Book panel): `.dcbook` files, continuous page numbering, style sync from a style source, one merged PDF.
- Track Changes (`changes.track/list/acceptAll/rejectAll`, Type ▸ Track Changes): typing is marked added (highlighted on screen), deletions are kept but hidden from layout and exports until accepted or rejected. Per-change accept/reject and authors aren't there yet.
- Track Changes: per-change Accept / Reject (`changes.accept`, `changes.reject`) and a Track Changes panel listing every change.
@@ -146,7 +147,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- UI scaling (Preferences › Interface, 50–200%; `window.uiScale`); the window title steps aside when the bar is crowded.
- Underline / Strikethrough Options: weight, offset, colour and tint (Character panel; screen, PDF and IDML).
- Relink to Folder and Relink File Extension (`links.relinkFolder`; missing links found by name).
-- File › Package (⌥⇧⌘P): the document relinked to a Links folder, the placed files, the font files that draw its text in a Document Fonts folder (the fonts it names and the fallback fonts that draw characters those lack; except fonts whose licence restricts it, OS/2 `fsType`), an IDML copy, an optional PDF and a report (fonts, fallback fonts, links, preflight, instructions); Copy Links To (`links.copyTo`).
+- File › Package (⌥⇧⌘P): the document relinked to a Links folder, the placed files, the font files that draw its text in a Document Fonts folder (the fonts it names and any fallback fonts that draw characters those lack; except fonts whose licence restricts it, OS/2 `fsType`), an IDML copy, an optional PDF and a report (fonts, fallback fonts, links, preflight, instructions); Copy Links To (`links.copyTo`).
- Document fonts: opening a `.designcraft` or `.idml` file loads the fonts in the `Document Fonts` folder beside it (as Package writes it), ahead of installed fonts with the same name, so a packaged document opens with its fonts on another machine. Damaged, oversized (over 256 MB per file, 512 MB in all) and surplus (over 200) font files are skipped and listed in `file.open`'s `warnings`; `font.list` gives each font's `source`. Document fonts belong to their document, as in InDesign: other open documents don't see them (each document with a same-named font draws with its own), and closing the document (or reverting it, or a book chapter's export ending) makes them unavailable. Their files stay in memory until DesignCraft quits, so reopening a document doesn't read or load them again; on the web there is no folder to read.
- Load Swatches / Save Swatches for Exchange (.ase: CMYK, RGB, Lab, Gray; spot or process) from the Swatches panel menu; `swatch.load` / `swatch.save`.
- Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); `object.pathfinder`.
diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs
index 28b555ba4..6d6b1b980 100644
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@ -108,6 +108,8 @@ impl Cache {
// Advanced Type sizes super/subscripts.
let a = doc.settings.advanced_type;
sig.extend([a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position].map(|v| v.to_bits() as usize));
+ // Missing glyphs: fallback fonts or the font's box.
+ sig.push(usize::from(doc.settings.glyph_fallback));
// Named lists continue from earlier stories.
for l in &doc.settings.lists {
sig.push(doc.list_start(sid, &l.name) as usize);
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 062a6929c..d088201c0 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -584,7 +584,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
}
let sub_objects = sub.objects.clone();
let mut table = StyleTable { styles: &mut styles_tab, missing: &mut missing_fonts };
- let env = shape::TypeEnv { auto_leading: pp.auto_leading, adv: doc.settings.advanced_type };
+ let env = shape::TypeEnv { auto_leading: pp.auto_leading, adv: doc.settings.advanced_type, glyph_fallback: doc.settings.glyph_fallback };
let mut sp = shape::shape_para(
db,
&doc.styles,
@@ -654,28 +654,30 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
);
}
}
+ // List labels take the default super/subscript settings.
+ let label_env = shape::TypeEnv { adv: Default::default(), ..env };
match pp.list_type {
designcraft_doc::ListType::Numbers if !pp.list_name.is_empty() => {
// A named list: carries on past other paragraphs (and from earlier stories).
let n = named_numbers.get(pi).copied().flatten().unwrap_or(1);
let label = format!("{}.{}", pp.number_style.format(n), pp.list_separator);
- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, &pp, &mut table);
+ prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);
}
designcraft_doc::ListType::Numbers => {
list_counter = pp.start_at.map_or(list_counter + 1, |s| s.max(1));
let label = format!("{}.{}", pp.number_style.format(list_counter), pp.list_separator);
- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, &pp, &mut table);
+ prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);
}
designcraft_doc::ListType::Bullets => {
let label = format!("{}{}", pp.bullet_char, pp.list_separator);
- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, &pp, &mut table);
+ prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);
}
designcraft_doc::ListType::None => list_counter = 0,
}
if pi == 0
&& let Some(label) = &opts.label
{
- prepend_label(db, &mut sp.glyphs, label, prange.start, &base_chars, &pp, &mut table);
+ prepend_label(db, &mut sp.glyphs, label, prange.start, &base_chars, label_env, &mut table);
}
let mut glyphs = sp.glyphs;
let bidi_text = bidi::paragraph_text(&mut glyphs, &story.text);
@@ -844,7 +846,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
let last = k + 1 == breaks.len();
let (mut placed, end_x, ratio) =
layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page, &bidi_info);
- ruby::annotate(db, &styles_tab, &mut placed);
+ ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
let range_start = if line_no == 0 { prange.start } else { range_start };
@@ -1991,27 +1993,14 @@ fn prepend_label(
label: &str,
at: usize,
base: &designcraft_doc::CharProps,
- pp: &ParaProps,
+ env: shape::TypeEnv,
table: &mut StyleTable<'_>,
) {
// Shape the label as a tiny standalone story so it uses the paragraph's base character style.
let mut tmp = Story::new(StoryId(0));
tmp.insert(0, label);
let styles = designcraft_doc::Styles::default();
- let shaped = shape::shape_para(
- db,
- &styles,
- &tmp,
- 0,
- 0..label.len(),
- base,
- shape::TypeEnv { auto_leading: pp.auto_leading, adv: Default::default() },
- &SubstCtx::default(),
- table,
- &[],
- &[],
- &[],
- );
+ let shaped = shape::shape_para(db, &styles, &tmp, 0, 0..label.len(), base, env, &SubstCtx::default(), table, &[], &[], &[]);
let mut pre: Vec<Glyph> = shaped
.glyphs
.into_iter()
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
index c909e06b5..cea4a5545 100644
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@ -40,18 +40,21 @@ fn set(base: &PlacedGlyph, text: &str, size: f64, base_size: f64) -> (Vec<Placed
(out, x)
}
-/// A sesame dot (or a bullet, when the font has none) centred over `b`.
-fn kenten(db: &ScopedFonts<'_>, b: &PlacedGlyph, size: f64, character: &str) -> Vec<PlacedGlyph> {
+/// The emphasis `character` (a sesame dot when empty) centred over `b`, in `b`'s font. A
+/// character the font lacks is its missing-glyph box, unless `fallback` (fallback fonts draw
+/// missing glyphs): then a fallback font draws it, or failing that a bullet.
+fn kenten(db: &ScopedFonts<'_>, b: &PlacedGlyph, size: f64, character: &str, fallback: bool) -> Vec<PlacedGlyph> {
let character = if character.is_empty() { "\u{FE45}" } else { character };
let mut base = b.clone();
- if let Some(c) = character.chars().next()
+ if fallback
+ && let Some(c) = character.chars().next()
&& !base.face.covers(c)
&& let Some(face) = db.fallback_for(c, base.face.id(), None)
{
base.face = designcraft_fonts::FaceRef::of(&face);
}
let (mut dot, mut w) = set(&base, character, size * SCALE, size);
- if dot.first().is_some_and(|d| d.gid == 0) {
+ if fallback && dot.first().is_some_and(|d| d.gid == 0) {
(dot, w) = set(b, "\u{2022}", size * SCALE, size);
}
// Centre the mark's ink (its advance may hold it off centre) and sit it just over the text.
@@ -68,8 +71,9 @@ fn kenten(db: &ScopedFonts<'_>, b: &PlacedGlyph, size: f64, character: &str) ->
dot
}
-/// Add the ruby and kenten of a laid-out line's glyphs.
-pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec<PlacedGlyph>) {
+/// Add the ruby and kenten of a laid-out line's glyphs. `glyph_fallback`: the document draws
+/// missing glyphs from fallback fonts (a missing font's substitute always does).
+pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec<PlacedGlyph>, glyph_fallback: bool) {
let style = |g: &PlacedGlyph| styles.get(g.style as usize);
if !line.iter().any(|g| style(g).is_some_and(|s| s.ruby.is_some() || s.kenten)) {
return;
@@ -83,7 +87,7 @@ pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec
continue;
};
if st.kenten && g.adv > 0.0 {
- extra.extend(kenten(db, g, st.size, &st.kenten_character));
+ extra.extend(kenten(db, g, st.size, &st.kenten_character, glyph_fallback || st.missing_font));
}
let Some(text) = &st.ruby else {
i += 1;
@@ -115,7 +119,7 @@ pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec
extra.extend(glyphs);
// Kenten on the rest of the group.
for b in line[i + 1..j].iter().filter(|b| st.kenten && b.len > 0 && b.adv > 0.0) {
- extra.extend(kenten(db, b, st.size, &st.kenten_character));
+ extra.extend(kenten(db, b, st.size, &st.kenten_character, glyph_fallback || st.missing_font));
}
i = j;
}
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 2f46a9dee..41583b0a9 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -169,6 +169,13 @@ impl StyleTable<'_> {
self.styles.push(rs);
(self.styles.len() - 1) as u32
}
+
+ /// `env` for text in run style `style`: a missing font's substitute draws the characters it
+ /// lacks from fallback fonts whatever the document's setting.
+ fn env_for(&self, env: TypeEnv, style: u32) -> TypeEnv {
+ let missing = self.styles.get(style as usize).is_some_and(|s| s.missing_font);
+ TypeEnv { glyph_fallback: env.glyph_fallback || missing, ..env }
+ }
}
/// Resolve and shape one paragraph.
@@ -246,6 +253,8 @@ pub(crate) fn shape_para(
}
for (a, b, props, fmt, resolved_base) in resolved {
let style = table.intern(db, &props);
+ // A missing font's substitute stands in for the whole font: fallback fonts help it.
+ let auto_leading = table.env_for(auto_leading, style);
let deleted = props.change == designcraft_doc::ChangeMark::Deleted;
if deleted || (!props.conditions.is_empty() && props.conditions.iter().all(|c| sub.hidden_conditions.contains(c))) {
// Hidden conditional text: zero-width, unbreakable, undrawn place-holders keep every
@@ -276,10 +285,12 @@ pub(crate) fn shape_para(
rf.over.position = Some(sub.note_position);
let rprops = styles.resolve_char(&resolved_base, &rf);
let rstyle = table.intern(db, &rprops);
+ let renv = table.env_for(auto_leading, rstyle);
let mut ef = fmt.clone();
ef.over.position = Some(designcraft_doc::Position::Superscript);
let eprops = styles.resolve_char(&resolved_base, &ef);
let estyle = table.intern(db, &eprops);
+ let eenv = table.env_for(auto_leading, estyle);
let mut k = a;
for (i, m) in story.text[a..b].match_indices(is_ref) {
let i = a + i;
@@ -288,9 +299,9 @@ pub(crate) fn shape_para(
}
let e = i + m.len();
if m.starts_with(designcraft_doc::ENDNOTE_REF) {
- shape_run(db, &story.text, i..e, &eprops, auto_leading, estyle, sub, &mut glyphs);
+ shape_run(db, &story.text, i..e, &eprops, eenv, estyle, sub, &mut glyphs);
} else {
- shape_run(db, &story.text, i..e, &rprops, auto_leading, rstyle, sub, &mut glyphs);
+ shape_run(db, &story.text, i..e, &rprops, renv, rstyle, sub, &mut glyphs);
}
k = e;
}
@@ -478,8 +489,12 @@ fn shape_run_raw(
out: &mut Vec<Glyph>,
) {
let primary = db.face(&p.font_family, &p.font_style);
- // The language picks the fallback for CJK characters the primary font lacks.
+ // The language picks the fallback for CJK characters the primary font lacks. Without
+ // fallback, the primary font sets them: the shaper gives its .notdef (glyph 0).
let lang = designcraft_doc::language_tag(&p.language);
+ let fallback = |c: char| {
+ if auto_leading.glyph_fallback { db.fallback_for(c, primary.id(), lang).unwrap_or_else(|| primary.clone()) } else { primary.clone() }
+ };
let strong = |c| match unicode_bidi::bidi_class(c) {
unicode_bidi::BidiClass::AL => Some(true),
unicode_bidi::BidiClass::L | unicode_bidi::BidiClass::R => Some(false),
@@ -515,8 +530,7 @@ fn shape_run_raw(
if d != c {
flush(seg_start, i, &seg_face, out);
seg_start = i + c.len_utf8();
- let face =
- if primary.covers(d) { primary.clone() } else { db.fallback_for(d, primary.id(), lang).unwrap_or_else(|| primary.clone()) };
+ let face = if primary.covers(d) { primary.clone() } else { fallback(d) };
shape_segment(db, text, i..i + c.len_utf8(), Some(d.encode_utf8(&mut [0; 4])), p, &face, auto_leading, style, out, sub.vertical);
continue;
}
@@ -614,11 +628,7 @@ fn shape_run_raw(
continue;
}
let covered = c.is_whitespace() || c.is_control() || c == SOFT_HYPHEN || primary.covers(c);
- let face = if covered || is_mark(c) {
- if is_mark(c) { seg_face.clone() } else { primary.clone() }
- } else {
- db.fallback_for(c, primary.id(), lang).unwrap_or_else(|| primary.clone())
- };
+ let face = if covered || is_mark(c) { if is_mark(c) { seg_face.clone() } else { primary.clone() } } else { fallback(c) };
if face.id() != seg_face.id() {
flush(seg_start, i, &seg_face, out);
seg_start = i;
@@ -724,6 +734,8 @@ fn metrics(face: &FontFace, p: &CharProps, auto_leading: TypeEnv) -> (f64, f64,
pub struct TypeEnv {
pub auto_leading: f64,
pub adv: designcraft_doc::AdvancedType,
+ /// Characters the font lacks are drawn from fallback fonts (else as its .notdef glyph).
+ pub glyph_fallback: bool,
}
/// Synthesised super/subscript: size and shift from Advanced Type (percent of the font size).
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 10deca33d..7943adfd8 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -892,6 +892,8 @@ fn check_kashida_justification(db: &FontDb, require_fallback: bool) {
..Default::default()
};
let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 260.0, 400.0), lid, text, pf).unwrap();
+ // The Arabic is drawn from a fallback font when the database has one.
+ d.settings.glyph_fallback = true;
let composed = |d: &Document| compose_with_db(d, d.story(sid).unwrap(), &frame_specs(d, sid), &ComposeOptions::default(), db);
let first = |d: &Document| composed(d).frames[0].lines[0].clone();
let with = first(&d);
@@ -1276,6 +1278,7 @@ fn arabic_fallback_marks_stay_with_bases_and_custom_offsets_move_only_marks() {
}
let text = "بُبَ";
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());
+ d.settings.glyph_fallback = true;
let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
assert!(plain.iter().all(|g| g.face.id() == face.id()), "fallback must not split Arabic marks into the Latin face");
assert!(plain.iter().all(|g| g.gid != 0));
@@ -1303,6 +1306,7 @@ fn arabic_fallback_marks_stay_with_bases_and_custom_offsets_move_only_marks() {
fn arabic_joining_context_crosses_character_style_boundaries() {
let text = "ببب";
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 600.0, 200.0), ParaAttrs::default());
+ d.settings.glyph_fallback = true;
let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
if plain.iter().any(|g| g.gid == 0) {
return;
@@ -1320,6 +1324,7 @@ fn arabic_character_kashida_switch_prevents_insertion() {
Rect::new(0.0, 0.0, 160.0, 300.0),
ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::RightJustified), ..Default::default() },
);
+ d.settings.glyph_fallback = true;
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.allow_kashidas = Some(false));
let off = compose_story(&d, sid, &ComposeOptions::default());
assert!(all_lines(&off).iter().all(|l| l.glyphs.iter().all(|g| g.len > 0 || g.face.glyph_for('\u{0640}') != g.gid)));
@@ -1342,6 +1347,7 @@ fn arabic_indic_digit_conversion_retains_original_utf8_ranges() {
fn arabic_contextual_digits_follow_strong_text_across_style_changes() {
let text = "ب 12 A 34";
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ d.settings.glyph_fallback = true;
let arabic_digits = text.find('1').unwrap();
d.story_mut(sid).unwrap().format_chars(arabic_digits..arabic_digits + 2, |f| f.over.fill = Some("Paper".into()));
let cs = compose_story(&d, sid, &ComposeOptions::default());
@@ -1390,6 +1396,7 @@ fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {
Rect::new(0.0, 0.0, 180.0, 100.0),
ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },
);
+ d.settings.glyph_fallback = true;
let with = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
if with.iter().any(|g| g.gid == 0) {
return;
@@ -1404,11 +1411,12 @@ fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {
assert!(((a.x - first_a.x) - (b.x - first_b.x)).abs() < 1e-6, "marks detached from their cluster");
}
let text = "ب\u{200C}ب ب\u{200C}ب";
- let (d, sid, _) = doc_with(
+ let (mut d, sid, _) = doc_with(
text,
Rect::new(0.0, 0.0, 180.0, 100.0),
ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::FullyJustified), ..Default::default() },
);
+ d.settings.glyph_fallback = true;
let cs = compose_story(&d, sid, &ComposeOptions::default());
assert!(cs.frames[0].lines[0].glyphs.iter().all(|g| g.gid != g.face.glyph_for('\u{0640}') || g.len > 0));
}
@@ -1417,6 +1425,7 @@ fn arabic_kashida_moves_marks_with_their_cluster_and_respects_nonjoiners() {
fn arabic_explicit_isolated_forms_disable_contextual_joining() {
let text = "بب";
let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 180.0, 100.0), ParaAttrs::default());
+ d.settings.glyph_fallback = true;
d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.positional_form = Some("Isolated".into()));
let cs = compose_story(&d, sid, &ComposeOptions::default());
let gs = &cs.frames[0].lines[0].glyphs;
@@ -1492,6 +1501,7 @@ fn cjk_fallback_follows_the_language() {
// (face of the Latin letter, face of the ideograph)
let faces_of = |language: &str| {
let (mut d, sid, _) = doc_with("a直", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ d.settings.glyph_fallback = true;
d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.language = Some(language.into()));
let cs = compose_story(&d, sid, &ComposeOptions::default());
let face_at = |byte: usize| all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| g.face).unwrap();
@@ -1506,6 +1516,49 @@ fn cjk_fallback_follows_the_language() {
assert_eq!(Some(han.family.clone()), db.fallback_for('直', primary.id(), None).map(|f| f.family.clone()));
}
+#[test]
+fn missing_glyphs_are_the_fonts_box_unless_fallback_is_on() {
+ use designcraft_fonts::testing::font_with;
+ // Some font draws 語 when fallback fonts are allowed (a system CJK font, or this stand-in).
+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Missing Glyph Helper", &['語']).unwrap());
+ let text = "a語";
+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.language = Some("Japanese".into()));
+ let glyph_at = |d: &Document, byte: usize| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ all_lines(&cs).iter().flat_map(|l| l.glyphs.iter()).find(|g| g.byte == byte).map(|g| (g.face, g.gid, g.adv)).unwrap()
+ };
+ assert!(!d.settings.glyph_fallback, "new documents draw missing glyphs as InDesign does");
+ let (face, gid, adv) = glyph_at(&d, 1);
+ assert_eq!((face.family.as_str(), gid), (designcraft_fonts::DEFAULT_FAMILY, 0), "Source Serif 4's .notdef");
+ assert!((adv - face.advance(0) * 12.0 / face.upem).abs() < 1e-6, "its advance: {adv}");
+ d.settings.glyph_fallback = true;
+ let (face, gid, _) = glyph_at(&d, 1);
+ assert_ne!(face.family, designcraft_fonts::DEFAULT_FAMILY);
+ assert_ne!(gid, 0, "a fallback font draws it");
+}
+
+#[test]
+fn kenten_missing_from_the_font_are_its_box_unless_fallback_is_on() {
+ use designcraft_fonts::testing::font_with;
+ // Some font draws the sesame dot when fallback fonts are allowed (a system font, or this one).
+ designcraft_fonts::FontDb::global().add_font(font_with("DC Test Kenten Helper", &['\u{FE45}']).unwrap());
+ let (mut d, sid, _) = doc_with("ab", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.kenten = Some(true));
+ let marks = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ cs.frames[0].lines[0].glyphs[plain..].iter().map(|g| (g.face.family.clone(), g.gid)).collect::<Vec<_>>()
+ };
+ let missing = marks(&d);
+ assert_eq!(missing.len(), 2);
+ assert!(missing.iter().all(|(family, gid)| family == designcraft_fonts::DEFAULT_FAMILY && *gid == 0), "{missing:?}");
+ d.settings.glyph_fallback = true;
+ let drawn = marks(&d);
+ assert_eq!(drawn.len(), 2);
+ assert!(drawn.iter().all(|(family, gid)| family != designcraft_fonts::DEFAULT_FAMILY && *gid != 0), "{drawn:?}");
+}
+
#[test]
fn each_document_shapes_words_in_its_own_fonts() {
use designcraft_fonts::testing::font_with_glyph;
diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs
index 92fbee735..8626abc51 100644
--- a/crates/doc/src/build.rs
+++ b/crates/doc/src/build.rs
@@ -116,6 +116,7 @@ impl Document {
horizontal_units: nd.units,
vertical_units: nd.units,
blend_space: if nd.intent == Intent::Print { crate::BlendSpace::Cmyk } else { crate::BlendSpace::Rgb },
+ glyph_fallback: false,
..Default::default()
};
let mut d = Document {
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 8f80a78ea..455a8dcd3 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -340,6 +340,12 @@ pub struct DocSettings {
pub overprint_black: bool,
/// Type › Track Changes: edits are recorded as inserted / deleted text.
pub track_changes: bool,
+ /// Preferences › Composition › Draw Missing Glyphs from Fallback Fonts: characters the
+ /// applied font lacks are drawn from other fonts. Off (InDesign's behaviour, and new
+ /// documents'), they are drawn as the font's missing-glyph box and Preflight lists them.
+ /// Documents saved before the setting existed read as on, the way they were drawn.
+ #[serde(default = "yes")]
+ pub glyph_fallback: bool,
}
impl Default for DocSettings {
@@ -371,6 +377,7 @@ impl Default for DocSettings {
blend_space: BlendSpace::Cmyk,
overprint_black: true,
track_changes: false,
+ glyph_fallback: false,
}
}
}
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 71340ec76..6e572a98a 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -829,6 +829,8 @@ mod document_fonts_tests {
let mut s = Session::new();
open(&mut s, &a.join("A.designcraft"));
open(&mut s, &b.join("B.designcraft"));
+ // Fallback fonts for the `a` B's font lacks: never A's font.
+ s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap();
let in_b = glyph_faces(&s);
s.execute("file.activate", &json!({"index": 0})).unwrap();
let in_a = glyph_faces(&s);
diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs
index e0febf80c..5cc4cc860 100644
--- a/crates/engine/src/cmd/package.rs
+++ b/crates/engine/src/cmd/package.rs
@@ -318,6 +318,7 @@ mod tests {
std::fs::write(fonts.join("restricted.otf"), with_fs_type(font_with(RESTRICTED, &[restricted]).unwrap(), 0x0002).unwrap()).unwrap();
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
+ s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap();
let text = format!("N{helped}{restricted}");
let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": text})).unwrap();
s.execute("text.select", &json!({"story": r["story"], "anchor": 0, "focus": text.len()})).unwrap();
diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs
index b8c345dd4..3fc061d7d 100644
--- a/crates/engine/src/cmd/preflight.rs
+++ b/crates/engine/src/cmd/preflight.rs
@@ -1,7 +1,10 @@
//! Live preflight (the Preflight panel and the status-bar indicator): overset text, missing
-//! fonts, missing or low-resolution graphics, RGB content in print documents, empty text frames.
+//! fonts and glyphs, missing or low-resolution graphics, RGB content in print documents, empty
+//! text frames.
+use designcraft_compose::ComposedStory;
use designcraft_doc::{Content, Document, Intent, Item, SpreadRef};
+use designcraft_fonts::FaceRef;
use serde::Serialize;
use serde_json::{Value, json};
@@ -32,6 +35,42 @@ fn page_of(d: &Document, sr: SpreadRef, it: &Item) -> Option<usize> {
Some(d.first_page_of_spread(si) + sp.page_at_x(it.bounds().center().x).unwrap_or(0))
}
+/// Characters a missing-glyph report names before "and N more".
+const MISSING_GLYPHS_LISTED: usize = 20;
+
+/// Add the characters drawn as their font's missing glyph (.notdef) in `cs`, composed from
+/// `text` (table cells and footnotes included), to `out` by face, each once. Text in a missing
+/// font is left to the missing-font report; generated text (list labels, page numbers) and
+/// markers have no character of their own to name.
+fn missing_glyphs(cs: &ComposedStory, text: &str, depth: usize, out: &mut Vec<(FaceRef, Vec<char>)>) {
+ // Cells and footnotes hold composed stories of their own; tables nest only so deep.
+ if depth > 16 {
+ return;
+ }
+ for f in &cs.frames {
+ for g in f.lines.iter().flat_map(|l| &l.glyphs).filter(|g| g.visible && g.gid == 0 && g.len > 0) {
+ if cs.styles.get(g.style as usize).is_none_or(|st| st.missing_font) {
+ continue;
+ }
+ let Some(c) = text.get(g.byte..).and_then(|t| t.chars().next()) else { continue };
+ if c.is_control() || c.is_whitespace() || ('\u{E000}'..='\u{E1FF}').contains(&c) {
+ continue;
+ }
+ match out.iter_mut().find(|(face, _)| *face == g.face) {
+ Some((_, chars)) if !chars.contains(&c) => chars.push(c),
+ Some(_) => {}
+ None => out.push((g.face, vec![c])),
+ }
+ }
+ for c in f.tables.iter().flat_map(|t| &t.cells) {
+ missing_glyphs(&c.text, &c.source, depth + 1, out);
+ }
+ for n in &f.notes {
+ missing_glyphs(&n.text, &n.source, depth + 1, out);
+ }
+ }
+}
+
pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let Some(st) = s.active() else { return vec![] };
let d = &st.doc;
@@ -40,8 +79,10 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let db = designcraft_fonts::FontDb::global().scoped(d.font_scope);
let mut missing_fonts: Vec<String> = Vec::new();
let mut unsupported_typography = std::collections::BTreeSet::new();
+ let mut missing: Vec<(FaceRef, Vec<char>)> = Vec::new();
for story in d.stories.values() {
let cs = s.cache.get(d, story.id, None);
+ missing_glyphs(&cs, &story.text, 0, &mut missing);
if cs.is_overset() {
let last = story.frames.last().copied();
let page = last.and_then(|f| d.find(f).zip(d.item(f))).and_then(|(loc, it)| page_of(d, loc.spread, it));
@@ -108,6 +149,18 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
for message in unsupported_typography {
out.push(Issue { severity: "warning", kind: "unsupportedTypography", message, item: None, page: None });
}
+ for (face, chars) in missing {
+ let listed: Vec<String> = chars.iter().take(MISSING_GLYPHS_LISTED).map(char::to_string).collect();
+ let more = chars.len().saturating_sub(MISSING_GLYPHS_LISTED);
+ let more = if more > 0 { format!(" and {more} more") } else { String::new() };
+ out.push(Issue {
+ severity: "error",
+ kind: "missingGlyphs",
+ message: format!("Missing glyphs in {} {}: {}{more}", face.family, face.style, listed.join(" ")),
+ item: None,
+ page: None,
+ });
+ }
// Items.
for (si, sp) in d.spreads.iter().enumerate() {
for top in &sp.items {
@@ -225,3 +278,47 @@ mod arabic_tests {
assert!(typography.iter().all(|i| i.severity == "warning"));
}
}
+
+#[cfg(test)]
+mod missing_glyph_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ fn missing_glyphs(s: &mut Session) -> Vec<(String, String)> {
+ let r = s.execute("preflight.run", &json!({})).unwrap();
+ r["issues"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|i| i["kind"] == "missingGlyphs")
+ .map(|i| (i["severity"].as_str().unwrap().to_string(), i["message"].as_str().unwrap().to_string()))
+ .collect()
+ }
+
+ #[test]
+ fn characters_drawn_as_missing_glyphs_are_listed() {
+ // Some font has them, for when fallback fonts are on.
+ designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::font_with("DC Test Preflight Helper", &['日', '本', '語']).unwrap());
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Hello 日本語 日本 and 語."})).unwrap();
+ let family = designcraft_fonts::DEFAULT_FAMILY;
+ assert_eq!(missing_glyphs(&mut s), [("error".to_string(), format!("Missing glyphs in {family} Regular: 日 本 語"))]);
+ // Drawn from fallback fonts: nothing missing.
+ s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap();
+ assert!(missing_glyphs(&mut s).is_empty());
+ }
+
+ #[test]
+ fn a_long_list_of_missing_glyphs_is_cut_short() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ // 30 private-use characters no font has.
+ let text: String = (0..30).filter_map(|i| char::from_u32(0xF0B00 + i)).collect();
+ s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": text})).unwrap();
+ let found = missing_glyphs(&mut s);
+ assert_eq!(found.len(), 1);
+ assert!(found[0].1.ends_with(" and 10 more"), "{}", found[0].1);
+ }
+}
diff --git a/crates/engine/src/cmd/prefs.rs b/crates/engine/src/cmd/prefs.rs
index 27d31b173..cfd7f74c1 100644
--- a/crates/engine/src/cmd/prefs.rs
+++ b/crates/engine/src/cmd/prefs.rs
@@ -20,6 +20,7 @@ const DOC_KEYS: &[&str] = &[
"slugColor",
"advancedType",
"overprintBlack",
+ "glyphFallback",
];
pub fn specs() -> Vec<CommandSpec> {
@@ -61,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Preferences",
[],
None,
- "{horizontalUnits?, verticalUnits?: points|picas|inches|millimeters|…, keyboardIncrement? (pt), baselineGrid?: {start, increment, relativeTo, color, viewThreshold}, grid?: {horizontal, vertical, subdivisions, color, inBack}, pasteboard?: [h, v], marginColor?, columnColor?, bleedColor?, slugColor?: [r, g, b], advancedType?: {superscriptSize, superscriptPosition, subscriptSize, subscriptPosition} (%)} → those settings",
+ "{horizontalUnits?, verticalUnits?: points|picas|inches|millimeters|…, keyboardIncrement? (pt), baselineGrid?: {start, increment, relativeTo, color, viewThreshold}, grid?: {horizontal, vertical, subdivisions, color, inBack}, pasteboard?: [h, v], marginColor?, columnColor?, bleedColor?, slugColor?: [r, g, b], advancedType?: {superscriptSize, superscriptPosition, subscriptSize, subscriptPosition} (%), overprintBlack?, glyphFallback? (draw characters the font lacks from fallback fonts; off: as the font's missing-glyph box)} → those settings",
has_doc,
|s, p| {
let cur = serde_json::to_value(&s.doc()?.doc.settings).map_err(|e| bad("document.preferences", e.to_string()))?;
@@ -264,3 +265,37 @@ mod blend_space_tests {
assert!(s.execute("edit.transparencyBlendSpace", &json!({"space": "lab"})).is_err());
}
}
+
+#[cfg(test)]
+mod glyph_fallback_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn glyph_fallback_is_an_undoable_document_preference() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ assert_eq!(s.execute("document.preferences", &json!({})).unwrap()["glyphFallback"], false, "new documents: off");
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "語"})).unwrap();
+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
+ let gid = |s: &Session| s.cache.get(&s.doc().unwrap().doc, sid, None).frames[0].lines[0].glyphs[0].gid;
+ assert_eq!(gid(&s), 0);
+ designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::font_with("DC Test Prefs Helper", &['語']).unwrap());
+ assert_eq!(s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap()["glyphFallback"], true);
+ assert!(s.doc().unwrap().doc.settings.glyph_fallback);
+ assert_ne!(gid(&s), 0, "drawn from a fallback font");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(!s.doc().unwrap().doc.settings.glyph_fallback);
+ assert_eq!(gid(&s), 0);
+ }
+
+ #[test]
+ fn idml_imports_draw_missing_glyphs_as_boxes() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("document.preferences", &json!({"glyphFallback": true})).unwrap();
+ let back = designcraft_idml::import_idml(&designcraft_idml::export_idml(&s.doc().unwrap().doc)).unwrap();
+ assert!(!back.settings.glyph_fallback, "as InDesign draws them");
+ }
+}
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index dd88b7b58..c8bc0fad3 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -1371,7 +1371,8 @@ mod language_tests {
.collect();
assert!(stories.contains(r#"AppliedLanguage="$ID/Simplified Chinese""#), "{stories}");
// The name comes back as written and sets the text as Simplified Chinese.
- let back = designcraft_idml::import_idml(&idml).unwrap();
+ let mut back = designcraft_idml::import_idml(&idml).unwrap();
+ back.settings.glyph_fallback = true;
let st = back.stories.values().find(|st| st.text.contains('直')).unwrap();
let (_, base) = back.styles.resolve_para(&st.paras[0]);
assert_eq!(back.styles.resolve_char(&base, st.char_format_at(0)).language, "Simplified Chinese");
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index a1461db3f..909906b1d 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -1079,19 +1079,43 @@ impl FontDb {
false
}
- /// Glyph outline in font units, y-down (flipped), cached per (face, glyph).
+ /// The box drawn for `face`'s missing glyph (.notdef) when the font's own has no outline, in
+ /// font units, y-down: a hollow rectangle across the glyph's advance, cap height tall. `None`
+ /// when the font draws its own.
+ pub fn missing_box(&self, face: &FontFace) -> Option<BezPath> {
+ if !font_outline(face, 0).elements().is_empty() {
+ return None;
+ }
+ let adv = Some(face.advance(0)).filter(|a| a.is_finite() && *a > 0.0).unwrap_or(face.upem * 0.5);
+ let top = Some(face.cap_height).filter(|h| h.is_finite() && *h > 0.0).unwrap_or(face.upem * 0.7);
+ let outer = kurbo::Rect::new(adv * 0.1, -top, adv * 0.9, 0.0);
+ let t = (face.upem * 0.05).min(outer.width() / 4.0).min(top / 4.0);
+ let inner = outer.inset(-t);
+ let mut p = BezPath::new();
+ // The inner rectangle runs the other way round, so filling leaves it empty.
+ p.move_to((outer.x0, outer.y0));
+ p.line_to((outer.x1, outer.y0));
+ p.line_to((outer.x1, outer.y1));
+ p.line_to((outer.x0, outer.y1));
+ p.close_path();
+ p.move_to((inner.x0, inner.y0));
+ p.line_to((inner.x0, inner.y1));
+ p.line_to((inner.x1, inner.y1));
+ p.line_to((inner.x1, inner.y0));
+ p.close_path();
+ Some(p)
+ }
+
+ /// Glyph outline in font units, y-down (flipped), cached per (face, glyph). A `.notdef`
+ /// without an outline is drawn as [`FontDb::missing_box`], so a missing character never
+ /// disappears.
pub fn outline(&self, face: &FontFace, gid: u32) -> Arc<BezPath> {
let key = (face.id, gid);
if let Some(p) = self.outlines.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
return p.clone();
}
- let mut pen = FlipPen(BezPath::new());
- if let Some(f) = face.skrifa()
- && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))
- {
- let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
- }
- let p = Arc::new(pen.0);
+ let drawn = font_outline(face, gid);
+ let p = Arc::new(if gid == 0 && drawn.elements().is_empty() { self.missing_box(face).unwrap_or(drawn) } else { drawn });
let mut cache = self.outlines.lock().unwrap_or_else(|e| e.into_inner());
if cache.len() >= OUTLINE_CACHE_MAX {
cache.clear();
@@ -1308,6 +1332,17 @@ fn over_total() -> String {
format!("over the {} MB the folder's fonts may take in all", MAX_DOCUMENT_FONTS_TOTAL >> 20)
}
+/// Glyph `gid`'s outline as the font draws it, in font units, y-down (flipped).
+fn font_outline(face: &FontFace, gid: u32) -> BezPath {
+ let mut pen = FlipPen(BezPath::new());
+ if let Some(f) = face.skrifa()
+ && let Some(g) = f.outline_glyphs().get(GlyphId::new(gid))
+ {
+ let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), face.location()), &mut pen);
+ }
+ pen.0
+}
+
struct FlipPen(BezPath);
impl OutlinePen for FlipPen {
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 1957c5b95..f8cb9e42f 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -434,6 +434,49 @@ mod tests {
assert!(feature("abc").is_none());
}
+ #[test]
+ fn a_notdef_without_an_outline_is_drawn_as_a_box() {
+ let db = FontDb::with_font_dirs(Vec::new());
+ db.set_system_fallback(false);
+ let font = testing::font_with("DC Test Empty Notdef", &['a']).unwrap();
+ db.add_font(testing::with_empty_notdef(font).unwrap());
+ let face = db.face("DC Test Empty Notdef", "Regular");
+ assert!(face.skrifa().unwrap().outline_glyphs().get(skrifa::GlyphId::NOTDEF).is_some_and(|g| {
+ let mut pen = kurbo::BezPath::new();
+ let _ = g.draw(skrifa::outline::DrawSettings::unhinted(skrifa::instance::Size::unscaled(), face.location()), &mut BezPen(&mut pen));
+ pen.elements().is_empty()
+ }));
+ // The box spans the glyph's advance, above the baseline (outlines are y-down).
+ let b = kurbo::Shape::bounding_box(&*db.outline(&face, 0));
+ assert!(b.width() > 0.0 && b.width() <= face.advance(0), "{b:?}");
+ assert!(b.y0 < 0.0 && b.y1 <= 0.0, "{b:?}");
+ assert!(db.missing_box(&face).is_some());
+ // A font's own .notdef stays as drawn.
+ let serif = db.face(DEFAULT_FAMILY, "Regular");
+ assert!(db.missing_box(&serif).is_none());
+ assert!(!db.outline(&serif, 0).elements().is_empty());
+ }
+
+ struct BezPen<'a>(&'a mut kurbo::BezPath);
+
+ impl skrifa::outline::OutlinePen for BezPen<'_> {
+ fn move_to(&mut self, x: f32, y: f32) {
+ self.0.move_to((x as f64, y as f64));
+ }
+ fn line_to(&mut self, x: f32, y: f32) {
+ self.0.line_to((x as f64, y as f64));
+ }
+ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
+ self.0.quad_to((cx0 as f64, cy0 as f64), (x as f64, y as f64));
+ }
+ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
+ self.0.curve_to((cx0 as f64, cy0 as f64), (cx1 as f64, cy1 as f64), (x as f64, y as f64));
+ }
+ fn close(&mut self) {
+ self.0.close_path();
+ }
+ }
+
#[test]
fn craft_fonts_japanese_faces_cover_japanese_and_have_vertical_forms() {
if CRAFT_FONTS.is_empty() {
diff --git a/crates/fonts/src/testing.rs b/crates/fonts/src/testing.rs
index beec1a70e..07361c102 100644
--- a/crates/fonts/src/testing.rs
+++ b/crates/fonts/src/testing.rs
@@ -198,3 +198,15 @@ pub fn with_table_u16(mut font: Vec<u8>, tag: &[u8; 4], at: usize, value: u16) -
font.get_mut(offset + at..offset + at + 2)?.copy_from_slice(&value.to_be_bytes());
Some(font)
}
+
+/// `font` (a TrueType font) with an empty `.notdef`: glyph 0's `loca` entry starts where it ends,
+/// so the glyph has no outline. `None` if the font has no `head`/`loca` tables.
+pub fn with_empty_notdef(mut font: Vec<u8>) -> Option<Vec<u8>> {
+ let (_, head, _) = table(&font, b"head")?;
+ let long = font.get(head + 50..head + 52)? != [0, 0];
+ let (_, loca, _) = table(&font, b"loca")?;
+ let width = if long { 4 } else { 2 };
+ let end = font.get(loca + width..loca + 2 * width)?.to_vec();
+ font.get_mut(loca..loca + width)?.copy_from_slice(&end);
+ Some(font)
+}
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index 6b57e2a53..f80ad0a65 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -273,6 +273,20 @@ mod tests {
}
}
+ #[test]
+ fn documents_saved_before_glyph_fallback_keep_their_fallback_fonts() {
+ let d = Document::new(&NewDocument::default());
+ assert!(!d.settings.glyph_fallback);
+ assert!(!load(&save(&d).unwrap()).unwrap().settings.glyph_fallback, "saved and read as off");
+ let mut on = d.clone();
+ on.settings.glyph_fallback = true;
+ assert!(load(&save(&on).unwrap()).unwrap().settings.glyph_fallback);
+ // Written before the setting existed: drawn from fallback fonts, as they were.
+ let mut v = serde_json::to_value(&d).unwrap();
+ v["settings"].as_object_mut().unwrap().remove("glyphFallback").unwrap();
+ assert!(load(&serde_json::to_vec(&v).unwrap()).unwrap().settings.glyph_fallback);
+ }
+
#[test]
fn rejects_garbage_and_newer_versions() {
assert!(load(b"nope").is_err());
diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml
index 348a29f70..c6c03363b 100644
--- a/crates/pdf/Cargo.toml
+++ b/crates/pdf/Cargo.toml
@@ -27,3 +27,4 @@ hayro-syntax = "0.7.2"
hayro-interpret = { version = "0.7.0", default-features = false, features = ["embed-fonts"] }
hayro-cmap = "0.1"
kurbo = { workspace = true }
+designcraft-fonts = { workspace = true, features = ["testing"] }
diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs
index 82ce3c821..2b385e42a 100644
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@ -201,3 +201,70 @@ fn tables_export_cell_text() {
assert!(text.contains(w), "{w} missing from {text:?}");
}
}
+
+/// What a page draws: each glyph (its text and outline bounds) and each filled path's bounds.
+fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>) {
+ use hayro_interpret::font::Glyph;
+ use hayro_interpret::{
+ BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
+ interpret_page,
+ };
+ use kurbo::Shape as _;
+ #[derive(Default)]
+ struct Rec(Vec<(String, kurbo::Rect)>, Vec<kurbo::Rect>);
+ impl Device<'_> for Rec {
+ fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
+ fn set_blend_mode(&mut self, _: BlendMode) {}
+ fn draw_path(&mut self, p: &kurbo::BezPath, xf: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {
+ self.1.push((xf * p.clone()).bounding_box());
+ }
+ fn push_clip_path(&mut self, _: &ClipPath) {}
+ fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
+ fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {
+ let text = match g.as_unicode() {
+ Some(hayro_cmap::BfString::Char(c)) => c.to_string(),
+ Some(hayro_cmap::BfString::String(s)) => s,
+ None => String::new(),
+ };
+ let bounds = match g {
+ Glyph::Outline(o) => o.outline().bounding_box(),
+ Glyph::Type3(_) => kurbo::Rect::ZERO,
+ };
+ self.0.push((text, bounds));
+ }
+ fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}
+ fn pop_clip_path(&mut self) {}
+ fn pop_transparency_group(&mut self) {}
+ }
+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");
+ let cache = InterpreterCache::new();
+ let page = &pdf.pages()[0];
+ let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
+ let mut rec = Rec::default();
+ interpret_page(page, &mut ctx, &mut rec);
+ (rec.0, rec.1)
+}
+
+#[test]
+fn missing_glyphs_print_as_boxes() {
+ // Source Serif 4 lacks 語: its .notdef box is drawn as a path, not as a .notdef glyph
+ // (which PDF/A and PDF/UA forbid).
+ let boxes = |paths: &[kurbo::Rect]| paths.iter().filter(|r| r.width() > 1.0 && r.width() < 12.0 && r.height() > 3.0 && r.height() < 12.0).count();
+ let d = doc_with_text("a語b");
+ assert!(!d.settings.glyph_fallback);
+ let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap());
+ assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["a", "b"], "{glyphs:?}");
+ assert_eq!(boxes(&paths), 1, "{paths:?}");
+ let a = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..Default::default() });
+ assert!(a.is_ok(), "PDF/A takes the box: {:?}", a.err());
+ // A font whose .notdef is empty: the box DesignCraft draws for it.
+ const FAMILY: &str = "DC Test PDF Empty Notdef";
+ let font = designcraft_fonts::testing::font_mapping(FAMILY, &[('a', 'a'), ('b', 'b')]).unwrap();
+ designcraft_fonts::FontDb::global().add_font(designcraft_fonts::testing::with_empty_notdef(font).unwrap());
+ let mut d = doc_with_text("a語b");
+ let sid = *d.stories.keys().next().unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."a語b".len(), |f| f.over.font_family = Some(FAMILY.into()));
+ let (glyphs, paths) = drawn(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap());
+ assert_eq!(glyphs.iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["a", "b"], "{glyphs:?}");
+ assert_eq!(boxes(&paths), 1, "{paths:?}");
+}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index cf22083a4..7fd8e3654 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -27,8 +27,11 @@ fn is_marker(c: char) -> bool {
('\u{E000}'..='\u{E1FF}').contains(&c)
}
+/// Can `b` join the run `a` is in? A missing glyph (.notdef) is a run of its own.
fn same_run(a: &PlacedGlyph, b: &PlacedGlyph) -> bool {
b.visible
+ && a.gid != 0
+ && b.gid != 0
&& a.face.id() == b.face.id()
&& a.style == b.style
&& (a.sx - b.sx).abs() < 1e-9
@@ -277,6 +280,11 @@ impl Exporter<'_> {
let hs = g0.sx / g0.sy;
let skew = if st.skew != 0.0 { Affine::new([1.0, 0.0, -st.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
let origin = Affine::translate((g0.x, baseline + g0.y)) * skew * Affine::scale_non_uniform(hs, 1.0);
+ // A missing glyph is drawn as its box: PDF/A and PDF/UA forbid showing .notdef as text.
+ if g0.gid == 0 {
+ self.outline_run(s, glyphs, origin, size, fill, stroke, st.stroke_weight);
+ return;
+ }
let Some(font) = self.font(&face) else {
self.warn(format!("font `{} {}` could not be embedded; its text was drawn as outlines", face.family, face.style));
self.outline_run(s, glyphs, origin, size, fill, stroke, st.stroke_weight);
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 0fda53442..1449110f0 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -536,6 +536,11 @@ fn preferences(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
check(ui, d, "highlightHj", crate::i18n::tr(&app.ui.language, "H&J Violations"));
check(ui, d, "highlightCustomTracking", crate::i18n::tr(&app.ui.language, "Custom Tracking/Kerning"));
check(ui, d, "highlightSubstitutedFonts", crate::i18n::tr(&app.ui.language, "Substituted Fonts"));
+ if d.fields.contains_key("glyphFallback") {
+ ui.add_space(6.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Missing Glyphs")).font(semibold(12.0)));
+ check(ui, d, "glyphFallback", crate::i18n::tr(&app.ui.language, "Draw Missing Glyphs from Fallback Fonts"));
+ }
}
"advancedType" => {
ui.label(crate::rtl::widget(
@@ -1591,6 +1596,7 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
}
doc["advancedType"] = adv;
doc["overprintBlack"] = json!(d.b("overprintBlack"));
+ doc["glyphFallback"] = json!(d.b("glyphFallback"));
app.run("document.preferences", doc)
}
"newWorkspace" => app.run("window.newWorkspace", json!({"name": d.s("name")})),
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index fdf8afe2f..c3c5352de 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -2559,6 +2559,17 @@ const TABLE: &[(&str, [&str; 5])] = &[
("Interface", ["Interface", "Interface", "Interface", "Interface", "界面"]),
("Advanced Type", ["Advanced Type", "Advanced Type", "Advanced Type", "Advanced Type", "高级文字"]),
("Composition", ["Composition", "Composition", "Composition", "Composition", "排版"]),
+ ("Missing Glyphs", ["Fehlende Glyphen", "Glyphes manquants", "Glifos que faltan", "欠落グリフ", "缺失字形"]),
+ (
+ "Draw Missing Glyphs from Fallback Fonts",
+ [
+ "Fehlende Glyphen aus Ersatzschriften zeichnen",
+ "Dessiner les glyphes manquants avec des polices de substitution",
+ "Dibujar los glifos que faltan con fuentes alternativas",
+ "欠落グリフを代替フォントで表示",
+ "用后备字体绘制缺失字形",
+ ],
+ ),
("Units & Increments", ["Units & Increments", "Units & Increments", "Units & Increments", "Units & Increments", "单位与增量"]),
("Grids", ["Grids", "Grids", "Grids", "Grids", "网格"]),
("Guides & Pasteboard", ["Guides & Pasteboard", "Guides & Pasteboard", "Guides & Pasteboard", "Guides & Pasteboard", "参考线与粘贴板"]),
diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs
index fabd36da5..9f8f4e3d1 100644
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@ -971,6 +971,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[
("Interface", "الواجهة"),
("Advanced Type", "إعدادات النص المتقدمة"),
("Composition", "تنضيد النص"),
+ ("Missing Glyphs", "الحروف الناقصة"),
+ ("Draw Missing Glyphs from Fallback Fonts", "رسم الحروف الناقصة بخطوط بديلة"),
("Units & Increments", "الوحدات والزيادات"),
("Grids", "الشبكات"),
("Guides & Pasteboard", "الأدلة ولوحة اللصق"),
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 8f5401d35..bdd50d023 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -950,6 +950,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
let doc = app.session.execute("document.preferences", &json!({})).unwrap_or_default();
f["horizontalUnits"] = doc["horizontalUnits"].clone();
f["overprintBlack"] = doc["overprintBlack"].clone();
+ f["glyphFallback"] = doc["glyphFallback"].clone();
for k in ["superscriptSize", "superscriptPosition", "subscriptSize", "subscriptPosition"] {
f[format!("adv.{k}")] = json!(format!("{}", doc["advancedType"][k].as_f64().unwrap_or(0.0)));
}
diff --git a/docs/cjk.md b/docs/cjk.md
index ccb5a03dd..2ca3de2e9 100644
--- a/docs/cjk.md
+++ b/docs/cjk.md
@@ -43,7 +43,8 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built
| Kenten | the IDML kinds and a custom character, drawn as characters; no position, size, alignment, colour or font |
| Composite fonts | done: model, `style.compositeFont.*`, shaping, IDML, font list, replace and Preflight; no dialog |
| Languages | Japanese, Korean, Simplified and Traditional Chinese reach the shaper (`locl`), font fallback, line breaking and typographer's quotes; IDML language names are kept as written and recognised in their common spellings and locale codes ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`, `ja_JP`, `ko-KR`) |
-| CJK fonts | Japanese faces (Shippori Mincho first) from the optional craft-fonts build input; fallback by language (Japanese: the craft-fonts faces, then system fonts; Simplified and Traditional Chinese, Korean: system fonts); document fonts: the fonts of a `Document Fonts` folder beside an opened file belong to that document (composition, export, font menus), ahead of installed fonts of the same name, and are forgotten when it closes; Package copies every font file that draws text, fallback fonts included (licence permitting). Font files stay in memory for the session (reopening a document reuses them) and aren't read on the web |
+| Missing glyphs | as in InDesign: characters the applied font lacks are drawn as its missing-glyph box (screen and PDF) and listed by Preflight; the document setting Draw Missing Glyphs from Fallback Fonts (Preferences › Composition, off in new documents and IDML imports, on in documents saved before it existed) draws them from fallback fonts instead |
+| CJK fonts | Japanese faces (Shippori Mincho first) from the optional craft-fonts build input, in the font menus for users to apply; fallback by language (with fallback fonts on) (Japanese: the craft-fonts faces, then system fonts; Simplified and Traditional Chinese, Korean: system fonts); document fonts: the fonts of a `Document Fonts` folder beside an opened file belong to that document (composition, export, font menus), ahead of installed fonts of the same name, and are forgotten when it closes; Package copies every font file that draws text, fallback fonts included (licence permitting). Font files stay in memory for the session (reopening a document reuses them) and aren't read on the web |
| Everything else below | missing |
Known bugs to fix first:
@@ -149,9 +150,13 @@ Jidori, tsume, aki before and after, em-box alignment and the other leading mode
to IDML and listed, replaced and preflighted by their member fonts; PDF embeds the member fonts.
Remaining: the Composite Fonts dialog, and the predefined character classes (kanji, kana,
full-width symbols, punctuation, Latin, numerals) beside custom sets.
-- **Language-aware fallback**: Japanese, Simplified Chinese, Traditional Chinese and Korean each
- have their own fallback chain of system fonts (Japanese: the craft-fonts Japanese faces first);
- `locl` follows the character language (IDML language names).
+- **Missing glyphs**: InDesign doesn't substitute fonts per character: a character the applied
+ font lacks shows as the font's missing-glyph box, prints that way and is a Preflight error.
+ DesignCraft does the same, with a document setting (Draw Missing Glyphs from Fallback Fonts)
+ that draws such characters from fallback fonts instead.
+- **Language-aware fallback** (when that setting is on): Japanese, Simplified Chinese, Traditional
+ Chinese and Korean each have their own fallback chain of system fonts (Japanese: the craft-fonts
+ Japanese faces first); `locl` follows the character language (IDML language names).
- **No CJK fonts in the repo.** CJK fonts are large (15–25 MB each even subset) and documents
should name the fonts they use. The Japanese UI and document faces come from the optional
craft-fonts build input when DesignCraft is built with it (release builds are).
@@ -260,9 +265,11 @@ Each follows what an InDesign user expects.
4. **No CJK fonts in the repo**; documents carry theirs in `Document Fonts`, scoped to the
document as in InDesign. DesignCraft embeds Japanese UI and document faces only when built with
the optional craft-fonts input (release builds are).
-5. **Package copies every font that draws text**, fallback fonts included, so a package
- reproduces what is on screen.
+5. **Package copies every font that draws text**, fallback fonts included (when the document
+ draws missing glyphs from them), so a package reproduces what is on screen.
6. **Korean fallback is serif first** (Myungjo), as Chinese and Japanese fall back to Song and
Mincho: the serif faces CJK editions of layout software default to.
7. **Language names on IDML import** accept the common spellings of Simplified and Traditional
Chinese, since the exact names InDesign writes are unconfirmed without a sample file.
+8. **Missing glyphs** are drawn as the font's box and reported, as in InDesign; drawing them from
+ fallback fonts is a per-document choice, on only for documents saved before it existed.