Skip to content

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

Merge remote-tracking branch 'origin/main' into codex/toc-right-indent-separator

moppeeer74ed76350731
diff --cc crates/idml/src/tests.rs
index e479ccb7d,35374a5e0..7de71324a
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -4369,94 -4398,143 +4398,235 @@@ fn cell_first_baseline_comes_from_cell_
assert_eq!(s2.first_baseline, Some(FirstBaseline::CapHeight));
}
+/// A TOC style as InDesign writes it: `$ID/`-prefixed separator (`^y`, the right indent tab) and entry style.
+const TOC_STYLES: &str = r#"<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+<RootParagraphStyleGroup>
+ <ParagraphStyle Self="ParagraphStyle/Heading 1" Name="Heading 1"/>
+ <ParagraphStyleGroup Self="psg-toc" Name="TOC">
+ <ParagraphStyle Self="ParagraphStyle/TOC%3aTOC body text" Name="TOC:TOC body text" Capitalization="AllCaps"/>
+ <ParagraphStyle Self="ParagraphStyle/TOC%3aTOC Header" Name="TOC:TOC Header"/>
+ </ParagraphStyleGroup>
+</RootParagraphStyleGroup>
+<RootCharacterStyleGroup><CharacterStyle Self="CharacterStyle/TOC Page Number" Name="TOC Page Number"/></RootCharacterStyleGroup>
+<TOCStyle Self="TOCStyle/$ID/DefaultTOCStyleName" TitleStyle="ParagraphStyle/TOC%3aTOC Header" Title="Table of Contents" Name="$ID/DefaultTOCStyleName">
+ <TOCStyleEntry Self="e1" Name="Heading 1" Level="1" PageNumberPosition="AfterEntry" Separator="$ID/^y">
+ <Properties><FormatStyle type="object">ParagraphStyle/$ID/TOC%3aTOC body text</FormatStyle>
+ <PageNumberStyle type="object">CharacterStyle/TOC Page Number</PageNumberStyle>
+ <SeparatorStyle type="string">$ID/[Same Style]</SeparatorStyle></Properties>
+ </TOCStyleEntry>
+</TOCStyle></idPkg:Styles>"#;
+
+const TOC_STORY: &str = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+<Story Self="s1" AppliedTOCStyle="TOCStyle/$ID/DefaultTOCStyleName"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/TOC%3aTOC body text"><CharacterStyleRange><Content>Welcome</Content></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;
+
+#[test]
+fn toc_style_entries_read_id_prefixed_separators_and_styles() {
+ let d = import_idml(&fixture_with_table_styles(TOC_STYLES, TOC_STORY)).unwrap();
+ let toc = d.toc.as_ref().expect("the story's TOC style is imported");
+ let entry = toc.entries.iter().find(|e| e.style == "Heading 1").unwrap();
+ assert_eq!(entry.separator.as_deref(), Some("\u{E006}"), "right-indent tabs must not become ordinary tab stops");
+ assert_eq!(entry.entry_style.as_deref(), Some("TOC/TOC body text"));
+ assert_eq!(entry.page_number_style.as_deref(), Some("TOC Page Number"));
+ assert_eq!(toc.title_style.as_deref(), Some("TOC/TOC Header"));
+}
+
+#[test]
+fn toc_style_entries_fall_back_on_malformed_and_unsupported_values() {
+ let long = "x".repeat(65);
+ let entries = format!(
+ r#"<TOCStyleEntry Self="e1" Name="Heading 1" Level="abc" PageNumberPosition="Sideways" Separator="$ID/^q">
+ <Properties><FormatStyle type="object">ParagraphStyle/Missing</FormatStyle>
+ <PageNumberStyle type="object">CharacterStyle/$ID/[None]</PageNumberStyle>
+ <SeparatorStyle type="object">CharacterStyle/Missing</SeparatorStyle></Properties>
+ </TOCStyleEntry>
+ <TOCStyleEntry Self="e2" Name="TOC:TOC Header" Level="12" Separator="{long}"/>
+ <TOCStyleEntry Self="e3" Name="Heading 1" Level="2" Separator="^t"/>
+ <TOCStyleEntry Self="e4" Name="" Level="3"/>"#
+ );
+ let start = TOC_STYLES.find("<TOCStyleEntry").unwrap();
+ let end = TOC_STYLES.find("</TOCStyle>").unwrap();
+ let styles = format!("{}{entries}\n{}", &TOC_STYLES[..start], &TOC_STYLES[end..])
+ .replace(r#"TitleStyle="ParagraphStyle/TOC%3aTOC Header""#, r#"TitleStyle="ParagraphStyle/Missing""#);
+ let d = import_idml(&fixture_with_table_styles(&styles, TOC_STORY)).unwrap();
+ d.check().unwrap();
+ let toc = d.toc.as_ref().expect("the TOC style is still imported");
+ assert_eq!(toc.title_style, None, "a title style the document lacks is dropped");
+ assert_eq!(toc.entries.len(), 3, "an entry without a style name is skipped: {:?}", toc.entries);
+ let e1 = &toc.entries[0];
+ assert_eq!(e1.level, 1, "an unreadable level falls back to 1");
+ assert_eq!(e1.page_number, designcraft_doc::TocPageNumber::After, "an unknown page-number position falls back to After");
+ assert_eq!(e1.separator.as_deref(), Some("^q"), "an unknown special-character code is kept as written");
+ assert_eq!(
+ (e1.entry_style.as_deref(), e1.page_number_style.as_deref(), e1.separator_style.as_deref()),
+ (None, None, None),
+ "undefined and [None] styles are no style"
+ );
+ let e2 = &toc.entries[1];
+ assert_eq!(e2.level, 9, "a level past 9 is clamped");
+ assert_eq!(e2.separator, None, "an over-long separator is dropped");
+ assert_eq!((toc.entries[2].level, toc.entries[2].separator.as_deref()), (2, None), "a plain tab is the default separator");
+}
+
+#[test]
+fn toc_style_references_in_indented_properties_resolve() {
+ // Property children laid out on their own lines: the whitespace around a reference isn't
+ // part of the style name.
+ let styles = TOC_STYLES
+ .replace(
+ ">ParagraphStyle/$ID/TOC%3aTOC body text<",
+ ">
+ ParagraphStyle/$ID/TOC%3aTOC body text
+ <",
+ )
+ .replace(
+ ">CharacterStyle/TOC Page Number<",
+ ">
+ CharacterStyle/TOC Page Number
+ <",
+ );
+ let d = import_idml(&fixture_with_table_styles(&styles, TOC_STORY)).unwrap();
+ let entry = d.toc.as_ref().unwrap().entries.iter().find(|e| e.style == "Heading 1").unwrap();
+ assert_eq!(entry.entry_style.as_deref(), Some("TOC/TOC body text"));
+ assert_eq!(entry.page_number_style.as_deref(), Some("TOC Page Number"));
+}
++
+ /// A graphic placed in a table cell is written into the cell, not dropped.
+ #[test]
+ fn exports_graphic_in_table_cell() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Intro", ParaFormat::default()).unwrap();
+ let asset = designcraft_doc::AssetId(d.alloc());
+ let id = d.add_asset(designcraft_doc::Asset {
+ id: asset,
+ name: "tick.png".into(),
+ mime: "image/png".into(),
+ data: std::sync::Arc::new(vec![1, 2, 3]),
+ ..Default::default()
+ });
+ let mut t = designcraft_doc::Table::new(d.alloc(), 2, 2, 0, 0, 200.0);
+ t.cell_mut(1, 0).unwrap().graphic = Some(designcraft_doc::Graphic {
+ asset: id,
+ size: (24.0, 24.0),
+ xf: designcraft_geom::Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
+ });
+ d.story_mut(sid).unwrap().insert_table(5, t);
+ let story = zip_text(&export_idml(&d), "Stories/");
+ let cell = story.split("<Cell ").nth(3).unwrap_or_default();
+ let cell = cell.split("</Cell>").next().unwrap_or_default();
+ assert!(cell.contains("<Image "), "{story}");
+ assert!(cell.contains("ClipContentToCell=\"true\""), "{story}");
+ }
+
+ /// Non-finite numbers in colour values, page bounds and item transforms (NaN, infinities and
+ /// values like 1e300 that overflow `f32`) never reach the model: JSON would write them as null.
+ #[test]
+ fn non_finite_number_lists_never_reach_the_model() {
+ let graphic = GRAPHIC.replace(r#"ColorValue="255 0 0""#, r#"ColorValue="NaN 1e300 inf""#);
+ let spread = SPREAD
+ .replace(r#"Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500""#, r#"Self="p2" AppliedMaster="m1" GeometricBounds="0 0 NaN 500""#)
+ .replace(r#"ItemTransform="1 0 0 1 50 -300""#, r#"ItemTransform="1 0 0 1 inf -300""#);
+ let bytes = 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),
+ ]);
+ let doc = import_idml(&bytes).unwrap();
+ for s in &doc.swatches {
+ if let SwatchValue::Color { color, .. } | SwatchValue::Paper { color } = &s.value {
+ let parts: Vec<f32> = match *color {
+ Color::Rgb { r, g, b } => vec![r, g, b],
+ Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
+ Color::Gray { k } => vec![k],
+ };
+ assert!(parts.iter().all(|v| v.is_finite()), "swatch {} is not finite: {color:?}", s.name);
+ }
+ }
+ for sp in doc.spreads.iter().chain(&doc.parents) {
+ for p in &sp.pages {
+ assert!(p.width.is_finite() && p.height.is_finite() && p.x.is_finite(), "page {p:?}");
+ }
+ }
+ assert_eq!(doc.non_finite_item(), None);
+ }
+
+ /// Cell Options › Text › Rotation: the angle survives the round trip, and the import says it is
+ /// not composed — narrow header columns of vertical labels come in horizontal and wrap mid-word,
+ /// and nothing said so (#1468).
+ #[test]
+ fn rotated_cell_text_round_trips_and_the_import_says_it_is_not_composed() {
+ let mut d = Document::new(&NewDocument::default());
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), d.default_layer(), "", ParaFormat::default()).unwrap();
+ let mut t = designcraft_doc::Table::new(7, 1, 3, 0, 0, 300.0);
+ t.cell_mut(0, 0).unwrap().rotation = 90.0;
+ t.cell_mut(0, 1).unwrap().rotation = 270.0;
+ d.story_mut(sid).unwrap().insert_table(0, t);
+ let bytes = export_idml(&d);
+ let story = zip_text(&bytes, "Stories/");
+ assert!(story.contains(r#"RotationAngle="90""#) && story.contains(r#"RotationAngle="270""#), "{story}");
+
+ let back = import_idml_report(&bytes, &|_| None).unwrap();
+ let t = back.document.stories.values().find(|st| !st.tables.is_empty()).unwrap().tables.values().next().unwrap().clone();
+ assert_eq!((t.cell(0, 0).unwrap().rotation, t.cell(0, 1).unwrap().rotation, t.cell(0, 2).unwrap().rotation), (90.0, 270.0, 0.0));
+ let about: Vec<&String> = back.warnings.iter().filter(|w| w.contains("rotated text")).collect();
+ assert_eq!(about.len(), 1, "one line for the file, not one per cell: {:?}", back.warnings);
+ assert!(about[0].starts_with("2 table cell(s)"), "{}", about[0]);
+ assert!(about[0].contains("composed horizontally"), "{}", about[0]);
+
+ // A file with no rotated cell says nothing.
+ let mut plain = Document::new(&NewDocument::default());
+ let (_, sid) =
+ plain.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), plain.default_layer(), "", ParaFormat::default()).unwrap();
+ plain.story_mut(sid).unwrap().insert_table(0, designcraft_doc::Table::new(8, 1, 2, 0, 0, 200.0));
+ let quiet = import_idml_report(&export_idml(&plain), &|_| None).unwrap();
+ assert!(quiet.warnings.iter().all(|w| !w.contains("rotated text")), "{:?}", quiet.warnings);
+ }
+
+ #[test]
+ fn style_names_with_a_literal_colon_survive_a_round_trip() {
+ use designcraft_doc::styles::{CellStyle, CharacterStyle, ObjectStyle, ParagraphStyle, TableStyle};
+ let names = ["Title: Big", "Group/Child: X", "Back\\slash: \\:"];
+ let mut d = small_doc();
+ for n in names {
+ let st = d.styles_mut();
+ st.paragraph.push(ParagraphStyle {
+ name: n.into(),
+ based_on: None,
+ next_style: None,
+ para: Default::default(),
+ chars: Default::default(),
+ shortcut: String::new(),
+ });
+ st.character.push(CharacterStyle { name: n.into(), based_on: None, chars: Default::default(), shortcut: String::new() });
+ st.cell.push(CellStyle { name: n.into(), ..Default::default() });
+ st.table.push(TableStyle { name: n.into(), ..Default::default() });
+ st.object.push(ObjectStyle { name: n.into(), ..Default::default() });
+ }
+ let back = import_idml(&export_idml(&d)).unwrap();
+ for n in names {
+ assert!(
+ back.styles.paragraph.iter().any(|s| s.name == n),
+ "paragraph {n:?}: {:?}",
+ back.styles.paragraph.iter().map(|s| &s.name).collect::<Vec<_>>()
+ );
+ assert!(back.styles.character.iter().any(|s| s.name == n), "character {n:?}");
+ assert!(back.styles.cell.iter().any(|s| s.name == n), "cell {n:?}");
+ assert!(back.styles.table.iter().any(|s| s.name == n), "table {n:?}");
+ assert!(back.styles.object.iter().any(|s| s.name == n), "object {n:?}");
+ }
+ // A group is still written as an IDML `:` group path.
+ assert_eq!(names::style_name_out(names::PARA_BUILTINS, "Group/Child"), "Group:Child");
+ for n in names {
+ assert_eq!(names::style_name_in(names::PARA_BUILTINS, &names::style_name_out(names::PARA_BUILTINS, n)), n);
+ }
+ }