DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #839: INDD graphics whose linked file is missing show the document's preview
aiongg588e83199b14
diff --cc crates/engine/src/cmd/interchange.rsindex befb2c58d,b5fdfa5f4..4840cbd17--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@@ -55,9 -64,8 +64,9 @@@ fn import_report_with_previewsNone}};- let designcraft_idml::Imported { document, warnings } =+ let designcraft_idml::Imported { mut document, warnings } =- designcraft_idml::import_idml_report(bytes, &read).map_err(|e| EngineError::Other(e.to_string()))?;+ designcraft_idml::import_idml_report_with_previews(bytes, &read, previews).map_err(|e| EngineError::Other(e.to_string()))?;+ resolve_pdf_crops(&mut document);#[cfg(not(target_arch = "wasm32"))]let document = {let mut document = document;diff --cc crates/idml/src/import.rsindex 96a10f7b7,56f172edf..2ab191982--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -113,24 -116,9 +124,24 @@@ pub fn import_idml_report_with_previewstop.push(c.clone());}}- let mut im = Importer::new(read_link);+ let mut im = Importer::new(read_link, previews);+ if let Some(m) = files.get("META-INF/metadata.xml") {+ let m = String::from_utf8_lossy(m);+ im.created = xmp_date(&m, "xmp:CreateDate");+ im.modified = xmp_date(&m, "xmp:ModifyDate");+ }im.run(&root, &top)?;- let document = im.finish(&root).map_err(|e| match e {+ if im.repaired_tab_lists > 0 {+ warnings.push(format!(+ "tab lists repaired to fit the limits (at most {} stops, finite positions up to {} in, leaders of at most {} characters, one stop per position): {}",+ designcraft_doc::MAX_TAB_STOPS,+ designcraft_doc::MAX_TAB_POSITION / 72.0,+ designcraft_doc::MAX_TAB_LEADER,+ im.repaired_tab_lists,+ ));+ }+ warnings.append(&mut im.warnings);+ let mut document = im.finish(&root).map_err(|e| match e {// Without its spread parts there is nothing to open: say which parts were missing.IdmlError::Invalid(msg) if !warnings.is_empty() => IdmlError::Invalid(format!("{msg} ({})", warnings.join("; "))),e => e,diff --cc crates/idml/src/tests.rsindex 54f9fb379,a522d2686..890638b5a--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -3488,185 -1480,18 +3488,201 @@@ fn type_on_a_path_keeps_its_start_and_e}}+/// Based on Parent travels as the parent pages' `AppliedMaster`; a cycle in a file is broken on+/// import with a warning.+#[test]+fn parent_based_on_round_trips_and_cycles_are_broken() {+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });+ let a = d.parents[0].id;+ let b = d.add_parent("B", "Opening", 2, 12.0, designcraft_doc::Margins::uniform(36.0));+ d.add_parent("C", "Closing", 2, 12.0, designcraft_doc::Margins::uniform(36.0));+ let set = |d: &mut Document, pi: usize, on| std::sync::Arc::make_mut(&mut d.parents[pi]).parent.as_mut().unwrap().based_on = on;+ set(&mut d, 1, Some(a));+ set(&mut d, 2, Some(b));+ let back = import_idml(&export_idml(&d)).unwrap();+ let base_of = |d: &Document, pi: usize| {+ let b = d.parents[pi].parent.as_ref().unwrap().based_on?;+ d.parents.iter().find(|p| p.id == b).and_then(|p| p.parent.as_ref()).map(|i| i.prefix.clone())+ };+ assert_eq!((base_of(&back, 0), base_of(&back, 1), base_of(&back, 2)), (None, Some("A".into()), Some("B".into())));++ set(&mut d, 0, Some(b));+ let r = import_idml_report(&export_idml(&d), &|_| None).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("A-Parent") && w.contains("cycle")), "{:?}", r.warnings);+ assert_eq!((base_of(&r.document, 0), base_of(&r.document, 1)), (None, Some("A".into())));+}++#[test]+fn object_style_effects_round_trip() {+ use designcraft_doc::{DropShadow, Effects, ObjectStyle};+ let mut d = Document::new(&NewDocument::default());+ let fx = Effects {+ drop_shadow: DropShadow { on: true, distance: 5.0, size: 12.0, opacity: 0.28, ..Default::default() },+ feather: 3.0,+ ..Default::default()+ };+ d.styles_mut().object.push(ObjectStyle { name: "Photo".into(), effects: Some(fx.clone()), ..Default::default() });+ d.styles_mut().object.push(ObjectStyle { name: "Plain".into(), fill: Some(Fill::swatch("Black")), ..Default::default() });+ let lid = d.default_layer();+ let id = designcraft_doc::ItemId(d.alloc());+ let mut it = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)));+ it.object_style = "Photo".into();+ it.effects = fx.clone();+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ // A frame that turned the style's effects off writes them off, so it doesn't take the style's.+ let id = designcraft_doc::ItemId(d.alloc());+ let mut off = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(200.0, 40.0, 300.0, 140.0)));+ off.object_style = "Photo".into();+ d.insert_item(SpreadRef::Doc(0), off, None).unwrap();++ let bytes = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut spreads = String::new();+ for i in 0..zip.len() {+ let mut f = zip.by_index(i).unwrap();+ if f.name().starts_with("Spreads/") {+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();+ }+ }+ assert!(spreads.contains(r#"<DropShadowSetting Mode="None""#) && spreads.contains(r#"<FeatherSetting Mode="None""#), "{spreads}");+ let back = import_idml(&bytes).unwrap();+ let style = |n: &str| back.styles.object.iter().find(|s| s.name == n).unwrap();+ let got = style("Photo").effects.clone().unwrap();+ let ds = &got.drop_shadow;+ assert!(ds.on && ds.size == 12.0 && (ds.opacity - 0.28).abs() < 1e-6, "{ds:?}");+ assert!((ds.distance - 5.0).abs() < 1e-6 && (ds.angle - DropShadow::default().angle).abs() < 1e-6, "{ds:?}");+ assert_eq!(got.feather, 3.0);+ assert!(style("Plain").effects.is_none());+ // The frame's effects are the style's, so it follows later edits of the style.+ let frames: Vec<_> = back.spreads[0].items.iter().filter(|i| i.object_style == "Photo").collect();+ assert_eq!(frames[0].effects, got);+ assert_eq!(frames[1].effects, Effects::default());+}++#[test]+fn object_style_effects_import_by_category_and_based_on() {+ let styles = r#"+ <ObjectStyle Self="ObjectStyle/Base" Name="Base">+ <TransparencySetting>+ <DropShadowSetting Mode="Drop" XOffset="3" YOffset="4" Size="9" Opacity="50"/>+ <FeatherSetting Mode="Standard" Width="6"/>+ </TransparencySetting>+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="false"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child">+ <Properties><BasedOn type="object">ObjectStyle/Base</BasedOn></Properties>+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true" EnableFeather="true"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Off" Name="Off">+ <TransparencySetting><DropShadowSetting Mode="Drop" Size="9"/></TransparencySetting>+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="false" EnableFeather="false"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Loop" Name="Loop">+ <Properties><BasedOn type="object">ObjectStyle/Loop</BasedOn></Properties>+ <ObjectStyleObjectEffectsCategorySettings EnableDropShadow="true"/>+ </ObjectStyle>"#;+ let d = inset_fixture("", styles);+ let fx = |n: &str| d.styles.object.iter().find(|s| s.name == n).unwrap().effects.clone();+ let base = fx("Base").unwrap();+ assert!(base.drop_shadow.on && base.drop_shadow.size == 9.0 && (base.drop_shadow.distance - 5.0).abs() < 1e-9);+ assert_eq!(base.feather, 0.0, "EnableFeather=false");+ let child = fx("Child").unwrap();+ assert_eq!((child.drop_shadow.size, child.feather), (9.0, 6.0), "settings from the BasedOn style");+ assert!(fx("Off").is_none());+ assert!(!fx("Loop").unwrap().drop_shadow.on);+}++#[test]+fn a_strokes_gradient_vector_round_trips() {+ let mut d = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default());+ let id = designcraft_doc::ItemId(d.alloc());+ let mut it = designcraft_doc::Item::new(+ id,+ d.default_layer(),+ designcraft_doc::Shape::Path,+ designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(10.0, 10.0, 110.0, 60.0)),+ );+ it.stroke.gradient_vector = Some([10.0, 35.0, 110.0, 35.0]);+ d.insert_item(designcraft_doc::SpreadRef::Doc(0), it, None).unwrap();+ let back = crate::import_idml(&crate::export_idml(&d)).unwrap();+ let v = back.spreads[0].items[0].stroke.gradient_vector.unwrap();+ assert!(v.iter().zip([10.0, 35.0, 110.0, 35.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{v:?}");+}++#[test]+fn feather_choke_and_corners_round_trip() {+ use designcraft_doc::{Effects, FeatherCorners, FeatherOptions, Item, ItemId, ObjectStyle};+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let feathers = [(6.0, 40.0, FeatherCorners::Sharp), (4.0, 0.0, FeatherCorners::Rounded), (3.0, 12.5, FeatherCorners::Diffused)];+ let fx = |(w, choke, corners): (f64, f64, FeatherCorners)| Effects {+ feather: w,+ feather_options: FeatherOptions { choke, corners },+ ..Default::default()+ };+ for (i, f) in feathers.into_iter().enumerate() {+ let x = 40.0 + 120.0 * i as f64;+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, 40.0, x + 100.0, 140.0)));+ it.effects = fx(f);+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ }+ let styled = fx((5.0, 25.0, FeatherCorners::Rounded));+ d.styles_mut().object.push(ObjectStyle { name: "Soft".into(), effects: Some(styled.clone()), ..Default::default() });+ let back = import_idml(&export_idml(&d)).unwrap();+ let got: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();+ assert_eq!(got, feathers.map(fx));+ let style = back.styles.object.iter().find(|s| s.name == "Soft").and_then(|s| s.effects.clone()).unwrap();+ assert_eq!((style.feather, style.feather_options), (styled.feather, styled.feather_options));+}++#[test]+fn style_names_ending_in_a_space_and_partial_rule_overrides_import() {+ // Nested style "Decimals " (a name with a trailing space, as InDesign allows) and a label+ // style that only recolours the rule of the style it is based on.+ let styles = STYLES+ .replace(+ r#" </RootCharacterStyleGroup>"#,+ r#" <CharacterStyle Self="CharacterStyle/Decimals " Name="Decimals " Position="Superscript"/>+ </RootCharacterStyleGroup>"#,+ )+ .replace(+ r#" </RootParagraphStyleGroup>"#,+ r#" <ParagraphStyle Self="ParagraphStyle/Price" Name="Price">+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn>+ <AllNestedStyles type="list"><ListItem type="record"><AppliedCharacterStyle type="object">CharacterStyle/Decimals </AppliedCharacterStyle><Delimiter type="enumeration">AnyCharacter</Delimiter><Repetition type="long">2</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles>+ </Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Label white" Name="Label white" RuleAbove="true" RuleAboveLineWeight="16" RuleAboveOffset="-3">+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><RuleAboveColor type="object">Color/Paper</RuleAboveColor></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Label black" Name="Label black">+ <Properties><BasedOn type="object">ParagraphStyle/Label white</BasedOn><RuleAboveColor type="object">Color/Black</RuleAboveColor></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#,+ );+ let d = import_idml(&fixture_with_table_styles(&styles, STORY)).unwrap();+ let style = |n: &str| d.styles.paragraph.iter().find(|s| s.name == n).unwrap();+ let nested = style("Price").para.nested_styles.clone().unwrap();+ assert_eq!(nested[0].style, "Decimals ", "the trailing space is part of the name");+ let white = style("Label white").para.rule_above.clone().unwrap();+ let black = style("Label black").para.rule_above.clone().unwrap();+ assert!(black.on, "the rule stays on");+ assert_eq!((black.weight, black.offset), (16.0, -3.0), "weight and offset come from the base style");+ assert_ne!(black.color, white.color, "only the colour is overridden");+}+++ #[test]+ fn missing_linked_graphics_show_their_preview_and_keep_their_link() {+ // InDesign's preview of the missing photo (a PNG header is all the importer reads: 4 × 3).+ let png: Vec<u8> = [b"\x89PNG\r\n\x1a\n".as_slice(), &[0, 0, 0, 13], b"IHDR", &4u32.to_be_bytes(), &3u32.to_be_bytes()].concat();+ let previews = std::collections::HashMap::from([("im".to_string(), png.clone())]);+ let d = crate::import_idml_report_with_previews(&fixture(), &|_| None, &previews).unwrap().document;+ let img = d.spreads.iter().flat_map(|sp| sp.items.iter()).find(|i| i.graphic().is_some()).unwrap();+ let a = &d.assets[&img.graphic().unwrap().asset];+ assert_eq!(a.data.as_slice(), png.as_slice(), "the preview shows");+ assert_eq!(a.mime, "image/png");+ assert_eq!(a.link.as_deref(), Some("/definitely/missing dir/photo.jpg"), "relinking still finds the file");+ // Without a preview it stays empty, as before.+ let d = import_idml(&fixture()).unwrap();+ assert!(d.assets.values().all(|a| a.data.is_empty() || a.link.is_none()));+ }