DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
INDD: graphics whose linked file is missing show InDesign's preview
Govinda Roy82ffb692fccf
diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rsindex fba6ccbf5..b5fdfa5f4 100644--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@ -40,6 +40,15 @@ pub fn import(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<Document> {/// [`import`], with the problems that did not stop it (parts missing from the package, …).pub fn import_report(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<(Document, Vec<String>)> {+ import_report_with_previews(bytes, dir, &std::collections::HashMap::new())+}++/// [`import_report`], showing `previews` (graphic `Self` → image) for linked files that can't be read.+fn import_report_with_previews(+ bytes: &[u8],+ dir: Option<&std::path::Path>,+ previews: &std::collections::HashMap<String, Vec<u8>>,+) -> Result<(Document, Vec<String>)> {#[cfg(not(target_arch = "wasm32"))]let resolved = std::cell::RefCell::new(std::collections::HashMap::new());let read = |link: &str| -> Option<Vec<u8>> {@@ -56,7 +65,7 @@ pub fn import_report(bytes: &[u8], dir: Option<&std::path::Path>) -> Result<(Doc}};let designcraft_idml::Imported { 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()))?;#[cfg(not(target_arch = "wasm32"))]let document = {let mut document = document;@@ -152,14 +161,22 @@ pub(crate) fn open_idml(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad("file.openIdml", "missing `path` or `base64`"));};let mut warnings = Vec::new();+ // InDesign's previews of linked graphics show while their files are missing (graphic `Self` →+ // preview), as InDesign shows them.+ 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 {+ for g in p.graphics {+ previews.insert(g, p.data.clone());+ }+ }conversion.idml} else {bytes};- let (mut d, import_warnings) = import_report(&bytes, dir.as_deref())?;+ let (mut d, import_warnings) = import_report_with_previews(&bytes, dir.as_deref(), &previews)?;warnings.extend(import_warnings);if !title.is_empty() {d.title = title;diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 59ca44be7..56f172edf 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -62,6 +62,17 @@ pub struct Imported {/// Import with a custom reader for linked files, reporting the problems that did not stop it.pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<Imported> {+ import_idml_report_with_previews(bytes, read_link, &HashMap::new())+}++/// [`import_idml_report`], with stand-in images for graphics whose file neither the package nor+/// `read_link` provides: `previews` maps a graphic's `Self` to an image (an InDesign document's+/// screen preview of a linked file). The graphic keeps its link, so relinking replaces it.+pub fn import_idml_report_with_previews(+ bytes: &[u8],+ read_link: &dyn Fn(&str) -> Option<Vec<u8>>,+ previews: &HashMap<String, 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();// Normalised part name → entry name, first entry wins (zip order, so the choice is stable).@@ -105,7 +116,7 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<utop.push(c.clone());}}- let mut im = Importer::new(read_link);+ let mut im = Importer::new(read_link, previews);im.run(&root, &top)?;let document = im.finish(&root).map_err(|e| match e {// Without its spread parts there is nothing to open: say which parts were missing.@@ -159,6 +170,8 @@ 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>>,next_id: u64,settings: DocSettings,default_margins: Option<(Margins, Columns)>,@@ -259,7 +272,7 @@ fn tint(v: Option<f64>) -> Option<f32> {}impl<'r> Importer<'r> {- fn new(read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>) -> Self {+ fn new(read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>, previews: &'r HashMap<String, 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());@@ -271,6 +284,7 @@ impl<'r> Importer<'r> {styles.paragraph.iter_mut().for_each(|s| s.based_on = None);Importer {read_link,+ previews,next_id: 0,settings: DocSettings::default(),default_margins: None,@@ -2318,6 +2332,12 @@ 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);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(),diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rsindex 0526070d0..949b8ad49 100644--- a/crates/idml/src/lib.rs+++ b/crates/idml/src/lib.rs@@ -49,7 +49,7 @@ mod xml;mod tests;pub use export::{ExportOptions, export_idml, export_idml_with};-pub use import::{Imported, import_idml, import_idml_report, import_idml_with};+pub use import::{Imported, import_idml, import_idml_report, import_idml_report_with_previews, import_idml_with};/// The IDML package mimetype (content of the first, stored `mimetype` entry).pub const MIMETYPE: &str = "application/vnd.adobe.indesign-idml-package";diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex a2ee8f2d5..a522d2686 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -1479,3 +1479,19 @@ fn type_on_a_path_keeps_its_start_and_end_brackets() {assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");}}++#[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()));+}