Skip to content

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

Merge PR #971

Brandon Thomasd5cea4f3de4a
diff --cc crates/idml/src/import.rs
index 8475e0cfb,54e1da5db..23afead97
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -123,14 -100,68 +90,76 @@@ pub fn import_idml_report(bytes: &[u8]
Ok(Imported { document, warnings })
}
+/// View Preferences › Ruler Origin.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum RulerOrigin {
+ Spread,
+ Page,
+ Spine,
+}
+
+ /// Most entries an IDML package may hold.
+ const MAX_ENTRIES: usize = 100_000;
+ /// Most bytes one package part may expand to.
+ const MAX_PART_BYTES: u64 = 512 << 20;
+ /// Most bytes all the parts read from one package may expand to together.
+ const MAX_TOTAL_BYTES: u64 = 2 << 30;
+
+ /// An IDML package whose parts are decompressed only when the import asks for them, within
+ /// byte budgets that don't trust the sizes the archive claims.
+ struct Package<'a> {
+ zip: zip::ZipArchive<std::io::Cursor<&'a [u8]>>,
+ /// Normalised part name → entry name, first entry wins (zip order, so the choice is stable).
+ lenient: HashMap<String, String>,
+ /// Bytes the parts still to be read may expand to.
+ left: u64,
+ }
+
+ impl<'a> Package<'a> {
+ fn open(bytes: &'a [u8]) -> Result<Self> {
+ let zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
+ if zip.len() > MAX_ENTRIES {
+ return Err(IdmlError::NotIdml(format!("{} entries (at most {MAX_ENTRIES})", zip.len())));
+ }
+ let mut lenient: HashMap<String, String> = HashMap::new();
+ for i in 0..zip.len() {
+ let Some(name) = zip.name_for_index(i) else { continue };
+ if name.ends_with('/') {
+ continue;
+ }
+ lenient.entry(normalize_part_name(name)).or_insert_with(|| name.to_string());
+ }
+ Ok(Package { zip, lenient, left: MAX_TOTAL_BYTES })
+ }
+
+ /// The bytes of part `name` (matched exactly, then leniently), or `None` if the package has
+ /// no such part.
+ fn part(&mut self, name: &str) -> Result<Option<Vec<u8>>> {
+ let exact = self.zip.index_for_name(name).filter(|_| !name.ends_with('/'));
+ let Some(i) = exact.or_else(|| self.lenient.get(&normalize_part_name(name)).and_then(|n| self.zip.index_for_name(n))) else {
+ return Ok(None);
+ };
+ let f = self.zip.by_index(i).map_err(|e| IdmlError::NotIdml(e.to_string()))?;
+ let part = f.name().to_string();
+ let limit = MAX_PART_BYTES.min(self.left);
+ let too_big = || IdmlError::Part {
+ part: part.clone(),
+ msg: format!("larger than the {MAX_PART_BYTES}-byte part limit (or the package is larger than {MAX_TOTAL_BYTES} bytes)"),
+ };
+ if f.size() > limit {
+ return Err(too_big());
+ }
+ let mut buf = Vec::new();
+ f.take(limit.saturating_add(1)).read_to_end(&mut buf).map_err(|e| IdmlError::Part { part: part.clone(), msg: e.to_string() })?;
+ let n = buf.len() as u64;
+ if n > limit {
+ return Err(too_big());
+ }
+ self.left = self.left.saturating_sub(n);
+ Ok(Some(buf))
+ }
+ }
+
/// 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 {
@@@ -3144,25 -3092,3 +3173,4 @@@ mod frame_preference_scalar_tests
assert_eq!(Prefs(&[&exact]).prop("ColumnRuleStrokeColor").as_deref(), Some(" Color/Named "));
}
}
+
- #[cfg(test)]
- mod part_size_tests {
- use std::io::Write;
-
- use super::*;
-
- /// A small package part can inflate to gigabytes; the read is capped, so an oversized entry
- /// is an error instead of an unbounded read.
- #[test]
- fn an_oversized_part_is_an_error_not_a_huge_read() {
- let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
- let deflated = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
- w.start_file("Stories/Story_big.xml", deflated).unwrap();
- w.write_all(&vec![b' '; 64 * 1024]).unwrap();
- let bytes = w.finish().unwrap().into_inner();
- let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
- assert!(matches!(read_part(&mut zip, 0, 4096), Err(IdmlError::Part { .. })));
- // At or under the cap reads fine: the same entry with a 64 KiB limit.
- assert_eq!(read_part(&mut zip, 0, 64 * 1024).unwrap().map(|(_, b)| b.len()), Some(64 * 1024));
- }
- }
diff --cc crates/idml/src/tests.rs
index a1ec494f7,4cc273ca1..16a0f465f
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2219,53 -2170,88 +2219,139 @@@ fn frame_preference_property_color_reso
assert_eq!(d.styles.object_style("Child").unwrap().text_frame.as_ref().unwrap().column_rule_color, "Near");
}
+/// A two-page spread with ruler guides on its pages (and one on the parent), in `origin` ruler
+/// coordinates.
+fn guides_package(origin: &str) -> Vec<u8> {
+ let prefs = PREFS.replace("</idPkg:Preferences>", &format!(r#"<ViewPreference RulerOrigin="{origin}"/></idPkg:Preferences>"#));
+ let spread = SPREAD.replace(
+ r#"<Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>"#,
+ r#"<Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350">
+ <Guide Self="g1" Orientation="Vertical" Location="40" FitToPage="true" ItemLayer="L1" Locked="true"/>
+ <Guide Self="g2" Orientation="Horizontal" Location="100" FitToPage="false"/>
+ </Page>"#,
+ );
+ let master = MASTER.replace(
+ r#"<Page Self="mp1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>"#,
+ r#"<Page Self="mp1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"><Guide Self="mg" Orientation="Vertical" Location="84"/></Page>"#,
+ );
+ 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),
+ ])
+}
+
+/// Ruler guides come in from IDML (they were dropped): on their page, measured from the ruler
+/// origin, with Fit to Page, Locked and their layer; parent pages' too. They go out again.
+#[test]
+fn ruler_guides_import_and_round_trip() {
+ use designcraft_doc::Orientation::{Horizontal, Vertical};
+ let guides = |d: &Document| {
+ let p = &d.spreads[0].pages[1];
+ p.guides.iter().map(|g| (g.orientation, g.position, g.spread, g.locked, g.layer.is_some())).collect::<Vec<_>>()
+ };
+ // The second page starts at x 500 in our spread coordinates.
+ let d = import_idml(&guides_package("PageOrigin")).unwrap();
+ assert_eq!(guides(&d), [(Vertical, 540.0, false, true, true), (Horizontal, 100.0, true, false, false)]);
+ let d = import_idml(&guides_package("SpineOrigin")).unwrap();
+ assert_eq!(guides(&d)[0].1, 540.0, "the spine is the second page's left edge");
+ let d = import_idml(&guides_package("SpreadOrigin")).unwrap();
+ assert_eq!(guides(&d)[0].1, 40.0);
+ assert_eq!(d.parents[0].pages[0].guides.len(), 1, "a parent page's guide");
+ assert_eq!(d.parents[0].pages[0].guides[0].position, 84.0);
+ // Round trip: written under each page, read back where they were.
+ let d = import_idml(&guides_package("PageOrigin")).unwrap();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(guides(&back), guides(&d));
+ assert_eq!(back.parents[0].pages[0].guides.len(), 1);
+}
++
+ /// A package entry nothing in `designmap.xml` refers to is never decompressed: a damaged one
+ /// (its checksum no longer matches) does not stop the import.
+ #[test]
+ fn unreferenced_entries_are_not_read() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for (n, c) in [
+ ("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),
+ ] {
+ w.start_file(n, SimpleFileOptions::default()).unwrap();
+ w.write_all(c.as_bytes()).unwrap();
+ }
+ w.start_file("junk/irrelevant.bin", stored).unwrap();
+ w.write_all(b"<<payload-of-an-unused-entry>>").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ let at = bytes.windows(9).position(|w| w == b"<<payload").unwrap();
+ bytes[at] = b'X';
+ let d = import_idml(&bytes).unwrap();
+ assert_eq!(d.spreads.len(), 1);
+ }
+
+ /// A part that expands past the 512 MiB limit while claiming to hold one byte is refused once the
+ /// limit is reached, with an error that says so, instead of being read whole into memory.
+ #[test]
+ fn oversized_part_is_refused() {
+ use zip::write::SimpleFileOptions;
+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">
+ <idPkg:Story src="Stories/Story_big.xml"/>
+ </Document>"#;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ w.start_file("mimetype", SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored)).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ w.start_file("designmap.xml", SimpleFileOptions::default()).unwrap();
+ w.write_all(designmap.as_bytes()).unwrap();
+ w.start_file("Stories/Story_big.xml", SimpleFileOptions::default()).unwrap();
+ let chunk = vec![b' '; 1 << 20];
+ for _ in 0..512 {
+ w.write_all(&chunk).unwrap();
+ }
+ w.write_all(b" ").unwrap();
+ let mut bytes = w.finish().unwrap().into_inner();
+ assert!(bytes.len() < 8 << 20, "{}", bytes.len());
+ // Claim one byte in the local header and the central directory record (no ZIP64 fields or
+ // data descriptors here), so only the bytes actually decompressed can show the part is too big.
+ let mut patched = 0;
+ for i in 0..bytes.len().saturating_sub(46) {
+ let (size_at, len_at, name_at) = match &bytes[i..i + 4] {
+ b"PK\x03\x04" => (22, 26, 30),
+ b"PK\x01\x02" => (24, 28, 46),
+ _ => continue,
+ };
+ let len = u16::from_le_bytes([bytes[i + len_at], bytes[i + len_at + 1]]) as usize;
+ if bytes.get(i + name_at..i + name_at + len) == Some(b"Stories/Story_big.xml".as_slice()) {
+ bytes[i + size_at..i + size_at + 4].copy_from_slice(&1u32.to_le_bytes());
+ patched += 1;
+ }
+ }
+ assert_eq!(patched, 2);
+ let Err(err) = import_idml(&bytes) else { panic!("an oversized part imported") };
+ assert!(err.to_string().contains("limit"), "{err}");
+ }
+
+ /// A package with more entries than any document needs is refused before any is read.
+ #[test]
+ fn too_many_entries_are_refused() {
+ use zip::write::SimpleFileOptions;
+ let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
+ w.start_file("mimetype", stored).unwrap();
+ w.write_all(MIMETYPE.as_bytes()).unwrap();
+ for i in 0..100_000 {
+ w.start_file(format!("junk/{i}"), stored).unwrap();
+ }
+ let Err(err) = import_idml(&w.finish().unwrap().into_inner()) else { panic!("a package with 100 001 entries imported") };
+ assert!(err.to_string().contains("entries"), "{err}");
+ }