From 09e87fadeae0cd1fff6aefc3e4d25b57998d0190 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Wed, 7 Oct 2026 22:19:20 +0000 Subject: [PATCH] feat: write page item values only where they differ from the object style IDML leaves out the values of a page item that equal those of its applied object style. The writer now compares with the style's effective values (its own, then the styles it is based on, then [None]): - TextFramePreference: an attribute is written when its category is off in the style's category list (chunk 0x1B92E, also for [None]) or its value differs; TextColumnMaxWidth (DOM 8), TextColumnCount (DOM 10) and InsetSpacing (DOM 11) are always written; footnote values from 13.1 (objects.md, text frame preferences). - Fill, stroke, miter and corner attributes (attributes.md). - Transparency effects: only differing values, and an effect element only when it has one or its opacity stops differ (transparency.md). New decoding: object style chunk 0x1B924 fields for balance, fixed width, justification, first baseline offset (code 4 = XHeight, also for frames) and auto-sizing; chunk 0x1B92C (style transparency). Object styles get the DOM 12 text frame values from DOM 8 and FootnotesEnableOverrides from 13.1 (idml-values.md). --- docs/format/attributes.md | 27 +++++ docs/format/idml-values.md | 15 +++ docs/format/objects.md | 76 +++++++++++- docs/format/transparency.md | 21 ++++ src/audit.rs | 3 + src/idml/applied.rs | 139 ++++++++++++++++++++++ src/idml/attrs.rs | 7 -- src/idml/mod.rs | 6 + src/idml/spread.rs | 224 +++++++++++++++++++++++++++--------- src/idml/styles.rs | 65 +++++++++++ src/idml/transparency.rs | 33 +++++- src/model/ids.rs | 1 + src/model/style.rs | 41 +++++++ 13 files changed, 590 insertions(+), 68 deletions(-) create mode 100644 src/idml/applied.rs diff --git a/docs/format/attributes.md b/docs/format/attributes.md index 81323a0..6d15d58 100644 --- a/docs/format/attributes.md +++ b/docs/format/attributes.md @@ -64,6 +64,33 @@ corners of object styles (chunk 0x1B92B) and of the page item defaults (class 0x6E07): all four radii and options of `PageItemDefault` match in 495 of 495 documents. +**Values equal to the object style.** The style's effective value is +its own (chunk 0x1B92B), else that of the style it is based on, else the +root `[None]`'s (`StrokeWeight="0"`, `FillTint="-1"`, `FillColor` and +`StrokeColor` `Swatch/None`, `CornerRadius="12"`, `MiterLimit="4"`, +`CornerOption="None"`; `idml-values.md`). Over the 489 trustworthy pairs, +the converter wrote these values where the IDML has none, and every one +of them equals the style's effective value: + +| Attribute | Written though the IDML has none | IDML writes it though equal | +|---|---:|---:| +| `StrokeWeight` | 27,989 | 5 | +| `CornerRadius` | 1,608 | 0 | +| `FillTint` | 1,423 | 0 | +| `StrokeColor` | 1,336 | 0 | +| `FillColor` | 312 | 0 | +| `CornerOption` | 87 | 0 | +| `MiterLimit` | 26 | 0 | + +Of the `StrokeWeight` values, the 26,969 on items whose IDML element has +the same tag all equal the style (17,501 text frames, 7,070 rectangles, +2,074 polygons, 297 ovals, 27 lines); the others are on shapes written +as another element type. The converter leaves out these attributes, and +the four corner radii and options, when they equal the style's value +(numbers to 6 significant digits). `StrokeWeight="1"` on an item with +`[None]` and no stroke weight of its own (`objects.md`, page item +settings) differs from `[None]`'s 0 and is still written. + Transparency attributes (IDs 0x108xx and 0x1EBxx) are described in `transparency.md`. diff --git a/docs/format/idml-values.md b/docs/format/idml-values.md index b40bb58..24b5db9 100644 --- a/docs/format/idml-values.md +++ b/docs/format/idml-values.md @@ -204,6 +204,21 @@ column, inset, footnote and column rule values of many of these from the INDD. Values that only the 2 files with DOM 20 have (18) are left out as for the preferences. +The `TextFramePreference` values that the file lists from DOM 12 +(`UseFlexibleColumnWidth="false"`, `TextColumnMaxWidth="0"`, +`UseNoLineBreaksForAutoSizing="false"` and the auto-sizing values) are +on every object style from DOM 8: 607 of 607 styles of DOM 8 to 11 in +the trustworthy pairs, `[None]` included, and none of the 28 of DOM 7 +(the file's source had no DOM 8 to 11 files). The converter writes them +from DOM 8; the auto-sizing values it reads from the INDD take +precedence. + +`TextFramePreference` `FootnotesEnableOverrides="false"` is on every +object style, `[None]` included, from InDesign 13.1 (INDD header +version): 1,392 of 1,392 styles of the trustworthy pairs, none before. +The value file has it only from DOM 15, since it is generated per major +version; the converter writes it from 13.1. + ## Composite font entries `Locked="true"` is in all 1,440 `CompositeFontEntry` elements of the diff --git a/docs/format/objects.md b/docs/format/objects.md index 2748ad3..09ede66 100644 --- a/docs/format/objects.md +++ b/docs/format/objects.md @@ -1328,8 +1328,16 @@ leaves it out with a warning (`big-endian.md`). |---|---|---| | 0 | f64 | `TextColumnFixedWidth` | | 8 | f64 | `TextColumnGutter` | +| 32 | u16, 1 = true | `VerticalBalanceColumns` | | 34, 42, 50, 58 | four f64, inset spacing | `InsetSpacing` (below) | | 66 | u32 | `TextColumnCount` | +| 70 | u16, 1 = true | `UseFixedColumnWidth` | +| 74 | u16, codes as for frames | `VerticalJustification` | +| 76 | u16, codes as for frames, and 4 `XHeight` | `FirstBaselineOffset` | +| 116 | u16, codes as for frames | `AutoSizingType` | +| 118 | u16, codes as for frames | `AutoSizingReferencePoint` | +| 120, 122 | u16 1 = true, f64 | `UseMinimumHeightForAutoSizing`, `MinimumHeightForAutoSizing` | +| 130, 132 | u16 1 = true, f64 | `UseMinimumWidthForAutoSizing`, `MinimumWidthForAutoSizing` | | 144 | u16, 1 = true | `FootnotesSpanAcrossColumns`, `SpanFootnotesAcross` | | 146 | f64 | `FootnotesMinimumSpacing`, `MinimumSpacingOption` | | 154 | f64 | `FootnotesSpaceBetween`, `SpaceBetweenFootnotes` | @@ -1337,6 +1345,34 @@ leaves it out with a warning (`big-endian.md`). | 198 | u32 swatch, 0 = `n` | `ColumnRuleStrokeColor` | | 210 | f64 | `ColumnRuleStrokeTint` | +The fields from offset 32 to 132 were found by testing every offset +against the IDML style, over the 2,155 object styles of the trustworthy +pairs that match an IDML style by name (1,000 with 222 bytes, 607 with +142 and 520 with 162). Each is the only offset that matches all styles +of the 222- and 142-byte layouts: + +| Offset | Values seen (222 / 142 bytes) | +|---|---| +| 32 | 1 true in each layout, all match | +| 70 | 142: 1 true; 222: all false | +| 74 | 222: 4 `CenterAlign`; 142: 3 `CenterAlign`, 2 `BottomAlign` | +| 76 | 222: 952 `AscentOffset`, 42 `EmboxHeight`, 6 `XHeight`; 142: 584, 1 and 22; 162: 516 `AscentOffset`, 4 `EmboxHeight` | +| 116 | 3 distinct values in each layout | +| 118 | 142: 5 distinct values | +| 120, 122 | 142: 6 true, 6 distinct heights | +| 130, 132 | 142: 2 true, 3 distinct widths | + +In the 162-byte layout the justification and auto-sizing fields have one +value in every style, and in the 106-byte layout (28 styles) every field +but offset 76 does; the converter assumes the offsets of the larger +layouts for 162 bytes and reads only offset 76 from 106 bytes. +`IgnoreWrap`, `MinimumFirstBaselineOffset`, `VerticalThreshold`, +`UseFlexibleColumnWidth`, `TextColumnMaxWidth` and +`UseNoLineBreaksForAutoSizing` have one value in every style (false or +0), so no field can be shown for them; the converter writes the observed +value (`idml-values.md`). Code 4 of `FirstBaselineOffset` is shown only +in styles; the converter reads it in frames too. + Footnote and column rule values: 305 of 305 styles whose chunk has them. The column rule colour maps one to one over 41 (file, UID) pairs. Only one style (3 copies) has unequal insets, and it shows only the top inset @@ -1528,7 +1564,7 @@ From the frame's multi-column frame object (class 0x263): | 0x2D1 | u32 0 | `TextColumnCount` (1,052/1,052) | | 0x2D1 | f64 4 | `TextColumnGutter` (93/93) | | 0x2D1 | f64 14 | `TextColumnFixedWidth` (1,045/1,045) | -| 0x2CE | u16 0 | `FirstBaselineOffset`: 0 LeadingOffset, 1 AscentOffset, 2 CapHeight, 3 EmboxHeight (below) | +| 0x2CE | u16 0 | `FirstBaselineOffset`: 0 LeadingOffset, 1 AscentOffset, 2 CapHeight, 3 EmboxHeight, 4 XHeight (below) | | 0x2CE | u16 2 | `VerticalJustification`: 0 Top, 1 Center, 2 Bottom, 3 Justify (350/350) | | 0x2CE | u16 20 | `VerticalBalanceColumns` (18/18) | | 0x2CE | u16 22 | `AutoSizingType`: 0 Off, 1 HeightOnly, 2 WidthOnly, 3 HeightAndWidth (61/61) | @@ -1567,6 +1603,44 @@ them); what decides this was not found, and the converter writes the list for every frame from DOM 11 on. DOM 7 to 10 files give most frames no `InsetSpacing` at all, and the converter writes none for them. +**Values written on frames.** IDML writes an attribute of a frame's +`TextFramePreference` when its category is off in the frame's object +style (the category ID is not in the style's list, chunk 0x1B92E, also +for `[None]`), or when the frame's value differs from the style's +value. The style's values are its own, or, if it has no text frame +settings, those of the style it is based on, then `[None]`'s. + +| Category | ID | Attributes | +|---|---|---| +| General | 0x1B93E | `TextColumnCount`, `TextColumnGutter`, `TextColumnFixedWidth`, `UseFixedColumnWidth`, `UseFlexibleColumnWidth`, `TextColumnMaxWidth`, `VerticalJustification`, `VerticalThreshold`, `IgnoreWrap`, `VerticalBalanceColumns`, `InsetSpacing` | +| Baseline | 0xADC8 | `FirstBaselineOffset`, `MinimumFirstBaselineOffset` | +| Auto-sizing | 0xADC9 | the seven auto-sizing attributes | +| Footnotes | 0xADCA | the four `Footnotes…` attributes | +| Column rules | 0xADCB | the ten `ColumnRule…` attributes | + +Evidence over the 489 trustworthy pairs. Frames with style `[None]` +write a whole category in a document if and only if `[None]`'s list +lacks the ID (counting documents with such frames): + +| Category | ID missing | ID present | +|---|---|---| +| Auto-sizing (DOM 8 on) | written in 28 of 28 documents | written in 0 of 224 (one more has frames whose values differ) | +| Footnotes (13.1 on) | 21 of 21 | 0 of 153 | +| Column rules (DOM 15 on) | 35 of 35 | 0 of 64 | +| General, baseline | (ID present in all 254) | 0 of 254 | + +Exceptions: `TextColumnMaxWidth` is on every frame from DOM 8 (22,775 of +22,775), `TextColumnCount` on every frame from DOM 10 (18,679 of 18,680; +before, it follows the rule: absent in 4,006 frames where it equals the +style), and `InsetSpacing` on every frame from DOM 11. The footnote +values are on no frame before 13.1: none of the 3 documents of 13.0 has +them, though one has frames whose style has the category off. + +Applied to the converter's frame values and the reference styles' +values, the rule leaves out 379,953 values that the IDML does not have, +keeps the 200,434 it has, and leaves out one value that the IDML has (a +`TextColumnFixedWidth` equal to its style's). + `ColumnRuleOverride`: chunk 0x2265A is all zero in the frames of the pairs except one, whose IDML has `true`; the converter writes `false` for zero chunks and frames without it (7,247 of 7,248). diff --git a/docs/format/transparency.md b/docs/format/transparency.md index 5b465b7..71cba34 100644 --- a/docs/format/transparency.md +++ b/docs/format/transparency.md @@ -29,6 +29,27 @@ value itself, which is the evidence that tells the attribute apart. The 576 object styles of the pairs (matched by name) agree with their IDML style on every attribute below. +## Values equal to the object style + +The converter writes only the values that differ from the object +style's (its chunk 0x1B92C, then the styles it is based on), and an +effect element only when it has such a value or its opacity stops +differ from the style's. Per effect element the converter wrote before +this rule, over the 489 trustworthy pairs (D = the attributes whose value +differs from the style's effective value; style values followed through +`BasedOn`, then `TransparencyDefaultContainerObject`): + +| Element | D empty, IDML writes nothing | D empty, IDML writes it | D not empty, IDML writes exactly D or more | +|---|---:|---:|---:| +| `GradientFeatherSetting` | 6,251 | 53 | 2,604 | +| `InnerShadowSetting` | 2,884 | 0 | 17 | +| `DropShadowSetting` | 44 | 8 | 289 | +| `BlendingSetting` | 1 | 0 | 1,616 | + +Where IDML writes more than D (349 elements), the converter already +wrote those values. The 53 + 8 elements with D empty that IDML still +writes are not explained. + ## Object transparency (`TransparencySetting`) | ID | IDML | Encoding | On the item | diff --git a/src/audit.rs b/src/audit.rs index d748c56..c137b99 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -30,6 +30,8 @@ pub enum List { ObjectStyle, /// An object style's frame fitting attributes. ObjectStyleFitting, + /// An object style's transparency attributes. + ObjectStyleTransparency, /// A paragraph or character style's text attributes. Style, /// The text attributes of a run of text. @@ -47,6 +49,7 @@ impl List { List::Item => "page item", List::ObjectStyle => "object style", List::ObjectStyleFitting => "object style fitting", + List::ObjectStyleTransparency => "object style transparency", List::Style => "style", List::Text => "text", List::Table => "table", diff --git a/src/idml/applied.rs b/src/idml/applied.rs new file mode 100644 index 0000000..eaddd60 --- /dev/null +++ b/src/idml/applied.rs @@ -0,0 +1,139 @@ +//! The values of an applied object style that a page item is compared +//! with. IDML writes some values of a page item only when they differ +//! from its object style (`docs/format/objects.md`, page item settings and +//! text frame preferences). + +use super::*; + +/// The effective values of an object style as the converter writes them: +/// its own, then those of the styles it is based on, then the root +/// `[None]`. +#[derive(Debug, Default)] +pub(super) struct StyleValues { + /// Page item attributes (`FillColor`, `StrokeWeight`, …). + pub item: Vec<(String, String)>, + /// `TextFramePreference` attributes. + pub frame: Vec<(String, String)>, + /// The style's category list (chunk 0x1B92E); `None` without it. + pub enabled: Option>, + /// Transparency attributes (chunk 0x1B92C) by attribute-list ID. + pub transparency: Vec<(u32, crate::model::Value)>, +} + +impl StyleValues { + pub(super) fn item(&self, name: &str) -> Option<&str> { + self.item + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + } + + pub(super) fn transparency(&self, id: u32) -> Option<&crate::model::Value> { + self.transparency + .iter() + .find(|(i, _)| *i == id) + .map(|(_, v)| v) + } + + pub(super) fn frame(&self, name: &str) -> Option<&str> { + self.frame + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.as_str()) + } +} + +/// Whether two IDML values are the same: equal text, or numbers equal to +/// 6 significant digits (as `tools/compare.py` compares them). +pub(super) fn same_value(a: &str, b: &str) -> bool { + if a == b { + return true; + } + match (a.parse::(), b.parse::()) { + (Ok(x), Ok(y)) => (x - y).abs() <= 5e-7 * x.abs().max(y.abs()), + _ => false, + } +} + +fn add_missing(to: &mut Vec<(String, String)>, from: &[(String, String)]) { + for (k, v) in from { + if !to.iter().any(|(n, _)| n == k) { + to.push((k.clone(), v.clone())); + } + } +} + +impl Writer<'_> { + /// Whether `os` is the root object style `[None]`. + pub(super) fn is_root_object_style(os: &crate::model::ObjectStyle) -> bool { + os.builtin && os.name == "[None]" && os.based_on.is_none() + } + + /// The effective values of object style `uid`, or `None` if the + /// document has no such style. + pub(super) fn style_values(&self, uid: u32) -> Option> { + if let Some(v) = self.style_values.borrow().get(&uid) { + return Some(v.clone()); + } + let styles = &self.doc.object_styles; + let os = styles.get(&uid)?; + let root = styles.values().find(|s| Self::is_root_object_style(s)); + let mut out = StyleValues { + enabled: os.enabled.clone(), + ..StyleValues::default() + }; + let mut seen = std::collections::HashSet::new(); + let mut cur = Some(os); + while let Some(s) = cur { + if !seen.insert(s.uid) { + break; + } + let is_root = Self::is_root_object_style(s); + let node = self.object_style_node(s, is_root); + add_missing(&mut out.item, &node.attrs); + for (id, v) in &s.transparency.values { + if out.transparency.iter().all(|(i, _)| i != id) { + out.transparency.push((*id, v.clone())); + } + } + // A style without text frame settings takes them from the + // style it is based on. + if (s.frame.is_some() || is_root) + && let Some(t) = node.child("TextFramePreference") + { + add_missing(&mut out.frame, &t.attrs); + } + cur = match s.based_on.and_then(|b| styles.get(&b)) { + Some(b) => Some(b), + None if !is_root => root, + None => None, + }; + } + // A chain with no text frame settings: the style's own written + // values. + if out.frame.is_empty() + && let Some(t) = self + .object_style_node(os, false) + .child("TextFramePreference") + { + out.frame = t.attrs.clone(); + } + let v = std::rc::Rc::new(out); + self.style_values.borrow_mut().insert(uid, v.clone()); + Some(v) + } +} + +#[cfg(test)] +mod tests { + use super::same_value; + + #[test] + fn compares_numbers_to_six_digits() { + assert!(same_value("12", "12.0000001")); + assert!(same_value("Swatch/None", "Swatch/None")); + assert!(!same_value("0", "1e-13")); + assert!(!same_value("12", "12.01")); + assert!(!same_value("TopAlign", "CenterAlign")); + } +} diff --git a/src/idml/attrs.rs b/src/idml/attrs.rs index b87e06e..af2869f 100644 --- a/src/idml/attrs.rs +++ b/src/idml/attrs.rs @@ -746,13 +746,6 @@ impl Writer<'_> { .collect() } - /// Write page item attributes from the item's attribute list. - pub(super) fn item_attrs(&self, x: &mut Xml, attrs: &Attrs) { - for (name, text) in self.item_attr_values(attrs) { - x.attr(name, text); - } - } - /// Page item attributes from an attribute list, as IDML values. pub(super) fn item_attr_values(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { self.attr_values(attrs, ITEM_ATTRS) diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 8baee73..d84e28e 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -7,6 +7,7 @@ //! the text forms of values, `pages` page numbering, `values` the values //! every IDML has, and `transparency` the effect settings. +mod applied; mod attrs; mod designmap; mod export; @@ -65,6 +66,9 @@ struct Writer<'a> { page_sections: Vec<(Section, u32)>, /// Observed attributes by element path (`values::element_attrs`). observed: std::cell::RefCell>, + /// Effective values of object styles, by UID (`applied`). + style_values: + std::cell::RefCell>>, } /// Attributes observed on an element path (`values::element_attrs`). @@ -118,6 +122,7 @@ pub fn write(doc: &Document, name: &str, out: impl std::io::Write) -> std::io::R group_path: group_paths(doc), warnings: Default::default(), observed: Default::default(), + style_values: Default::default(), page_layouts: alternate_layouts(doc).1, page_sections: page_sections(doc), }; @@ -171,6 +176,7 @@ impl<'a> Writer<'a> { group_path: Default::default(), warnings: Default::default(), observed: Default::default(), + style_values: Default::default(), page_layouts: Vec::new(), page_sections: Vec::new(), } diff --git a/src/idml/spread.rs b/src/idml/spread.rs index 33a02ae..8cc1c8c 100644 --- a/src/idml/spread.rs +++ b/src/idml/spread.rs @@ -19,6 +19,91 @@ pub(super) fn spread_origin(pages: &[Page]) -> (f64, f64) { .unwrap_or((0.0, 0.0)) } +/// Page item attributes that IDML writes only when they differ from the +/// applied object style (attributes.md, page item attributes). +const STYLE_COMPARED: &[&str] = &[ + "FillColor", + "FillTint", + "StrokeColor", + "StrokeWeight", + "MiterLimit", + "CornerOption", + "CornerRadius", + "TopLeftCornerRadius", + "TopRightCornerRadius", + "BottomLeftCornerRadius", + "BottomRightCornerRadius", + "TopLeftCornerOption", + "TopRightCornerOption", + "BottomLeftCornerOption", + "BottomRightCornerOption", +]; + +/// The category of a `TextFramePreference` attribute: the ID that turns +/// it on in an object style's category list (objects.md, text frame +/// preferences). +fn frame_category(name: &str) -> Option { + Some(match name { + "TextColumnCount" + | "TextColumnGutter" + | "TextColumnFixedWidth" + | "UseFixedColumnWidth" + | "UseFlexibleColumnWidth" + | "TextColumnMaxWidth" + | "VerticalJustification" + | "VerticalThreshold" + | "IgnoreWrap" + | "VerticalBalanceColumns" => 0x1B93E, + "FirstBaselineOffset" | "MinimumFirstBaselineOffset" => 0xADC8, + n if n.starts_with("Footnotes") => 0xADCA, + n if n.starts_with("ColumnRule") => 0xADCB, + n if n.contains("AutoSizing") => 0xADC9, + _ => return None, + }) +} + +/// `TextFramePreference` attributes that IDML writes on every frame of +/// the version, whatever the object style (objects.md, text frame +/// preferences). `InsetSpacing` (DOM 11 on) is written separately. +fn frame_always(name: &str, major: u32) -> bool { + match name { + "TextColumnMaxWidth" => major >= 8, + "TextColumnCount" => major >= 10, + _ => false, + } +} + +/// `AutoSizingReferencePoint` codes of frames and object styles. +pub(super) const POINTS: [&str; 9] = [ + "TopLeftPoint", + "TopCenterPoint", + "TopRightPoint", + "LeftCenterPoint", + "CenterPoint", + "RightCenterPoint", + "BottomLeftPoint", + "BottomCenterPoint", + "BottomRightPoint", +]; +/// `VerticalJustification` codes. +pub(super) const JUSTIFY: [&str; 4] = ["TopAlign", "CenterAlign", "BottomAlign", "JustifyAlign"]; +/// `FirstBaselineOffset` codes (objects.md, text frame preferences). +pub(super) const FIRST_BASELINE: [&str; 5] = [ + "LeadingOffset", + "AscentOffset", + "CapHeight", + "EmboxHeight", + "XHeight", +]; +/// `AutoSizingType` codes. +pub(super) const SIZING: [&str; 5] = [ + "Off", + "HeightOnly", + "WidthOnly", + "HeightAndWidth", + "HeightAndWidthProportionally", +]; + impl Writer<'_> { pub(super) fn path_geometry(x: &mut Xml, paths: &[Path]) { if paths.is_empty() { @@ -44,92 +129,108 @@ impl Writer<'_> { x.end().end(); } + /// `TextFramePreference` of a text frame. IDML writes an attribute + /// only when its category is off in the frame's object style or its + /// value differs from the style's, apart from a few attributes it + /// always writes (objects.md, text frame preferences). `style` is the + /// applied style's values; without a style every value is written. pub(super) fn text_frame_preference( + &self, x: &mut Xml, p: &TextFramePreferences, - major: u32, - swatch: impl Fn(u32) -> Option, + style: Option<&applied::StyleValues>, ) { - const POINTS: [&str; 9] = [ - "TopLeftPoint", - "TopCenterPoint", - "TopRightPoint", - "LeftCenterPoint", - "CenterPoint", - "RightCenterPoint", - "BottomLeftPoint", - "BottomCenterPoint", - "BottomRightPoint", + let v = self.doc.version; + let major = v.major; + let swatch = |u: u32| match u { + 0 => Some("n".to_string()), + u => self.doc.swatches.get(&u).cloned(), + }; + let mut attrs: Vec<(&str, String)> = vec![ + ("TextColumnCount", p.column_count.to_string()), + ("TextColumnGutter", num(p.column_gutter)), + ("TextColumnFixedWidth", num(p.column_fixed_width)), ]; - const JUSTIFY: [&str; 4] = ["TopAlign", "CenterAlign", "BottomAlign", "JustifyAlign"]; - const FIRST_BASELINE: [&str; 4] = - ["LeadingOffset", "AscentOffset", "CapHeight", "EmboxHeight"]; - const SIZING: [&str; 5] = [ - "Off", - "HeightOnly", - "WidthOnly", - "HeightAndWidth", - "HeightAndWidthProportionally", - ]; - x.start("TextFramePreference") - .attr("TextColumnCount", p.column_count.to_string()) - .attr("TextColumnGutter", num(p.column_gutter)) - .attr("TextColumnFixedWidth", num(p.column_fixed_width)); if let Some(v) = FIRST_BASELINE.get(p.first_baseline_offset as usize) { - x.attr("FirstBaselineOffset", *v); + attrs.push(("FirstBaselineOffset", v.to_string())); } if let Some(v) = JUSTIFY.get(p.vertical_justification as usize) { - x.attr("VerticalJustification", *v); + attrs.push(("VerticalJustification", v.to_string())); } - x.attr( + attrs.push(( "VerticalBalanceColumns", p.vertical_balance_columns.to_string(), - ); + )); if let Some(v) = SIZING.get(p.auto_sizing_type as usize) { - x.attr("AutoSizingType", *v); + attrs.push(("AutoSizingType", v.to_string())); } if let Some(v) = POINTS.get(p.auto_sizing_reference_point as usize) { - x.attr("AutoSizingReferencePoint", *v); + attrs.push(("AutoSizingReferencePoint", v.to_string())); } if let Some(w) = p.max_width { - x.attr("TextColumnMaxWidth", num(w)); + attrs.push(("TextColumnMaxWidth", num(w))); } - x.attr("UseFixedColumnWidth", p.use_fixed_width.to_string()); + attrs.push(("UseFixedColumnWidth", p.use_fixed_width.to_string())); if let Some(([use_height, use_width], [height, width], no_breaks)) = p.minimum_sizes { - x.attr("UseMinimumHeightForAutoSizing", use_height.to_string()) - .attr("MinimumHeightForAutoSizing", num(height)) - .attr("UseMinimumWidthForAutoSizing", use_width.to_string()) - .attr("MinimumWidthForAutoSizing", num(width)) - .attr("UseNoLineBreaksForAutoSizing", no_breaks.to_string()); + attrs.push(("UseMinimumHeightForAutoSizing", use_height.to_string())); + attrs.push(("MinimumHeightForAutoSizing", num(height))); + attrs.push(("UseMinimumWidthForAutoSizing", use_width.to_string())); + attrs.push(("MinimumWidthForAutoSizing", num(width))); + attrs.push(("UseNoLineBreaksForAutoSizing", no_breaks.to_string())); } if let Some(v) = p.ignore_wrap { - x.attr("IgnoreWrap", v.to_string()); + attrs.push(("IgnoreWrap", v.to_string())); } // Values every IDML of the version has where it writes them; they // also say from which version the column rule and footnote - // settings exist (idml-values.md). + // settings exist (idml-values.md). Footnote values from 13.1. let written = values::when_written("TextFrame/TextFramePreference", major); let has = |k: &str| written.iter().any(|(n, _)| n == k); + let footnotes = (major, v.minor) >= (13, 1); if has("ColumnRuleOffset") { let (width, color) = match p.column_rule { Some((w, c)) => (w, swatch(c)), // Without the chunk (objects.md). None => (1.0, Some("Color/Black".to_string())), }; - x.attr("ColumnRuleStrokeWidth", num(width)); + attrs.push(("ColumnRuleStrokeWidth", num(width))); if let Some(c) = color { - x.attr("ColumnRuleStrokeColor", c); + attrs.push(("ColumnRuleStrokeColor", c)); } if p.column_rule_override != Some(true) { - x.attr("ColumnRuleOverride", "false"); + attrs.push(("ColumnRuleOverride", "false".into())); } } - if has("FootnotesEnableOverrides") { + if has("FootnotesEnableOverrides") && footnotes { let [spacing, between] = p.footnotes.unwrap_or([12.0, 6.0]); - x.attr("FootnotesMinimumSpacing", num(spacing)) - .attr("FootnotesSpaceBetween", num(between)); + attrs.push(("FootnotesMinimumSpacing", num(spacing))); + attrs.push(("FootnotesSpaceBetween", num(between))); + } + for (k, val) in written.iter() { + if !footnotes && k.starts_with("Footnotes") { + continue; + } + if !attrs.iter().any(|(n, _)| n == k) { + attrs.push((k.as_str(), val.clone())); + } + } + if let Some(s) = style { + attrs.retain(|(k, val)| { + frame_always(k, major) + || !s + .enabled + .as_ref() + .is_some_and(|on| frame_category(k).is_some_and(|c| on.contains(&c))) + || !s.frame(k).is_some_and(|sv| applied::same_value(sv, val)) + }); + } + if attrs.is_empty() && major < 11 { + return; + } + x.start("TextFramePreference"); + for (k, val) in attrs { + x.attr(k, val); } - x.attrs_missing(written.iter()); if major >= 11 { let [top, left, bottom, right] = p.inset; let item = |v: f64| Node { @@ -273,7 +374,19 @@ impl Writer<'_> { }; x.attr("ContentType", content); } - self.item_attrs(x, &item.attrs); + let applied = item.object_style.and_then(|u| self.style_values(u)); + for (name, v) in self.item_attr_values(&item.attrs) { + // Fill, stroke and corner values equal to the object style's + // are left out (attributes.md, page item attributes). + let same = STYLE_COMPARED.contains(&name) + && applied + .as_ref() + .and_then(|s| s.item(name)) + .is_some_and(|s| applied::same_value(s, &v)); + if !same { + x.attr(name, v); + } + } let style = item .object_style .and_then(|u| self.doc.object_styles.get(&u)); @@ -303,10 +416,7 @@ impl Writer<'_> { .. } = &item.kind { - Self::text_frame_preference(x, p, self.doc.version.major, |u| match u { - 0 => Some("n".to_string()), - u => self.doc.swatches.get(&u).cloned(), - }); + self.text_frame_preference(x, p, applied.as_deref()); } let frame = matches!( item.kind, @@ -342,7 +452,13 @@ impl Writer<'_> { ], ); } - for (effect, attr, v) in transparency::write(self, x, &item.attrs, &uref(Some(item.uid))) { + for (effect, attr, v) in transparency::write( + self, + x, + &item.attrs, + applied.as_deref(), + &uref(Some(item.uid)), + ) { self.warnings.borrow_mut().push(format!( "item {}: {effect} {attr} {v} is outside the IDML range; left out", item.uid diff --git a/src/idml/styles.rs b/src/idml/styles.rs index 6402615..19b2e60 100644 --- a/src/idml/styles.rs +++ b/src/idml/styles.rs @@ -4,6 +4,7 @@ //! Evidence: `docs/format/objects.md` (styles and style groups), //! `attributes.md`, `tables.md` and `idml-values.md`. +use super::spread::{FIRST_BASELINE, JUSTIFY, POINTS, SIZING}; use super::*; /// `KeyboardShortcut` and `ExtendedKeyboardShortcut` of a style, from its @@ -453,6 +454,42 @@ impl Writer<'_> { if let Some(v) = fr.column_fixed_width { tf.push(("TextColumnFixedWidth", num(v))); } + // Fields of the text frame settings that use the frame codes + // (objects.md, object style settings). + if let Some(v) = fr.vertical_balance_columns { + tf.push(("VerticalBalanceColumns", v.to_string())); + } + if let Some(v) = fr.use_fixed_width { + tf.push(("UseFixedColumnWidth", v.to_string())); + } + if let Some(v) = fr + .vertical_justification + .and_then(|c| JUSTIFY.get(c as usize)) + { + tf.push(("VerticalJustification", v.to_string())); + } + if let Some(v) = fr + .first_baseline_offset + .and_then(|c| FIRST_BASELINE.get(c as usize)) + { + tf.push(("FirstBaselineOffset", v.to_string())); + } + if major >= 8 + && let Some((ty, point)) = fr.auto_sizing + && let (Some(ty), Some(point)) = + (SIZING.get(ty as usize), POINTS.get(point as usize)) + { + tf.push(("AutoSizingType", ty.to_string())); + tf.push(("AutoSizingReferencePoint", point.to_string())); + } + if major >= 8 + && let Some(([use_height, use_width], [height, width])) = fr.minimum_sizes + { + tf.push(("UseMinimumHeightForAutoSizing", use_height.to_string())); + tf.push(("MinimumHeightForAutoSizing", num(height))); + tf.push(("UseMinimumWidthForAutoSizing", use_width.to_string())); + tf.push(("MinimumWidthForAutoSizing", num(width))); + } let mut footnote = Vec::new(); if let Some((span, min, between)) = fr.footnotes && span <= 1 @@ -516,6 +553,34 @@ impl Writer<'_> { node.set(&["TextFrameFootnoteOptionsObject"], footnote); } } + // The text frame values every object style has from DOM 12 hold + // from DOM 8 (idml-values.md, object styles other than the root). + if (8..12).contains(&major) + && let Some(t) = values::object_style(12).child("TextFramePreference") + { + node.merge(&Node { + tag: "ObjectStyle".into(), + children: vec![Node { + tag: "TextFramePreference".into(), + attrs: t.attrs.clone(), + ..Node::default() + }], + ..Node::default() + }); + } + // Every object style has it from 13.1 (idml-values.md, object + // styles other than the root). + if version >= (13, 1) { + node.merge(&Node { + tag: "ObjectStyle".into(), + children: vec![Node { + tag: "TextFramePreference".into(), + attrs: vec![("FootnotesEnableOverrides".into(), "false".into())], + ..Node::default() + }], + ..Node::default() + }); + } let mut story = Vec::new(); if let Some(st) = &os.story { match st.frame_type { diff --git a/src/idml/transparency.rs b/src/idml/transparency.rs index 55df9df..294289a 100644 --- a/src/idml/transparency.rs +++ b/src/idml/transparency.rs @@ -1,5 +1,6 @@ //! Transparency settings of page items. See `docs/format/transparency.md`. +use super::applied::{StyleValues, same_value}; use super::kind::Kind; use super::xml::Xml; use super::{Writer, num}; @@ -236,13 +237,16 @@ fn stops(raw: &[[f64; 3]]) -> Option> { } /// Write the transparency settings found in a page item's attribute list. -/// `item` is the item's `Self`, which names the opacity stops. Returns the -/// values left out because they are outside the schema's range, as -/// (effect, attribute, value). +/// IDML writes only the values that differ from the object style `style` +/// (all values without a style), and an effect element only when one of +/// its values or its opacity stops differ. `item` is the item's `Self`, +/// which names the opacity stops. Returns the values left out because +/// they are outside the schema's range, as (effect, attribute, value). pub(super) fn write( w: &Writer, x: &mut Xml, attrs: &Attrs, + style: Option<&StyleValues>, item: &str, ) -> Vec<(&'static str, &'static str, f64)> { let mut left_out = Vec::new(); @@ -267,7 +271,16 @@ pub(super) fn write( continue; } match w.value_text(kind, v) { - Some(t) => values.push((name, t)), + Some(t) => { + let same = style.is_some_and(|s| { + s.transparency(id) + .and_then(|sv| w.value_text(kind, sv)) + .is_some_and(|st| same_value(&st, &t)) + }); + if !same { + values.push((name, t)); + } + } None if kind.is_code() => attrs.unknown_code(id, v), None => {} } @@ -276,9 +289,17 @@ pub(super) fn write( STOPS .iter() .find(|(_, s)| *s == setting) - .and_then(|(id, _)| match attrs.get(*id) { - Some(Value::Stops(raw)) => stops(raw), + .and_then(|(id, _)| { + match attrs.get(*id) { + Some(Value::Stops(raw)) + if !style.is_some_and(|s| { + matches!(s.transparency(*id), Some(Value::Stops(st)) if st == raw) + }) => + { + stops(raw) + } _ => None, + } }) .unwrap_or_default() } else { diff --git a/src/model/ids.rs b/src/model/ids.rs index c04a418..ace553a 100644 --- a/src/model/ids.rs +++ b/src/model/ids.rs @@ -203,6 +203,7 @@ pub mod chunk { pub const OBJECT_STYLE_FITTING: u32 = 0x1B956; /// Page item attributes of an object style (u16 count, records). pub const OBJECT_STYLE_ATTRS: u32 = 0x1B92B; + pub const OBJECT_STYLE_TRANSPARENCY: u32 = 0x1B92C; pub const OBJECT_STYLE_FRAME: u32 = 0x1B924; pub const OBJECT_STYLE_STORY: u32 = 0x285B; pub const OBJECT_STYLE_DIRECTION: u32 = 0x50F28; diff --git a/src/model/style.rs b/src/model/style.rs index 61f838b..9e4cf00 100644 --- a/src/model/style.rs +++ b/src/model/style.rs @@ -61,6 +61,8 @@ pub struct ObjectStyle { pub fitting: Attrs, /// Page item attributes (chunk 0x1B92B): fill, stroke, corners. pub attrs: Attrs, + /// Transparency attributes (chunk 0x1B92C), the IDs of page items. + pub transparency: Attrs, /// Text frame settings (chunk 0x1B924). pub frame: Option, /// Story settings (chunk 0x285B). @@ -321,6 +323,20 @@ impl<'a> Reader<'a> { .unwrap_or_default(), None => Attrs::default(), }, + transparency: match self.chunk(uid, chunk::OBJECT_STYLE_TRANSPARENCY)? { + Some(d) => self + .attrs_or_warn( + || format!("object style {uid}, transparency"), + Attrs::parse_short( + self.enc(), + &d, + List::ObjectStyleTransparency, + self.db.recorder(), + ), + ) + .unwrap_or_default(), + None => Attrs::default(), + }, // The layout is known for these sizes only // (`docs/format/big-endian.md`). frame: match self.chunk(uid, chunk::OBJECT_STYLE_FRAME)? { @@ -397,11 +413,30 @@ pub struct ObjectStyleFrame { /// Column rule: f64 stroke width at 190, u32 colour at 198 (0 for /// none) and f64 tint at 210. pub column_rule: Option<(f64, u32, f64)>, + /// u16 at 76: first baseline offset code, as for frames (the 106-byte + /// layout too). + pub first_baseline_offset: Option, + /// The fields below are read from the 142-, 162- and 222-byte layouts. + /// u16 at 32, 1 = true. + pub vertical_balance_columns: Option, + /// u16 at 70, 1 = true. + pub use_fixed_width: Option, + /// u16 at 74: vertical justification code, as for frames. + pub vertical_justification: Option, + /// u16 at 116 and 118: auto-sizing type and reference point codes, as + /// for frames. + pub auto_sizing: Option<(u16, u16)>, + /// u16 at 120 and f64 at 122 (minimum height), u16 at 130 and f64 at + /// 132 (minimum width). + pub minimum_sizes: Option<([bool; 2], [f64; 2])>, } impl ObjectStyleFrame { pub(super) fn read(enc: Encoding, d: &[u8]) -> ObjectStyleFrame { let f = |o: usize| enc.f64_at(d, o); + let long = d.len() >= 142; + let flag = |o: usize| enc.u16_at(d, o).filter(|_| long).map(|v| v == 1); + let code = |o: usize| enc.u16_at(d, o).filter(|_| long); ObjectStyleFrame { column_fixed_width: f(0), column_gutter: f(8), @@ -409,6 +444,12 @@ impl ObjectStyleFrame { column_count: enc.u32_at(d, 66), footnotes: (|| Some((enc.u16_at(d, 144)?, f(146)?, f(154)?)))(), column_rule: (|| Some((f(190)?, enc.u32_at(d, 198)?, f(210)?)))(), + first_baseline_offset: enc.u16_at(d, 76), + vertical_balance_columns: flag(32), + use_fixed_width: flag(70), + vertical_justification: code(74), + auto_sizing: (|| Some((code(116)?, code(118)?)))(), + minimum_sizes: (|| Some(([flag(120)?, flag(130)?], [f(122)?, f(132)?])))(), } } }