DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #288: IDML: resolve table styles and correct cell height fitting
aiongge1ed4ff118e7
diff --cc crates/doc/src/styles.rsindex 18b0f3dde,5812715a2..f936371a7--- a/crates/doc/src/styles.rs+++ b/crates/doc/src/styles.rs@@@ -417,24 -814,104 +829,122 @@@ mod testsassert!(!st.para_based_on_cycles(BASIC_PARAGRAPH, NO_PARA_STYLE));}+ #[test]+ fn character_style_attrs_include_its_based_on_chain_only() {+ let mut st = Styles::default();+ let cs = |name: &str, based_on: Option<&str>, chars| CharacterStyle {+ name: name.into(),+ based_on: based_on.map(Into::into),+ chars,+ shortcut: String::new(),+ };+ st.character.push(cs("Base", None, CharAttrs { font_style: Some("Bold".into()), size: Some(9.0), ..Default::default() }));+ st.character.push(cs("Strong", Some("Base"), CharAttrs { size: Some(14.0), ..Default::default() }));+ st.character.push(cs("Loop", Some("Loop"), CharAttrs { tracking: Some(5.0), ..Default::default() }));+ assert_eq!(st.char_style_attrs("Strong"), CharAttrs { font_style: Some("Bold".into()), size: Some(14.0), ..Default::default() });+ assert_eq!(st.char_style_attrs("Loop"), CharAttrs { tracking: Some(5.0), ..Default::default() });+ assert!(st.char_style_attrs(NO_CHAR_STYLE).is_empty());+ assert!(st.char_style_attrs("Missing").is_empty());+ }++ #[test]+ fn legacy_cell_and_table_style_json_keep_uniform_values() {+ let cell: CellStyle =+ serde_json::from_str(r#"{"name":"Legacy","insets":[1,2,3,4],"stroke":{"weight":2,"color":"Brand","tint":0.5,"kind":{"kind":"solid"}}}"#)+ .unwrap();+ assert!(cell.based_on.is_none());+ assert!(no_edge_attrs(&cell.strokes));+ assert!(no_inset_attrs(&cell.inset_overrides));+ let resolved = resolve_cell_style(std::slice::from_ref(&cell), "Legacy");+ let mut target = crate::table::Cell::default();+ resolved.apply_to(&mut target);+ assert_eq!(target.insets, [1.0, 2.0, 3.0, 4.0]);+ assert!(target.strokes.iter().all(|s| s.weight == 2.0 && s.color == "Brand" && s.tint == 0.5));+ let json = serde_json::to_value(&cell).unwrap();+ assert!(json.get("strokes").is_none());+ assert_eq!(serde_json::from_value::<CellStyle>(json).unwrap(), cell);++ let table: TableStyle =+ serde_json::from_str(r#"{"name":"Legacy","body":"Legacy","border":{"weight":3},"altRows":{"first":2,"firstColor":"Brand"}}"#).unwrap();+ let styles = Styles { cell: vec![cell], table: vec![table.clone()], ..Styles::default() };+ let mut target = crate::table::Table::new(1, 1, 2, 0, 0, 100.0);+ styles.resolve_table_style("Legacy").apply_to(&mut target, &styles.cell);+ assert_eq!(target.options.border_for(3).weight, 3.0);+ assert_eq!(target.options.alt_rows.as_ref().unwrap().first, 2);+ assert_eq!(target.cell(0, 0).unwrap().strokes[0].weight, 2.0);+ assert_eq!(serde_json::from_str::<TableStyle>(&serde_json::to_string(&table).unwrap()).unwrap(), table);+ }++ #[test]+ fn table_region_flags_cover_footer_right_column_and_rtl() {+ let cells = [+ CellStyle { name: "Body".into(), fill: Some("Body".into()), ..Default::default() },+ CellStyle { name: "Footer".into(), fill: Some("Footer".into()), ..Default::default() },+ CellStyle { name: "Right".into(), fill: Some("Right".into()), ..Default::default() },+ ];+ let mut style = TableStyle {+ body: Some("Body".into()),+ footer: Some("Footer".into()),+ right_column: Some("Right".into()),+ footer_same_as_body: Some(false),+ right_column_same_as_body: Some(false),+ ..Default::default()+ };+ for direction in [crate::TextDirection::LeftToRight, crate::TextDirection::RightToLeft] {+ let mut table = crate::table::Table::new(1, 1, 3, 0, 1, 100.0);+ table.options.direction = direction;+ let right = if direction == crate::TextDirection::LeftToRight { 2 } else { 0 };+ style.apply_to(&mut table, &cells);+ assert_eq!(table.cell(0, right).unwrap().fill, "Right");+ assert_eq!(table.cell(1, right).unwrap().fill, "Footer");+ }+ style.footer_same_as_body = Some(true);+ style.right_column_same_as_body = Some(true);+ let mut table = crate::table::Table::new(1, 1, 3, 0, 1, 100.0);+ style.apply_to(&mut table, &cells);+ assert!(table.cells.iter().all(|c| c.fill == "Body"));+ }++ #[test]+ fn single_column_tables_use_a_configured_right_region_when_left_is_absent() {+ let cells = [CellStyle { name: "Right".into(), fill: Some("Right".into()), ..Default::default() }];+ let style = TableStyle { right_column: Some("Right".into()), ..Default::default() };+ let mut table = crate::table::Table::new(1, 1, 1, 0, 0, 100.0);+ style.apply_to(&mut table, &cells);+ assert_eq!(table.cell(0, 0).unwrap().fill, "Right");+ }++ #[test]+ fn cell_and_table_style_resolution_stop_at_the_depth_limit() {+ let cells: Vec<_> = (0..40)+ .map(|i| CellStyle {+ name: i.to_string(),+ based_on: Some((i + 1).to_string()),+ fill: (i == 32).then(|| "Too deep".into()),+ fill_tint: (i == 31).then_some(0.5),+ ..Default::default()+ })+ .collect();+ let resolved = resolve_cell_style(&cells, "0");+ assert!(resolved.fill.is_none());+ assert_eq!(resolved.fill_tint, Some(0.5));+ let styles = Styles {+ table: (0..40)+ .map(|i| TableStyle {+ name: i.to_string(),+ based_on: Some((i + 1).to_string()),+ space_before: (i == 32).then_some(123.0),+ space_after: (i == 31).then_some(15.0),+ ..Default::default()+ })+ .collect(),+ ..Styles::default()+ };+ let resolved = styles.resolve_table_style("0");+ assert!(resolved.space_before.is_none());+ assert_eq!(resolved.space_after, Some(15.0));+ }+#[test]fn unique_names() {let names = ["Body", "Body 2"];diff --cc crates/idml/src/tests.rsindex d6befa5ea,806620c7a..8cc30cfa8--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -1285,336 -857,333 +1285,666 @@@ fn arabic_story_and_table_directions_suassert_eq!(st.direction, designcraft_doc::TextDirection::RightToLeft);assert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);}++#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap, its character style and a nested style through it; a paragraph+ // overriding it locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ 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 check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ let ns = st.para.nested_styles.clone().unwrap();+ assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap+ // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}++/// InDesign's designmap lists layers back to front; `Document::layers[0]` is the front layer.+#[test]+fn layers_import_and_export_in_stacking_order() {+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <Layer Self="L1" Name="Background"/>+ <Layer Self="L2" Name="Content"/>+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#;+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/>+ <Rectangle Self="r" ItemLayer="L1">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>+ <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ </Rectangle>+ </Spread>+ </idPkg:Spread>"#;+ let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap();+ let names = |d: &Document| d.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();+ assert_eq!(names(&d), ["Content", "Background"]);+ assert_eq!(d.spreads[0].items[0].layer, d.layers[1].id, "the rectangle stays on Background");++ let bytes = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut map = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("designmap.xml").unwrap(), &mut map).unwrap();+ let (bg, content) = (map.find(r#"Name="Background""#).unwrap(), map.find(r#"Name="Content""#).unwrap());+ assert!(bg < content, "designmap lists the back layer first");+ let back = import_idml(&bytes).unwrap();+ assert_eq!(names(&back), ["Content", "Background"]);+ assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id);+}++/// Synthetic forward references: both a body anchor and a footnote anchor own+/// a group containing a text frame whose story is serialized later.+#[test]+fn round_trips_anchored_text_frames_in_body_and_footnotes() {+ use designcraft_doc::{AnchorPosition, AnchoredObject, Content, Item, ItemId};+ use std::sync::Arc;+ let mut d = Document::new(&NewDocument::default());+ let layer = d.default_layer();+ let (_, body) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(20.0, 20.0, 400.0, 600.0), layer, "Body", ParaFormat::default()).unwrap();+ d.story_mut(body).unwrap().insert_note(4, "Note", ParaFormat::default());+ for in_note in [false, true] {+ let (frame, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 60.0, 30.0), layer, "Symbol", ParaFormat::default()).unwrap();+ let child = d.item(frame).unwrap().clone();+ d.spread_mut(SpreadRef::Doc(0)).unwrap().items.retain(|i| i.id != frame);+ let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Group, Default::default());+ group.content = Content::Group { items: vec![Arc::new(child)] };+ let anchor = AnchoredObject::new(group, AnchorPosition::Inline { y_offset: 2.0 });+ let story = d.story_mut(body).unwrap();+ if in_note {+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, anchor);+ } else {+ story.insert_object(0, anchor);+ }+ }+ d.check().unwrap();+ for _ in 0..2 {+ d = import_idml(&export_idml(&d)).unwrap();+ d.check().unwrap();+ assert_eq!(d.stories.len(), 3);+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ assert_eq!(body.notes.len(), 1);+ assert_eq!(body.objects.len(), 1);+ assert_eq!(body.notes[0].text.objects.len(), 1);+ let children: Vec<_> = d.anchored_items().into_iter().filter(|(_, i)| i.text_frame().is_some()).collect();+ assert_eq!(children.len(), 2);+ for (_, item) in children {+ let story = d.story(item.text_frame().unwrap().story).unwrap();+ assert_eq!(story.text, "Symbol");+ assert_eq!(story.frames, vec![item.id]);+ }+ }+}++#[test]+fn composite_references_resolve_by_identity_and_export_as_objects() {+ let map = DESIGNMAP.replace("</Document>", r#"+ <CompositeFont Self="CompositeFont/opaque%3a17" Name="Mixed%3a literal">+ <CompositeFontEntry Name="Base" FontStyle="$ID/Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>+ <CompositeFontEntry Name="Digits" CustomCharacters="0123456789" FontStyle="$ID/Bold" RelativeSize="80" HorizontalScale="90" VerticalScale="110" BaselineShift="5" ScaleOption="false"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry>+ </CompositeFont></Document>"#);+ let styles = STYLES+ .replace("<AppliedFont type=\"string\">Source Serif 4</AppliedFont>", "<AppliedFont type=\"object\">CompositeFont/opaque%3a17</AppliedFont>");+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Content>A1</Content><Footnote><ParagraphStyleRange><CharacterStyleRange><Content>B2</Content></CharacterStyleRange></ParagraphStyleRange></Footnote></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("Resources/Styles.xml", &styles),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", story),+ ]);+ let d = import_idml(&bytes).unwrap();+ let f = &d.styles.composite_fonts[0];+ assert_eq!(f.name, "Mixed%3a literal", "display names are not encoded identifiers");+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();+ for text in [body.as_ref(), &body.notes[0].text] {+ let (_, base) = d.styles.resolve_para(&text.paras[0]);+ let p = d.styles.resolve_char(&base, &text.chars[0].format);+ assert_eq!(d.styles.composite_font(&p.font_family), Some(f));+ }+ let output = export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&output)).unwrap();+ let mut xml = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut xml).unwrap();+ assert!(xml.contains("<AppliedFont type=\"object\">CompositeFont/Mixed%253a literal</AppliedFont>"), "{xml}");+ let back = import_idml(&output).unwrap();+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);+}++#[test]+fn malformed_mojikumi_rows_are_not_silently_coerced() {+ let good = r#"<OverrideMojikumiAkiType TargetMojikumiClass="12" SideMojikumiClass="18" SideIsAfterTarget="true" Minimum="0" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="false"/>"#;+ for (key, value) in [+ ("TargetMojikumiClass", "12.9"),+ ("SideMojikumiClass", "65536"),+ ("Minimum", "NaN"),+ ("Desired", "oops"),+ ("Minimum", "0.4"),+ ("Maximum", "0.1"),+ ("Maximum", "101"),+ ("CompressionPriority", "10"),+ ("AkiDoesNotFloat", "maybe"),+ ] {+ let mut row = crate::xml::parse(good.as_bytes()).unwrap();+ row.set(key, value);+ let mut xml = String::new();+ row.write(&mut xml, 0);+ let map = DESIGNMAP.replace("</Document>", &format!("<MojikumiTable Name=\"Bad\" BasedOnMojikumiSet=\"SimpChineseDefault\"><Properties><OverrideMojikumiAkiList>{xml}</OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"));+ let bytes = zip_files(&[+ ("designmap.xml", &map),+ ("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),+ ]);+ if matches!((key, value), ("Minimum", "0.4") | ("Maximum", "0.1" | "101") | ("CompressionPriority", "10")) {+ // Finite, representable rules survive import even if composition+ // cannot apply them. The resolver supplies a diagnostic instead.+ let document = import_idml(&bytes).unwrap();+ document.check().unwrap();+ assert!(designcraft_doc::mojikumi::Rules::resolve(&document.styles, "MojikumiTable/Bad").is_err());+ let restored = import_idml(&export_idml(&document)).unwrap();+ assert_eq!(restored.styles.mojikumi_tables, document.styles.mojikumi_tables);+ } else {+ let err = import_idml(&bytes).unwrap_err().to_string();+ assert!(err.contains("Mojikumi"), "{key}={value}: {err}");+ }+ }+}++#[test]+fn imports_column_rules_from_frames_and_object_styles() {+ let rule = r#"ColumnRuleOverride="true" ColumnRuleStrokeWidth="2.5" ColumnRuleStrokeColor="Color/Black" ColumnRuleStrokeTint="40"+ ColumnRuleStrokeType="StrokeStyle/$ID/Solid" ColumnRuleOverprintOverride="false" ColumnRuleOffset="-3" ColumnRuleTopInset="6"+ ColumnRuleBottomInset="9" ColumnRuleInsetChainOverride="false""#;+ let styles = format!(+ r#"<ObjectStyle Self="ObjectStyle/Padded" Name="Padded" EnableTextFrameGeneralOptions="true"><TextFramePreference TextColumnCount="2" {rule}/></ObjectStyle>"#+ );+ let d = inset_fixture(&format!(r#"<TextFramePreference TextColumnCount="3" {rule}/>"#), &styles);+ let style = d.styles.object.iter().find(|s| s.name == "Padded").unwrap().text_frame.clone().unwrap();+ for o in [d.spreads[0].items[0].text_frame().unwrap().options.clone(), style] {+ assert!(o.column_rule, "{o:?}");+ assert_eq!(o.column_rule_weight, 2.5);+ assert_eq!(o.column_rule_color, designcraft_color::swatch::BLACK);+ assert!((o.column_rule_tint - 0.4).abs() < 1e-6);+ assert_eq!((o.column_rule_offset, o.column_rule_top_inset, o.column_rule_bottom_inset), (-3.0, 6.0, 9.0));+ }+ // Absent attributes: no rule, InDesign's defaults.+ let d = inset_fixture(r#"<TextFramePreference TextColumnCount="3"/>"#, "");+ assert_eq!(d.spreads[0].items[0].text_frame().unwrap().options, designcraft_doc::TextFrameOptions { columns: 3, ..Default::default() });+}++#[test]+fn column_rules_round_trip() {+ let mut d = small_doc();+ let fid = d.spreads[0].items[0].id;+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.columns = 2;+ o.column_rule = true;+ o.column_rule_weight = 0.75;+ o.column_rule_color = "Brand".into();+ o.column_rule_tint = 0.5;+ o.column_rule_offset = 1.5;+ o.column_rule_top_inset = 4.0;+ o.column_rule_bottom_inset = 2.0;+ let want = o.clone();+ let bytes = export_idml(&d);+ let back = import_idml(&bytes).unwrap();+ let got = back.spreads[0].items.iter().find_map(|i| i.text_frame().filter(|t| t.options.column_rule)).unwrap().options.clone();+ assert_eq!(got, want);+ // Frames without a rule stay without one.+ let plain = export_idml(&small_doc());+ let back = import_idml(&plain).unwrap();+ assert!(back.spreads.iter().flat_map(|s| &s.items).filter_map(|i| i.text_frame()).all(|t| !t.options.column_rule));+}+ /// Fully synthetic style-only table, including sparse based-on attributes and local overrides.+ const CASCADE_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-base" Name="Base" FillColor="Color/Brand" FillTint="25"+ TopInset="2" LeftInset="3" BottomInset="4" RightInset="5" VerticalJustification="CenterAlign"+ TopEdgeStrokeWeight="2" TopEdgeStrokeColor="Color/Brand" TopEdgeStrokeTint="40" TopEdgeStrokeType="StrokeStyle/$ID/Dashed"+ LeftEdgeStrokeWeight="3" BottomEdgeStrokeWeight="4" RightEdgeStrokeWeight="5"+ AppliedParagraphStyle="ParagraphStyle/CellParagraph"/>+ <CellStyle Self="cs-body" Name="Body" FillTint="50"><Properties><BasedOn type="object">cs-base</BasedOn></Properties></CellStyle>+ <CellStyle Self="cs-left" Name="Left" FillColor="Color/Black" LeftEdgeStrokeWeight="0"><Properties><BasedOn type="object">cs-body</BasedOn></Properties></CellStyle>+ <CellStyle Self="cs-header" Name="Header" FillColor="Color/Paper" BottomEdgeStrokeColor="Color/Brand" BottomEdgeStrokeWeight="6">+ <Properties><BasedOn type="object">cs-body</BasedOn></Properties>+ </CellStyle>+ <CellStyle Self="cs-explicit" Name="Explicit" FillColor="Color/Brand" FillTint="75" TopInset="0"+ TopEdgeStrokeColor="Swatch/None" RightEdgeStrokeTint="30"/>+ </RootCellStyleGroup>+ <RootParagraphStyleGroup><ParagraphStyle Self="ParagraphStyle/CellParagraph" Name="CellParagraph" PointSize="9"/></RootParagraphStyleGroup>+ <RootTableStyleGroup>+ <TableStyle Self="TableStyle/$ID/[No table style]" Name="$ID/[No table style]"+ TopBorderStrokeWeight="7" LeftBorderStrokeWeight="8" BottomBorderStrokeWeight="9" RightBorderStrokeWeight="10"+ StartRowFillCount="0" StartRowFillColor="Color/Brand" StartRowFillTint="20" EndRowFillCount="0" EndRowFillColor="Swatch/None"+ HeaderRegionSameAsBodyRegion="true" FooterRegionSameAsBodyRegion="true"+ LeftColumnRegionSameAsBodyRegion="true" RightColumnRegionSameAsBodyRegion="true"/>+ <TableStyle Self="ts-base" Name="BaseTable" BodyRegionCellStyle="cs-body" HeaderRegionCellStyle="cs-header"+ LeftColumnRegionCellStyle="cs-left" HeaderRegionSameAsBodyRegion="false" LeftColumnRegionSameAsBodyRegion="false">+ <Properties><BasedOn type="string">$ID/[No table style]</BasedOn></Properties>+ </TableStyle>+ <TableStyle Self="ts-child" Name="Table" SpaceBefore="12" StartRowFillCount="1" EndRowFillCount="1">+ <Properties><BasedOn type="object">ts-base</BasedOn></Properties>+ </TableStyle>+ <TableStyle Self="TableStyle/$ID/[Basic Table]" Name="$ID/[Basic Table]" SpaceAfter="17">+ <Properties><BasedOn type="object">ts-child</BasedOn></Properties>+ </TableStyle>+ </RootTableStyleGroup></idPkg:Styles>"#;++ const CASCADE_STORY: &str = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table AppliedTableStyle="ts-child" HeaderRowCount="1" SpaceBefore="19" RightBorderStrokeColor="Color/Brand">+ <Row Name="0" MinimumHeight="24"/><Row Name="1" MinimumHeight="24"/>+ <Column Name="0" SingleColumnWidth="60"/><Column Name="1" SingleColumnWidth="60"/><Column Name="2" SingleColumnWidth="60"/>+ <Cell Name="0:0" AppliedCellStyle="CellStyle/$ID/[None]"><ParagraphStyleRange><CharacterStyleRange><Content>Header left</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+ <Cell Name="1:0" AppliedCellStyle="cs-explicit"><ParagraphStyleRange><CharacterStyleRange><Content>Explicit</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+ <Cell Name="2:0" AppliedCellStyle="cs-explicit" FillColor="Swatch/None" FillTint="0" LeftInset="0" VerticalJustification="BottomAlign"+ TopEdgeStrokeWeight="0" RightEdgeStrokeColor="Swatch/None" RightEdgeStrokePriority="7">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange><Content>Local</Content></CharacterStyleRange></ParagraphStyleRange>+ </Cell>+ <Cell Name="0:1" AppliedCellStyle="CellStyle/$ID/[None]"><ParagraphStyleRange><CharacterStyleRange><Content>Left</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+ <Cell Name="1:1"><ParagraphStyleRange><CharacterStyleRange><Content>Body</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+ <Cell Name="2:1"><ParagraphStyleRange><CharacterStyleRange><Content>Body right</Content></CharacterStyleRange></ParagraphStyleRange></Cell>+ </Table></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;++ fn fixture_with_table_styles(styles: &str, story: &str) -> Vec<u8> {+ 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),+ ])+ }++ #[test]+ fn table_style_cascade_preserves_sparse_edges_and_local_overrides() {+ let d = import_idml(&fixture_with_table_styles(CASCADE_STYLES, CASCADE_STORY)).unwrap();+ d.check().unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!((table.nrows(), table.ncols()), (2, 3));+ assert_eq!(table.style, "Table");+ assert_eq!(table.options.space_before, 19.0);+ assert_eq!(std::array::from_fn::<_, 4, _>(|i| table.options.border_for(i).weight), [7.0, 8.0, 9.0, 10.0]);+ assert_eq!(table.options.border_for(3).color, "Brand");+ let fills = table.options.alt_rows.as_ref().unwrap();+ assert_eq!((fills.first, fills.next, fills.first_tint), (1, 1, 0.2));+ assert_eq!(fills.first_color, "Brand");+ let header = table.cell(0, 0).unwrap();+ assert_eq!(header.fill, designcraft_color::swatch::PAPER, "header takes precedence over left region");+ assert!(header.style.is_empty(), "a table region does not become AppliedCellStyle");+ assert_eq!(header.insets, [2.0, 3.0, 4.0, 5.0]);+ assert_eq!(header.vj, designcraft_doc::VerticalJustification::Center);+ assert_eq!(header.text.paras[0].style, "CellParagraph");+ assert_eq!(header.strokes[0].weight, 2.0);+ assert_eq!(header.strokes[0].tint, 0.4);+ assert_ne!(header.strokes[0].kind, designcraft_doc::StrokeType::Solid);+ assert_eq!(header.strokes[2].weight, 6.0);+ assert_eq!(header.border_overrides, [true; 4]);+ assert_eq!(header.stroke_defined, [true; 4]);+ assert_eq!(header.stroke_priorities, [0; 4]);+ let explicit = table.cell(0, 1).unwrap();+ assert_eq!(explicit.fill, "Brand");+ assert_eq!(explicit.fill_tint, 0.75);+ assert_eq!(explicit.insets, [0.0, 3.0, 4.0, 5.0]);+ assert_eq!(explicit.strokes[0].weight, 2.0, "color-only override inherits weight");+ assert_eq!(explicit.strokes[0].color, designcraft_color::swatch::NONE);+ assert_eq!(explicit.strokes[3].weight, 5.0);+ assert_eq!(explicit.strokes[3].tint, 0.3);+ let local = table.cell(0, 2).unwrap();+ assert_eq!(local.fill, designcraft_color::swatch::NONE);+ assert_eq!(local.fill_tint, 0.0);+ assert_eq!(local.insets[1], 0.0);+ assert_eq!(local.vj, designcraft_doc::VerticalJustification::Bottom);+ assert_eq!(local.strokes[0].weight, 0.0);+ assert_eq!(local.strokes[3].color, designcraft_color::swatch::NONE);+ assert_eq!(local.stroke_priorities, [0, 0, 0, 7]);+ assert_eq!(local.text.paras[0].style, st::BASIC_PARAGRAPH, "explicit paragraph style wins");+ assert_eq!(table.cell(1, 0).unwrap().fill, designcraft_color::swatch::BLACK);+ assert_eq!(table.cell(1, 0).unwrap().strokes[1].weight, 0.0);+ assert_eq!(table.cell(1, 1).unwrap().fill_tint, 0.5);+ assert_eq!(table.cell(1, 2).unwrap().fill, "Brand");++ let back = import_idml(&export_idml(&d)).unwrap();+ let roundtrip = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ for (before, after) in table.cells.iter().zip(&roundtrip.cells) {+ assert_eq!(after.strokes, before.strokes);+ assert_eq!(after.border_overrides, before.border_overrides);+ assert_eq!(after.stroke_priorities, before.stroke_priorities);+ assert_eq!(after.style, before.style);+ assert_eq!(after.fill, before.fill);+ assert_eq!(after.insets, before.insets);+ }+ for i in 0..4 {+ assert_eq!(roundtrip.options.border_for(i), table.options.border_for(i));+ }+ let style = back.styles.cell.iter().find(|s| s.name == "Explicit").unwrap();+ assert_eq!(style.strokes[0].weight, None, "style export keeps absence distinct from zero");+ assert_eq!(style.strokes[0].color.as_deref(), Some(designcraft_color::swatch::NONE));+ assert_eq!(back.styles.table.iter().find(|s| s.name == "Table").unwrap().based_on.as_deref(), Some("BaseTable"));+ }++ #[test]+ fn table_style_same_as_body_flags_and_editable_basic_table_are_inherited() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\" SpaceBefore",+ "Name=\"Table\" HeaderRegionSameAsBodyRegion=\"true\" LeftColumnRegionSameAsBodyRegion=\"true\" SpaceBefore",+ );+ let story = CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"TableStyle/$ID/[Basic Table]\"");+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert!(table.style.is_empty());+ assert_eq!(table.options.space_after, 17.0);+ assert_eq!(table.cell(0, 0).unwrap().fill, "Brand");+ assert_eq!(table.cell(0, 0).unwrap().strokes[2].weight, 4.0);+ assert_eq!(table.cell(1, 0).unwrap().fill, "Brand");+ assert_eq!(table.cell(1, 0).unwrap().strokes[1].weight, 3.0);+ }++ #[test]+ fn table_style_cycles_and_missing_bases_terminate_without_losing_nearest_values() {+ let styles = r#"<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <RootCellStyleGroup>+ <CellStyle Self="CellStyle/A" Name="A" TopEdgeStrokeWeight="0"><Properties><BasedOn type="object">CellStyle/B</BasedOn></Properties></CellStyle>+ <CellStyle Self="CellStyle/B" Name="B" TopEdgeStrokeColor="Color/Brand"><Properties><BasedOn type="object">CellStyle/A</BasedOn></Properties></CellStyle>+ <CellStyle Self="CellStyle/Missing" Name="Missing" LeftInset="0"><Properties><BasedOn type="object">CellStyle/Unknown</BasedOn></Properties></CellStyle>+ </RootCellStyleGroup><RootTableStyleGroup>+ <TableStyle Self="ts-child" Name="A" BodyRegionCellStyle="CellStyle/A"><Properties><BasedOn type="object">TableStyle/B</BasedOn></Properties></TableStyle>+ <TableStyle Self="TableStyle/B" Name="B" SpaceAfter="20"><Properties><BasedOn type="object">ts-child</BasedOn></Properties></TableStyle>+ </RootTableStyleGroup></idPkg:Styles>"#;+ let d = import_idml(&fixture_with_table_styles(styles, CASCADE_STORY)).unwrap();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.options.space_after, 20.0);+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].weight, 0.0);+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].color, "Brand");+ let missing = designcraft_doc::resolve_cell_style(&d.styles.cell, "Missing");+ assert_eq!(missing.inset_overrides[1], Some(0.0));+ }++ #[test]+ fn table_local_alternating_fill_off_survives_named_style_roundtrip() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\" SpaceBefore",+ "Name=\"Table\" StartColumnFillCount=\"1\" EndColumnFillCount=\"1\" StartColumnFillColor=\"Color/Brand\" SpaceBefore",+ );+ let story = CASCADE_STORY.replace("HeaderRowCount=\"1\"", "HeaderRowCount=\"1\" StartRowFillCount=\"0\" StartColumnFillCount=\"0\"");+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert!(table.options.alt_rows.is_none());+ assert!(table.options.alt_cols.is_none());+ }+ }++ #[test]+ fn table_local_fill_counts_enable_inherited_disabled_pattern_colors() {+ let story =+ CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"ts-base\" StartRowFillCount=\"1\" EndRowFillCount=\"1\"");+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let fills = table.options.alt_rows.as_ref().unwrap();+ assert_eq!((fills.first, fills.next), (1, 1));+ assert_eq!(fills.first_color, "Brand");+ assert_eq!(fills.first_tint, 0.2);+ }++ #[test]+ fn table_absent_and_explicit_default_edges_remain_distinct_on_idml_roundtrip() {+ let story = CASCADE_STORY+ .replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"Missing\"")+ .replace("Name=\"1:1\"", "Name=\"1:1\" TopEdgeStrokeWeight=\"1\" TopEdgeStrokePriority=\"0\"");+ let document = import_idml(&fixture_with_table_styles(STYLES, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 0).unwrap().stroke_defined, [false; 4]);+ assert_eq!(table.cell(1, 1).unwrap().stroke_defined, [true, false, false, false]);+ assert_eq!(table.cell(1, 1).unwrap().border_overrides, [false; 4]);+ assert_eq!(table.cell(1, 1).unwrap().stroke_priorities, [0; 4]);+ }+ }++ #[test]+ fn multiline_table_and_cell_style_bases_resolve() {+ let styles = CASCADE_STYLES.replace(">cs-base</BasedOn>", ">\n cs-base \n</BasedOn>").replace(">ts-base</BasedOn>", ">\n ts-base \n</BasedOn>");+ let document = import_idml(&fixture_with_table_styles(&styles, CASCADE_STORY)).unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().strokes[0].weight, 2.0);+ assert_eq!(table.options.border_for(0).weight, 7.0);+ }++ #[test]+ fn legacy_native_documents_export_both_builtin_table_styles_when_missing() {+ let story = CASCADE_STORY.replace("AppliedTableStyle=\"ts-child\"", "AppliedTableStyle=\"TableStyle/$ID/[Basic Table]\"");+ let mut document = import_idml(&fixture_with_story(&story)).unwrap();+ document.styles_mut().table.clear();+ let bytes = export_idml(&document);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();+ let mut styles = String::new();+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut styles).unwrap();+ assert_eq!(styles.matches("Self=\"TableStyle/$ID/[Basic Table]\"").count(), 1);+ assert_eq!(styles.matches("Self=\"TableStyle/$ID/[No table style]\"").count(), 1);+ let back = import_idml(&bytes).unwrap();+ assert!(back.styles.table.iter().any(|s| s.name == designcraft_doc::BASIC_TABLE));+ }++ #[test]+ fn hostile_table_spans_are_clamped_before_arithmetic() {+ let story = CASCADE_STORY.replace("Name=\"1:1\"", "Name=\"1:1\" RowSpan=\"inf\" ColumnSpan=\"inf\"");+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ document.check().unwrap();+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().row_span, 1);+ assert_eq!(table.cell(1, 1).unwrap().col_span, 2);+ }++ #[test]+ fn signed_idml_edge_priorities_roundtrip_without_clamping() {+ let story = CASCADE_STORY.replace(+ "Name=\"1:1\"",+ "Name=\"1:1\" TopEdgeStrokePriority=\"-5\" LeftEdgeStrokePriority=\"-2147483648\" RightEdgeStrokePriority=\"2147483647\"",+ );+ let document = import_idml(&fixture_with_table_styles(CASCADE_STYLES, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(table.cell(1, 1).unwrap().stroke_priorities, [-5, i32::MIN, 0, i32::MAX]);+ }+ }++ #[test]+ fn alternating_table_strokes_inherit_and_roundtrip_without_flattening_cell_edges() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"BaseTable\"",+ "Name=\"BaseTable\" StartRowStrokeCount=\"1\" EndRowStrokeCount=\"1\" StartRowStrokeWeight=\"0\" EndRowStrokeWeight=\"0\" StartRowStrokeColor=\"Color/Paper\" EndRowStrokeColor=\"Color/Brand\" StartColumnStrokeCount=\"2\" EndColumnStrokeCount=\"1\" StartColumnStrokeWeight=\"1\" EndColumnStrokeWeight=\"2\" EndColumnLineStyle=\"StrokeStyle/$ID/Dotted\" SkipFirstAlternatingStrokeColumns=\"1\"",+ ).replace("Name=\"Table\"", "Name=\"Table\" StartRowStrokeTint=\"25\"");+ let story = CASCADE_STORY.replace("HeaderRowCount=\"1\"", "HeaderRowCount=\"1\" EndRowStrokeColor=\"Swatch/None\"");+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ let before = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let row = before.options.row_strokes.as_ref().unwrap();+ assert_eq!((row.first, row.next), (1, 1));+ assert_eq!(row.first_stroke.tint, 0.25);+ assert_eq!(row.first_stroke.color, designcraft_color::swatch::PAPER);+ assert_eq!(row.next_stroke.color, designcraft_color::swatch::NONE);+ assert!(!row.uniform_stroke().unwrap().is_visible(), "zero patterns are uniform even when their colors differ");+ let column = before.options.column_strokes.as_ref().unwrap();+ assert_eq!((column.first, column.next, column.skip_first), (2, 1, 1));+ assert_eq!(column.next_stroke.kind, designcraft_doc::StrokeType::Dotted);+ assert!(column.uniform_stroke().is_none(), "nonuniform/skipped patterns are preserved without guessing their phase");+ assert_eq!(before.cell(0, 0).unwrap().strokes[2].weight, 6.0, "cell styles remain higher-precedence edges");+ let back = import_idml(&export_idml(&document)).unwrap();+ let after = back.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ assert_eq!(after.options.row_strokes, before.options.row_strokes);+ assert_eq!(after.options.column_strokes, before.options.column_strokes);+ let style = back.styles.table.iter().find(|s| s.name == "Table").unwrap();+ assert_eq!(style.row_strokes.first_stroke.weight, None);+ assert_eq!(style.row_strokes.first_stroke.tint, Some(0.25));+ }++ #[test]+ fn alternating_table_strokes_local_off_overrides_named_style_on_roundtrip() {+ let styles = CASCADE_STYLES.replace(+ "Name=\"Table\"",+ "Name=\"Table\" StartRowStrokeCount=\"1\" EndRowStrokeCount=\"1\" StartColumnStrokeCount=\"1\" EndColumnStrokeCount=\"1\"",+ );+ let story = CASCADE_STORY.replace(+ "HeaderRowCount=\"1\"",+ "HeaderRowCount=\"1\" StartRowStrokeCount=\"0\" EndRowStrokeCount=\"0\" StartRowStrokeWeight=\"4\" EndRowStrokeColor=\"Color/Brand\" StartColumnStrokeCount=\"0\" EndColumnStrokeCount=\"0\" SkipFirstAlternatingStrokeColumns=\"3\" EndColumnLineStyle=\"StrokeStyle/$ID/Dotted\"",+ );+ let document = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ for document in [&document, &import_idml(&export_idml(&document)).unwrap()] {+ let table = document.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let row = table.options.row_strokes.as_ref().unwrap();+ let column = table.options.column_strokes.as_ref().unwrap();+ assert_eq!((row.first, row.next, column.first, column.next), (0, 0, 0, 0));+ assert!(row.uniform_stroke().is_none());+ assert!(column.uniform_stroke().is_none());+ assert_eq!(row.first_stroke.weight, 4.0);+ assert_eq!(row.next_stroke.color, "Brand");+ assert_eq!(column.skip_first, 3);+ assert_eq!(column.next_stroke.kind, designcraft_doc::StrokeType::Dotted);+ }+ }++ #[test]+ fn complete_uniform_native_style_fields_keep_legacy_identity_on_idml_roundtrip() {+ let mut document = import_idml(&fixture()).unwrap();+ let stroke = designcraft_doc::CellStroke { weight: 3.0, tint: 0.5, ..Default::default() };+ document.styles_mut().cell.push(designcraft_doc::CellStyle {+ name: "Uniform".into(),+ insets: Some([5.0; 4]),+ stroke: Some(stroke.clone()),+ ..Default::default()+ });+ document.styles_mut().table.push(designcraft_doc::TableStyle { name: "Uniform".into(), border: Some(stroke.clone()), ..Default::default() });+ let back = import_idml(&export_idml(&document)).unwrap();+ let cell = back.styles.cell.iter().find(|s| s.name == "Uniform").unwrap();+ assert_eq!(cell.insets, Some([5.0; 4]));+ assert_eq!(cell.stroke.as_ref(), Some(&stroke));+ assert!(cell.strokes.iter().all(designcraft_doc::CellStrokeAttrs::is_empty));+ let table = back.styles.table.iter().find(|s| s.name == "Uniform").unwrap();+ assert_eq!(table.border.as_ref(), Some(&stroke));+ assert!(table.borders.iter().all(designcraft_doc::CellStrokeAttrs::is_empty));+ }