DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge PR #1249: IDML import of TOC separators and entry styles
aionggd00e7fce2154
diff --cc crates/idml/src/import/document.rsindex a31eb0bad,000000000..83ed58f25mode 100644,000000..100644--- a/crates/idml/src/import/document.rs+++ b/crates/idml/src/import/document.rs@@@ -1,352 -1,0 +1,353 @@@+use super::values::tint;+use super::{BaselineGrid, El, GridRelative, Importer, PARA_BUILTINS, names};++/// IDML stores a sort key on each topic, rather than on its page references.+#[derive(Clone, Default)]+pub(super) struct IndexTopic {+ pub(super) path: Vec<String>,+ pub(super) sort: Vec<String>,+}++impl IndexTopic {+ fn child(&self, topic: &El) -> Self {+ let mut path = self.path.clone();+ path.push(topic.get("Name").unwrap_or("").to_string());+ let mut sort = self.sort.clone();+ if let Some(key) = topic.get("SortOrder").filter(|key| !key.is_empty()) {+ // Keep empty positions before a child's key, but omit trailing defaults.+ sort.resize(self.path.len(), String::new());+ sort.push(key.to_string());+ }+ Self { path, sort }+ }+}++impl<'r> Importer<'r> {+ pub(super) fn doc_prefs(&mut self, e: &El) {+ let s = &mut self.settings;+ if let Some(v) = e.get("OverprintBlack") {+ s.overprint_black = v != "false";+ }+ if let Some(v) = e.num("PageWidth") {+ s.page_width = v;+ }+ if let Some(v) = e.num("PageHeight") {+ s.page_height = v;+ }+ if let Some(v) = e.boolean("FacingPages") {+ s.facing_pages = v;+ }+ if let Some(v) = e.get("PageBinding") {+ s.right_to_left_binding = v == "RightToLeft";+ }+ for (i, k) in ["DocumentBleedTopOffset", "DocumentBleedBottomOffset", "DocumentBleedInsideOrLeftOffset", "DocumentBleedOutsideOrRightOffset"]+ .iter()+ .enumerate()+ {+ if let Some(v) = e.num(k) {+ s.bleed[i] = v;+ }+ }+ for (i, k) in ["SlugTopOffset", "SlugBottomOffset", "SlugInsideOrLeftOffset", "SlugRightOrOutsideOffset"].iter().enumerate() {+ if let Some(v) = e.num(k) {+ s.slug[i] = v;+ }+ }+ if let Some(i) = e.get("Intent") {+ s.intent = match i {+ "WebIntent" => designcraft_doc::Intent::Web,+ "MobileIntent" => designcraft_doc::Intent::Mobile,+ _ => designcraft_doc::Intent::Print,+ };+ }+ if let Some(v) = e.boolean("CreatePrimaryTextFrame") {+ s.primary_text_frame = v;+ }+ if let Some(v) = e.boolean("ColumnGuideLocked") {+ s.column_guides_locked = v;+ }+ }++ pub(super) fn grid_prefs(&mut self, e: &El) {+ let s = &mut self.settings;+ let bg: &mut BaselineGrid = &mut s.baseline_grid;+ if let Some(v) = e.num("BaselineStart") {+ bg.start = v;+ }+ if let Some(v) = e.num("BaselineDivision") {+ bg.increment = v;+ }+ if let Some(v) = e.num("BaselineViewThreshold") {+ bg.view_threshold = v / 100.0;+ }+ if let Some(v) = e.get("BaselineGridRelativeOption") {+ bg.relative_to = if v.contains("Margin") { GridRelative::TopMargin } else { GridRelative::TopOfPage };+ }+ if let Some(v) = e.num("HorizontalGridlineDivision") {+ s.grid.horizontal = v;+ }+ if let Some(v) = e.num("VerticalGridlineDivision") {+ s.grid.vertical = v;+ }+ if let Some(v) = e.num("HorizontalGridSubdivision") {+ s.grid.subdivisions = v.max(1.0) as u32;+ }+ if let Some(v) = e.boolean("GridsInBack") {+ s.grid.in_back = v;+ }+ }++ /// Index topics (recursively); at the root, their See / See also cross-references too.+ pub(super) fn index_topics_of(&mut self, e: &El, prefix: &IndexTopic) {+ for t in e.find_all("Topic") {+ let topic = prefix.child(t);+ if let Some(me) = t.get("Self") {+ self.index_topics.insert(me.to_string(), topic.clone());+ }+ self.index_topics_of(t, &topic);+ }+ if !prefix.path.is_empty() {+ return;+ }+ let mut stack = vec![(e, IndexTopic::default())];+ while let Some((el, prefix)) = stack.pop() {+ for t in el.find_all("Topic") {+ let topic = prefix.child(t);+ for x in t.find_all("CrossReference") {+ let target = x.get("ReferencedTopic").and_then(|r| self.index_topics.get(r)).map(|t| t.path.join(": ")).unwrap_or_default();+ use designcraft_doc::index::IndexRange as R;+ let range = match x.get("CrossReferenceType") {+ Some("SeeAlso") | Some("SeeAlsoHerein") => R::SeeAlso(target),+ _ => R::See(target),+ };+ self.index_xrefs.push(designcraft_doc::IndexRef { topics: topic.path.clone(), sort: topic.sort.clone(), range });+ }+ stack.push((t, topic));+ }+ }+ }++ /// `CrossReferenceFormat`: building blocks back to a format definition.+ /// A `TextVariable` definition. Types that aren't computed here keep their settings and show+ /// the result of their first instance.+ pub(super) fn text_variable(&mut self, e: &El) {+ use designcraft_doc::vars::{TextVariable, Use, VAR_MAX, VarKind};+ let ty = e.get("VariableType").unwrap_or("");+ // Cross-reference internals; export writes its own.+ if ty.is_empty() || ty.starts_with("Xref") {+ return;+ }+ let vars = self.text_vars.get_or_insert_with(Vec::new);+ if vars.len() >= VAR_MAX {+ return;+ }+ let pref = e.elements().find(|c| c.local().ends_with("Preference"));+ let attr = |k: &str| pref.and_then(|p| p.get(k)).unwrap_or("");+ let date = || Some(attr("Format")).filter(|f| !f.is_empty()).unwrap_or("MM/dd/yy").to_string();+ let kind = match ty {+ "CustomTextType" => Some(VarKind::Custom { text: attr("Contents").into() }),+ "LastPageNumberType" => Some(VarKind::LastPageNumber { section: attr("Scope") == "SectionScope" }),+ "ChapterNumberType" => Some(VarKind::ChapterNumber),+ "FileNameType" if attr("IncludePath") != "true" => Some(VarKind::FileName { extension: attr("IncludeExtension") == "true" }),+ "CreationDateType" => Some(VarKind::CreationDate { format: date() }),+ "ModificationDateType" => Some(VarKind::ModificationDate { format: date() }),+ "OutputDateType" => Some(VarKind::OutputDate { format: date() }),+ "MatchParagraphStyleType" | "MatchCharacterStyleType" => {+ let character = ty == "MatchCharacterStyleType";+ let r = attr(if character { "AppliedCharacterStyle" } else { "AppliedParagraphStyle" });+ let use_ = if attr("SearchStrategy") == "LastOnPage" { Use::LastOnPage } else { Use::FirstOnPage };+ // Change Case and Delete End Punctuation aren't modelled: the header shows the text as set.+ (!r.is_empty()).then(|| VarKind::RunningHeader {+ style: if character { self.char_style_ref(r) } else { self.para_style_ref(r) },+ use_,+ character,+ })+ }+ _ => None,+ };+ let name = e.get("Name").unwrap_or("").to_string();+ let v = match kind {+ Some(kind) => {+ let mut v = TextVariable::new(&name, kind);+ v.before = attr("TextBefore").into();+ v.after = attr("TextAfter").into();+ v+ }+ None => TextVariable::new(+ &name,+ VarKind::Imported {+ variable_type: ty.into(),+ result: String::new(),+ settings_element: pref.map(|p| p.name.clone()).unwrap_or_default(),+ settings: pref.map(|p| p.attrs.clone()).unwrap_or_default(),+ },+ ),+ };+ let vars = self.text_vars.get_or_insert_with(Vec::new);+ if let Some(s) = e.get("Self") {+ self.text_var_ids.insert(s.to_string(), vars.len());+ }+ vars.push(v);+ }++ /// A `TextVariableInstance`: the variable's character, or its recorded text when the file+ /// doesn't define the variable.+ pub(super) fn text_variable_instance(&mut self, e: &El) -> String {+ use designcraft_doc::vars::{VarKind, var_char};+ let result = e.get("ResultText").unwrap_or("");+ let found = e.get("AssociatedTextVariable").and_then(|r| self.text_var_ids.get(r)).copied();+ let var = found.and_then(|i| Some((i, self.text_vars.as_mut()?.get_mut(i)?)));+ match var.and_then(|(i, v)| Some((var_char(i)?, v))) {+ Some((c, v)) => {+ if let VarKind::Imported { result: r, .. } = &mut v.kind+ && r.is_empty()+ {+ *r = result.to_string();+ }+ c.to_string()+ }+ None => result.to_string(),+ }+ }++ pub(super) fn xref_format(&mut self, e: &El) {+ let name = e.get("Name").unwrap_or("Format").to_string();+ let mut def = String::new();+ for b in e.find_all("BuildingBlock") {+ let text = |k: &str| b.get(k).filter(|v| *v != "$ID/").unwrap_or("").to_string();+ match b.get("BlockType").unwrap_or("") {+ "CustomStringBuildingBlock" => def.push_str(&text("CustomText")),+ "FullParagraphBuildingBlock" => def.push_str("<fullPara />"),+ "ParagraphTextBuildingBlock" => def.push_str("<paraText />"),+ "ParagraphNumberBuildingBlock" => def.push_str("<paraNum />"),+ "PageNumberBuildingBlock" => def.push_str("<pageNum />"),+ "BookmarkNameBuildingBlock" => def.push_str("<txtAnchrName />"),+ "ChapterNumberBuildingBlock" => def.push_str("<chapNum />"),+ "FileNameBuildingBlock" => def.push_str("<fileName />"),+ "PartialParagraphBuildingBlock" => def.push_str(&format!(+ "<partialPara delim=\"{}\" includeDelim=\"{}\" />",+ text("AppliedDelimiter"),+ b.get("IncludeDelimiter") == Some("true")+ )),+ _ => {}+ }+ }+ if let Some(me) = e.get("Self") {+ self.xref_format_names.insert(me.to_string(), name.clone());+ }+ match self.xref_formats.iter_mut().find(|f| f.name == name) {+ Some(f) => f.definition = def,+ None => self.xref_formats.push(designcraft_doc::XrefFormat { name, definition: def }),+ }+ }++ /// Preferences › `EPubExportPreference`: Split Document (after styles: it can name one). An+ /// empty style name splits on the styles' export tags; a style the file lacks splits nothing.+ pub(super) fn epub_split(&mut self, e: &El) {+ if e.boolean("BreakDocument") != Some(true) {+ return;+ }+ let name = e.get("ParagraphStyleName").unwrap_or("$ID/NormalParagraphStyle");+ self.settings.epub_split = if name.trim().is_empty() {+ designcraft_doc::EpubSplit::ExportTags+ } else {+ let style = self.para_style_ref(name);+ if self.styles.para(&style).is_some() { designcraft_doc::EpubSplit::Style(style) } else { designcraft_doc::EpubSplit::Off }+ };+ }++ /// Preferences › `FootnoteOption` (after styles: it names the footnote text and marker styles).+ pub(super) fn footnote_option(&mut self, e: &El) {+ let mut o = designcraft_doc::FootnoteOptions::default();+ if let Some(v) = e.num("StartAt") {+ o.start_at = v.max(0.0) as u32;+ }+ o.prefix = e.get("Prefix").unwrap_or("").into();+ o.suffix = e.get("Suffix").unwrap_or("").into();+ if let Some(r) = e.get("FootnoteTextStyle") {+ o.para_style = self.para_style_ref(r);+ }+ if let Some(r) = e.get("FootnoteMarkerStyle") {+ o.ref_char_style = self.char_style_ref(r);+ }+ if let Some(v) = e.get("SeparatorText") {+ o.separator = v.into();+ }+ o.space_between = e.num("SpaceBetween").unwrap_or(0.0);+ o.space_before = e.num("Spacer").unwrap_or(0.0);+ if let Some(v) = e.prop("FootnoteFirstBaselineOffset") {+ o.first_baseline = names::first_baseline_in(v.trim());+ }+ o.first_baseline_min = e.num("FootnoteMinimumFirstBaselineOffset").unwrap_or(0.0);+ o.span_columns = e.boolean("EnableStraddling").unwrap_or(false);+ o.rule.on = e.boolean("RuleOn").unwrap_or(true);+ o.rule.weight = e.num("RuleLineWeight").unwrap_or(1.0);+ o.rule.tint = tint(e.num("RuleTint")).unwrap_or(1.0);+ o.rule.left_indent = e.num("RuleLeftIndent").unwrap_or(0.0);+ o.rule.width = e.num("RuleWidth").unwrap_or(72.0);+ o.rule.offset = e.num("RuleOffset").unwrap_or(0.0);+ if let Some(c) = e.prop("RuleColor") {+ o.rule.color = self.swatch_ref(c.trim());+ }+ if let Some(v) = e.prop("FootnoteNumberingStyle") {+ o.style = names::note_style_in(v.trim());+ }+ if let Some(v) = e.prop("RestartNumbering") {+ o.restart = names::NOTE_RESTART.iter().find(|r| r.1 == v.trim()).map_or(Default::default(), |r| r.0);+ }+ if let Some(v) = e.prop("ShowPrefixSuffix") {+ o.affix_in = names::NOTE_AFFIX.iter().find(|r| r.1 == v.trim()).map_or(Default::default(), |r| r.0);+ }+ if let Some(v) = e.prop("MarkerPositioning") {+ o.ref_position = names::note_marker_in(v.trim());+ }+ self.footnote_options = o;+ }++ /// The table of contents: the TOC style a story is generated from (`AppliedTOCStyle`), with+ /// its entries. Styles the document doesn't have fall back to the generated TOC styles.+ pub(super) fn toc_of(&self, top: &[El]) -> Option<designcraft_doc::Toc> {+ use designcraft_doc::{TocEntry, TocPageNumber};+ let (ts, story) = top.iter().filter(|e| e.local() == "TOCStyle").find_map(|ts| {+ let id = ts.get("Self")?;+ let story = top.iter().find(|e| e.local() == "Story" && e.get("AppliedTOCStyle") == Some(id))?;+ Some((ts, *self.story_ids.get(story.get("Self")?)?))+ })?;+ let known = |r: Option<&str>| r.map(|r| self.para_style_ref(r)).filter(|n| self.styles.para(n).is_some());+ // Character styles the document has; [None] is stored as no style.+ let known_chars = |r: Option<&str>| {+ r.map(|r| self.char_style_ref(r)).filter(|n| n != designcraft_doc::NO_CHAR_STYLE && self.styles.char_style(n).is_some())+ };+ let entries: Vec<TocEntry> = ts+ .elements()+ .filter(|e| e.local() == "TOCStyleEntry")+ .filter_map(|e| {+ let style = names::style_name_in(PARA_BUILTINS, e.get("Name")?);+ if style.is_empty() || style.chars().count() > 256 {+ return None;+ }+ let level = e.get("Level").and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);+ let page_number = match e.get("PageNumberPosition") {+ Some("BeforeEntry") => TocPageNumber::Before,+ Some("NoPageNumber") => TocPageNumber::None,+ _ => TocPageNumber::After,+ };+ let separator = e.get("Separator").map(crate::names::toc_separator_in).filter(|s| s != "\t" && s.chars().count() <= 64);- let entry_style = known(e.get("FormatStyle")).filter(|n| *n != format!("TOC Level {level}"));- let page_number_style = known_chars(e.get("PageNumberStyle"));- let separator_style = known_chars(e.get("SeparatorStyle"));++ // InDesign writes these as `Properties` children; attributes are read too.++ let entry_style = known(e.prop("FormatStyle").as_deref()).filter(|n| *n != format!("TOC Level {level}"));++ let page_number_style = known_chars(e.prop("PageNumberStyle").as_deref());++ let separator_style = known_chars(e.prop("SeparatorStyle").as_deref());+ let sort = e.get("Sort").is_some_and(|v| v.trim() == "true");+ Some(TocEntry { style, level, entry_style, page_number, separator, page_number_style, separator_style, sort })+ })+ .take(64)+ .collect();+ if entries.is_empty() {+ return None;+ }+ let title: String = ts.get("Title").unwrap_or("").chars().filter(|c| !matches!(c, '\n' | '\r' | '\u{2029}')).take(1024).collect();+ let title_style = known(ts.get("TitleStyle")).filter(|n| n != "TOC Title");+ let create_bookmarks = ts.get("CreateBookmarks").or_else(|| ts.get("CreatePdfBookmarks")) == Some("true");+ Some(designcraft_doc::Toc { story, title, entries, page_numbers: true, title_style, create_bookmarks })+ }+}diff --cc crates/idml/src/tests.rsindex 07a1154f1,785bf458f..9fa5cd23a--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -4470,361 -4190,34 +4470,394 @@@ mod liquid_page_rules}}+/// A dragged column gutter (InDesign's Custom columns) survives an IDML import, and an even set —+/// which InDesign writes for every page, moved or not — does not pretend to be custom (#1096).+#[test]+fn custom_column_positions_import_and_round_trip() {+ // Page 1 of SPREAD is 500 wide with Left=20 Right=30, so its margin box is 450 wide and+ // starts at x=30. Two columns with gutter 20 split evenly as "0 215 235 450".+ let with = |cols: &str| {+ let spread = SPREAD.replace(+ r#"<MarginPreference ColumnCount="3" ColumnGutter="12" Top="10" Bottom="10" Left="20" Right="30"/>"#,+ &format!(+ r#"<MarginPreference ColumnCount="2" ColumnGutter="20" Top="10" Bottom="10" Left="20" Right="30" ColumnDirection="Horizontal" {cols}/>"#+ ),+ );+ import_idml_with(+ &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),+ ]),+ &|_| None,+ )+ .unwrap()+ };+ let rects = |d: &designcraft_doc::Document| d.spreads[0].pages[0].column_rects().iter().map(|r| (r.x0, r.x1)).collect::<Vec<_>>();++ // Dragged: the gutter sits at 150..170 instead of 215..235, and the columns follow it.+ let d = with(r#"ColumnsPositions="0 150 170 450""#);+ assert_eq!(d.spreads[0].pages[0].columns.positions, Some(vec![0.0, 150.0, 170.0, 450.0]));+ assert_eq!(rects(&d), vec![(30.0, 180.0), (200.0, 480.0)]);++ // The even set is dropped, so a later change of count or gutter is not frozen out. The+ // geometry is the same either way, which is what makes keeping it pointless.+ let even = with(r#"ColumnsPositions="0 215 235 450""#);+ assert_eq!(even.spreads[0].pages[0].columns.positions, None);+ assert_eq!(rects(&even), vec![(30.0, 245.0), (265.0, 480.0)]);+ // Including when InDesign's own arithmetic leaves the last bits different.+ assert_eq!(with(r#"ColumnsPositions="0 215.00000000000003 234.99999999999997 450""#).spreads[0].pages[0].columns.positions, None);++ // Malformed sets are ignored rather than half-read: an odd count, three columns' worth for a+ // count of two, a descending pair, a NaN, a set that stops short of the page's margin box, and+ // a list far longer than any count allows. Each page keeps the even split.+ let huge = format!(r#"ColumnsPositions="{}""#, (0..10_000).map(|i| i.to_string()).collect::<Vec<_>>().join(" "));+ for bad in [+ r#"ColumnsPositions="0 150 170""#,+ r#"ColumnsPositions="0 100 120 200 220 450""#,+ r#"ColumnsPositions="0 150 90 450""#,+ r#"ColumnsPositions="0 x 170 450""#,+ r#"ColumnsPositions="0 NaN 170 450""#,+ r#"ColumnsPositions="0 150 170 400""#,+ r#"ColumnsPositions="""#,+ huge.as_str(),+ ] {+ let d = with(bad);+ assert_eq!(d.spreads[0].pages[0].columns.positions, None, "{}", bad.get(..bad.len().min(60)).unwrap_or(""));+ assert_eq!(rects(&d), rects(&even));+ }++ // And they come back from an export, so the round trip keeps the dragged gutter.+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.spreads[0].pages[0].columns.positions, Some(vec![0.0, 150.0, 170.0, 450.0]));+ assert_eq!(rects(&back), rects(&d));+ // A page nobody dragged still exports the even split, not a frozen copy of it.+ assert_eq!(import_idml(&export_idml(&even)).unwrap().spreads[0].pages[0].columns.positions, None);+}++/// #1096: a ruler guide inside the gutter of a two-column page, written the way InDesign writes+/// it (a `<Page>` child after its `MarginPreference`, with `Properties`/`GuideColor`, `PageIndex`+/// and `GuideZone`), in a document without facing pages. A spread guide sits beside it.+#[test]+fn ruler_guide_in_a_column_gutter_imports_without_facing_pages() {+ use designcraft_doc::Orientation::{Horizontal, Vertical};+ let package = |view: &str| {+ let prefs =+ PREFS.replace(r#"FacingPages="true""#, r#"FacingPages="false""#).replace("</idPkg:Preferences>", &format!("{view}</idPkg:Preferences>"));+ let spread = SPREAD.replace(+ r#"<Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350">+ <MarginPreference ColumnCount="3" ColumnGutter="12" Top="10" Bottom="10" Left="20" Right="30"/>+ </Page>"#,+ r#"<Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350" Name="1" OverrideList="">+ <Properties><PageColor type="enumeration">UseMasterColor</PageColor></Properties>+ <MarginPreference ColumnCount="2" ColumnGutter="20" Top="10" Bottom="10" Left="20" Right="30" ColumnDirection="Horizontal" ColumnsPositions="0 150 170 450"/>+ <GridDataInformation FontStyle="Regular" PointSize="12"/>+ <Guide Self="g1" OverriddenPageItemProps="" Orientation="Vertical" Location="180" FitToPage="true" ViewThreshold="0" Locked="false" ItemLayer="L1" PageIndex="0" GuideType="Ruler" GuideZone="0">+ <Properties><GuideColor type="enumeration">Cyan</GuideColor></Properties>+ </Guide>+ <Guide Self="g2" OverriddenPageItemProps="" Orientation="Horizontal" Location="300" FitToPage="false" ViewThreshold="5" Locked="false" ItemLayer="L1" PageIndex="0" GuideType="Ruler" GuideZone="1">+ <Properties><GuideColor type="enumeration">Cyan</GuideColor></Properties>+ </Guide>+ </Page>"#,+ );+ assert_ne!(spread, SPREAD, "the fixture's first page was replaced");+ import_idml(&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),+ ]))+ .unwrap()+ };+ let guides =+ |d: &Document| d.spreads[0].pages[0].guides.iter().map(|g| (g.orientation, g.position, g.spread, g.layer.is_some())).collect::<Vec<_>>();+ // The first page starts at x 0 in our spread coordinates, so the spread's and the page's ruler+ // origins agree; no ViewPreference means InDesign's default, the spread.+ for view in ["", r#"<ViewPreference RulerOrigin="SpreadOrigin"/>"#, r#"<ViewPreference RulerOrigin="PageOrigin"/>"#] {+ let first = package(view);+ assert!(!first.settings.facing_pages);+ assert_eq!(guides(&first), [(Vertical, 180.0, false, true), (Horizontal, 300.0, true, true)], "{view:?}");+ // The guide sits between the page's left margin (20) and right margin (470).+ let m = first.spreads[0].pages[0].margin_rect();+ assert!(m.x0 < 180.0 && 180.0 < m.x1);+ let back = import_idml(&export_idml(&first)).unwrap();+ assert_eq!(guides(&back), guides(&first), "round trip, {view:?}");+ }+}++/// Cell Options › Text › First Baseline, set by a cell style that a table style applies to its body+/// region (cells with `[None]` take it from there) and overridden on one cell.+const FIRST_BASELINE_STYLES: &str = r#"<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+<RootCellStyleGroup>+ <CellStyle Self="CellStyle/$ID/[None]" Name="$ID/[None]"/>+ <CellStyle Self="cs-cap" Name="Cap" FirstBaselineOffset="CapHeight" MinimumFirstBaselineOffset="2" VerticalJustification="CenterAlign"/>+ <CellStyle Self="cs-cap-child" Name="CapChild" FillTint="50"><Properties><BasedOn type="object">cs-cap</BasedOn></Properties></CellStyle>+</RootCellStyleGroup>+<RootParagraphStyleGroup/>+<RootTableStyleGroup>+ <TableStyle Self="ts" Name="Tbl" BodyRegionCellStyle="cs-cap-child"/>+</RootTableStyleGroup></idPkg:Styles>"#;++const FIRST_BASELINE_STORY: &str = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table AppliedTableStyle="ts" HeaderRowCount="0">+<Row Name="0" MinimumHeight="20"/>+<Column Name="0" SingleColumnWidth="60"/><Column Name="1" SingleColumnWidth="60"/>+<Cell Name="0:0" AppliedCellStyle="CellStyle/$ID/[None]"><ParagraphStyleRange><CharacterStyleRange><Content>Region</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+<Cell Name="1:0" AppliedCellStyle="CellStyle/$ID/[None]" FirstBaselineOffset="LeadingOffset"><ParagraphStyleRange><CharacterStyleRange><Content>Local</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+</Table></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;++#[test]+fn cell_first_baseline_comes_from_cell_styles_table_regions_and_cells_and_round_trips() {+ use designcraft_doc::FirstBaseline;+ let d = import_idml(&fixture_with_table_styles(FIRST_BASELINE_STYLES, FIRST_BASELINE_STORY)).unwrap();+ d.check().unwrap();+ let style = d.styles.cell.iter().find(|c| c.name == "Cap").unwrap();+ assert_eq!((style.first_baseline, style.first_baseline_min), (Some(FirstBaseline::CapHeight), Some(2.0)));+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let region = table.cell(0, 0).unwrap();+ assert_eq!((region.first_baseline, region.first_baseline_min), (FirstBaseline::CapHeight, 2.0), "inherited through BasedOn and the body region");+ assert_eq!(table.cell(0, 1).unwrap().first_baseline, FirstBaseline::Leading, "a cell's own attribute wins");+ let back = import_idml(&export_idml(&d)).unwrap();+ let t2 = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(t2.cell(0, 0).unwrap().first_baseline, FirstBaseline::CapHeight);+ assert_eq!(t2.cell(0, 0).unwrap().first_baseline_min, 2.0);+ assert_eq!(t2.cell(0, 1).unwrap().first_baseline, FirstBaseline::Leading);+ let s2 = back.styles.cell.iter().find(|c| c.name == "Cap").unwrap();+ assert_eq!(s2.first_baseline, Some(FirstBaseline::CapHeight));+}++/// 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 {+ layer_options: None,+ 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);+ }+}++/// Split Document (EPUB only) comes from the style, or from its EPUB export tag map, and is+/// written back on the style.+#[test]+fn split_document_round_trips() {+ let xml = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <RootParagraphStyleGroup Self="rp">+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12" SplitDocument="false"/>+ <ParagraphStyle Self="ParagraphStyle/Part" Name="Part" SplitDocument="true"/>+ <ParagraphStyle Self="ParagraphStyle/Chapter" Name="Chapter" SplitDocument="false">+ <StyleExportTagMap Self="uaStyleExportTagMapnEPUB" ExportType="EPUB" ExportTag="h1" ExportClass="" ExportAttributes="" SplitDocument="true" EmitCss="true"/>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" SplitDocument="false"/>+ </RootParagraphStyleGroup>+</idPkg:Styles>"#;+ let d = import_idml_with(&fixture_with_styles(xml), &|_| None).unwrap();+ let split = |d: &designcraft_doc::Document, name: &str| d.styles.export_tag(name, false).is_some_and(|t| t.split);+ assert!(split(&d, "Part") && split(&d, "Chapter") && !split(&d, "Body"));+ let back = import_idml(&export_idml(&d)).unwrap();+ assert!(split(&back, "Part") && split(&back, "Chapter") && !split(&back, "Body"));+}++/// EPUB Export Options › Split Document: off, one style (built in or not) or the styles' export+/// tags, read from the file's `EPubExportPreference` and written back.+#[test]+fn epub_split_document_round_trips() {+ use designcraft_doc::EpubSplit;+ let styles =+ STYLES.replace("</RootParagraphStyleGroup>", r#"<ParagraphStyle Self="ParagraphStyle/Chapter" Name="Chapter"/></RootParagraphStyleGroup>"#);+ assert!(styles.contains("ParagraphStyle/Chapter"), "the fixture has a paragraph style group");+ for (attrs, want) in [+ (r#"BreakDocument="false" ParagraphStyleName="ParagraphStyle/Chapter""#, EpubSplit::Off),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Chapter""#, EpubSplit::Style("Chapter".into())),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Text%3aBody""#, EpubSplit::Style("Text/Body".into())),+ (r#"BreakDocument="true" ParagraphStyleName="$ID/NormalParagraphStyle""#, EpubSplit::Style(designcraft_doc::BASIC_PARAGRAPH.into())),+ (r#"BreakDocument="true" ParagraphStyleName="""#, EpubSplit::ExportTags),+ (r#"BreakDocument="true" ParagraphStyleName="ParagraphStyle/Missing""#, EpubSplit::Off),+ ] {+ let prefs = PREFS.replace("</idPkg:Preferences>", &format!("<EPubExportPreference {attrs}/></idPkg:Preferences>"));+ let file = 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 d = import_idml_with(&file, &|_| None).unwrap();+ assert_eq!(d.settings.epub_split, want, "{attrs}");+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.epub_split, want, "{attrs}");+ }+}+++++ /// 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, None, "`$ID/^y` is the right indent tab, the default separator, not text: {:?}", entry.separator);+ 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"));+ }