feat: convert cell formatting, cell and table styles, and table attributes

This commit is contained in:
aiongg committed 2026-10-07 00:24:59 +00:00
1 parent 9594ac557b
commit c976451c2f
5 files changed
+557 -22

No files matched your search

+265 -1
View File
@@ -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<u32, crate::model::TableStyle>,
) {
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<String> {
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<String> {
{
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<u32> = 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();
}
+4
View File
@@ -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 {
+28 -7
View File
@@ -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<u32, StyleGroup>,
pub object_styles: BTreeMap<u32, ObjectStyle>,
pub cell_styles: BTreeMap<u32, TableStyle>,
pub table_styles: BTreeMap<u32, TableStyle>,
pub sections: Vec<Section>,
pub text_variables: Vec<TextVariable>,
pub hyperlinks: Vec<Hyperlink>,
@@ -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()
+123 -9
View File
@@ -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<f64>,
pub min_height: Option<f64>,
/// Stored auto-grow value (0 in every sample, `AutoGrow="false"`).
pub auto_grow: Option<u32>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -46,11 +64,39 @@ pub struct Cell {
pub row_span: usize,
pub column_span: usize,
pub runs: Vec<TextRun>,
/// Formatting of the cell: its attribute set, if it has one.
pub format: Option<CellFormat>,
}
/// 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<u32>,
pub attrs: Attrs,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
pub uid: u32,
/// Applied table style.
pub style: Option<u32>,
/// Local table attributes.
pub attrs: Attrs,
pub header_rows: u32,
pub footer_rows: u32,
pub rows: Vec<Row>,
@@ -86,9 +132,54 @@ struct Position {
size: Option<(f64, f64)>,
/// Covered by a merged cell.
covered: bool,
format: Option<CellFormat>,
}
impl Reader<'_> {
/// An attribute list stored as a u16 count and records.
fn counted_attrs(&self, uid: u32, id: u32) -> Result<Attrs, Error> {
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<Option<TableStyle>, 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<Option<Table>, 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<Position>], rows: &[Row], columns: &[f64]) -> Vec
row_span,
column_span,
runs: Vec::new(),
format: pos.format.clone(),
});
}
}