Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge fix/idml-missing-spread: a spread missing from the package is reported, and part names match leniently

aiongg15167058b942
diff --cc crates/engine/src/cmd/file.rs
index 875bc6d6e,74ce10c1e..3e4438b84
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -13,35 -13,14 +13,35 @@@ use crate::{DocState, EngineError, Resu
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),
- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",
+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?}",
always, file_new),
cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),
- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),
+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {
+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();
+ presets.extend(
+ s.prefs
+ .document_presets
+ .iter()
+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),
+ );
+ Ok(Value::Array(presets))
+ }),
+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,
+ "{name, …the settings file.new takes} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",
+ always, save_preset),
+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {
+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();
+ let before = s.prefs.document_presets.len();
+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));
+ if s.prefs.document_presets.len() == before {
+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));
+ }
+ ok()
+ }),
cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),
- "{path} — .designcraft, .idml, or an InDesign .indd/.indt (converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped}",
- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped (and, for .idml, package parts missing)}",
++ "{path} — .designcraft, .idml, or an InDesign .indd/.indt (converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped and, for IDML and InDesign files, package parts missing}",
always, file_open),
- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", always, file_open_bytes),
+ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt", always, file_open_bytes),
cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),
cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),
cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {
diff --cc crates/engine/src/cmd/interchange.rs
index 85157908b,a0af09f5f..898e78891
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@@ -14,7 -13,7 +14,7 @@@ pub fn specs() -> Vec<CommandSpec>
"{path?, embedImages?: true} — writes an IDML package to `path`, or returns {base64} without a path",
has_doc, export_idml),
cmd!(noundo "file.openIdml", "Open IDML", [], None,
- "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings}",
- "{path | base64, name?} — opens an IDML package as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: package parts missing, font files skipped}",
++ "{path | base64, name?} — opens an IDML package, or an InDesign document or template (.indd, .indt: converted to IDML first; its conversion warnings join `warnings`), as a new document (linked images are read next to the file or from its Links/ folder; the fonts in a `Document Fonts` folder beside it load first) → {index, documentFonts, warnings: conversion warnings, package parts missing, font files skipped}",
always, open_idml),
]
}
@@@ -50,8 -54,8 +55,9 @@@ pub fn import_report(bytes: &[u8], dir
None
}
};
- let mut document = designcraft_idml::import_idml_with(bytes, &read).map_err(|e| EngineError::Other(e.to_string()))?;
- 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()))?;
+ resolve_pdf_crops(&mut document);
#[cfg(not(target_arch = "wasm32"))]
let document = {
let mut document = document;
@@@ -64,55 -68,9 +70,55 @@@
resolve_packaged_links(&mut document, dir);
document
};
- Ok(document)
+ Ok((document, warnings))
}
+/// Placed PDFs read from IDML name their crop (`PDFCrop`): find where each box sits on its page,
+/// which the IDML reader can't (it doesn't parse PDFs). The box spans the graphic's
+/// `GraphicBounds`; a graphic without bounds takes the box's size.
+pub(crate) fn resolve_pdf_crops(d: &mut Document) {
+ use std::collections::HashMap;
+ use std::sync::Arc;
+
+ use designcraft_doc::{AssetId, Content, Item, PdfCrop};
+ let mut sizes: HashMap<AssetId, (f64, f64)> = HashMap::new();
+ for a in d.assets.values_mut() {
+ if a.pdf_crop == PdfCrop::Crop || a.pdf_box.is_some() {
+ continue;
+ }
+ let a = Arc::make_mut(a);
+ if let Some(size) = super::file::crop_pdf(a) {
+ sizes.insert(a.id, size);
+ }
+ }
+ let no_size = |i: &Item| matches!(&i.content, Content::Graphic(g) if !(g.size.0 > 0.0 && g.size.1 > 0.0) && sizes.contains_key(&g.asset));
+ fn fix(it: &mut Arc<Item>, sizes: &HashMap<AssetId, (f64, f64)>, no_size: &dyn Fn(&Item) -> bool) {
+ let mut any = false;
+ it.walk(&mut |i| any |= no_size(i));
+ if !any {
+ return;
+ }
+ let it = Arc::make_mut(it);
+ if let Content::Graphic(g) = &mut it.content
+ && let Some(size) = sizes.get(&g.asset)
+ && !(g.size.0 > 0.0 && g.size.1 > 0.0)
+ {
+ g.size = *size;
+ }
+ for k in it.children_mut().into_iter().flatten() {
+ fix(k, sizes, no_size);
+ }
+ }
+ if sizes.is_empty() {
+ return;
+ }
+ for sp in d.spreads.iter_mut().chain(d.parents.iter_mut()) {
+ for it in &mut Arc::make_mut(sp).items {
+ fix(it, &sizes, &no_size);
+ }
+ }
+}
+
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINK_PATH_BYTES: usize = 128 * 1024;
@@@ -192,17 -148,9 +198,18 @@@ pub(crate) fn open_idml(s: &mut Session
} else {
return Err(bad("file.openIdml", "missing `path` or `base64`"));
};
- let (mut d, mut warnings) = import_report(&bytes, dir.as_deref())?;
- if let Some(n) = name {
- d.title = n;
+ let mut warnings = Vec::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()));
+ conversion.idml
+ } else {
+ bytes
+ };
- let mut d = import(&bytes, dir.as_deref())?;
++ let (mut d, import_warnings) = import_report(&bytes, dir.as_deref())?;
++ warnings.extend(import_warnings);
+ if !title.is_empty() {
+ d.title = title;
}
let (fonts, faces, font_warnings) = match str_param(p, "path").filter(|_| str_param(p, "base64").is_none()) {
Some(path) => super::file::load_document_fonts(&mut d, path),
diff --cc crates/idml/src/import.rs
index defb5c40e,f983914d4..efed6534f
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -84,30 -106,52 +106,70 @@@ pub fn import_idml_report(bytes: &[u8]
}
}
let mut im = Importer::new(read_link);
+ 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 d = im.finish(&root)?;
- d.check().map_err(|e| IdmlError::Invalid(e.to_string()))?;
- Ok(d)
+ let 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,
+ })?;
+ document.check().map_err(|e| IdmlError::Invalid(e.to_string()))?;
+ Ok(Imported { document, warnings })
+ }
+
+ /// A package part name in the form the lookup compares: InDesign and other IDML writers differ
+ /// in percent-encoding, case, path separators and a leading `./` or `/`.
+ fn normalize_part_name(name: &str) -> String {
+ let decoded = percent_decode(&name.replace('\\', "/"));
+ let mut rest = decoded.as_str();
+ loop {
+ if let Some(r) = rest.strip_prefix("./") {
+ rest = r;
+ } else if let Some(r) = rest.strip_prefix('/') {
+ rest = r;
+ } else {
+ break;
+ }
+ }
+ rest.to_lowercase()
+ }
+
+ /// Decode `%XX` escapes; anything else (including a malformed escape) is kept as written.
+ pub(crate) fn percent_decode(s: &str) -> String {
+ let b = s.as_bytes();
+ let mut out = Vec::with_capacity(b.len());
+ let mut i = 0;
+ while let Some(&c) = b.get(i) {
+ if c == b'%'
+ && let (Some(h), Some(l)) = (b.get(i + 1).and_then(|h| (*h as char).to_digit(16)), b.get(i + 2).and_then(|l| (*l as char).to_digit(16)))
+ {
+ out.push((h * 16 + l) as u8);
+ i += 3;
+ continue;
+ }
+ out.push(c);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
}
+/// An XMP date property, written as an element or an attribute.
+fn xmp_date(xmp: &str, key: &str) -> Option<i64> {
+ let value = if let Some(i) = xmp.find(&format!("<{key}>")) {
+ let rest = xmp.get(i + key.len() + 2..)?;
+ rest.get(..rest.find('<')?)?
+ } else {
+ let i = xmp.find(&format!("{key}=\""))?;
+ let rest = xmp.get(i + key.len() + 2..)?;
+ rest.get(..rest.find('"')?)?
+ };
+ designcraft_doc::vars::parse_iso_date(value)
+}
+
struct ItemCtx {
/// Self → (story self, prev self, next self)
threads: Vec<(ItemId, String, String, String)>,