DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #126: Fix composite font resolution, missing-glyph diagnostics, and document-wide font replacement
aiongg988e45b0bb89
diff --cc ROADMAP.mdindex 63a0c195f,d9ae42fe9..ac8472d57--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -1,7 -1,13 +1,15 @@@# DesignCraft roadmap+- FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage.++ - 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.++ - FONT4: generated note labels resolve composite character mappings and glyph fallback while retaining a single source anchor; composed glyphs retain the actual rendered character for diagnostics.+- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.diff --cc crates/compose/src/shape.rsindex 7657f0d7f,fdba938b0..68d9788e5--- a/crates/compose/src/shape.rs+++ b/crates/compose/src/shape.rs@@@ -92,59 -86,6 +94,62 @@@ pub struct ShapedParapub range: std::ops::Range<usize>,}+/// A resolved piece of a paragraph: one character format (and overlay) over `range`.+struct Piece {+ range: std::ops::Range<usize>,+ props: CharProps,+ style: u32,+ /// Shaping settings for the style (a missing font turns glyph fallback on).+ env: TypeEnv,+ /// Hidden conditional text or tracked deletions: laid out as zero-width place-holders.+ hidden: bool,++ /// A note reference set in a composite font: its label is shaped alone, each part in the++ /// composite entry's font.++ composite_note: bool,+}++/// The style of each byte of a shaped run: `(first byte, style)` in story order.+struct StyleRuns<'a>(&'a [(usize, u32)]);++impl StyleRuns<'_> {+ fn at(&self, byte: usize) -> u32 {+ let k = self.0.partition_point(|&(start, _)| start <= byte);+ self.0.get(k.saturating_sub(1)).map_or(0, |&(_, s)| s)+ }+}++/// The attributes that decide how text is shaped: `p` with everything that only paints the+/// glyphs (colour, stroke, underline and strikethrough, skew, markers) reset, so two pieces with+/// equal keys can be shaped as one. Attributes not listed here keep pieces apart.+fn shaping_key(p: &CharProps) -> CharProps {+ let d = CharProps::default();+ CharProps {+ skew: d.skew,+ fill: d.fill,+ fill_tint: d.fill_tint,+ stroke: d.stroke,+ stroke_tint: d.stroke_tint,+ stroke_weight: d.stroke_weight,+ underline: d.underline,+ strikethrough: d.strikethrough,+ underline_weight: d.underline_weight,+ underline_offset: d.underline_offset,+ underline_color: d.underline_color,+ underline_tint: d.underline_tint,+ strikethrough_weight: d.strikethrough_weight,+ strikethrough_offset: d.strikethrough_offset,+ strikethrough_color: d.strikethrough_color,+ strikethrough_tint: d.strikethrough_tint,+ ruby: d.ruby,+ kenten: d.kenten,+ kenten_character: d.kenten_character,+ conditions: d.conditions,+ change: d.change,+ xml_tag: d.xml_tag,+ ..p.clone()+ }+}+/// Context for substitutions (page number markers).#[derive(Clone, Debug, Default)]pub struct SubstCtx {@@@ -327,12 -258,23 +331,12 @@@ pub(crate) fn shape_paralet 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))) {- pieces.push(Piece { range: a..b, props, style, env: auto_leading, hidden: true });- // Hidden conditional text: zero-width, unbreakable, undrawn place-holders keep every- // byte addressable (caret, selection) without taking space.- let face = db.face(&props.font_family, &props.font_style);- for (i, c) in story.text[a..b].char_indices() {- if c == '\n' {- continue;- }- let mut g = control_glyph(&face, &props, auto_leading, style, a + i, c);- g.ch = HIDDEN;- (g.ascent, g.descent, g.leading, g.cap, g.xh) = (0.0, 0.0, 0.0, 0.0, 0.0);- glyphs.push(g);- }++ pieces.push(Piece { range: a..b, props, style, env: auto_leading, hidden: true, composite_note: false });continue;}let is_ref = |c: char| c == designcraft_doc::FOOTNOTE_REF || c == designcraft_doc::ENDNOTE_REF;if !story.text[a..b].contains(is_ref) {- pieces.push(Piece { range: a..b, props, style, env: auto_leading, hidden: false });- shape_run(db, &story.text, a..b, &props, auto_leading, style, sub, &mut glyphs);++ pieces.push(Piece { range: a..b, props, style, env: auto_leading, hidden: false, composite_note: false });continue;}// Footnote references take the reference position / character style; endnote references@@@ -354,66 -296,44 +358,102 @@@for (i, m) in story.text[a..b].match_indices(is_ref) {let i = a + i;if k < i {- pieces.push(Piece { range: k..i, props: props.clone(), style, env: auto_leading, hidden: false });- shape_run(db, &story.text, k..i, &props, auto_leading, style, sub, &mut glyphs);++ pieces.push(Piece { range: k..i, props: props.clone(), style, env: auto_leading, hidden: false, composite_note: false });}let e = i + m.len();if m.starts_with(designcraft_doc::ENDNOTE_REF) {- pieces.push(Piece { range: i..e, props: eprops.clone(), style: estyle, env: eenv, hidden: false });- shape_run(db, &story.text, i..e, &eprops, eenv, estyle, sub, &mut glyphs);++ pieces.push(Piece { range: i..e, props: eprops.clone(), style: estyle, env: eenv, hidden: false, composite_note: false });} else {- pieces.push(Piece { range: i..e, props: rprops.clone(), style: rstyle, env: renv, hidden: false });- if let Some(composite) = styles.composite_font(&rprops.font_family) {- let label = sub.notes.get(&i).map_or("#", String::as_str);- let begin = glyphs.len();- let mut segments: Vec<(usize, usize, Option<&designcraft_doc::cjk::CompositeFontEntry>)> = Vec::new();- for (at, c) in label.char_indices() {- let entry = composite.entry(c);- if let Some((_, end, _)) = segments.last_mut().filter(|(_, _, previous)| *previous == entry) {- *end = at + c.len_utf8();- } else {- segments.push((at, at + c.len_utf8(), entry));- }- }- for (a, b, entry) in segments {- let props = composite_props(db, &rprops, entry);- let style = table.intern(db, &props);- let env = table.env_for(auto_leading, style);- let face = db.face(&props.font_family, &props.font_style);- shape_segment(db, &story.text, i..e, label.get(a..b), &props, &face, env, style, &mut glyphs, sub.vertical);- }- for (index, glyph) in glyphs[begin..].iter_mut().enumerate() {- glyph.len = if index == 0 { e - i } else { 0 };- glyph.no_break = true;- }++ if styles.composite_font(&rprops.font_family).is_some() {++ // Shaped entry by entry below, from the run's env: the composite font's own++ // name is never an installed family, so `renv` would force glyph fallback.++ pieces.push(Piece { range: i..e, props: rprops.clone(), style: rstyle, env: auto_leading, hidden: false, composite_note: true });+ } else {- shape_run(db, &story.text, i..e, &rprops, renv, rstyle, sub, &mut glyphs);++ pieces.push(Piece { range: i..e, props: rprops.clone(), style: rstyle, env: renv, hidden: false, composite_note: false });+ }}k = e;}if k < b {- pieces.push(Piece { range: k..b, props, style, env: auto_leading, hidden: false });- shape_run(db, &story.text, k..b, &props, auto_leading, style, sub, &mut glyphs);++ pieces.push(Piece { range: k..b, props, style, env: auto_leading, hidden: false, composite_note: false });+ }+ }+ let mut i = 0;+ while i < pieces.len() {+ let first = &pieces[i];+ if first.hidden {+ // Hidden conditional text: zero-width, unbreakable, undrawn place-holders keep every+ // byte addressable (caret, selection) without taking space.+ let face = db.face(&first.props.font_family, &first.props.font_style);+ for (k, c) in story.text[first.range.clone()].char_indices() {+ if c == '\n' {+ continue;+ }+ let mut g = control_glyph(&face, &first.props, first.env, first.style, first.range.start + k, c);+ g.ch = HIDDEN;+ (g.ascent, g.typo_ascent, g.descent, g.leading, g.cap, g.xh) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);+ glyphs.push(g);+ }+ i += 1;+ continue;+ }++ if first.composite_note {++ if let Some(composite) = styles.composite_font(&first.props.font_family) {++ let at = first.range.start;++ let label = sub.notes.get(&at).map_or("#", String::as_str);++ let begin = glyphs.len();++ let mut segments: Vec<(usize, usize, Option<&designcraft_doc::cjk::CompositeFontEntry>)> = Vec::new();++ for (at, c) in label.char_indices() {++ let entry = composite.entry(c);++ if let Some((_, end, _)) = segments.last_mut().filter(|(_, _, previous)| *previous == entry) {++ *end = at + c.len_utf8();++ } else {++ segments.push((at, at + c.len_utf8(), entry));++ }++ }++ for (a, b, entry) in segments {++ let props = composite_props(db, &first.props, entry);++ let style = table.intern(db, &props);++ let env = table.env_for(first.env, style);++ let face = db.face(&props.font_family, &props.font_style);++ shape_segment(db, &story.text, first.range.clone(), label.get(a..b), &props, &face, env, &StyleRuns(&[(at, style)]), &mut glyphs, sub.vertical);++ }++ for (index, glyph) in glyphs[begin..].iter_mut().enumerate() {++ glyph.len = if index == 0 { first.range.len() } else { 0 };++ glyph.no_break = true;++ }++ }++ i += 1;++ continue;++ }+ let key = shaping_key(&first.props);+ let mut j = i + 1;+ // Jidori fits its own run into whole ems: such pieces stay apart.+ while j < pieces.len()+ && first.props.jidori == 0+ && !pieces[j].hidden++ && !pieces[j].composite_note+ && pieces[j].range.start == pieces[j - 1].range.end+ && pieces[j].env.glyph_fallback == first.env.glyph_fallback+ && shaping_key(&pieces[j].props) == key+ {+ j += 1;}+ let group = &pieces[i..j];+ let range = group[0].range.start..group[j - i - 1].range.end;+ let runs: Vec<(usize, u32)> = group.iter().map(|p| (p.range.start, p.style)).collect();+ let start = glyphs.len();+ shape_run(db, &story.text, range, &first.props, first.env, &StyleRuns(&runs), sub, &mut glyphs);+ // A cluster (a ligature, a letter with its marks) that spans two styles would paint one+ // of them in the other's colour: shape those pieces apart instead.+ let spans_cut = |g: &Glyph| runs[1..].iter().any(|&(cut, _)| g.byte < cut && cut < g.byte + g.len);+ if group.len() > 1 && glyphs[start..].iter().any(spans_cut) {+ glyphs.truncate(start);+ for p in group {+ shape_run(db, &story.text, p.range.clone(), &p.props, p.env, &StyleRuns(&[(p.range.start, p.style)]), sub, &mut glyphs);+ }+ }+ i = j;}collapse_tcy(&mut glyphs, sub.vertical);ShapedPara { glyphs, range }@@@ -919,7 -830,32 +960,32 @@@ fn shape_segmentout: &mut Vec<Glyph>,vertical: bool,) {- let _ = db;+ // Generated labels need the same coverage fallback as ordinary text. Keep the+ // original marker address and one carrier even when several faces draw the label.+ if let Some(label) = replacement.filter(|_| auto_leading.glyph_fallback) {+ let lang = designcraft_doc::language_tag(&p.language);+ let mut segments: Vec<(usize, usize, Arc<FontFace>)> = Vec::new();+ for (at, c) in label.char_indices() {+ let selected = if face.covers(c) { face.clone() } else { db.fallback_for(c, face.id(), lang).unwrap_or_else(|| face.clone()) };+ if let Some((_, end, previous)) = segments.last_mut().filter(|(_, _, previous)| previous.id() == selected.id()) {+ *end = at + c.len_utf8();+ let _ = previous;+ } else {+ segments.push((at, at + c.len_utf8(), selected));+ }+ }+ if segments.iter().any(|(_, _, selected)| selected.id() != face.id()) {+ let begin = out.len();+ for (a, b, selected) in segments {- shape_segment(db, text, range.clone(), label.get(a..b), p, &selected, auto_leading, style, out, vertical);++ shape_segment(db, text, range.clone(), label.get(a..b), p, &selected, auto_leading, styles, out, vertical);+ }+ for (i, glyph) in out[begin..].iter_mut().enumerate() {+ glyph.len = if i == 0 { range.len() } else { 0 };+ glyph.no_break = true;+ }+ return;+ }+ }let (size, k, ascent, descent, leading, cap, xh, shift) = metrics(face, p, auto_leading);let hs = p.h_scale;let tracking = p.tracking / 1000.0 * p.size;diff --cc crates/compose/src/tests.rsindex 484bd5f04,860f9284c..0738c907f--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -3082,83 -1878,84 +3082,165 @@@ fn vertical_lines_fit_the_em_box()}}+/// A drop cap set in one of the document's own fonts measures its side bearing in that font.+#[test]+fn drop_cap_in_a_document_font_aligns_its_left_edge() {+ use designcraft_geom::Shape as _;+ const FAMILY: &str = "DocFont Drop Cap";+ let text = format!("Once {LOREM}");+ let mut chars: Vec<char> = text.chars().collect();+ chars.sort_unstable();+ chars.dedup();+ let folder = std::env::temp_dir().join(format!("dc-compose-dropcap-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("dropcap.ttf"), designcraft_fonts::testing::font_with_glyph(FAMILY, &chars, 'O').unwrap()).unwrap();+ let scope = designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope;+ let para = ParaAttrs { left_indent: Some(10.0), ..drop_cap(2, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let dc = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(dc.face.family, FAMILY);+ let ink_left = dc.x + designcraft_fonts::FontDb::global().outline(dc.face.get(), dc.gid).bounding_box().x0 * dc.sx;+ assert!(ink_left - dc.x > 0.5, "the O has a visible side bearing");+ assert!((ink_left - 10.0).abs() < 1e-6, "ink at {ink_left}");+ let _ = std::fs::remove_dir_all(&folder);+}++#[test]+fn embedded_text_frames_compose_and_footnotes_retain_object_sources() {+ use designcraft_doc::{AnchorPosition, AnchoredObject};+ let (mut d, body, _) = doc_with("Body", Rect::new(20.0, 20.0, 400.0, 600.0), ParaAttrs::default());+ let (fid, child) =+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 40.0), d.default_layer(), "Embedded", ParaFormat::default()).unwrap();+ let item = d.item(fid).unwrap().clone();+ d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != fid);+ let story = d.story_mut(body).unwrap();+ story.insert_note(4, "Note", ParaFormat::default());+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 0.0 }));+ d.check().unwrap();+ let child_cs = compose_story(&d, child, &ComposeOptions::default());+ assert!(!child_cs.is_overset());+ assert!(!child_cs.frame(fid).unwrap().lines.is_empty());+ let cs = compose_story(&d, body, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let note = &cs.frames[0].notes[0];+ assert_eq!(note.text.story, StoryId(0));+ assert_eq!(note.text.frames[0].objects[0].object.item.id, fid);++ let cache = Cache::new();+ assert!(!cache.get(&d, child, None).is_overset());+ let note = Arc::make_mut(&mut d.story_mut(body).unwrap().notes[0]);+ let anchor = Arc::make_mut(&mut note.text.objects[0]);+ let original_path = anchor.item.path.clone();+ anchor.item.path = designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 1.0));+ assert!(cache.get(&d, child, None).is_overset(), "embedded frame geometry must invalidate cached composition");+ Arc::make_mut(&mut Arc::make_mut(&mut d.story_mut(body).unwrap().notes[0]).text.objects[0]).item.path = original_path;++ // A reference back into the owning story must be rejected before rendering.+ let mut cycle = d.anchored_item(fid).unwrap().clone();+ cycle.id = ItemId(d.alloc());+ cycle.text_frame_mut().unwrap().story = body;+ d.story_mut(body).unwrap().frames.push(cycle.id);+ d.story_mut(child).unwrap().insert_object(0, AnchoredObject::new(cycle, AnchorPosition::Inline { y_offset: 0.0 }));+ assert!(d.check().unwrap_err().to_string().contains("cyclic"));+}++#[test]+fn inline_object_only_line_does_not_reserve_phantom_font_descent() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, Item, Shape};+ let (mut d, sid, _) = doc_with("", Rect::new(0.0, 0.0, 10.0, 15.0), ParaAttrs::default());+ let item = Item::new(ItemId(d.alloc()), d.default_layer(), Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 7.0, 9.0)));+ d.story_mut(sid).unwrap().insert_object(0, AnchoredObject::new(item, AnchorPosition::Inline { y_offset: 5.0 }));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_eq!(cs.frames[0].objects.len(), 1);+ assert_eq!(cs.frames[0].lines[0].descent, 0.0);+ // Genuine geometric overflow must still be reported.+ d.story_mut(sid).unwrap().objects[0] =+ Arc::new(AnchoredObject::new(cs.frames[0].objects[0].object.item.clone(), AnchorPosition::Inline { y_offset: 7.0 }));+ assert!(compose_story(&d, sid, &ComposeOptions::default()).is_overset());+}+++ #[test]+ fn composite_metrics_and_character_mappings_apply_inside_footnotes() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry {+ characters: "12".into(),+ family: "Source Sans 3".into(),+ relative_size: 0.8,+ horizontal_scale: 0.9,+ vertical_scale: 1.1,+ baseline_shift: 0.1,+ scale_option: false,+ ..Default::default()+ },+ CompositeFontEntry { characters: "2".into(), family: "Inter".into(), ..Default::default() },+ ],+ });+ let story = d.story_mut(sid).unwrap();+ story.insert_note(4, "A12", ParaFormat::default());+ let note = Arc::make_mut(&mut story.notes[0]);+ note.text.format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let note = &cs.frames[0].notes[0];+ let glyphs = ¬e.text.frames[0].lines[0].glyphs;+ let a = glyphs.iter().find(|g| g.byte == 0 && g.len > 0).unwrap();+ let one = glyphs.iter().find(|g| g.byte == 1 && g.len > 0).unwrap();+ let two = glyphs.iter().find(|g| g.byte == 2 && g.len > 0).unwrap();+ assert_eq!(a.face.family, "Source Serif 4");+ assert_eq!(one.face.family, "Source Sans 3");+ assert_eq!(two.face.family, "Inter");+ let style = ¬e.text.styles[one.style as usize];+ assert!((style.size - 9.6).abs() < 1e-8);+ assert!(!note.text.styles.iter().any(|s| s.missing_font));+ }++ #[test]+ fn generated_note_labels_resolve_composite_components_and_keep_one_anchor() {+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Generated Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "[]".into(), family: "Inter".into(), relative_size: 0.8, ..Default::default() },+ ],+ });+ d.footnote_options.affix_in = designcraft_doc::notes::AffixIn::Both;+ d.footnote_options.prefix = "[".into();+ d.footnote_options.suffix = "]".into();+ let story = d.story_mut(sid).unwrap();+ story.insert_note(4, "Note", ParaFormat::default());+ story.format_chars(4..7, |f| f.over.font_family = Some("Generated Mixed".into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyphs: Vec<_> = cs.frames[0].lines.iter().flat_map(|l| &l.glyphs).filter(|g| g.byte == 4).collect();+ assert_eq!(glyphs.iter().filter(|g| g.len > 0).count(), 1);+ assert_eq!(glyphs.iter().map(|g| g.rendered_char).collect::<String>(), "[1]");+ assert!(glyphs.iter().all(|g| g.gid != 0));+ assert!(glyphs.iter().filter(|g| matches!(g.rendered_char, '[' | ']')).all(|g| g.face.family == "Inter"));+ assert_eq!(glyphs.iter().find(|g| g.rendered_char == '1').unwrap().face.family, "Source Serif 4");+ assert_eq!(cs.frames[0].notes.len(), 1);+ }++ #[test]+ fn generated_note_labels_use_coverage_fallback() {+ let font = designcraft_fonts::testing::font_with("Generated Label Coverage", &['\u{E888}']).unwrap();+ designcraft_fonts::FontDb::global().add_font(font);+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());+ d.footnote_options.affix_in = designcraft_doc::notes::AffixIn::Both;+ d.footnote_options.prefix = "\u{E888}".into();+ d.footnote_options.suffix = "".into();+ d.settings.glyph_fallback = true;+ d.story_mut(sid).unwrap().insert_note(4, "Note", ParaFormat::default());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let glyph = cs.frames[0].lines.iter().flat_map(|l| &l.glyphs).find(|g| g.rendered_char == '\u{E888}').unwrap();+ assert_ne!(glyph.gid, 0);+ assert_eq!(glyph.face.family, "Generated Label Coverage");+ }diff --cc crates/engine/src/cmd/fonts.rsindex 3b173c199,83acd685b..449e37d75--- a/crates/engine/src/cmd/fonts.rs+++ b/crates/engine/src/cmd/fonts.rs@@@ -189,40 -277,100 +277,135 @@@ mod testslet 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()));+ }++ /// InDesign names a family installed in several formats `Family (OTF)`; the plain family+ /// stands for it, and a family that isn't available under either name is still missing.+ #[test]+ fn a_family_with_a_format_suffix_uses_the_plain_family() {+ 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": 15})).unwrap();+ s.execute("type.char", &json!({"fontFamily": "Source Serif 4 (OTF)", "fontStyle": "Bold"})).unwrap();+ let l = s.execute("font.list", &json!({})).unwrap();+ let entry = l.as_array().unwrap().iter().find(|f| f["family"] == "Source Serif 4 (OTF)").unwrap();+ assert_eq!((&entry["missing"], &entry["styleMissing"], &entry["source"]), (&json!(false), &json!(false), &json!("bundled")), "{l}");+ let st = s.doc().unwrap();+ let cs = s.cache.get(&st.doc, sid, None);+ let faces: Vec<_> =+ cs.frames.iter().flat_map(|f| &f.lines).flat_map(|l| &l.glyphs).filter(|g| g.visible && g.len > 0).map(|g| g.face.get()).collect();+ assert!(!faces.is_empty() && faces.iter().all(|f| f.family == "Source Serif 4" && f.style == "Bold"));+ let kinds = |s: &mut Session| {+ s.execute("preflight.run", &json!({})).unwrap()["issues"]+ .as_array()+ .unwrap()+ .iter()+ .map(|i| i["kind"].as_str().unwrap().to_string())+ .collect::<Vec<_>>()+ };+ assert!(!kinds(&mut s).iter().any(|k| k == "missingFont"));++ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": 4})).unwrap();+ s.execute("type.char", &json!({"fontFamily": "Nope (OTF)"})).unwrap();+ let l = s.execute("font.list", &json!({})).unwrap();+ assert_eq!((&l[0]["family"], &l[0]["missing"]), (&json!("Nope (OTF)"), &json!(true)), "{l}");+ assert!(kinds(&mut s).iter().any(|k| k == "missingFont"));}}++ #[cfg(test)]+ mod composite_tests {+ use super::*;+ use designcraft_doc::{+ ParaFormat,+ cjk::{CompositeFont, CompositeFontEntry},+ };++ #[test]+ fn inventory_resolves_composites_in_nested_cell_notes() {+ use designcraft_doc::{StoryId, Table, build::NewDocument};+ let mut d = Document::new(&NewDocument::default());+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "1".into(), family: "Source Sans 3".into(), ..Default::default() },+ ],+ });+ let mut story = Story::new(StoryId(d.alloc()));+ let mut table = Table::new(1, 1, 1, 0, 0, 100.0);+ let cell = &mut table.cells[0].text;+ cell.insert_note(0, "1", ParaFormat::default());+ Arc::make_mut(&mut cell.notes[0]).text.format_chars(0..1, |f| f.over.font_family = Some("Mixed".into()));+ story.insert_table(0, table);+ d.stories.insert(story.id, Arc::new(story));+ let fonts = list(&d);+ assert!(fonts.iter().any(|f| f["family"] == "Source Sans 3" && f["characters"] == 1));+ assert!(!fonts.iter().any(|f| f["family"] == "Mixed"));+ }++ #[test]+ fn preflight_and_font_list_follow_used_composite_entries_in_notes() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect": [20,20,400,600], "content":"text", "text":"Body"})).unwrap();+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ d.styles_mut().composite_fonts.push(CompositeFont {+ name: "Mixed".into(),+ entries: vec![+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },+ CompositeFontEntry { characters: "1".into(), family: "Missing Note Digits".into(), ..Default::default() },+ CompositeFontEntry { characters: "2".into(), family: "Unused Missing Digits".into(), ..Default::default() },+ ],+ });+ let sid = *d.stories.keys().next().unwrap();+ let st = d.story_mut(sid).unwrap();+ st.insert_note(4, "A1", ParaFormat::default());+ Arc::make_mut(&mut st.notes[0]).text.format_chars(0..2, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));+ let list = s.execute("font.list", &json!({})).unwrap();+ assert!(list.as_array().unwrap().iter().any(|f| f["family"] == "Missing Note Digits" && f["characters"] == 1));+ assert!(!list.to_string().contains("Unused Missing Digits"));+ let issues = s.execute("preflight.run", &json!({})).unwrap();+ let fonts: Vec<_> = issues["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "missingFont").collect();+ assert_eq!(fonts.len(), 1, "{issues}");+ assert!(fonts[0]["message"].as_str().unwrap().contains("Missing Note Digits"));+ s.execute("font.replace", &json!({"family":"Missing Note Digits", "toFamily":"Source Sans 3", "toStyle":"Regular"})).unwrap();+ let issues = s.execute("preflight.run", &json!({})).unwrap();+ assert!(issues["issues"].as_array().unwrap().iter().all(|i| i["kind"] != "missingFont"));+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].characters, "1");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].family, "Missing Note Digits");+ }+ }++ #[cfg(test)]+ mod resolution_tests {+ use super::*;++ #[test]+ fn inventory_distinguishes_missing_styles_and_replacement_chooses_an_available_style() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("frame.create", &json!({"rect":[20,20,300,400],"content":"text","text":"Body"})).unwrap();+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0..4, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.font_style = Some("Unavailable Style".into());+ });+ let before = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(before[0]["matchStatus"], "styleSubstitute");+ assert_eq!(before[0]["missing"], false);+ assert_eq!(before[0]["styleMissing"], true);+ assert_eq!(before[0]["resolvedStyle"], "Regular");+ let preflight = s.execute("preflight.run", &json!({})).unwrap();+ assert!(preflight["issues"].as_array().unwrap().iter().any(|i| i["kind"] == "missingFontStyle"));+ s.execute("font.replace", &json!({"family":"Source Sans 3","toFamily":"Source Serif 4"})).unwrap();+ let after = s.execute("font.list", &json!({})).unwrap();+ assert_eq!(after[0]["matchStatus"], "exact");+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(before, s.execute("font.list", &json!({})).unwrap());+ }+ }diff --cc crates/engine/src/cmd/preflight.rsindex f615da300,d02fc1cd5..25b9d45fd--- a/crates/engine/src/cmd/preflight.rs+++ b/crates/engine/src/cmd/preflight.rs@@@ -115,29 -76,17 +115,28 @@@ pub fn check(s: &Session, min_ppi: f64let d = &st.doc;let mut out = Vec::new();// Stories: overset and fonts.- 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();+ let mut missing: Vec<(FaceRef, Vec<char>, designcraft_doc::ItemId)> = 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);+ missing_glyphs(&cs, None, 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));- let n = story.text[cs.overset_at.unwrap_or(0).min(story.len())..].chars().count();- out.push(Issue { severity: "error", kind: "overset", message: format!("Overset text: {n} characters"), item: last.map(|i| i.0), page });+ let location = last.and_then(|f| overset_location(s, f));+ let n = story.text.get(cs.overset_at.unwrap_or(0)..).unwrap_or("").chars().count();+ let unplaced = story.frames.is_empty();+ out.push(Issue {+ severity: if unplaced { "warning" } else { "error" },+ kind: if unplaced { "unplacedStory" } else { "overset" },+ message: if unplaced {+ format!("Unplaced story {}: {n} characters have no text frame", story.id)+ } else {+ format!("Overset text: {n} characters")+ },+ item: location.map(|(item, _)| item.0).or(last.map(|i| i.0)),+ page: location.and_then(|(_, page)| page),+ });}let ranges = story.para_ranges();for (pi, pf) in story.paras.iter().enumerate() {diff --cc crates/fonts/src/fontdb.rsindex 92afc91e6,2bc2b00ed..caee15a6a--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -1267,59 -1333,8 +1382,61 @@@ impl ScopedFonts<'_>/// Style names available for `family` (Regular first, then by weight).pub fn styles(&self, family: &str) -> Vec<String> {+ self.style_traits(family).into_iter().map(|t| t.2).collect()+ }++ /// Weight and italic of a style of `family`: from the font when it is known, else from the+ /// style's name.+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {+ let base = base_style(style);+ self.style_traits(family)+ .into_iter()+ .find(|t| t.2.eq_ignore_ascii_case(base))+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))+ }++ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the+ /// family has no such style.+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {+ let (weight, cur_italic) = self.traits_of(family, current);+ let want_italic = italic.unwrap_or(cur_italic);+ let want_weight = match bold {+ Some(true) => 700.0,+ Some(false) => 400.0,+ None => weight,+ };+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];+ let widths = |s: &str| {+ let n = norm(s);+ WIDTHS.iter().filter(|w| n.contains(*w)).count()+ };+ let cur_widths = widths(current);+ self.style_traits(family)+ .into_iter()+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))+ .min_by(|a, b| {+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());+ let (ka, kb) = (key(a), key(b));+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))+ })+ .map(|t| t.2)+ }++ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),+ /// Regular first, then by weight.+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {+ let v = self.exact_style_traits(family);+ match without_format_suffix(family) {+ Some(base) if v.is_empty() => self.exact_style_traits(base),+ _ => v,+ }+ }++ fn exact_style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {+ let canonical = self.canonical_family(family);+ let family = canonical.as_deref().unwrap_or(family);let mut v: Vec<(bool, f32, String)> = self.own().iter()@@@ -1339,10 -1354,17 +1456,14 @@@}/// Resolve a family + style to a face, falling back to the closest style of the family, then to- /// Source Sans 3 Regular. Installed system fonts are found by name whatever ran before.+ /// Source Sans 3 Regular. Installed system fonts are found by name whatever ran before. A+ /// family with a format suffix (`Minion Pro (OTF)`) that isn't found is looked up without it.pub fn face(&self, family: &str, style: &str) -> Arc<FontFace> {- if let Some(f) = self.find_or_load(family, style).or_else(|| without_format_suffix(family).and_then(|base| self.find_or_load(base, style))) {- let canonical = self.canonical_family(family).unwrap_or_else(|| self.substitute_family(family));- let family = canonical.as_str();- if let Some(f) = self.find(family, style) {- return f;- }- #[cfg(not(target_arch = "wasm32"))]- if self.db.load_cataloged(family)- && let Some(f) = self.find(family, style)- {++ let canonical = self++ .canonical_family(family)++ .or_else(|| without_format_suffix(family).and_then(|base| self.canonical_family(base)))++ .unwrap_or_else(|| self.substitute_family(without_format_suffix(family).unwrap_or(family)));++ if let Some(f) = self.find_or_load(&canonical, style) {return f;}self.find(FALLBACK_FAMILY, style)@@@ -1351,32 -1373,9 +1472,21 @@@.unwrap_or_else(last_resort_face)}- /// Is `family` available (the document's, loaded, or installed on the system)?+ fn find_or_load(&self, family: &str, style: &str) -> Option<Arc<FontFace>> {+ if let Some(f) = self.find(family, style) {+ return Some(f);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if self.db.load_cataloged(family) {+ return self.find(family, style);+ }+ None+ }++ /// Is `family` available (the document's, loaded, or installed on the system), as named or+ /// without a format suffix (see [`ScopedFonts::face`])?pub fn has_family(&self, family: &str) -> bool {- self.has_exact_family(family) || without_format_suffix(family).is_some_and(|base| self.has_exact_family(base))- }-- fn has_exact_family(&self, family: &str) -> bool {- if self.own().iter().any(|f| f.family.eq_ignore_ascii_case(family)) || self.db.is_loaded(family) {- return true;- }- #[cfg(not(target_arch = "wasm32"))]- if self.db.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {- return true;- }- false- self.canonical_family(family).is_some()++ self.canonical_family(family).is_some() || without_format_suffix(family).is_some_and(|base| self.canonical_family(base).is_some())}/// A variable font's axes: (tag, name, min, default, max), empty for static fonts.diff --cc crates/idml/src/tests.rsindex f451dc397,956a5f19f..eddd42e12--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1244,209 -858,39 +1244,246 @@@ fn arabic_story_and_table_directions_suassert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);}+#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap, its character style and a nested style through it; a paragraph+ // overriding it locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ let ns = st.para.nested_styles.clone().unwrap();+ assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap+ // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}++/// InDesign's designmap lists layers back to front; `Document::layers[0]` is the front layer.+#[test]+fn layers_import_and_export_in_stacking_order() {+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <Layer Self="L1" Name="Background"/>+ <Layer Self="L2" Name="Content"/>+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#;+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/>+ <Rectangle Self="r" ItemLayer="L1">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>+ <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ </Rectangle>+ </Spread>+ </idPkg:Spread>"#;+ let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();+ let names = |d: &Document| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();+ assert_eq!(names(&d), ["Content", "Background"]);+ assert_eq!(d.spreads[0].items[0].layer, d.layers[1].id, "the rectangle stays on Background");++ let bytes = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut map = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("designmap.xml").unwrap(), &mut map).unwrap();+ let (bg, content) = (map.find(r#"Name="Background""#).unwrap(), map.find(r#"Name="Content""#).unwrap());+ assert!(bg < content, "designmap lists the back layer first");+ let back = import_idml(&bytes).unwrap();+ assert_eq!(names(&back), ["Content", "Background"]);+ assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);+}++/// Synthetic forward references: both a body anchor and a footnote anchor own+/// a group containing a text frame whose story is serialized later.+#[test]+fn round_trips_anchored_text_frames_in_body_and_footnotes() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, Content, Item, ItemId};+ use std::sync::Arc;+ let mut d = Document::new(&NewDocument::default());+ let layer = d.default_layer();+ let (_, body) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(20.0, 20.0, 400.0, 600.0), layer, "Body", ParaFormat::default()).unwrap();+ d.story_mut(body).unwrap().insert_note(4, "Note", ParaFormat::default());+ for in_note in [false, true] {+ let (frame, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 60.0, 30.0), layer, "Symbol", ParaFormat::default()).unwrap();+ let child = d.item(frame).unwrap().clone();+ d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != frame);+ let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Group, Default::default());+ group.content = Content::Group { items: vec![Arc::new(child)] };+ let anchor = AnchoredObject::new(group, AnchorPosition::Inline { y_offset: 2.0 });+ let story = d.story_mut(body).unwrap();+ if in_note {+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, anchor);+ } else {+ story.insert_object(0, anchor);+ }+ }+ d.check().unwrap();+ for _ in 0..2 {+ d = import_idml(&export_idml(&d)).unwrap();+ d.check().unwrap();+ assert_eq!(d.stories.len(), 3);+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ assert_eq!(body.notes.len(), 1);+ assert_eq!(body.objects.len(), 1);+ assert_eq!(body.notes[0].text.objects.len(), 1);+ let children: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_some()).collect();+ assert_eq!(children.len(), 2);+ for (_, item) in children {+ let story = d.story(item.text_frame().unwrap().story).unwrap();+ assert_eq!(story.text, "Symbol");+ assert_eq!(story.frames, vec![item.id]);+ }+ }+}+++ #[test]+ fn composite_references_resolve_by_identity_and_export_as_objects() {+ let map = DESIGNMAP.replace("</Document>", r#"+ <CompositeFont Self="CompositeFont/opaque%3a17" Name="Mixed%3a literal">+ <CompositeFontEntry Name="Base" FontStyle="$ID/Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>+ <CompositeFontEntry Name="Digits" CustomCharacters="0123456789" FontStyle="$ID/Bold" RelativeSize="80" HorizontalScale="90" VerticalScale="110" BaselineShift="5" ScaleOption="false"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry>+ </CompositeFont></Document>"#);+ let styles = STYLES+ .replace("<AppliedFont type=\"string\">Source Serif 4</AppliedFont>", "<AppliedFont type=\"object\">CompositeFont/opaque%3a17</AppliedFont>");+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Content>A1</Content><Footnote><ParagraphStyleRange><CharacterStyleRange><Content>B2</Content></CharacterStyleRange></ParagraphStyleRange></Footnote></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("Resources/Styles.xml", &styles),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let d = import_idml(&bytes).unwrap();+ let f = &d.styles.composite_fonts[0];+ assert_eq!(f.name, "Mixed%3a literal", "display names are not encoded identifiers");+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ for text in [body.as_ref(), &body.notes[0].text] {+ let (_, base) = d.styles.resolve_para(&text.paras[0]);+ let p = d.styles.resolve_char(&base, &text.chars[0].format);+ assert_eq!(d.styles.composite_font(&p.font_family), Some(f));+ }+ let output = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&output)).unwrap();+ let mut xml = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut xml).unwrap();+ assert!(xml.contains("<AppliedFont type=\"object\">CompositeFont/Mixed%253a literal</AppliedFont>"), "{xml}");+ let back = import_idml(&output).unwrap();+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);+ }diff --cc crates/ui-egui/src/dialogs.rsindex 57b3efa54,2ef15a776..e011da20b--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1391,7 -1369,6 +1391,11 @@@ pub fn show(app: &mut DesignApp, ctx: &_ => {}}ui.add_space(12.0);- let ok_label = if d.id == "closeDocument" { " Save " } else { " OK " };++ let ok_label = match d.id.as_str() {++ "closeDocument" => " Save ",++ "findFont" => "Replace All",++ _ => " OK ",++ };ui.horizontal(|ui| {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if ui@@@ -1404,15 -1381,9 +1408,15 @@@{result = Some(true);}- if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if d.id == "findFont" { "Done" } else { "Cancel" }))).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) {+ // An alert only has OK.- let cancel = d.id != "alert" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Cancel"))).clicked();++ let cancel = d.id != "alert" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, if d.id == "findFont" { "Done" } else { "Cancel" }))).clicked();+ if cancel || ui.input(|i| i.key_pressed(egui::Key::Escape)) {result = Some(false);}+ if d.id == "closeDocument" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Don't Save"))).clicked() {+ d.fields.insert("discard".into(), json!(true));+ result = Some(true);+ }});});});@@@ -3219,13 -2672,28 +3266,27 @@@ fn find_font(app: &mut DesignApp, ui: &ui.add_space(8.0);crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&app.ui.language, "Replace With")).font(semibold(12.0)));let db = crate::panels::fonts(app);- let menu = crate::panels::font_menu(app);+ if d.s("toFamily").is_empty() {+ d.fields.insert("toFamily".into(), json!(designcraft_fonts::FALLBACK_FAMILY));+ }- let english = app.session.prefs.show_font_names_in_english;- let fam_opts: Vec<(&str, &str)> = menu.iter().map(|f| (f.family.as_str(), f.label(english))).collect();egui::Grid::new("ff_to").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Family:"));- combo(ui, d, "toFamily", &fam_opts);+ if let Some(f) = crate::panels::font_combo(app, ui, "toFamily", &d.s("toFamily"), 170.0) {+ d.fields.insert("toFamily".into(), json!(f));+ }ui.end_row();let styles = db.styles(&d.s("toFamily"));+ if !styles.iter().any(|style| style == &d.s("toStyle")) {+ let preferred = d.s("style");+ let style = styles+ .iter()+ .find(|s| s.eq_ignore_ascii_case(&preferred))+ .or_else(|| styles.iter().find(|s| s.eq_ignore_ascii_case("Regular")))+ .or_else(|| styles.first());+ if let Some(style) = style {+ d.fields.insert("toStyle".into(), json!(style));+ }+ }let st_opts: Vec<(&str, &str)> = styles.iter().map(|s| (s.as_str(), s.as_str())).collect();crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Font Style:"));combo(ui, d, "toStyle", &st_opts);diff --cc crates/ui-egui/src/lib.rsindex f63fac31c,0d7bb8a0b..1f036cdb2--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -537,33 -497,29 +537,51 @@@ impl DesignAppif let Some(r) = menus::run_ui(self, id, ¶ms) {return r;}+ // Only user-initiated runs touch the system clipboard, never the control channel's.+ let system_clipboard = !self.in_control;+ let params = if system_clipboard { self.with_system_clipboard(id, params) } else { params };let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string());self.after_engine();+ match &r {+ Err(e) => self.status(e.clone()),+ // Copied text goes to the system clipboard too, whichever way Copy was chosen.+ Ok(v) if system_clipboard && matches!(id, "edit.copy" | "edit.cut") => {+ let text = match v.get("text").and_then(Value::as_str) {+ Some(t) => {+ self.object_clip_text = None;+ Some(t.to_string())+ }+ None if !self.native_menu => {+ self.object_clip_text = Some(self.copied_objects_text());+ self.object_clip_text.clone()+ }+ None => None,+ };+ if let (Some(t), Some(ctx)) = (text, &self.egui_ctx) {+ ctx.copy_text(t);+ ctx.request_repaint();+ }+ }+ Ok(_) => {}+ }+ if r.is_ok() && matches!(id, "file.open" | "file.openIdml" | "file.openBytes") {+ if self.ui.dialog.as_ref().is_some_and(|d| d.id == "findFont") {+ self.ui.dialog = None;+ }+ match self.session.execute("font.list", &json!({})) {+ Ok(fonts) if fonts.as_array().is_some_and(|fonts| fonts.iter().any(|f| f["missing"] == true || f["styleMissing"] == true)) => {+ self.ui.dialog = Some(dialogs::Dialog::new("findFont", json!({"_fonts": fonts, "onOpen": true})));+ }+ Err(e) => self.status(e.to_string()),+ _ => {}+ }+ }+ if r.is_ok()+ && matches!(id, "font.replace" | "edit.undo" | "edit.redo")+ && let Some(dialog) = self.ui.dialog.as_mut().filter(|d| d.id == "findFont")+ {+ dialog.fields.remove("_fonts");+ }- if let Err(e) = &r {- self.status(e.clone());- }r}@@@ -1097,117 -890,40 +1115,151 @@@ pub fn drop_key_name_text(raw: &mut egumod tests {use super::*;+ /// The Control panel's two-row groups were centred as if they were one row tall, so the second+ /// row hung below the panel and was cut off.+ #[test]+ fn control_bar_shows_its_second_row() {+ use egui_kittest::kittest::Queryable as _;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default());+ app.run("file.newSample", json!({})).unwrap();+ app.ui.control_bar = true;+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let ctx = ui.ctx().clone();+ app.logic(&ctx);+ app.ui(ui);+ },+ app,+ );+ h.run_steps(4);+ let bar = egui::containers::panel::PanelState::load(&h.ctx, egui::Id::new("control_bar")).unwrap().outer_rect;+ assert!(bar.height() > 40.0, "{bar:?}");+ let rows: Vec<egui::Rect> = h.query_all_by_label("Y:").map(|n| n.rect()).filter(|r| bar.contains(r.left_top())).collect();+ assert_eq!(rows.len(), 1, "the Y: caption of the Control panel");+ assert!(rows[0].bottom() <= bar.bottom(), "Y: caption {:?} hangs below the Control panel {bar:?}", rows[0]);+ }++ #[test]+ fn key_names_sent_as_text_are_dropped() {+ let text = |t: &str| egui::Event::Text(t.to_string());+ let events = || {+ vec![text("AltGraph"), text("é"), text("Dead"), text("A"), text("Unidentified"), text("ß"), text("AudioVolumeUp"), text("ab"), text("Æ")]+ };+ let mut raw = egui::RawInput { events: events(), ..Default::default() };+ drop_key_name_text(&mut raw, false);+ assert_eq!(raw.events, vec![text("é"), text("A"), text("ß"), text("ab"), text("Æ")]);+ // A focused text field gets its text from input events, which can be whole words.+ let mut raw = egui::RawInput { events: events(), ..Default::default() };+ drop_key_name_text(&mut raw, true);+ assert_eq!(raw.events, events());+ }++ /// An app with one document that has an unsaved edit.+ fn app_with_unsaved_document() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default());+ app.run("file.new", json!({})).unwrap();+ assert!(!app.session.documents()[0].is_dirty(), "a new document has nothing to save");+ app.run("frame.create", json!({"rect": [36, 36, 136, 136]})).unwrap();+ assert!(app.session.documents()[0].is_dirty());+ app+ }++ /// File ▸ Close (and its shortcut) closed a document with unsaved changes without asking, and+ /// closing discards the document's recovery data too.+ #[test]+ fn closing_an_unsaved_document_asks_first() {+ let mut app = app_with_unsaved_document();+ menus::activate(&mut app, "file.close", &Value::Null);+ assert_eq!(app.session.documents().len(), 1, "the document stays open until the user answers");+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument"));+ // Cancel: nothing happens.+ app.ui.dialog = None;+ assert!(app.session.documents()[0].is_dirty());+ // The tab's × asks too.+ menus::close_document(&mut app, Some(0));+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("closeDocument"));+ assert_eq!(app.session.documents().len(), 1);+ }++ #[test]+ fn closing_without_saving_discards_the_document() {+ let mut app = app_with_unsaved_document();+ menus::close_document(&mut app, None);+ app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));+ dialogs::confirm(&mut app).unwrap();+ assert!(app.session.documents().is_empty());+ assert!(app.ui.dialog.is_none());+ }++ #[test]+ fn closing_with_save_writes_the_file_then_closes() {+ let mut app = app_with_unsaved_document();+ let path = std::env::temp_dir().join(format!("designcraft-close-test-{}.designcraft", std::process::id()));+ app.run("file.saveAs", json!({"path": path})).unwrap();+ let saved = std::fs::metadata(&path).unwrap().len();+ app.run("frame.create", json!({"rect": [200, 200, 300, 300]})).unwrap();+ menus::close_document(&mut app, None);+ dialogs::confirm(&mut app).unwrap();+ assert!(app.session.documents().is_empty());+ let written = std::fs::metadata(&path).unwrap().len();+ std::fs::remove_file(&path).unwrap();+ assert!(written > saved, "the second frame was saved ({saved} → {written} bytes)");+ }++ /// Save on a document that has no file opens the file picker; cancelling it must not close the+ /// document. (No picker service here: the same as cancelling.)+ #[test]+ fn a_cancelled_save_keeps_the_document_open() {+ let mut app = app_with_unsaved_document();+ menus::close_document(&mut app, None);+ dialogs::confirm(&mut app).unwrap();+ assert_eq!(app.session.documents().len(), 1);+ assert!(app.session.documents()[0].is_dirty());+ }++ #[test]+ fn closing_a_saved_document_does_not_ask() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Services::default());+ app.run("file.new", json!({})).unwrap();+ menus::activate(&mut app, "file.close", &Value::Null);+ assert!(app.session.documents().is_empty());+ assert!(app.ui.dialog.is_none());+ }++ #[test]+ fn opening_missing_fonts_offers_repeated_replacement_and_keeps_errors_visible() {+ let mut app = DesignApp::new(Session::new(), Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect":[0,0,200,200], "content":"text", "text":"Sample"})).unwrap();+ let d = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc);+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0..6, |f| {+ f.over.font_family = Some("Unavailable Test Family".into());+ f.over.font_style = Some("Regular".into());+ });+ let path = std::env::temp_dir().join(format!("designcraft-font-open-{}.designcraft", std::process::id()));+ app.run("file.save", json!({"path":path})).unwrap();+ app.run("file.open", json!({"path":path})).unwrap();+ let dialog = app.ui.dialog.as_mut().unwrap();+ assert_eq!(dialog.id, "findFont");+ assert_eq!(dialog.fields["onOpen"], true);+ dialog.fields.insert("family".into(), json!("Unavailable Test Family"));+ dialog.fields.insert("style".into(), json!("Regular"));+ dialog.fields.insert("toFamily".into(), json!("Unavailable Target"));+ dialog.fields.insert("toStyle".into(), json!("Regular"));+ assert!(dialogs::confirm(&mut app).is_err());+ assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("error"));+ app.ui.dialog.as_mut().unwrap().fields.insert("toFamily".into(), json!("Source Sans 3"));+ dialogs::confirm(&mut app).unwrap();+ assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("_fonts"));+ assert!(app.run("font.list", json!({})).unwrap().as_array().unwrap().iter().all(|f| f["missing"] == false));+ app.ui.dialog = None;+ app.run("file.save", json!({"path":path})).unwrap();+ app.run("file.open", json!({"path":path})).unwrap();+ assert!(app.ui.dialog.is_none());+ std::fs::remove_file(path).unwrap();+ }+#[test]fn snap_view_uses_the_saved_switches() {let mut ui = UiState::default();