DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
M2: Find/Replace Font and missing-font highlighting
Brandon Thomas69563933be61
diff --git a/ROADMAP.md b/ROADMAP.mdindex de45c6f39..4205ec896 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -24,6 +24,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Anchored objects: items flow in the text inline (on the baseline, with Y offset; lines grow to fit) or above the line (left/center/right, space before/after); paste copied items into text to anchor them; Anchored Object Options and Release (back onto the page where shown); rendered, exported to PDF and to/from IDML (InDesign anchored object settings; verified in InDesign 2026); copy/paste and threading carry them; `anchored.*` commands.- 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`.- Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation.- Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page.- Soft effects: blurred drop shadow, inner shadow, outer glow, basic feather.diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex a00f12017..d17f80796 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -48,6 +48,8 @@ pub struct RunStyle {pub strikethrough: bool,pub skew: f64,pub size: f64,+ /// The run's font isn't installed (shown in a substitute; highlighted on screen).+ pub missing_font: bool,}/// A positioned glyph. `x` is absolute in frame inner space; `y` is relative to the line baseline.@@ -298,6 +300,7 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compolet db = FontDb::global();let mut out = ComposedStory { story: story.id, rev: story.rev, text_len: story.text.len(), ..Default::default() };let mut styles_tab: Vec<RunStyle> = Vec::new();+ let mut missing_fonts: HashMap<String, bool> = HashMap::new();out.frames = frames.iter().map(|f| FrameText { frame: f.id, columns: f.columns(), ..Default::default() }).collect();let cols: Vec<Vec<Rect>> = frames.iter().map(FrameSpec::columns).collect();let mut cur = Cursor { fi: 0, col: 0, last_baseline: None, last_descent: 0.0, pending: 0.0 };@@ -393,7 +396,7 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Componotes.number_refs(doc, prange.clone(), cur_frame.and_then(|f| f.page), &mut sub);}let sub_objects = sub.objects.clone();- let mut table = StyleTable { styles: &mut styles_tab };+ let mut table = StyleTable { styles: &mut styles_tab, missing: &mut missing_fonts };let mut sp = shape::shape_para(db, &doc.styles, story, pi, prange.clone(), &base_chars, pp.auto_leading, &sub, &mut table);match pp.list_type {designcraft_doc::ListType::Numbers => {diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rsindex f4dd241dd..a62640d57 100644--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@ -93,6 +93,8 @@ pub struct ObjectSpec {pub(crate) struct StyleTable<'a> {pub styles: &'a mut Vec<RunStyle>,+ /// Font availability by family (looked up once per composition).+ pub missing: &'a mut HashMap<String, bool>,}impl StyleTable<'_> {@@ -107,6 +109,10 @@ impl StyleTable<'_> {strikethrough: p.strikethrough,skew: p.skew,size: p.size,+ missing_font: *self+ .missing+ .entry(p.font_family.clone())+ .or_insert_with(|| !p.font_family.is_empty() && !designcraft_fonts::FontDb::global().has_family(&p.font_family)),};if let Some(i) = self.styles.iter().rposition(|s| *s == rs) {return i as u32;diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rsnew file mode 100644index 000000000..8dd4c8e28--- /dev/null+++ b/crates/engine/src/cmd/fonts.rs@@ -0,0 +1,163 @@+//! Type › Find/Replace Font: the fonts a document uses (missing ones flagged) and replacing one+//! font with another everywhere — local formatting and style definitions.++use std::collections::BTreeMap;+use std::sync::Arc;++use designcraft_doc::{CharAttrs, Document, Story};+use serde_json::{Value, json};++use super::{CommandSpec, bad, cmd, has_doc, str_param};+use crate::{Result, Session};++pub fn specs() -> Vec<CommandSpec> {+ vec![+ cmd!(query "font.list", "Fonts in Document", [], None, "{} → [{family, style, characters, missing, styleMissing}] (missing first)", has_doc, |s, _| {+ Ok(Value::Array(list(&s.doc()?.doc)))+ }),+ cmd!(+ "font.replace",+ "Find/Replace Font…",+ ["Type"],+ None,+ "{family, style?, toFamily, toStyle?, redefineStyles?: true} — replaces the font in text and (by default) in paragraph and character styles",+ has_doc,+ replace+ ),+ ]+}++/// Every story's text, including table cells and footnotes.+fn for_each_story(d: &Document, f: &mut dyn FnMut(&Story)) {+ for st in d.stories.values() {+ f(st);+ for t in st.tables.values() {+ for c in &t.cells {+ f(&c.text);+ }+ }+ for n in &st.notes {+ f(&n.text);+ }+ }+}++fn list(d: &Document) -> Vec<Value> {+ let db = designcraft_fonts::FontDb::global();+ let mut used: BTreeMap<(String, String), usize> = BTreeMap::new();+ for_each_story(d, &mut |st| {+ let ranges = st.para_ranges();+ for (pi, r) in ranges.iter().enumerate() {+ let (_, base) = d.styles.resolve_para(&st.paras[pi]);+ for (rr, fmt) in st.runs() {+ let n = st.text[rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))].chars().count();+ if n == 0 && !(r.is_empty() && rr.contains(&r.start)) {+ continue;+ }+ let p = d.styles.resolve_char(&base, fmt);+ *used.entry((p.font_family, p.font_style)).or_default() += n;+ }+ }+ });+ let mut out: Vec<(bool, Value)> = used+ .into_iter()+ .map(|((family, style), n)| {+ let missing = !db.has_family(&family);+ let style_missing = !missing && !db.styles(&family).iter().any(|s| s.eq_ignore_ascii_case(&style));+ (missing || style_missing, json!({"family": family, "style": style, "characters": n, "missing": missing, "styleMissing": style_missing}))+ })+ .collect();+ out.sort_by_key(|(m, _)| !*m);+ out.into_iter().map(|(_, v)| v).collect()+}++/// Replace the font in a sparse attribute set (only where the family is set); true when it changed.+fn swap(a: &mut CharAttrs, family: &str, style: Option<&str>, to_family: &str, to_style: Option<&str>) -> bool {+ let fam_ok = a.font_family.as_deref().is_some_and(|f| f.eq_ignore_ascii_case(family));+ let style_ok = style.is_none_or(|s| a.font_style.as_deref().is_some_and(|x| x.eq_ignore_ascii_case(s)));+ if !fam_ok || !style_ok {+ return false;+ }+ a.font_family = Some(to_family.to_string());+ if let Some(ts) = to_style {+ a.font_style = Some(ts.to_string());+ }+ true+}++fn replace(s: &mut Session, p: &Value) -> Result<Value> {+ let family = str_param(p, "family").ok_or_else(|| bad("font.replace", "missing family"))?.to_string();+ let style = str_param(p, "style").map(str::to_string);+ let to_family = str_param(p, "toFamily").ok_or_else(|| bad("font.replace", "missing toFamily"))?.to_string();+ let to_style = str_param(p, "toStyle").map(str::to_string);+ let styles_too = p.get("redefineStyles").and_then(Value::as_bool).unwrap_or(true);+ s.edit(|d, _| {+ let mut changed = 0usize;+ if styles_too {+ let st = d.styles_mut();+ for ps in &mut st.paragraph {+ changed += swap(&mut ps.chars, &family, style.as_deref(), &to_family, to_style.as_deref()) as usize;+ }+ for cs in &mut st.character {+ changed += swap(&mut cs.chars, &family, style.as_deref(), &to_family, to_style.as_deref()) as usize;+ }+ }+ // Local formatting in every story (cells and footnotes too).+ let fix = |st: &mut Story, changed: &mut usize| {+ let mut any = false;+ for r in &mut st.chars {+ if swap(&mut r.format.over, &family, style.as_deref(), &to_family, to_style.as_deref()) {+ any = true;+ *changed += 1;+ }+ }+ if any {+ st.rev += 1;+ }+ };+ let ids: Vec<_> = d.stories.keys().copied().collect();+ for sid in ids {+ let Some(st) = d.story_mut(sid) else { continue };+ fix(st, &mut changed);+ for t in st.tables.values_mut() {+ for c in &mut Arc::make_mut(t).cells {+ fix(&mut c.text, &mut changed);+ }+ }+ for n in &mut st.notes {+ fix(&mut Arc::make_mut(n).text, &mut changed);+ }+ }+ Ok(json!({"changed": changed}))+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn find_and_replace_font() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 300], "content": "text", "text": "Some text here."})).unwrap();+ let sid = s.doc().unwrap().doc.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 4})).unwrap();+ s.execute("type.char", &json!({"fontFamily": "Nonexistent Sans", "fontStyle": "Bold"})).unwrap();+ let l = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(l[0]["family"], "Nonexistent Sans", "missing fonts first: {l}");+ assert_eq!(l[0]["missing"], true);+ assert_eq!(l[0]["characters"], 4);+ // Replace it with an available family.+ let avail = l.as_array().unwrap().iter().find(|f| f["missing"] == false).unwrap()["family"].as_str().unwrap().to_string();+ let r = s.execute("font.replace", &json!({"family": "Nonexistent Sans", "toFamily": avail, "toStyle": "Regular"})).unwrap();+ assert_eq!(r["changed"], 1);+ let l = s.execute("font.list", &json!({})).unwrap();+ assert!(l.as_array().unwrap().iter().all(|f| f["missing"] == false), "{l}");+ // Style definitions are redefined too.+ s.execute("style.paragraph.create", &json!({"name": "Odd", "chars": {"fontFamily": "Nonexistent Sans"}})).unwrap();+ let r = s.execute("font.replace", &json!({"family": "Nonexistent Sans", "toFamily": avail})).unwrap();+ assert_eq!(r["changed"], 1);+ assert_eq!(s.doc().unwrap().doc.styles.para("Odd").unwrap().chars.font_family.as_deref(), Some(avail.as_str()));+ }+}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 6a5fdaf9e..b212bf3dd 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -6,6 +6,7 @@ mod edit;mod export;mod file;mod find;+mod fonts;mod guides;mod index;mod inspect;@@ -134,6 +135,7 @@ pub fn command_specs() -> &'static [CommandSpec] {v.extend(anchored::specs());v.extend(guides::specs());v.extend(links::specs());+ v.extend(fonts::specs());v.extend(spelling::specs());v.extend(datamerge::specs());v.extend(interactive::specs());diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex e87ab1bf6..8d2b738b1 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -96,11 +96,21 @@ pub struct RenderOptions {pub greek_below_px: f64,/// Drop shadow on pages (screen view).pub page_shadow: bool,+ /// Pink highlight behind text set in fonts that aren't installed (screen view).+ pub highlight_missing_fonts: bool,}impl Default for RenderOptions {fn default() -> Self {- Self { background: None, paper: true, printing_only: false, hidden: vec![], greek_below_px: 0.0, page_shadow: false }+ Self {+ background: None,+ paper: true,+ printing_only: false,+ hidden: vec![],+ greek_below_px: 0.0,+ page_shadow: false,+ highlight_missing_fonts: false,+ }}}@@ -648,6 +658,28 @@ mod tests {assert!(r.stats.glyphs >= 15);}+ #[test]+ fn missing_fonts_are_highlighted_on_screen_only() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 336.0, 100.0), lid, "Missing font", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0..12, |f| f.over.font_family = Some("No Such Family".into()));+ let cache = Cache::new();+ let cs = cache.get(&d, sid, None);+ assert!(cs.styles.iter().any(|s| s.missing_font));+ let l = &cs.frames[0].lines[0];+ // A point inside the line box but between glyph strokes: the space after "Missing".+ let g = l.glyphs.iter().find(|g| g.byte == 7).unwrap();+ let (x, y) = ((g.x + g.adv / 2.0) as u32, (l.baseline - l.ascent * 0.5) as u32);+ let mut r = Renderer::new();+ r.threads = 0;+ let plain = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();+ let shown = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions { highlight_missing_fonts: true, ..Default::default() }).unwrap();+ assert_eq!(plain.pixel(x, y)[1], 255, "no highlight in output");+ let p = shown.pixel(x, y);+ assert!(p[0] > 240 && p[1] < 200, "pink on screen: {p:?}");+ }+#[test]fn renders_tables() {let mut d = Document::new(&NewDocument::default());diff --git a/crates/render/src/text.rs b/crates/render/src/text.rsindex d3610996f..fb5a39b3f 100644--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@ -201,6 +201,16 @@ impl Renderer {if !ft.tables.is_empty() {self.draw_tables(ctx, f, ft, xf);}+ // Text in fonts that aren't installed: pink behind the glyphs (screen only).+ if f.opts.highlight_missing_fonts && cs.styles.iter().any(|s| s.missing_font) {+ ctx.set_transform(m);+ ctx.set_paint(peniko::Color::from_rgb8(255, 166, 214));+ for l in &ft.lines {+ for g in l.glyphs.iter().filter(|g| g.adv > 0.0 && cs.styles.get(g.style as usize).is_some_and(|s| s.missing_font)) {+ ctx.fill_rect(&kurbo::Rect::new(g.x, l.baseline - l.ascent, g.x + g.adv, l.baseline + l.descent));+ }+ }+ }let scale = m.determinant().abs().sqrt();let greek_px = f.opts.greek_below_px;let mut greek = BezPath::new();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex eb4381a96..d0e0c8881 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -306,7 +306,12 @@ fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rect, xf: &Xf,let w = (target.size.0 as f64 * ppp).round().max(1.0) as u32;let h = (target.size.1 as f64 * ppp).round().max(1.0) as u32;let view = Affine::scale(ppp) * Affine::scale(xf.zoom) * Affine::translate((-target.origin.x, -target.origin.y));- let opts = designcraft_render::RenderOptions { printing_only: preview, greek_below_px: 3.0 * ppp, ..Default::default() };+ let opts = designcraft_render::RenderOptions {+ printing_only: preview,+ greek_below_px: 3.0 * ppp,+ highlight_missing_fonts: !preview,+ ..Default::default()+ };(st.doc.clone(), placed, w, h, view, opts)};// Synchronous path: document edits (keep editing crisp), first frame, or no worker.diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex d26d894b7..1883d491f 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -123,6 +123,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {"paragraphStyleOptions" => "Paragraph Style Options","footnoteOptions" => "Footnote Options","insertXref" => "New Cross-Reference",+ "findFont" => "Find/Replace Font",id => match id.strip_prefix("cmd:").and_then(designcraft_engine::find_command) {Some(c) => c.label.trim_end_matches('…'),None => "Dialog",@@ -256,6 +257,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {"paragraphStyleOptions" => paragraph_style_options(app, ui, &mut d),"footnoteOptions" => footnote_options(app, ui, &mut d),"insertXref" => insert_xref(app, ui, &mut d),+ "findFont" => find_font(app, ui, &mut d),id if id.starts_with("cmd:") => command_form(ui, &mut d),"goToPage" => {ui.horizontal(|ui| {@@ -405,6 +407,13 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {}app.run("style.paragraph.edit", params)}+ "findFont" => {+ let (f, st) = (d.s("family"), d.s("style"));+ if f.is_empty() || d.s("toFamily").is_empty() {+ return Ok(Value::Null);+ }+ app.run("font.replace", json!({"family": f, "style": st, "toFamily": d.s("toFamily"), "toStyle": d.s("toStyle")}))+ }"insertXref" => {let format = d.s("format");let target = d.s("target");@@ -1032,6 +1041,52 @@ fn insert_xref(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {}}+/// Find/Replace Font: the document's fonts (missing ones first, flagged) and a replacement.+fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ // Listed once when the dialog opens (it scans every story).+ if !d.fields.contains_key("_fonts") {+ let list = app.session.execute("font.list", &json!({})).unwrap_or_default();+ d.fields.insert("_fonts".into(), list);+ }+ let fonts = d.fields.get("_fonts").and_then(Value::as_array).cloned().unwrap_or_default();+ let missing = fonts.iter().filter(|f| f["missing"] == true || f["styleMissing"] == true).count();+ ui.label(format!("Fonts in Document: {} Missing: {missing}", fonts.len()));+ egui::ScrollArea::vertical().id_salt("ff_list").max_height(180.0).show(ui, |ui| {+ for f in &fonts {+ let (fam, st) = (f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""));+ let warn = f["missing"] == true || f["styleMissing"] == true;+ let label = format!("{}{fam} {st}", if warn { "\u{26A0} " } else { "" });+ let on = d.s("family") == fam && d.s("style") == st;+ let mut text = egui::RichText::new(label);+ if warn {+ text = text.color(egui::Color32::from_rgb(0xe5, 0x4b, 0x4b));+ }+ if ui.selectable_label(on, text).clicked() {+ d.fields.insert("family".into(), json!(fam));+ d.fields.insert("style".into(), json!(st));+ }+ }+ });+ ui.add_space(8.0);+ ui.label(egui::RichText::new("Replace With").font(semibold(12.0)));+ let db = designcraft_fonts::FontDb::global();+ let families = db.families();+ let fam_opts: Vec<(&str, &str)> = families.iter().map(|f| (f.as_str(), f.as_str())).collect();+ egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {+ ui.label("Font Family:");+ combo(ui, d, "toFamily", &fam_opts);+ ui.end_row();+ let styles = db.styles(&d.s("toFamily"));+ let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();+ ui.label("Font Style:");+ combo(ui, d, "toStyle", &st_opts);+ ui.end_row();+ });+ ui.label(+ egui::RichText::new("OK changes all: text and paragraph/character styles.").color(crate::theme::Tokens::get(ui.ctx()).text_dim).size(11.0),+ );+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 2e88d0cfb..a0721d8d8 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -18,6 +18,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),("app.footnoteOptionsDialog", "Document Footnote Options…", None, "{} — numbering, formatting and layout of footnotes"),+ ("app.findFontDialog", "Find/Replace Font…", None, "{} — fonts used (missing ones flagged) and replacing them"),("app.insertXrefDialog", "Insert Cross-Reference…", None, "{} — New Cross-Reference dialog (paragraph or text anchor, format)"),("app.deleteAllGuides", "Delete All Guides on Spread", None, "{} — the spread in view"),("app.deletePage", "Delete Page", None, "{} — deletes the page in view"),@@ -150,6 +151,8 @@ pub const MENUS: &[(&str, &[&str])] = &[("Type",&[+ "ui:app.findFontDialog",+ "-","cmd:type.fillWithPlaceholder",">Insert Special Character",">Symbols",@@ -455,6 +458,13 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,app.ui.dialog = Some(crate::dialogs::Dialog::new("footnoteOptions", o));Ok(Value::Null)}+ "app.findFontDialog" => {+ if app.session.active().is_none() {+ return Some(Err("no document open".into()));+ }+ app.ui.dialog = Some(crate::dialogs::Dialog::new("findFont", json!({})));+ Ok(Value::Null)+ }"app.insertXrefDialog" => {if app.session.active().is_none_or(|d| d.selection.text.is_none()) {return Some(Err("place the insertion point in text to insert a cross-reference".into()));