DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Integration: #839 previews keep the link's format and pixel size, share one buffer per preview, and preflight still reports their missing links
aionggb14e5feae704
diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rsindex 4840cbd17..39bf923be 100644--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@ -47,7 +47,7 @@ pub fn import_report(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<(Docfn import_report_with_previews(bytes: &[u8],dir: Option<&std::path::Path>,- previews: &std::collections::HashMap<String, Vec<u8>>,+ previews: &std::collections::HashMap<String, std::sync::Arc<Vec<u8>>>,) -> Result<(Document, Vec<String>)> {#[cfg(not(target_arch = "wasm32"))]let resolved = std::cell::RefCell::new(std::collections::HashMap::new());@@ -239,14 +239,16 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {};let mut warnings = Vec::new();// InDesign's previews of linked graphics show while their files are missing (graphic `Self` →- // preview), as InDesign shows them.+ // preview), as InDesign shows them. One preview can stand for any number of graphics: they+ // share its buffer.let mut previews = std::collections::HashMap::new();let bytes = if is_indd(&file, &bytes) {let conversion = indd::convert(&bytes, &file).map_err(|e| EngineError::Other(format!("can't convert the InDesign file: {e}")))?;warnings.extend(conversion.warnings.iter().map(|w| w.message().to_string()));for p in conversion.previews {+ let data = std::sync::Arc::new(p.data);for g in p.graphics {- previews.insert(g, p.data.clone());+ previews.insert(g, std::sync::Arc::clone(&data));}}conversion.idmldiff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rsindex 89d256e02..ea472a7e7 100644--- a/crates/engine/src/cmd/links.rs+++ b/crates/engine/src/cmd/links.rs@@ -126,6 +126,21 @@ fn uses(d: &Document, aid: AssetId) -> Vec<ItemId> {out}+/// Whether an asset's linked file is gone ([`status`] "missing" without reading the file). An+/// asset can hold data while its file is missing: the document's preview of it.+pub fn link_missing(a: &designcraft_doc::Asset) -> bool {+ let Some(path) = &a.link else { return false };+ #[cfg(not(target_arch = "wasm32"))]+ {+ std::fs::metadata(path).is_err()+ }+ #[cfg(target_arch = "wasm32")]+ {+ let _ = path;+ false+ }+}+/// Link status of an asset.pub fn status(a: &designcraft_doc::Asset) -> &'static str {let Some(path) = &a.link else { return "embedded" };diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rsindex f92bd70f4..7ae80a1bb 100644--- a/crates/engine/src/cmd/preflight.rs+++ b/crates/engine/src/cmd/preflight.rs@@ -251,7 +251,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {match &it.content {Content::Graphic(g) => match d.assets.get(&g.asset) {None => out.push(Issue { severity: "error", kind: "missingLink", message: "Missing graphic".into(), item: Some(it.id.0), page }),- Some(a) if a.data.is_empty() => out.push(Issue {+ Some(a) if a.data.is_empty() || super::links::link_missing(a) => out.push(Issue {severity: "error",kind: "missingLink",message: format!("Missing link: {}", a.link.as_deref().unwrap_or(&a.name)),@@ -339,6 +339,23 @@ mod placed_vector_tests {r["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "lowResolution").map(|i| i["message"].as_str().unwrap()).collect();assert_eq!(low, ["photo.png: effective 10 ppi (< 150)"]);}++ /// An .indd opened without its links shows each graphic's preview: the asset has data, but its+ /// file is still missing.+ #[test]+ fn a_missing_link_shown_by_its_preview_is_still_reported() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![200; 40 * 20 * 4] }.to_png();+ s.execute("file.place", &json!({"base64": base64_encode(&png), "name": "photo.jpg", "x": 72, "y": 72, "width": 20})).unwrap();+ let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);+ let asset = doc.assets.values_mut().next().unwrap();+ std::sync::Arc::make_mut(asset).link = Some("/definitely/missing dir/photo.jpg".into());+ let r = s.execute("preflight.run", &json!({})).unwrap();+ let missing: Vec<&str> =+ r["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "missingLink").map(|i| i["message"].as_str().unwrap()).collect();+ assert_eq!(missing, ["Missing link: /definitely/missing dir/photo.jpg"]);+ }}#[cfg(test)]diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 2ab191982..f84c367f3 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -79,7 +79,7 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<upub fn import_idml_report_with_previews(bytes: &[u8],read_link: &dyn Fn(&str) -> Option<Vec<u8>>,- previews: &HashMap<String, Vec<u8>>,+ previews: &HashMap<String, Arc<Vec<u8>>>,) -> Result<Imported> {let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;let mut files: HashMap<String, Vec<u8>> = HashMap::new();@@ -221,7 +221,7 @@ struct ItemCtx {struct Importer<'r> {read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>,/// Graphic `Self` → stand-in image for a linked file that can't be read.- previews: &'r HashMap<String, Vec<u8>>,+ previews: &'r HashMap<String, Arc<Vec<u8>>>,next_id: u64,settings: DocSettings,default_margins: Option<(Margins, Columns)>,@@ -412,7 +412,7 @@ fn tint(v: Option<f64>) -> Option<f32> {}impl<'r> Importer<'r> {- fn new(read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>, previews: &'r HashMap<String, Vec<u8>>) -> Self {+ fn new(read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>, previews: &'r HashMap<String, Arc<Vec<u8>>>) -> Self {let specials: Vec<Swatch> = designcraft_color::default_swatches().into_iter().filter(|s| s.locked).collect();let mut swatch_names = HashMap::new();swatch_names.insert("Swatch/None".to_string(), swatch::NONE.to_string());@@ -2923,13 +2923,10 @@ impl<'r> Importer<'r> {read_from = Some(p.clone());}}- // A linked file that can't be read shows the document's preview of it, if it has one.- if data.is_empty()- && let Some(preview) = g.get("Self").and_then(|s| self.previews.get(s))- {- data = preview.clone();- }- let (mime, px) = sniff_image(&data);+ // A linked file that can't be read shows the document's preview of it, if it has one. The+ // preview only stands in for the file: format and pixel size still describe the link.+ let preview = data.is_empty().then(|| g.get("Self").and_then(|s| self.previews.get(s))).flatten();+ let (mime, px) = if preview.is_some() { (None, None) } else { sniff_image(&data) };let mime = mime.map(str::to_string).unwrap_or_else(|| match link.and_then(|k| k.get("LinkResourceFormat")).unwrap_or("") {f if f.contains("JPEG") => "image/jpeg".into(),f if f.contains("TIFF") => "image/tiff".into(),@@ -2947,7 +2944,7 @@ impl<'r> Importer<'r> {let link_path = uri.filter(|p| p.contains('/') || p.contains('\\'));let id = designcraft_doc::insert_asset(&mut self.assets,- Asset { page, id: fresh, name, mime, link: link_path, data: Arc::new(data), pixels, pdf_crop, ..Default::default() },+ Asset { page, id: fresh, name, mime, link: link_path, data: preview.cloned().unwrap_or_else(|| Arc::new(data)), pixels, pdf_crop, ..Default::default() },);if let Some(p) = read_from {self.linked_assets.insert((p, page, pdf_crop), id);diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 890638b5a..a97461491 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -3675,14 +3675,53 @@ fn style_names_ending_in_a_space_and_partial_rule_overrides_import() {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 previews = std::collections::HashMap::from([("im".to_string(), std::sync::Arc::new(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.mime, "image/jpeg", "the link's format, not the preview's");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()));}++#[test]+fn a_preview_keeps_the_links_format_and_pixel_size_and_is_shared() {+ let png: std::sync::Arc<Vec<u8>> =+ std::sync::Arc::new([b"\x89PNG\r\n\x1a\n".as_slice(), &[0, 0, 0, 13], b"IHDR", &4u32.to_be_bytes(), &3u32.to_be_bytes()].concat());+ let spread = SPREAD+ .replace(r#"<Image Self="im" ItemTransform="1 0 0 1 0 0">"#, r#"<Image Self="im" ItemTransform="1 0 0 1 0 0" ActualPpi="300 300">"#)+ .replace(+ " </Spread>",+ r#" <Rectangle Self="pf" ItemLayer="L1" ItemTransform="1 0 0 1 300 100" ContentType="GraphicType">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 30"/><PathPointType Anchor="40 30"/><PathPointType Anchor="40 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ <PDF Self="pd" ItemTransform="1 0 0 1 0 0">+ <Properties><GraphicBounds Left="0" Top="0" Right="40" Bottom="30"/></Properties>+ <Link Self="lp" LinkResourceURI="file:/definitely/missing%20dir/logo.pdf" StoredState="Normal"/>+ </PDF>+ </Rectangle>+ </Spread>"#,+ );+ let idml = 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),+ ]);+ // One preview for both graphics, as indd-utils groups them.+ let previews = std::collections::HashMap::from([("im".to_string(), png.clone()), ("pd".to_string(), png.clone())]);+ let d = crate::import_idml_report_with_previews(&idml, &|_| None, &previews).unwrap().document;+ let asset = |name: &str| d.assets.values().find(|a| a.name == name).unwrap();+ let (photo, logo) = (asset("photo.jpg"), asset("logo.pdf"));+ // 40 × 30 pt at 300 ppi, from the link, not the preview's 4 × 3.+ assert_eq!((photo.mime.as_str(), photo.pixels), ("image/jpeg", Some((167, 125))));+ assert_eq!(logo.mime, "application/pdf", "a placed PDF stays a PDF, for IDML export");+ assert!(std::sync::Arc::ptr_eq(&photo.data, &png) && std::sync::Arc::ptr_eq(&logo.data, &png), "the preview's bytes are not copied");+}