diff --git a/docs/format/idml-values.md b/docs/format/idml-values.md index 9f1965e..c97aaef 100644 --- a/docs/format/idml-values.md +++ b/docs/format/idml-values.md @@ -129,6 +129,40 @@ and 49 EPS graphics with `ClippingPathSettings` have the same four values. The converter writes them (`objects.md`, clipping path settings). +## Object styles other than the root + +`tools/root_values.py` also collects the object styles other than +`[None]`: 295 styles in the 88 distinct IDML files, every file having at +least one. A value is kept when every such style of every IDML from some +DOM version on has it, with the same value, and at least 10 files show +it. The kept values are in `src/idml/object_style_values.xml`. The +converter writes them on every object style other than `[None]`, and +writes the values it reads from the INDD (`objects.md`, object style +settings) in their place. + +| Values | Same in | Written for version | +|---|---|---| +| 80 | 88 of 88 files | all | +| 40 | 87 of 87 files with DOM 12 or later | 12 and later | +| 14 | 80 of 80 files with DOM 15 or later | 15 and later | +| 1 | 74 of 74 files with DOM 18 or later | 18 and later | + +Among them are the nine `Enable…` effect flags other than +`EnableTransparency` in the four `ObjectStyle…EffectsCategorySettings` +elements (all `true`), all of `BaselineFrameGridOption`, +`ObjectExportOption` and `TransformAttributeOption`, and +`ApplyNextParagraphStyle="false"` and `EnableParagraphStyle="false"`. + +**Left out because they vary or are not in every style** (59): the +fill, stroke and corner values, most `Enable…` attributes, +`AnchoredObjectSetting` `PinPosition`, `AnchorPoint` and +`VerticalAlignment`, the frame fitting values, the story frame type, +orientation and direction, the text wrap mode and contour type, the +column, inset, footnote and column rule values of +`TextFramePreference`, and `EnableTransparency`. The converter reads +many of these from the INDD. Values that only the 2 files with DOM 20 +have (18) are left out as for the preferences. + ## Column direction of pages All 832 `MarginPreference` elements in the 240 corpus IDML files have diff --git a/docs/format/objects.md b/docs/format/objects.md index a303f61..a1b4dc4 100644 --- a/docs/format/objects.md +++ b/docs/format/objects.md @@ -548,6 +548,88 @@ u8 1 for a built-in name, then the name. A page item's chunk 0x1B916 is its applied object style (`AppliedObjectStyle`, 671/671 rectangles). A style based on the root `[None]` has its `BasedOn` written as a string. +## Object style settings + +Object styles (class 0x1B901) hold their settings in these chunks. +Evidence: the 337 object styles of the same-version pairs whose name +matches an IDML `ObjectStyle` (259 of them other than `[None]`); all +counts are matches of 337 unless stated. + +| Chunk | Contents | IDML | +|---|---|---| +| 0x1B92B | Attribute list, u16 count, page item records (`attributes.md`) | `FillColor`, `StrokeColor`, `StrokeWeight`, `StrokeType`, `CornerOption`, `CornerRadius`, `GradientFillAngle` (0x551E), `GradientStrokeAngle` (0x5524) | +| 0x1B956 | Attribute list, frame fitting (see frame fitting) | `FrameFittingOption` | +| 0x1B924 | Text frame settings (below) | `TextFramePreference`, `TextFrameFootnoteOptionsObject` | +| 0x285B | u16 story orientation at 0, f64 12 at 2, u16 frame type at 14 | `StoryPreference` | +| 0x50F28 | u16 story direction | `StoryPreference/StoryDirection` | +| 0x3776, 0x3777 | Text wrap, as chunks 0x3703 and 0x373D of page items | `TextWrapPreference` | +| 0x1B92E | u32 count, IDs of the categories the style turns on | `Enable…` attributes (below) | +| 0x1B946 | u32 paragraph style, 0 = none | `AppliedParagraphStyle` (`n` for none) | + +**Attribute list.** The IDs of page items carry over. `CornerOption` 0 +is `None` and 0x5A16 `InverseRoundedCorner` (1 style). The two gradient +angles are told apart by one style with −90 and 0. Per-corner values +come in pairs of IDs whose order is not known: the top-left and +top-right radius are 0x6E70 and 0x6E94, the bottom ones 0x6E92 and +0x6E93; the options 0x6E6F and 0x6E91, and 0x6E8F and 0x6E90. The two +of each pair are equal in every style. The converter writes the four +corner radii, and the four corner options, only when all four values +are equal (336 of 337 styles). + +**Text frame settings (chunk 0x1B924).** 222 bytes; 162 or 106 in files +from older versions. + +| Offset | Contents | Attribute | +|---|---|---| +| 0 | f64 | `TextColumnFixedWidth` | +| 8 | f64 | `TextColumnGutter` | +| 34, 42, 50, 58 | four f64, inset spacing | `InsetSpacing` (below) | +| 66 | u32 | `TextColumnCount` | +| 144 | u16, 1 = true | `FootnotesSpanAcrossColumns`, `SpanFootnotesAcross` | +| 146 | f64 | `FootnotesMinimumSpacing`, `MinimumSpacingOption` | +| 154 | f64 | `FootnotesSpaceBetween`, `SpaceBetweenFootnotes` | +| 190 | f64 | `ColumnRuleStrokeWidth` | +| 198 | u32 swatch, 0 = `n` | `ColumnRuleStrokeColor` | +| 210 | f64 | `ColumnRuleStrokeTint` | + +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 +(offset 50), so the converter writes `InsetSpacing` only when all four +are equal (334 of 337). + +**Story settings.** Frame type: 0 `Unknown`, 1 `TextFrameType`, 2 +`FrameGridType`. Orientation: 0 `Unknown`, 1 `Horizontal`. Direction: 1 +`LeftToRightDirection`, 0 or no chunk `UnknownDirection`. 337 of 337 +each. The f64 at 2 is 12 in every style, like `OpticalMarginSize`, and is +not used. + +**Text wrap.** 234 styles have chunk 0x3776 with mode 0, offsets 0 and +the u32 at 40 = 1, and chunk 0x3777 type 5: IDML `None` with +`ContourType="SameAsClipping"`. 103 styles have neither chunk and IDML +`None`. + +**Categories (chunk 0x1B92E).** An ID in the list means the attribute is +`true`: 0x1B940 `EnableStoryOptions`, 0x1B960 +`EnableFrameFittingOptions`, 0xADCB `EnableTextFrameColumnRuleOptions`, +no disagreement. Three more go with a pair of IDs that are both present +or both absent in every style, so either ID gives the value: 0x1B933 and +0x1B934 for `EnableFill` and `EnableStroke` (equal in every style), +0xADC8 and 0x1B93E for `EnableTextFrameGeneralOptions` and +`EnableTextFrameBaselineOptions` (equal in every style), and 0xADC9 or +0xADCA for `EnableTextFrameAutoSizingOptions`. The converter writes them +when the two IDs agree. Other `Enable…` attributes vary together with +several IDs and are not written. + +**Not written.** `AnchoredObjectSetting` `PinPosition`, `AnchorPoint` and +`VerticalAlignment` change together (312 against 25 styles) with four +u16 fields of chunk 0x2800, so the fields cannot be told apart. +`EnableTransparency` of the effects categories varies and has no +identified field. + +The other values of object styles come from IDML observation +(`idml-values.md`). + ## Master spread names and sections Master spread chunk 0x1402: a flag byte and the name prefix (`A`), a flag diff --git a/src/idml/mod.rs b/src/idml/mod.rs index cfea48d..53721c3 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -1559,6 +1559,14 @@ impl Writer<'_> { /// Write page item attributes from the item's attribute list. 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. + fn item_attr_values(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { + let mut out = Vec::new(); for &(id, name, kind) in ITEM_ATTRS { let Some(v) = attrs.get(id) else { continue }; let text = match kind { @@ -1581,9 +1589,10 @@ impl Writer<'_> { }, }; if let Some(t) = text { - x.attr(name, t); + out.push((name, t)); } } + out } /// `CellStyle/...` or `TableStyle/...` reference of a style. @@ -1861,53 +1870,48 @@ impl Writer<'_> { } else { os.name.clone() }; + let root = os.builtin && os.name == "[None]" && os.based_on.is_none(); + let node = self.object_style_node(os, root); x.start("ObjectStyle") .attr("Self", format!("ObjectStyle/{}", self_name(&name))) .attr("Name", &name); - let all: Vec = FITTING_ATTRS.iter().map(|(id, _)| *id).collect(); - let fitting = fitting_attrs(&os.fitting, &all); - if os.builtin && os.name == "[None]" && os.based_on.is_none() { - let (attrs, props, mut children) = self.root_values("ObjectStyle", &[], &[]); - for (k, v) in &attrs { - x.attr(k, v); - } - Self::properties_with(&mut x, &[], &props); - // Values read from the INDD take precedence. - if let Some(c) = children.iter_mut().find(|c| c.tag == "FrameFittingOption") { - let rest: Vec<_> = std::mem::take(&mut c.attrs) - .into_iter() - .filter(|(k, _)| !fitting.iter().any(|(f, _)| f == k)) - .collect(); - c.attrs = fitting - .iter() - .map(|(k, v)| (k.to_string(), v.clone())) - .chain(rest) - .collect(); - } - for c in &children { - c.write(&mut x); - } - } else if let Some(base) = os.based_on.and_then(|b| doc.object_styles.get(&b)) { + for (k, v) in &node.attrs { + x.attr(k, v); + } + let mut props: Vec = node + .child("Properties") + .map_or(Vec::new(), |p| p.children.clone()); + if !root && let Some(base) = os.based_on.and_then(|b| doc.object_styles.get(&b)) { let base_name = if base.builtin { format!("$ID/{}", base.name) } else { base.name.clone() }; // The root "[None]" is written as a string. - let prop = if base.builtin && base.name == "[None]" { - ("BasedOn", "string", base_name.into()) + let (ty, text) = if base.builtin && base.name == "[None]" { + ("string", base_name) } else { - ( - "BasedOn", - "object", - format!("ObjectStyle/{}", self_name(&base_name)).into(), - ) + ("object", format!("ObjectStyle/{}", self_name(&base_name))) }; - Self::properties(&mut x, &[prop]); + props.insert( + 0, + Node { + tag: "BasedOn".into(), + attrs: vec![("type".into(), ty.into())], + text: Some(text), + children: Vec::new(), + }, + ); } - if !(os.builtin && os.name == "[None]" && os.based_on.is_none()) && !fitting.is_empty() - { - x.empty("FrameFittingOption", &fitting); + if !props.is_empty() { + x.start("Properties"); + for p in &props { + p.write(&mut x); + } + x.end(); + } + for c in node.children.iter().filter(|c| c.tag != "Properties") { + c.write(&mut x); } x.end(); } @@ -1916,6 +1920,239 @@ impl Writer<'_> { x.finish() } + /// An object style as a values node: the values every exported IDML + /// has on such a style (`idml-values.md`), with the values read from + /// the INDD in their place. See `docs/format/objects.md`. + fn object_style_node(&self, os: &crate::model::ObjectStyle, root: bool) -> Node { + let major = self.doc.version.major; + let mut node = if root { + values::root_style("ObjectStyle", major) + } else { + values::object_style(major) + }; + let mut attrs = self.item_attr_values(&os.attrs); + for (id, name) in [ + (0x551E, "GradientFillAngle"), + (0x5524, "GradientStrokeAngle"), + ] { + if let Some(v) = os.attrs.get(id).and_then(Value::as_f64) { + attrs.push((name, num(v))); + } + } + match os.attrs.get(0x6E6F).and_then(Value::as_u32) { + Some(0) => attrs.push(("CornerOption", "None".into())), + Some(0x5A16) => attrs.push(("CornerOption", "InverseRoundedCorner".into())), + _ => {} + } + match os.paragraph_style { + Some(0) => attrs.push(("AppliedParagraphStyle", "n".into())), + Some(p) if self.doc.styles.contains_key(&p) => { + attrs.push(("AppliedParagraphStyle", self.style_ref(Some(p), true))) + } + _ => {} + } + // Per-corner values: the two IDs of each pair are equal in every + // sample, so the values are written only when all four agree. + let corners = |ids: [u32; 4]| { + let v: Vec<_> = ids.iter().map(|&id| os.attrs.get(id)).collect(); + (v[0].is_some() && v.iter().all(|x| *x == v[0])).then(|| v[0].cloned())? + }; + if let Some(r) = corners([0x6E70, 0x6E94, 0x6E92, 0x6E93]).and_then(|v| v.as_f64()) { + for name in [ + "TopLeftCornerRadius", + "TopRightCornerRadius", + "BottomLeftCornerRadius", + "BottomRightCornerRadius", + ] { + attrs.push((name, num(r))); + } + } + let corner_option = match corners([0x6E6F, 0x6E91, 0x6E8F, 0x6E90]).and_then(|v| v.as_u32()) + { + Some(0) => Some("None"), + Some(0x5A15) => Some("RoundedCorner"), + Some(0x5A16) => Some("InverseRoundedCorner"), + _ => None, + }; + if let Some(o) = corner_option { + for name in [ + "TopLeftCornerOption", + "TopRightCornerOption", + "BottomLeftCornerOption", + "BottomRightCornerOption", + ] { + attrs.push((name, o.into())); + } + } + if let Some(on) = &os.enabled { + // Pairs of IDs that are both present or both absent in every + // sample; either one gives the attribute. + for (ids, names) in [ + ([0x1B933, 0x1B934], &["EnableFill", "EnableStroke"][..]), + ( + [0xADC8, 0x1B93E], + &[ + "EnableTextFrameGeneralOptions", + "EnableTextFrameBaselineOptions", + ][..], + ), + ([0xADC9, 0xADCA], &["EnableTextFrameAutoSizingOptions"][..]), + ] { + let (a, b) = (on.contains(&ids[0]), on.contains(&ids[1])); + if a == b { + for name in names { + attrs.push((name, a.to_string())); + } + } + } + for (id, name) in [ + (0x1B940, "EnableStoryOptions"), + (0x1B960, "EnableFrameFittingOptions"), + (0xADCB, "EnableTextFrameColumnRuleOptions"), + ] { + attrs.push((name, on.contains(&id).to_string())); + } + } + node.set(&[], attrs); + if let Some(d) = &os.frame { + let f = |o: usize| { + (d.len() >= o + 8) + .then(|| Cursor::new(&d[o..]).f64().ok()) + .flatten() + }; + let u = |o: usize| { + (d.len() >= o + 4) + .then(|| Cursor::new(&d[o..]).u32().ok()) + .flatten() + }; + let h = |o: usize| { + (d.len() >= o + 2) + .then(|| Cursor::new(&d[o..]).u16().ok()) + .flatten() + }; + let mut tf = Vec::new(); + if let Some(n) = u(66) { + tf.push(("TextColumnCount", n.to_string())); + } + if let Some(v) = f(8) { + tf.push(("TextColumnGutter", num(v))); + } + if let Some(v) = f(0) { + tf.push(("TextColumnFixedWidth", num(v))); + } + let mut footnote = Vec::new(); + if let (Some(span), Some(min), Some(between)) = (h(144), f(146), f(154)) + && span <= 1 + { + let span = (span == 1).to_string(); + tf.push(("FootnotesSpanAcrossColumns", span.clone())); + tf.push(("FootnotesMinimumSpacing", num(min))); + tf.push(("FootnotesSpaceBetween", num(between))); + footnote = vec![ + ("SpanFootnotesAcross", span), + ("MinimumSpacingOption", num(min)), + ("SpaceBetweenFootnotes", num(between)), + ]; + } + if let (Some(width), Some(color), Some(tint)) = (f(190), u(198), f(210)) { + let color = match color { + 0 => Some("n".to_string()), + c => self.doc.swatches.get(&c).cloned(), + }; + tf.push(("ColumnRuleStrokeWidth", num(width))); + if let Some(c) = color { + tf.push(("ColumnRuleStrokeColor", c)); + } + tf.push(("ColumnRuleStrokeTint", num(tint))); + } + node.set(&["TextFramePreference"], tf); + // Only the top inset is shown apart from the others; the list is + // written when all four are equal. + if let (Some(a), Some(b), Some(c), Some(e)) = (f(34), f(42), f(50), f(58)) + && a == b + && b == c + && c == e + { + node.set(&["TextFramePreference", "Properties"], Vec::new()); + let props = node + .children + .iter_mut() + .find(|c| c.tag == "TextFramePreference") + .and_then(|t| t.children.iter_mut().find(|c| c.tag == "Properties")) + .expect("set above"); + props.children.retain(|c| c.tag != "InsetSpacing"); + props.children.push(Node { + tag: "InsetSpacing".into(), + attrs: vec![("type".into(), "list".into())], + text: None, + children: (0..4) + .map(|_| Node { + tag: "ListItem".into(), + attrs: vec![("type".into(), "unit".into())], + text: Some(num(a)), + children: Vec::new(), + }) + .collect(), + }); + } + if !footnote.is_empty() && node.child("TextFrameFootnoteOptionsObject").is_some() { + node.set(&["TextFrameFootnoteOptionsObject"], footnote); + } + } + let mut story = Vec::new(); + if let Some(d) = &os.story + && d.len() >= 16 + { + let h = |o: usize| u16::from_le_bytes([d[o], d[o + 1]]); + match h(14) { + 0 => story.push(("FrameType", "Unknown".to_string())), + 1 => story.push(("FrameType", "TextFrameType".to_string())), + 2 => story.push(("FrameType", "FrameGridType".to_string())), + _ => {} + } + match h(0) { + 0 => story.push(("StoryOrientation", "Unknown".to_string())), + 1 => story.push(("StoryOrientation", "Horizontal".to_string())), + _ => {} + } + } + match os.direction { + Some(1) => story.push(("StoryDirection", "LeftToRightDirection".into())), + Some(0) | None => story.push(("StoryDirection", "UnknownDirection".into())), + _ => {} + } + node.set(&["StoryPreference"], story); + let mode = match os.text_wrap.as_ref().map(|w| w.mode) { + None | Some(wrap_mode::NONE) => Some("None"), + Some(wrap_mode::JUMP_OBJECT) => Some("JumpObjectTextWrap"), + Some(wrap_mode::BOUNDING_BOX) => Some("BoundingBoxTextWrap"), + Some(wrap_mode::CONTOUR) => Some("Contour"), + Some(_) => None, + }; + if let Some(mode) = mode { + node.set(&["TextWrapPreference"], vec![("TextWrapMode", mode.into())]); + let [left, top, right, bottom] = os.text_wrap.as_ref().map_or([0.0; 4], |w| w.offsets); + node.set( + &["TextWrapPreference", "Properties", "TextWrapOffset"], + vec![ + ("Top", num(top)), + ("Left", num(left)), + ("Bottom", num(bottom)), + ("Right", num(right)), + ], + ); + if os.contour_type == Some(5) { + node.set( + &["TextWrapPreference", "ContourOption"], + vec![("ContourType", "SameAsClipping".into())], + ); + } + } + let all: Vec = FITTING_ATTRS.iter().map(|(id, _)| *id).collect(); + node.set(&["FrameFittingOption"], fitting_attrs(&os.fitting, &all)); + node + } + fn style_group_children( &self, x: &mut Xml, diff --git a/src/idml/object_style_values.xml b/src/idml/object_style_values.xml new file mode 100644 index 0000000..28ea876 --- /dev/null +++ b/src/idml/object_style_values.xml @@ -0,0 +1,58 @@ + + + + + + + + + LightBlue + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/idml/values.rs b/src/idml/values.rs index 718884f..5adb90f 100644 --- a/src/idml/values.rs +++ b/src/idml/values.rs @@ -26,6 +26,38 @@ impl Node { .map(|(_, v)| v.as_str()) } + /// Set the attributes of the descendant at `path`, creating missing + /// elements (`Properties` as the first child), replacing values + /// already there in place and adding the others at the end. + pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) { + let mut node = self; + for tag in path { + let i = match node.children.iter().position(|c| c.tag == *tag) { + Some(i) => i, + None => { + let new = Node { + tag: tag.to_string(), + ..Node::default() + }; + if *tag == "Properties" { + node.children.insert(0, new); + 0 + } else { + node.children.push(new); + node.children.len() - 1 + } + } + }; + node = &mut node.children[i]; + } + for (k, v) in attrs { + match node.attrs.iter_mut().find(|(a, _)| a == k) { + Some(e) => e.1 = v, + None => node.attrs.push((k.to_string(), v)), + } + } + } + /// Add the attributes and children of `other` that `self` lacks. /// Children with the same tag are merged. fn merge(&mut self, other: &Node) { @@ -86,6 +118,29 @@ pub fn root_style(tag: &str, major: u32) -> Node { out } +const OBJECT_STYLE_VALUES: &str = include_str!("object_style_values.xml"); + +/// The observed values of object styles other than the root `[None]`, for +/// a document of InDesign version `major`. +pub fn object_style(major: u32) -> Node { + let mut out = Node { + tag: "ObjectStyle".to_string(), + ..Node::default() + }; + let root = parse(OBJECT_STYLE_VALUES).expect("object_style_values.xml is well-formed"); + for block in &root.children { + let since = block + .attr("MinimumVersion") + .map_or(0, |v| v.parse().expect("MinimumVersion is a number")); + if since <= major + && let Some(n) = block.child("ObjectStyle") + { + out.merge(n); + } + } + out +} + const PREFERENCE_VALUES: &str = include_str!("preference_values.xml"); /// The observed preference elements (`TextDefault`, ...) for a document of @@ -218,6 +273,23 @@ mod tests { ); } + #[test] + fn gates_object_style_values_by_version() { + let old = object_style(7); + let new = object_style(21); + assert!(old.child("ObjectExportOption").is_none()); + assert!(new.child("ObjectExportOption").is_some()); + // Values that vary between styles are not in the file. + assert!(new.attr("FillColor").is_none()); + let mut n = new.clone(); + n.set( + &["TextWrapPreference", "Properties", "TextWrapOffset"], + vec![("Top", "1".into())], + ); + let wrap = n.child("TextWrapPreference").unwrap(); + assert_eq!(wrap.children[0].tag, "Properties"); + } + #[test] fn gates_preferences_by_version() { let old = preferences(7); diff --git a/src/model/mod.rs b/src/model/mod.rs index 040e2a5..37cb4a5 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -121,6 +121,15 @@ pub mod chunk { pub const PHOTOSHOP_CLIPPING: u32 = 0x8C39; /// Frame fitting attributes of an object style (u16 count, records). 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_FRAME: u32 = 0x1B924; + pub const OBJECT_STYLE_STORY: u32 = 0x285B; + pub const OBJECT_STYLE_DIRECTION: u32 = 0x50F28; + pub const OBJECT_STYLE_WRAP: u32 = 0x3776; + pub const OBJECT_STYLE_CONTOUR: u32 = 0x3777; + pub const OBJECT_STYLE_ENABLED: u32 = 0x1B92E; + pub const OBJECT_STYLE_PARAGRAPH_STYLE: u32 = 0x1B946; pub const GUIDE: u32 = 0x3308; } @@ -525,6 +534,22 @@ pub struct ObjectStyle { pub based_on: Option, /// Frame fitting attributes (chunk 0x1B956), same IDs as on page items. pub fitting: Attrs, + /// Page item attributes (chunk 0x1B92B): fill, stroke, corners. + pub attrs: Attrs, + /// Text frame settings (chunk 0x1B924); see `docs/format/objects.md`. + pub frame: Option>, + /// Story settings (chunk 0x285B). + pub story: Option>, + /// Story direction (chunk 0x50F28, u16). + pub direction: Option, + /// Text wrap (chunk 0x3776, the layout of chunk 0x3703). + pub text_wrap: Option, + /// Contour type of the text wrap (chunk 0x3777). + pub contour_type: Option, + /// IDs of the setting categories the style turns on (chunk 0x1B92E). + pub enabled: Option>, + /// Paragraph style applied to text frames (chunk 0x1B946). + pub paragraph_style: Option, } /// Reads typed objects from a database, caching them. @@ -697,6 +722,31 @@ impl<'a> Reader<'a> { Some(d) => Attrs::parse_short(&d).unwrap_or_default(), None => Attrs::default(), }, + attrs: match self.chunk(uid, chunk::OBJECT_STYLE_ATTRS)? { + Some(d) => Attrs::parse_short(&d).unwrap_or_default(), + None => Attrs::default(), + }, + frame: self.chunk(uid, chunk::OBJECT_STYLE_FRAME)?, + story: self.chunk(uid, chunk::OBJECT_STYLE_STORY)?, + direction: match self.chunk(uid, chunk::OBJECT_STYLE_DIRECTION)? { + Some(d) if d.len() >= 2 => Some(Cursor::new(&d).u16()?), + _ => None, + }, + text_wrap: self.wrap_chunk(uid, chunk::OBJECT_STYLE_WRAP)?, + contour_type: match self.chunk(uid, chunk::OBJECT_STYLE_CONTOUR)? { + Some(d) if d.len() >= 4 => Some(Cursor::new(&d).u32()?), + _ => None, + }, + enabled: match self.chunk(uid, chunk::OBJECT_STYLE_ENABLED)? { + Some(d) => Some(Cursor::new(&d).u32_list()?), + None => None, + }, + paragraph_style: match self + .chunk(uid, chunk::OBJECT_STYLE_PARAGRAPH_STYLE)? + { + Some(d) if d.len() >= 4 => Some(Cursor::new(&d).u32()?), + _ => None, + }, }, ); } @@ -1127,7 +1177,12 @@ impl<'a> Reader<'a> { /// Text wrap of a page item or graphic, from chunk 0x3703: u32 mode, /// u32 contour path object, four f64 offsets, u32 flags. fn text_wrap(&self, uid: u32) -> Result, Error> { - let Some(d) = self.chunk(uid, chunk::TEXT_WRAP)? else { + self.wrap_chunk(uid, chunk::TEXT_WRAP) + } + + /// A text wrap record in chunk `id` of object `uid`. + fn wrap_chunk(&self, uid: u32, id: u32) -> Result, Error> { + let Some(d) = self.chunk(uid, id)? else { return Ok(None); }; if d.len() < 44 { diff --git a/tools/root_values.py b/tools/root_values.py index 8fa06b7..c9b6a00 100644 --- a/tools/root_values.py +++ b/tools/root_values.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -"""Find the values that every corpus IDML has on its root styles and in -its preferences. +"""Find the values that every corpus IDML has on its root styles, on its +other object styles and in its preferences. Reads Resources/Styles.xml and Resources/Preferences.xml of every IDML in the corpus pairs (distinct files only) and collects each attribute, @@ -14,10 +14,14 @@ it reads is left out of the preferences. Preference values that refer to a style other than a root style are left out, since the package need not have that style. +Object styles other than the root style `[None]` are collected the same +way, all styles of a file together: a value is kept when every such style +in every IDML from some DOM version on has it, with the same value. + Usage: python3 -I tools/root_values.py [--write] Prints the evidence counts. With --write, regenerates -src/idml/root_values.xml and src/idml/preference_values.xml. See -docs/format/idml-values.md. +src/idml/root_values.xml, src/idml/object_style_values.xml and +src/idml/preference_values.xml. See docs/format/idml-values.md. """ import hashlib @@ -32,6 +36,7 @@ from xml.sax.saxutils import quoteattr ROOT = Path(__file__).resolve().parent.parent OUT = ROOT / "src" / "idml" / "root_values.xml" PREF_OUT = ROOT / "src" / "idml" / "preference_values.xml" +OBJECT_OUT = ROOT / "src" / "idml" / "object_style_values.xml" # Preference attributes the converter reads from the INDD. PREF_SKIP = { @@ -213,6 +218,85 @@ def analyse_preferences(idmls, doms): return tags, kept, left_out, order +OBJECT_HEADER = """ + +""" + + +def analyse_object_styles(idmls, doms): + """Values of the object styles other than the root style. A file + contributes a value for a key when all its such styles have the key + with one value; the key is kept when every file with such styles from + some DOM version on has the same value.""" + values = defaultdict(dict) + order = {} + files = [] + styles = 0 + for i, (_dom, idml) in enumerate(idmls): + root = ET.fromstring(zipfile.ZipFile(idml).read("Resources/Styles.xml")) + found = [el for el in root.iter("ObjectStyle") + if el.get("Self") != TARGETS["ObjectStyle"]] + if not found: + continue + files.append(i) + styles += len(found) + per_key = defaultdict(list) + for el in found: + out = {} + leaves(el, (), out, order) + for k, v in out.items(): + per_key[k].append(v) + for k, vs in per_key.items(): + if len(vs) == len(found) and len(set(vs)) == 1: + values[k][i] = vs[0] + sub_doms = [doms[i] if i in files else -1 for i in range(len(doms))] + kept, left_out = [], [] + for key, by_file in values.items(): + path, name = key + plain = name.split("/", 1)[1] if name.startswith("P/") else name[1:] + if not path and (plain in SKIP or plain == "BasedOn"): + continue + since = None + for m in sorted({sub_doms[i] for i in by_file}): + within = [i for i in files if sub_doms[i] >= m] + if all(i in by_file for i in within): + if len({by_file[i] for i in within}) == 1: + since = (m, len(within)) + break + if since is None or since[1] < MIN_FILES: + left_out.append("/".join(path + (plain,))) + continue + kept.append((key, by_file[next(iter(by_file))], since)) + return files, styles, kept, left_out, order + + +def write_object_styles(kept, order, first): + blocks = [] + for since in sorted({s for _, _, (s, _) in kept}): + gate = "" if since == first else f' MinimumVersion="{since}"' + items = sorted((it for it in kept if it[2][0] == since), key=lambda it: order[it[0]]) + tree = {"attrs": [], "props": [], "children": OrderedDict()} + for (path, name), v, _ in items: + node = tree + for p in path: + node = node["children"].setdefault( + p, {"attrs": [], "props": [], "children": OrderedDict()}) + if name.startswith("@"): + node["attrs"].append((name[1:], v)) + else: + node["props"].append(v) + blocks.append(f"\t\n" + element("ObjectStyle", tree, "\t\t") + "\t\n") + OBJECT_OUT.write_text(OBJECT_HEADER + "\n" + "".join(blocks) + + "\n") + + def write_preferences(tags, kept, order, first): blocks = [] for since in sorted({s for items in kept.values() for _, _, (s, _) in items}): @@ -302,7 +386,18 @@ def main(): print(f" {tag}: {len(pkept[tag])} kept, left out {counts}") if pleft[tag].get("refers to a style") or pleft[tag].get("read from the INDD"): print(f" {pleft[tag].get('refers to a style', [])} {pleft[tag].get('read from the INDD', [])}") + files, styles, okept, oleft, oorder = analyse_object_styles(idmls, doms) + print(f"\nObject styles other than [None]: {styles} in {len(files)} IDML files") + counts = defaultdict(int) + for _, _, since in okept: + counts[since] += 1 + for (since, n), k in sorted(counts.items()): + print(f" {k:4} values, the same in {n} of {n} IDML files with DOM >= {since}") + print(f" {len(oleft)} left out (vary, not in every style, or in fewer than {MIN_FILES} files):") + print(f" {', '.join(sorted(oleft))}") if "--write" in sys.argv: + write_object_styles(okept, oorder, min(doms)) + print(f"wrote {OBJECT_OUT.relative_to(ROOT)}") write(kept, order, min(doms)) print(f"\nwrote {OUT.relative_to(ROOT)}") write_preferences(tags, pkept, porder, min(doms))