DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #975
Brandon Thomas072ae1d94817
diff --cc ROADMAP.mdindex 6a412a42f,7daa06fa5..14a4c9351--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -135,14 -132,7 +135,15 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+- **2026-10-14** · The Type tool draws a new text frame over a locked empty frame, as InDesign does, instead of turning the locked frame into a text frame. No readiness percentage change.+- **2026-10-14** · 100% black shows as pure black on screen by default, as InDesign's Appearance of Black does out of the box (Display All Blacks as Rich Black); Preferences › Appearance of Black › Display All Blacks Accurately still shows it as the dark grey it prints, and a saved choice is kept. No readiness percentage change.+- **2026-10-14** · Pathfinder keeps the frontmost object, as InDesign does: a photo placed over shapes and intersected with them shows through the shapes (it was dropped, and the shapes kept their black fill); Add, Exclude Overlap and Minus Back take the front object's fill too, Subtract still keeps the back one. No readiness percentage change.+- **2026-10-14** · The Color panel's Tint field keeps what is typed while it has focus and applies it on Enter or when it loses focus, clamped to 0–100 %. Typing 60 over 100 % no longer snaps back to 100 after the first digit (10060), and a typed tint is no longer ignored. No readiness percentage change.+- **2026-10-15** · IDML: ruler guides import and export (they were dropped). Each page's guides come in measured from the document's ruler origin (spread, page or spine), with Fit to Page, Locked and their layer, parent pages' included, and go out again under their pages. No readiness percentage change.+- **2026-10-15** · Find Font no longer reports a style missing when it differs from the installed one only in spacing or case (InDesign files can name `Regular ` with a trailing space); the text was already drawn in the right face. No readiness percentage change.+- **2026-10-15** · A line of text is set when its baseline fits in the frame, as in InDesign: descenders may hang below the frame's bottom. A frame sized to the cap height of a big heading (103 pt in a 2.77 cm frame, as Zero2Graphic's magazine tutorial draws them) no longer oversets. No readiness percentage change.+- **2026-10-15** · A story that ends with a return is no longer overset when only its empty last paragraph doesn't fit, as in InDesign (Preflight said "Overset text: 0 characters" for a caption InDesign shows with no errors). No readiness percentage change.+ - **2026-10-15** · IDML: the CJK leading model InDesign writes on [No paragraph style] of every document (Aki Below) only applies when the document uses a Japanese composer, as in InDesign; a Western document's paragraphs after a size change no longer sit lower than in InDesign (Montilla Design's Flex Layout file: its captions came out overset). No readiness percentage change.- **2026-10-13** · Object › Fitting has InDesign's shortcuts: Fill Frame Proportionally ⌘⌥⇧C, Fit Content Proportionally ⌘⌥⇧E, Fit Frame to Content ⌘⌥C, Fit Content to Frame ⌘⌥E, Center Content ⌘⇧E. No readiness percentage change.- **2026-10-13** · Gradients between process colours blend as inks, as InDesign shows them: magenta to cyan passes through C 50 M 50 (a light lilac) on screen instead of the darker RGB mix, and a midpoint between CMYK or grey stops no longer turns the PDF shading RGB. No readiness percentage change.- **2026-10-14** · The Swatches panel has InDesign's header: a Fill/Stroke proxy, Formatting Affects Container/Text and the Tint of the colour in front (a tint alone keeps each object's own swatch). Clicking a swatch applies it to the fill or stroke in front (of the text, when formatting affects text), and the bottom row has New Color Group, New Swatch and Delete Swatch. No readiness percentage change.diff --cc crates/idml/src/import.rsindex 23afead97,a0aa73d00..36d8ed355--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -66,6 -92,6 +66,8 @@@ pub fn import_idml_report(bytes: &[u8]// Flatten includes: every `idPkg:*` child is replaced by the children of its part's root.let mut top: Vec<El> = Vec::new();let mut warnings = Vec::new();++ // Only the parts the import reads count (unreferenced entries are never decompressed).++ let mut japanese_composer = names_japanese_composer(&dm);for c in root.elements() {if c.name.starts_with("idPkg:") {let Some(src) = c.get("src") else { continue };@@@ -73,13 -99,14 +75,15 @@@warnings.push(format!("{src}: listed in designmap.xml but missing from the package; its contents were not imported"));continue;};- let el = parse(data).map_err(|msg| IdmlError::Part { part: src.into(), msg })?;++ japanese_composer |= names_japanese_composer(&data);+ let el = parse(&data).map_err(|msg| IdmlError::Part { part: src.into(), msg })?;top.extend(el.elements().cloned());} else {top.push(c.clone());}}let mut im = Importer::new(read_link);- im.japanese_composer = files.values().any(|data| names_japanese_composer(data));++ im.japanese_composer = japanese_composer;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.@@@ -90,76 -117,23 +94,93 @@@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))+ }+}++ /// Does this package part apply one of InDesign's Japanese composers (`HL Composer J`,+ /// `HL Single J`) anywhere? Only they use the CJK leading model.+ fn names_japanese_composer(data: &[u8]) -> bool {+ const KEY: &[u8] = b"Composer=\"";+ let mut rest = data;+ while let Some(at) = rest.windows(KEY.len()).position(|w| w == KEY) {+ let value = rest.get(at + KEY.len()..).unwrap_or_default();+ let end = value.iter().position(|b| *b == b'"').unwrap_or(value.len());+ let name = String::from_utf8_lossy(value.get(..end).unwrap_or_default());+ if name.ends_with(" J") || name.contains("Japanese") {+ return true;+ }+ rest = value.get(end..).unwrap_or_default();+ }+ false+ }+/// 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 {@@@ -203,8 -177,8 +224,10 @@@ struct ItemCtxstruct Importer<'r> {read_link: &'r dyn Fn(&str) -> Option<Vec<u8>>,+ /// View Preferences › Ruler Origin: where a guide's Location is measured from.+ ruler_origin: RulerOrigin,+ /// The package applies a Japanese composer somewhere (see [`names_japanese_composer`]).+ japanese_composer: bool,next_id: u64,settings: DocSettings,default_margins: Option<(Margins, Columns)>,@@@ -355,7 -295,7 +378,8 @@@ impl<'r> Importer<'r>styles.paragraph.iter_mut().for_each(|s| s.based_on = None);Importer {read_link,+ ruler_origin: RulerOrigin::Spread,+ japanese_composer: false,next_id: 0,settings: DocSettings::default(),default_margins: None,diff --cc crates/idml/src/tests.rsindex 16a0f465f,7c9087da1..ba0bad4eb--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2219,139 -2170,34 +2219,171 @@@ fn frame_preference_property_color_resoassert_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}");+}+++ /// InDesign writes `LeadingModel="LeadingModelAkiBelow"` on [No paragraph style] of every+ /// document, but only its Japanese composers use the leading model: with the Paragraph Composer,+ /// a 24 pt paragraph after a 32 pt one sits a Roman 28.8 pt below it (Montilla Design's Flex Layout+ /// file: frames fitted to that came out overset).+ #[test]+ fn the_default_cjk_leading_model_applies_only_with_a_japanese_composer() {+ let styles = |composer: &str| {+ STYLES.replace(+ r#"Name="$ID/[No paragraph style]" PointSize="12">"#,+ &format!(r#"Name="$ID/[No paragraph style]" PointSize="12" LeadingModel="LeadingModelAkiBelow" Composer="{composer}">"#),+ )+ };+ let model = |composer: &str| {+ let s = styles(composer);+ let pkg = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &s),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", STORY),+ ]);+ let d = import_idml(&pkg).unwrap();+ d.styles.para(designcraft_doc::NO_PARA_STYLE).unwrap().chars.leading_model+ };+ assert_eq!(model("HL Composer"), None, "the Paragraph Composer leads baseline to baseline");+ assert_eq!(model("HL Single"), None);+ assert_eq!(model("$ID/HL Composer J"), Some(designcraft_doc::cjk::LeadingModel::AkiBelow));+ assert_eq!(model("$ID/HL Single J"), Some(designcraft_doc::cjk::LeadingModel::AkiBelow));+ }