diff --git a/docs/format/tables.md b/docs/format/tables.md index 175f3cb..6eeccc4 100644 --- a/docs/format/tables.md +++ b/docs/format/tables.md @@ -1,6 +1,6 @@ # Tables -Implemented in `src/model/table.rs`. Checked against 24 tables in the +Implemented in `src/model/table.rs`. Checked against 37 tables in the corpus pairs (InDesign 12–21); the InDesign 9.2 table layout differs and is not read yet. @@ -38,6 +38,10 @@ IDML names a table `i`, where the scope is the story rows (columns), u16, u16 attribute count, text attribute records (see `attributes.md`), 8 bytes. +Row attribute 0xB69F is `AutoGrow`: 0 in all 32 rows of the pairs that +have it, and those rows have `AutoGrow="false"`; the 182 rows without it +have no `AutoGrow` in IDML. The converter writes `false` for 0 only. + ## Cells The part of class 0xB606 owns a strand (chunk 0x261) whose run data @@ -46,12 +50,21 @@ The part of class 0xB606 owns a strand (chunk 0x261) whose run data | Field | Contents | |---|---| | u32 | Number of attribute sets, *s* | -| *s* sets | u32, u16, u16 attribute count, attributes, u32, u32 | +| *s* sets | u32 number of columns, u16 flag; if the flag is 1: u16 count, attributes; then u32 cell style priority, u32 cell style | | u32 | Number of rows *r* in this record | | *r* lists | u32 count, then that many position IDs (one per column) | | u32 | Number of row records | | per row | u16 count, then one attribute record per position | +A run record covers rows that share their cell formatting. Its +attribute sets cover the columns from left to right: the first set the +first *n* columns, and so on; the column counts add up to the number of +columns (185 of 185 records with sets; 12 records have none). A set +with flag 0 has no attributes. All 47 +cell strands of the corpus pairs parse to the end with this layout. In +files whose sets all have flag 1 the earlier reader worked; files with +flag-0 sets (one pair, 8 tables) could not be read before. + Every grid position has an ID. A position whose attribute is 0xB666 starts a cell (its ID is the cell ID); 0xB614 marks a position covered by a merged cell. The second value of attribute 0xB666 holds the cell's text area: f64 @@ -61,8 +74,127 @@ whose widths (heights) reach the text area as the span. A cell that was never laid out has width and height 0; then its column span is the run of covered positions to its right, and its row span 1. -All 628 cells produced for the pairs match IDML `Name` (column:row), +All 1,089 cells produced for the pairs match IDML `Name` (column:row), `RowSpan` and `ColumnSpan`. -Not yet converted: cell, row and column formatting (insets, fills, -strokes), table and cell styles. +## Cell formatting + +A cell's formatting is the attribute set that covers its position. IDML +writes these attributes on a `Cell` exactly when the set has them, so +they are the cell's local values. The exception is the text insets: +IDML writes `TextTopInset` and the other three on every cell, with the +value in effect; where the set has an inset, it is that value. + +Evidence: the same-version pairs have 1,125 IDML cells with an INDD +cell, 952 of them in a set (5 files). For every attribute below, the INDD set has the +attribute on exactly the cells whose IDML `Cell` has it (no cell has one +without the other), and the values match on all of them. The 144 cells +of pairs whose IDML is from an older version agree as well. + +| ID | IDML | Encoding | Cells (files, distinct values) | +|---|---|---|---| +| 0xB62B | `LeftInset`, `TextLeftInset` | f64 | 601 (5, 5) | +| 0xB62C | `TopInset`, `TextTopInset` | f64 | 523 (5, 3) | +| 0xB62D | `RightInset`, `TextRightInset` | f64 | 631 (5, 3) | +| 0xB62E | `BottomInset`, `TextBottomInset` | f64 | 523 (5, 3) | +| 0xB63D | `FillColor` | swatch UID | 176 (4, 8) | +| 0xB63E | `FillTint` | f64 | 142 (2, 4) | +| 0xB677 | `VerticalJustification` | 1 `CenterAlign`, 2 `BottomAlign` | 457 (3) | +| 0xB6DE | `ClipContentToCell` | 0 = false | 664 (5, one value) | +| 0xB645, 0xB646, 0xB647, 0xB648 | `Left`, `Right`, `Top`, `BottomEdgeStrokeWeight` | f64 | 426, 358, 412, 443 (2) | +| 0xB649, 0xB64A, 0xB64B, 0xB64C | `Left`, `Top`, `Right`, `BottomEdgeStrokeColor` | swatch UID | 449, 449, 410, 449 (2) | +| 0xB64D, 0xB64E, 0xB64F, 0xB650 | `Left`, `Right`, `Top`, `BottomEdgeStrokeType` | stroke style code (below) | 426, 358, 412, 443 (2) | +| 0xB6A8, 0xB6A9, 0xB6AA, 0xB6AB | `Left`, `Right`, `Top`, `BottomEdgeStrokeTint` | f64 | 429, 364, 443, 443 (2) | +| 0xB6F9, 0xB6FA, 0xB6FB, 0xB6FC | `Left`, `Right`, `Top`, `BottomEdgeStrokePriority` | u32 | 593, 583, 593, 593 (3, 11–16 values) | + +Note the colours: their order is left, top, right, bottom, while the +other edge attributes are left, right, top, bottom. Each assignment was +checked against the alternatives; any swap gives mismatches (for +example 0xB648 as the top weight differs on 10 cells and is present on +31 cells without a top weight). The top and bottom stroke types have one +value (`Solid`), but they are told apart by which cells have them. + +**Edge stroke type.** Eight bytes: a stroke style code and 0. Code +0x5A29 is `StrokeStyle/$ID/Solid` (1,570 cell edges), the same code as +for page items (`attributes.md`); 0x1040C is `n`, no stroke type (69 +cell edges). +The converter uses the page item stroke style codes for cells too. + +**Right edge priority.** 10 cells have a right edge priority in IDML +but not in their set. The converter writes priorities only from the +set. + +**Applied cell style.** The set's two u32 after the attributes are the +applied cell style priority and the cell style. All 952 cells in a set +match `AppliedCellStylePriority`, and all match `AppliedCellStyle` (a +cell style UID; 0 for 70 cells whose IDML style is `[None]`). The 173 +cells of the pairs in records without sets all have +`AppliedCellStyle="CellStyle/$ID/[None]"` and priority 0, and the +converter writes those values for them. + +**Not converted.** The gap colour, gap tint and overprint of the edges +(0x10420–0x10423, 0x1040F–0x10412, 0xB6BA–0xB6BD) have one value in +every cell and the same set of cells for three edges, so the edges +cannot be told apart. Text insets of cells without a local inset come +from the cell style or elsewhere; for 74 cells neither the cell style nor +the table default gives the IDML value, so they are not written. + +## Cell and table styles + +**Cell styles** are objects of class 0x2021A, **table styles** of class +0xB63F. Both have chunk 0x230 as text styles do (`objects.md`): u32 at +offset 4 is the based-on style, and the name is a flag byte (1 for a +built-in name) followed by a non-empty in-object string. Their +attributes are a u16 count and records: chunk 0x20253 for cell styles +(chunk 0x2020C holds the same list in all 142 cell styles), chunk 0xB667 +for table styles. The root groups list their styles in chunk 0x2024E +(cell styles) and 0x104E5 (table styles): u32, u32, UID list. + +Evidence: all 142 cell styles and 274 table styles of the corpus pairs +match an IDML style by name. Their based-on style matches IDML +`BasedOn` for all 146 styles that have one: a root style +(`[None]`, `[No table style]`) is written as a string, any other as an +object reference (one table style). + +Cell styles use the cell attribute IDs above. All 7 named cell styles +of the pairs match their IDML on every attribute the converter writes. +Attribute 0x10463 is the paragraph style UID (`AppliedParagraphStyle`, +4 of 4 styles that have it). + +## Table attributes + +The table's chunk 0xB668 and a table style's chunk 0xB667 use the same +IDs. IDML writes on a `Table` the attributes its chunk 0xB668 has. + +| ID | IDML | Encoding | Evidence | +|---|---|---|---| +| 0xB662 | `SpaceBefore` | f64 | 2 styles (5.67), 5 tables (14.17) | +| 0xB663 | `SpaceAfter` | f64 | 2 styles (11.34), 5 tables | +| 0xB67B | `StartRowFillColor` | swatch UID | 5 tables (None) and 2 styles | +| 0xB67C | `EndRowFillColor` | swatch UID | 5 tables (a colour) and 2 styles | +| 0xB6B0 | `StartRowFillTint` | f64 | 2 styles (10, 50), 3 tables (10) | +| 0xB6B1 | `EndRowFillTint` | f64 | 2 styles (50, 10) | +| 0xB683 | `ColumnFillsPriority` | 0 = false | 8 tables | +| 0xB684 | `StartRowStrokeColor` | swatch UID | 5 tables | +| 0xB688 | `StartRowStrokeType` | stroke style code, as for cell edges | 1 table (`Canned Dotted`) | +| 0xB690 | `StartRowStrokeWeight` | f64 | 5 tables (0.25), 3 styles (0) | +| 0x10450 | `HeaderRegionCellStyle` | cell style UID, 0 = `n` | 2 styles | +| 0x10452 | `BodyRegionCellStyle` | cell style UID | 3 styles, and the root style in 135 files (`[None]`) | +| 0x10453 | `LeftColumnRegionCellStyle` | cell style UID | 1 style | +| 0x10454 | `RightColumnRegionCellStyle` | cell style UID | 1 style | +| 0x10457 | `HeaderRegionSameAsBodyRegion` | 0 false, 1 true | 2 styles (0); root style 1 | + +The style evidence is from one document with four named table styles; +the table evidence is from three documents. In these documents the two +spaces, the two fill tints and the two fill colours differ, which tells +each pair apart. + +**Not converted** because two or more attributes always have the same +value: the border weights, colours and types (0xB653–0xB65E, three per +side, same on all four sides in every sample), the row and column +stroke and fill counts (0xB67D, 0xB67E, 0xB686, 0xB687, 0xB68C, 0xB68D: +always 1 or always 0 in pairs), the end row and column stroke weights +(0xB691–0xB693), and the left and right column region flags (0x10459, +0x1045A). The alternating-pattern skip counts, `BreakHeaders`, +`SkipFirstHeader` and `SkipLastFooter` of 12 tables in IDML are not in +chunk 0xB668 and were not found. diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 03cd84d..2fb3760 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -354,6 +354,99 @@ const ITEM_ATTRS: &[(u32, &str, AttrKind)] = &[ AttrKind::Enum(&[(0, "CenterAlignment"), (1, "InsideAlignment")]), ), ]; +/// Kinds of cell attribute values. +#[derive(Clone, Copy)] +enum CellKind { + Number, + Integer, + Swatch, + Enum(&'static [(u32, &'static str)]), + /// A stroke style code in the first four of eight bytes; the other + /// four are 0. + StrokeType, + /// A cell style UID; 0 is written as `n`. + CellStyle, +} + +/// Cell attributes of a cell attribute set: ID, IDML attributes, kind. +/// See `docs/format/tables.md`. +const CELL_ATTRS: &[(u32, &[&str], CellKind)] = &[ + (0xB62C, &["TextTopInset", "TopInset"], CellKind::Number), + (0xB62B, &["TextLeftInset", "LeftInset"], CellKind::Number), + ( + 0xB62E, + &["TextBottomInset", "BottomInset"], + CellKind::Number, + ), + (0xB62D, &["TextRightInset", "RightInset"], CellKind::Number), + (0xB63D, &["FillColor"], CellKind::Swatch), + (0xB63E, &["FillTint"], CellKind::Number), + ( + 0xB677, + &["VerticalJustification"], + CellKind::Enum(&[(1, "CenterAlign"), (2, "BottomAlign")]), + ), + ( + 0xB6DE, + &["ClipContentToCell"], + CellKind::Enum(&[(0, "false")]), + ), + (0xB645, &["LeftEdgeStrokeWeight"], CellKind::Number), + (0xB64D, &["LeftEdgeStrokeType"], CellKind::StrokeType), + (0xB649, &["LeftEdgeStrokeColor"], CellKind::Swatch), + (0xB6A8, &["LeftEdgeStrokeTint"], CellKind::Number), + (0xB6F9, &["LeftEdgeStrokePriority"], CellKind::Integer), + (0xB647, &["TopEdgeStrokeWeight"], CellKind::Number), + (0xB64F, &["TopEdgeStrokeType"], CellKind::StrokeType), + (0xB64A, &["TopEdgeStrokeColor"], CellKind::Swatch), + (0xB6AA, &["TopEdgeStrokeTint"], CellKind::Number), + (0xB6FB, &["TopEdgeStrokePriority"], CellKind::Integer), + (0xB646, &["RightEdgeStrokeWeight"], CellKind::Number), + (0xB64E, &["RightEdgeStrokeType"], CellKind::StrokeType), + (0xB64B, &["RightEdgeStrokeColor"], CellKind::Swatch), + (0xB6A9, &["RightEdgeStrokeTint"], CellKind::Number), + (0xB6FA, &["RightEdgeStrokePriority"], CellKind::Integer), + (0xB648, &["BottomEdgeStrokeWeight"], CellKind::Number), + (0xB650, &["BottomEdgeStrokeType"], CellKind::StrokeType), + (0xB64C, &["BottomEdgeStrokeColor"], CellKind::Swatch), + (0xB6AB, &["BottomEdgeStrokeTint"], CellKind::Number), + (0xB6FC, &["BottomEdgeStrokePriority"], CellKind::Integer), +]; + +/// Table and table style attributes: ID, IDML attribute, kind. +/// See `docs/format/tables.md`. +const TABLE_ATTRS: &[(u32, &str, CellKind)] = &[ + (0xB662, "SpaceBefore", CellKind::Number), + (0xB663, "SpaceAfter", CellKind::Number), + (0xB684, "StartRowStrokeColor", CellKind::Swatch), + (0xB690, "StartRowStrokeWeight", CellKind::Number), + (0xB688, "StartRowStrokeType", CellKind::StrokeType), + ( + 0xB683, + "ColumnFillsPriority", + CellKind::Enum(&[(0, "false")]), + ), + (0xB67B, "StartRowFillColor", CellKind::Swatch), + (0xB6B0, "StartRowFillTint", CellKind::Number), + (0xB67C, "EndRowFillColor", CellKind::Swatch), + (0xB6B1, "EndRowFillTint", CellKind::Number), + ( + 0x10457, + "HeaderRegionSameAsBodyRegion", + CellKind::Enum(&[(0, "false"), (1, "true")]), + ), + (0x10450, "HeaderRegionCellStyle", CellKind::CellStyle), + (0x10452, "BodyRegionCellStyle", CellKind::CellStyle), + (0x10453, "LeftColumnRegionCellStyle", CellKind::CellStyle), + (0x10454, "RightColumnRegionCellStyle", CellKind::CellStyle), +]; + +/// Paragraph style of a cell style. +const CELL_STYLE_PARAGRAPH_STYLE: u32 = 0x10463; + +/// Stroke style code of a cell edge that has no stroke type (IDML `n`). +const CELL_NO_STROKE_TYPE: u32 = 0x1040C; + use values::Node; use xml::Xml; @@ -1366,6 +1459,46 @@ impl Writer<'_> { (attrs, extra_props, children) } + /// A cell or table style other than the root style. + fn table_style_element( + &self, + x: &mut Xml, + tag: &str, + s: &crate::model::TableStyle, + styles: &BTreeMap, + ) { + x.start(tag) + .attr("Self", Self::table_style_ref(tag, s)) + .attr("Name", Self::table_style_name(s)); + let attrs = if tag == "CellStyle" { + self.cell_attrs(&s.attrs) + } else { + self.table_attrs(&s.attrs) + }; + for (k, v) in attrs { + x.attr(k, v); + } + if tag == "CellStyle" + && let Some(p) = s + .attrs + .get(CELL_STYLE_PARAGRAPH_STYLE) + .and_then(Value::as_u32) + && self.doc.styles.contains_key(&p) + { + x.attr("AppliedParagraphStyle", self.style_ref(Some(p), true)); + } + if let Some(base) = s.based_on.and_then(|b| styles.get(&b)) { + // A root style is written as a string. + let prop = if base.builtin && base.based_on.is_none() { + ("BasedOn", "string", Self::table_style_name(base).into()) + } else { + ("BasedOn", "object", Self::table_style_ref(tag, base).into()) + }; + Self::properties(x, &[prop]); + } + x.end(); + } + /// A root cell or table style, from observed values only. fn root_table_style(&self, x: &mut Xml, tag: &str, name: &str) { let (attrs, props, children) = self.root_values(tag, &[], &[]); @@ -1411,6 +1544,96 @@ impl Writer<'_> { } } + /// `CellStyle/...` or `TableStyle/...` reference of a style. + fn table_style_ref(tag: &str, s: &crate::model::TableStyle) -> String { + format!("{tag}/{}", self_name(&Self::table_style_name(s))) + } + + fn table_style_name(s: &crate::model::TableStyle) -> String { + if s.builtin { + format!("$ID/{}", s.name) + } else { + s.name.clone() + } + } + + /// The reference for an applied cell style UID; 0 is `[None]`. + fn cell_style_ref(&self, uid: u32) -> Option { + if uid == 0 { + return Some("CellStyle/$ID/[None]".into()); + } + self.doc + .cell_styles + .get(&uid) + .map(|s| Self::table_style_ref("CellStyle", s)) + } + + /// IDML attributes of a table or table style attribute list. + fn table_attrs(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { + TABLE_ATTRS + .iter() + .filter_map(|&(id, name, kind)| { + let v = attrs.get(id)?; + let t = match kind { + CellKind::CellStyle => match v.as_u32()? { + 0 => Some("n".to_string()), + u => self + .doc + .cell_styles + .get(&u) + .map(|s| Self::table_style_ref("CellStyle", s)), + }, + _ => self.table_value(v, kind), + }?; + Some((name, t)) + }) + .collect() + } + + /// IDML attributes of a cell attribute set. + fn cell_attrs(&self, attrs: &Attrs) -> Vec<(&'static str, String)> { + let mut out = Vec::new(); + for &(id, names, kind) in CELL_ATTRS { + let Some(v) = attrs.get(id) else { continue }; + if let Some(t) = self.table_value(v, kind) { + for &name in names { + out.push((name, t.clone())); + } + } + } + out + } + + fn table_value(&self, v: &Value, kind: CellKind) -> Option { + { + match kind { + CellKind::Number => v.as_f64().map(num), + CellKind::Integer => v.as_u32().map(|u| u.to_string()), + CellKind::Swatch => v.as_ref().and_then(|u| self.doc.swatches.get(&u).cloned()), + CellKind::Enum(map) => v + .as_u32() + .and_then(|u| map.iter().find(|(k, _)| *k == u)) + .map(|(_, n)| n.to_string()), + CellKind::StrokeType => { + let b = raw_bytes(v); + let word = |i: usize| { + b.get(i..i + 4) + .map(|w| u32::from_le_bytes(w.try_into().unwrap())) + }; + match (word(0), word(4)) { + (Some(CELL_NO_STROKE_TYPE), Some(0)) => Some("n".to_string()), + (Some(code), Some(0)) => STROKE_TYPES + .iter() + .find(|(k, _)| *k == code) + .map(|(_, n)| format!("StrokeStyle/$ID/{n}")), + _ => None, + } + } + CellKind::CellStyle => v.as_u32().and_then(|u| self.cell_style_ref(u)), + } + } + } + /// Font families and their fonts. See docs/format/fonts.md. fn fonts(&self) -> String { let mut x = Xml::new(); @@ -1533,9 +1756,28 @@ impl Writer<'_> { "[No table style]", ), ] { - let id = root_of(kind).map_or(tag.to_string(), |g| uref(Some(g.uid))); + let root = root_of(kind); + let id = root.map_or(tag.to_string(), |g| uref(Some(g.uid))); x.start(tag).attr("Self", id); self.root_table_style(&mut x, style, name); + let styles = if style == "CellStyle" { + &doc.cell_styles + } else { + &doc.table_styles + }; + // Styles listed in the root group first, then any others; the + // root style is written above. + let mut order: Vec = root.map_or(Vec::new(), |g| g.children.clone()); + order.extend(styles.keys().copied()); + let mut seen = std::collections::HashSet::new(); + for uid in order { + let Some(s) = styles.get(&uid) else { continue }; + let is_root = s.builtin && s.based_on.is_none() && s.name == name; + if is_root || !seen.insert(Self::table_style_ref(style, s)) { + continue; + } + self.table_style_element(&mut x, style, s, styles); + } x.end(); } let object_root = root_of(root_kind::OBJECT); @@ -2134,6 +2376,12 @@ impl Writer<'_> { .to_string(), ) .attr("ColumnCount", t.columns.len().to_string()); + if let Some(st) = t.style.and_then(|u| self.doc.table_styles.get(&u)) { + x.attr("AppliedTableStyle", Self::table_style_ref("TableStyle", st)); + } + for (name, v) in self.table_attrs(&t.attrs) { + x.attr(name, v); + } for (i, r) in t.rows.iter().enumerate() { x.start("Row") .attr("Self", format!("{id}Row{i}")) @@ -2144,6 +2392,9 @@ impl Writer<'_> { if let Some(h) = r.min_height { x.attr("MinimumHeight", num(h)); } + if r.auto_grow == Some(0) { + x.attr("AutoGrow", "false"); + } x.end(); } for (i, w) in t.columns.iter().enumerate() { @@ -2164,6 +2415,19 @@ impl Writer<'_> { .attr("RowSpan", c.row_span.to_string()) .attr("ColumnSpan", c.column_span.to_string()) .attr("CellType", "TextTypeCell"); + if let Some(f) = &c.format { + for (name, v) in self.cell_attrs(&f.attrs) { + x.attr(name, v); + } + if let Some(r) = self.cell_style_ref(f.style) { + x.attr("AppliedCellStyle", r) + .attr("AppliedCellStylePriority", f.style_priority.to_string()); + } + } else { + // A cell without an attribute set has no cell style. + x.attr("AppliedCellStyle", "CellStyle/$ID/[None]") + .attr("AppliedCellStylePriority", "0"); + } self.text_ranges(x, &c.runs, story, &cell_id); x.end(); } diff --git a/src/model/attrs.rs b/src/model/attrs.rs index 3744dd6..4a1b2a4 100644 --- a/src/model/attrs.rs +++ b/src/model/attrs.rs @@ -94,6 +94,10 @@ impl Attrs { let id = c.u32()?; let size = c.u16()? as usize; let mut p = Cursor::new(c.bytes(size)?); + // A record without values (for example a merged-cell marker). + if size < 2 { + continue; + } let count = p.u16()?; let mut first = None; for i in 0..count { diff --git a/src/model/mod.rs b/src/model/mod.rs index 25182da..e1f32d5 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -15,7 +15,7 @@ pub use attrs::{Attrs, Value}; pub use color::{Color, Gradient, Tint}; pub use font::{Font, FontFamily}; pub use hyperlink::{Bookmark, Destination, DestinationKind, Hyperlink, SourceRange, TextSource}; -pub use table::{Cell, Table}; +pub use table::{Cell, CellFormat, Table, TableStyle}; pub use variable::TextVariable; pub use xref::CrossReferenceFormat; @@ -370,6 +370,8 @@ pub struct Document { /// Style groups, including the root groups (empty name). pub style_groups: BTreeMap, pub object_styles: BTreeMap, + pub cell_styles: BTreeMap, + pub table_styles: BTreeMap, pub sections: Vec
, pub text_variables: Vec, pub hyperlinks: Vec, @@ -553,6 +555,8 @@ impl<'a> Reader<'a> { let mut languages = BTreeMap::new(); let mut style_groups = BTreeMap::new(); let mut object_styles = BTreeMap::new(); + let mut cell_styles = BTreeMap::new(); + let mut table_styles = BTreeMap::new(); let mut text_variables = Vec::new(); let mut hyperlinks = Vec::new(); let mut text_sources = BTreeMap::new(); @@ -572,12 +576,17 @@ impl<'a> Reader<'a> { Some(d) => Cursor::new(&d).u32()?, None => 0, }; - let children = self.children(uid, chunk::STYLE_ROOT_CHILDREN)?; - let children = if children.is_empty() { - self.children(uid, chunk::OBJECT_STYLE_ROOT_CHILDREN)? - } else { - children - }; + let mut children = Vec::new(); + for id in [ + chunk::STYLE_ROOT_CHILDREN, + chunk::OBJECT_STYLE_ROOT_CHILDREN, + table::chunk::CELL_STYLE_ROOT_CHILDREN, + table::chunk::TABLE_STYLE_ROOT_CHILDREN, + ] { + if children.is_empty() { + children = self.children(uid, id)?; + } + } style_groups.insert( uid, StyleGroup { @@ -626,6 +635,16 @@ impl<'a> Reader<'a> { styles.insert(uid, style); } } + table::class::CELL_STYLE => { + if let Some(s) = self.table_style(uid, table::chunk::CELL_STYLE_ATTRS)? { + cell_styles.insert(uid, s); + } + } + table::class::TABLE_STYLE => { + if let Some(s) = self.table_style(uid, table::chunk::TABLE_STYLE_ATTRS)? { + table_styles.insert(uid, s); + } + } color::class::COLOR => { if self.db.object(uid)?.is_none() { continue; @@ -741,6 +760,8 @@ impl<'a> Reader<'a> { languages, style_groups, object_styles, + cell_styles, + table_styles, sections: self .uid_list(doc, chunk::DOC_SECTIONS)? .into_iter() diff --git a/src/model/table.rs b/src/model/table.rs index 35c3de0..11e581b 100644 --- a/src/model/table.rs +++ b/src/model/table.rs @@ -5,6 +5,8 @@ use crate::Error; use crate::object::Cursor; pub mod class { + pub const CELL_STYLE: u32 = 0x2021A; + pub const TABLE_STYLE: u32 = 0xB63F; /// Owned by the U+0016 character where a table sits in its story. pub const TABLE_ANCHOR: u32 = 0xB651; pub const TABLE: u32 = 0xB608; @@ -18,6 +20,18 @@ pub mod chunk { pub const TABLE_ROWS: u32 = 0xB616; pub const TABLE_COLUMNS: u32 = 0xB617; pub const TABLE_PARTS: u32 = 0xB6FB; + /// u32 applied table style, u32 (not identified). + pub const TABLE_STYLE: u32 = 0xB6FC; + /// Local table attributes: u16 count, attributes. + pub const TABLE_ATTRS: u32 = 0xB668; + /// Attributes of a cell style: u16 count, attributes. + pub const CELL_STYLE_ATTRS: u32 = 0x20253; + /// Attributes of a table style: u16 count, attributes. + pub const TABLE_STYLE_ATTRS: u32 = 0xB667; + /// Children of the root cell style group: u32, u32, UID list. + pub const CELL_STYLE_ROOT_CHILDREN: u32 = 0x2024E; + /// Children of the root table style group: u32, u32, UID list. + pub const TABLE_STYLE_ROOT_CHILDREN: u32 = 0x104E5; } /// Attribute IDs in table data. @@ -25,6 +39,8 @@ pub mod attr { pub const COLUMN_WIDTH: u32 = 0xB60D; pub const ROW_HEIGHT: u32 = 0xB60C; pub const ROW_MIN_HEIGHT: u32 = 0xB66E; + /// 0 = `AutoGrow="false"`. + pub const ROW_AUTO_GROW: u32 = 0xB69F; /// A grid position that starts a cell; its value holds cell geometry. pub const CELL: u32 = 0xB666; /// A grid position covered by a merged cell. @@ -35,6 +51,8 @@ pub mod attr { pub struct Row { pub height: Option, pub min_height: Option, + /// Stored auto-grow value (0 in every sample, `AutoGrow="false"`). + pub auto_grow: Option, } #[derive(Debug, Clone, PartialEq)] @@ -46,11 +64,39 @@ pub struct Cell { pub row_span: usize, pub column_span: usize, pub runs: Vec, + /// Formatting of the cell: its attribute set, if it has one. + pub format: Option, +} + +/// An attribute set shared by a run of cells in a row group. +#[derive(Debug, Clone, PartialEq)] +pub struct CellFormat { + /// Local cell attributes (insets, fill, edge strokes, ...). + pub attrs: Attrs, + /// Applied cell style priority (IDML `AppliedCellStylePriority`). + pub style_priority: u32, + /// Applied cell style UID, 0 for none. + pub style: u32, +} + +/// A cell or table style (class 0x2021A or 0xB63F). +#[derive(Debug, Clone, PartialEq)] +pub struct TableStyle { + pub uid: u32, + pub name: String, + /// The name is a built-in key, written with `$ID/` in IDML. + pub builtin: bool, + pub based_on: Option, + pub attrs: Attrs, } #[derive(Debug, Clone, PartialEq)] pub struct Table { pub uid: u32, + /// Applied table style. + pub style: Option, + /// Local table attributes. + pub attrs: Attrs, pub header_rows: u32, pub footer_rows: u32, pub rows: Vec, @@ -86,9 +132,54 @@ struct Position { size: Option<(f64, f64)>, /// Covered by a merged cell. covered: bool, + format: Option, } impl Reader<'_> { + /// An attribute list stored as a u16 count and records. + fn counted_attrs(&self, uid: u32, id: u32) -> Result { + Ok(match self.chunk(uid, id)? { + Some(d) if d.len() >= 2 => { + let mut c = Cursor::new(&d); + let n = c.u16()? as usize; + Attrs::parse_text(&mut c, n)? + } + _ => Attrs::default(), + }) + } + + /// A cell or table style: name and base from chunk 0x230 (as for text + /// styles), attributes from `attrs_chunk`. + pub(super) fn table_style( + &self, + uid: u32, + attrs_chunk: u32, + ) -> Result, Error> { + let Some(data) = self.chunk(uid, super::chunk::STYLE_INFO)? else { + return Ok(None); + }; + let based_on = Cursor::new(&data[4.min(data.len())..]).u32()?; + // A flag byte (1 = built-in name), then a non-empty in-object string. + let Some((at, name)) = (12..data.len().saturating_sub(6)).find_map(|i| { + if data[i] > 2 || data[i + 1] != 2 { + return None; + } + match Cursor::new(&data[i + 1..]).string() { + Ok(n) if !n.is_empty() => Some((i, n)), + _ => None, + } + }) else { + return Ok(None); + }; + Ok(Some(TableStyle { + uid, + name, + builtin: data[at] == 1, + based_on: super::uid_or_none(based_on), + attrs: self.counted_attrs(uid, attrs_chunk)?, + })) + } + /// The table owned by a table anchor object, without cell text. pub(super) fn table_of_anchor(&self, anchor: u32) -> Result, Error> { let Some(d) = self.chunk(anchor, chunk::ANCHOR_TABLE)? else { @@ -123,6 +214,7 @@ impl Reader<'_> { let row = Row { height: f64_attr(&a, attr::ROW_HEIGHT), min_height: f64_attr(&a, attr::ROW_MIN_HEIGHT), + auto_grow: a.get(attr::ROW_AUTO_GROW).and_then(Value::as_u32), }; rows.extend(std::iter::repeat_n(row, count)); } @@ -132,13 +224,21 @@ impl Reader<'_> { Row { height: None, min_height: None, + auto_grow: None, }, ); let grid = self.cell_grid(uid)?; let cells = cells_from_grid(&grid, &rows, &columns); + let style = match self.chunk(uid, chunk::TABLE_STYLE)? { + Some(d) => super::uid_or_none(Cursor::new(&d).u32()?), + None => None, + }; + let attrs = self.counted_attrs(uid, chunk::TABLE_ATTRS)?; Ok(Table { uid, + style, + attrs, header_rows, footer_rows, rows, @@ -177,16 +277,27 @@ impl Reader<'_> { for _ in 0..groups { let size = r.u32()? as usize; let mut g = Cursor::new(r.bytes(size)?); - // Attribute sets shared by the cells: u32, u16, u16 count, - // attributes, u32, u32. + // Attribute sets, each shared by a run of columns: u32 + // number of columns, u16 1 if attributes follow (u16 count, + // attributes), u32 cell style priority, u32 cell style. let sets = g.u32()?; + let mut formats = Vec::new(); for _ in 0..sets { - g.u32()?; - g.u16()?; - let na = g.u16()? as usize; - Attrs::parse_text(&mut g, na)?; - g.u32()?; - g.u32()?; + let columns = g.u32()? as usize; + let attrs = if g.u16()? != 0 { + let na = g.u16()? as usize; + Attrs::parse_text(&mut g, na)? + } else { + Attrs::default() + }; + let style_priority = g.u32()?; + let style = g.u32()?; + let f = CellFormat { + attrs, + style_priority, + style, + }; + formats.extend(std::iter::repeat_n(f, columns)); } let nr = g.u32()?; let mut ids = Vec::new(); @@ -204,10 +315,12 @@ impl Reader<'_> { let row = row_ids .into_iter() .zip(raw) - .map(|(id, (aid, value))| Position { + .enumerate() + .map(|(k, (id, (aid, value)))| Position { id, size: (aid == attr::CELL).then(|| cell_size(&value)).flatten(), covered: aid == attr::COVERED, + format: formats.get(k).cloned(), }) .collect(); grid.push(row); @@ -289,6 +402,7 @@ fn cells_from_grid(grid: &[Vec], rows: &[Row], columns: &[f64]) -> Vec row_span, column_span, runs: Vec::new(), + format: pos.format.clone(), }); } }