diff --git a/docs/format/tables.md b/docs/format/tables.md new file mode 100644 index 0000000..175f3cb --- /dev/null +++ b/docs/format/tables.md @@ -0,0 +1,68 @@ +# Tables + +Implemented in `src/model/table.rs`. Checked against 24 tables in the +corpus pairs (InDesign 12–21); the InDesign 9.2 table layout differs and is +not read yet. + +## Where a table sits + +The story text contains U+0016 where the table is, usually followed by one +or more U+0017 (internal markers; their count does not follow from the +table size). The story's owned-items strand (run kind 0x209, see +`objects.md`) gives the U+0016 position an object of class 0xB651, whose +chunk 0xB67D starts with the table UID (class 0xB608). IDML writes the +`Table` element in place of U+0016 and drops the U+0017 characters. + +**Cell text** is part of the same story text, after the paragraph that +holds the table, one stretch per cell in row-major order, each ending with +U+000D (the cell terminator, not written to IDML). A strand with run kind +0x2A4 assigns every stretch of text an owner: each record is u32 length, +u32 owner UID, u32 cell ID. Text owned by the story is the story's own; text +owned by a table belongs to that table's cell. + +IDML names a table `i`, where the scope is the story +(`udcf`) or, for a nested table, the enclosing cell; cells are named +`
i` and rows and columns `
Row` and +`
Column`. + +## Table object (class 0xB608) + +| Chunk | Contents | +|---|---| +| 0xB608 | u32 rows, u32 columns, u32 header rows, u32 footer rows (24/24 match) | +| 0xB617 | Column groups (below); attribute 0xB60D = `SingleColumnWidth` (24/24) | +| 0xB616 | Row groups; 0xB60C = `SingleRowHeight`, 0xB66E = `MinimumHeight` (24/24) | +| 0xB6FB | u32 count, then (UID, class) pairs of the table's parts | + +**Row and column groups:** u32 group count; per group: u32 number of +rows (columns), u16, u16 attribute count, text attribute records (see +`attributes.md`), 8 bytes. + +## Cells + +The part of class 0xB606 owns a strand (chunk 0x261) whose run data +(chunk 0x262, kind 0xB610) describes the grid. Each run record: + +| Field | Contents | +|---|---| +| u32 | Number of attribute sets, *s* | +| *s* sets | u32, u16, u16 attribute count, attributes, u32, u32 | +| 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 | + +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 +width at offset 32 and f64 height at offset 40, the cell's full size minus +its insets. The converter takes the smallest number of columns (rows) +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), +`RowSpan` and `ColumnSpan`. + +Not yet converted: cell, row and column formatting (insets, fills, +strokes), table and cell styles. diff --git a/src/idml/mod.rs b/src/idml/mod.rs index 25e36b9..bac76f7 100644 --- a/src/idml/mod.rs +++ b/src/idml/mod.rs @@ -7,7 +7,7 @@ use std::collections::BTreeMap; use crate::model::{ Attrs, Document, Graphic, GraphicKind, ItemKind, Matrix, PageItem, Path, Shape, Spread, Story, - Style, StyleGroup, root_kind, + Style, StyleGroup, Table, TextRun, root_kind, }; #[derive(Clone, Copy)] @@ -747,8 +747,18 @@ impl Writer<'_> { let mut x = Xml::new(); self.package_root(&mut x, "Story"); x.start("Story").attr("Self", uref(Some(s.uid))); - let mut runs: Vec<_> = s.runs.iter().collect(); - // The story's final paragraph return is implicit in IDML. + let scope = uref(Some(s.uid)); + self.text_ranges(&mut x, &s.runs, s, &scope); + x.end().end(); + x.finish() + } + + /// Paragraph and character ranges for `runs`. The final paragraph + /// return (a story's last, or a table cell's terminator) is not written. + /// `scope` is the `Self` of the enclosing story or table cell, which + /// prefixes the `Self` of tables inside the text. + fn text_ranges(&self, x: &mut Xml, runs: &[TextRun], story: &Story, scope: &str) { + let mut runs: Vec<&TextRun> = runs.iter().collect(); let mut last_text = None; if let Some(last) = runs.last() && last.text.ends_with('\r') @@ -766,7 +776,6 @@ impl Writer<'_> { _ => &runs[i].text, } }; - let mut offset = 0usize; let mut i = 0; while i < n { let para = (runs[i].paragraph_style, &runs[i].paragraph_attrs); @@ -776,7 +785,7 @@ impl Writer<'_> { for (k, v) in &plain { x.attr(k, v); } - Self::properties(&mut x, &props); + Self::properties(x, &props); while i < n && (runs[i].paragraph_style, &runs[i].paragraph_attrs) == para { let r = runs[i]; let (plain, props) = self.text_attrs(&r.character_attrs); @@ -787,27 +796,18 @@ impl Writer<'_> { for (k, v) in &plain { x.attr(k, v); } - Self::properties(&mut x, &props); - self.run_content(&mut x, text_of(i), offset, &s.anchors); - offset += r.text.encode_utf16().count(); + Self::properties(x, &props); + self.run_content(x, text_of(i), r.start, story, scope); x.end(); i += 1; } x.end(); } - x.end().end(); - x.finish() } - /// Content, line breaks and anchored items of one character range. - /// `offset` is the UTF-16 offset of the range in the story. - fn run_content( - &self, - x: &mut Xml, - text: &str, - offset: usize, - anchors: &BTreeMap>, - ) { + /// Content, line breaks, anchored items and tables of one character + /// range. `offset` is the UTF-16 offset of the range in the story. + fn run_content(&self, x: &mut Xml, text: &str, offset: usize, story: &Story, scope: &str) { let mut buf = String::new(); let flush = |x: &mut Xml, buf: &mut String| { if !buf.is_empty() { @@ -825,12 +825,18 @@ impl Writer<'_> { flush(x, &mut buf); x.start("Br").end(); } - '\u{FFFC}' if anchors.contains_key(&pos) => { + '\u{FFFC}' if story.anchors.contains_key(&pos) => { flush(x, &mut buf); - for item in &anchors[&pos] { + for item in &story.anchors[&pos] { self.page_item(x, item); } } + '\u{16}' if story.tables.contains_key(&pos) => { + flush(x, &mut buf); + self.table(x, &story.tables[&pos], story, scope); + } + // Internal table markers that follow U+0016. + '\u{17}' => {} c => buf.push(c), } pos += ch.len_utf16(); @@ -838,6 +844,55 @@ impl Writer<'_> { flush(x, &mut buf); } + fn table(&self, x: &mut Xml, t: &Table, story: &Story, scope: &str) { + let id = format!("{scope}i{:x}", t.uid); + let rows = t.rows.len() as u32; + x.start("Table") + .attr("Self", &id) + .attr("HeaderRowCount", t.header_rows.to_string()) + .attr("FooterRowCount", t.footer_rows.to_string()) + .attr( + "BodyRowCount", + rows.saturating_sub(t.header_rows + t.footer_rows) + .to_string(), + ) + .attr("ColumnCount", t.columns.len().to_string()); + for (i, r) in t.rows.iter().enumerate() { + x.start("Row") + .attr("Self", format!("{id}Row{i}")) + .attr("Name", i.to_string()); + if let Some(h) = r.height { + x.attr("SingleRowHeight", num(h)); + } + if let Some(h) = r.min_height { + x.attr("MinimumHeight", num(h)); + } + x.end(); + } + for (i, w) in t.columns.iter().enumerate() { + x.empty( + "Column", + &[ + ("Self", format!("{id}Column{i}")), + ("Name", i.to_string()), + ("SingleColumnWidth", num(*w)), + ], + ); + } + for c in &t.cells { + let cell_id = format!("{id}i{:x}", c.id); + x.start("Cell") + .attr("Self", &cell_id) + .attr("Name", format!("{}:{}", c.column, c.row)) + .attr("RowSpan", c.row_span.to_string()) + .attr("ColumnSpan", c.column_span.to_string()) + .attr("CellType", "TextTypeCell"); + self.text_ranges(x, &c.runs, story, &cell_id); + x.end(); + } + x.end(); + } + fn backing_story(&self) -> String { let mut x = Xml::new(); self.package_root(&mut x, "BackingStory"); diff --git a/src/lib.rs b/src/lib.rs index 13d6868..59abc36 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -88,10 +88,11 @@ pub fn read_header(path: impl AsRef) -> Result { /// Convert INDD bytes to an IDML package written to `out`. `name` is the /// document name recorded in the package (normally the INDD file name). -pub fn convert(indd: &[u8], name: &str, out: impl std::io::Write) -> Result<(), Error> { +/// Returns warnings about content that could not be converted. +pub fn convert(indd: &[u8], name: &str, out: impl std::io::Write) -> Result, Error> { let container = Container::parse(indd)?; let db = container.database()?; let doc = model::Reader::new(&db).document(container.header.version)?; idml::write(&doc, name, out)?; - Ok(()) + Ok(doc.warnings) } diff --git a/src/main.rs b/src/main.rs index 5850db0..dd3a62f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -157,6 +157,8 @@ fn convert(input: &str, output: &str) -> CliResult { .file_name() .map_or_else(|| input.to_string(), |n| n.to_string_lossy().into_owned()); let file = std::io::BufWriter::new(std::fs::File::create(output)?); - indd::convert(&bytes, &name, file)?; + for warning in indd::convert(&bytes, &name, file)? { + eprintln!("warning: {warning}"); + } Ok(()) } diff --git a/src/model/mod.rs b/src/model/mod.rs index 3bef543..4ae6145 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -3,11 +3,13 @@ pub mod attrs; pub mod color; +pub mod table; use std::collections::{BTreeMap, HashMap}; pub use attrs::{Attrs, Value}; pub use color::Color; +pub use table::{Cell, Table}; use crate::object::{Cursor, Object}; use crate::{Database, Error, Version}; @@ -96,6 +98,8 @@ pub mod strand { pub const PARAGRAPH_STYLE: u32 = 0x204; /// Objects owned by text positions (anchored items, tables, ...). pub const OWNED_ITEMS: u32 = 0x209; + /// Which object (story, or table and cell) each stretch of text belongs to. + pub const TEXT_OWNER: u32 = 0x2A4; } /// A 2D affine transform `[a b c d tx ty]`, as in IDML `ItemTransform`. @@ -235,6 +239,8 @@ pub struct Style { /// A stretch of story text with one paragraph style and one character style. #[derive(Debug, Clone, PartialEq)] pub struct TextRun { + /// UTF-16 offset of the run in the story text. + pub start: usize, pub text: String, pub paragraph_style: Option, pub character_style: Option, @@ -250,6 +256,8 @@ pub struct Story { pub runs: Vec, /// Page items anchored in the text, by UTF-16 offset of their U+FFFC. pub anchors: BTreeMap>, + /// Tables, by UTF-16 offset of their U+0016. + pub tables: BTreeMap, } #[derive(Debug, Clone, PartialEq)] @@ -270,6 +278,8 @@ pub struct Document { pub style_groups: BTreeMap, pub object_styles: BTreeMap, pub sections: Vec
, + /// Problems that did not stop the conversion (content left out). + pub warnings: Vec, } /// A style group: a root group of styles, or a named group in it. @@ -312,6 +322,7 @@ pub struct ObjectStyle { pub struct Reader<'a> { db: &'a Database<'a>, cache: std::cell::RefCell>>, + warnings: std::cell::RefCell>, } fn uid_or_none(v: u32) -> Option { @@ -323,6 +334,7 @@ impl<'a> Reader<'a> { Reader { db, cache: Default::default(), + warnings: Default::default(), } } @@ -339,6 +351,11 @@ impl<'a> Reader<'a> { Ok(obj) } + /// Record a problem that does not stop the conversion. + pub fn warn(&self, msg: String) { + self.warnings.borrow_mut().push(msg); + } + pub fn class(&self, uid: u32) -> Option { self.db.class_of(uid) } @@ -497,6 +514,7 @@ impl<'a> Reader<'a> { .into_iter() .map(|uid| self.section(uid)) .collect::, _>>()?, + warnings: self.warnings.borrow().clone(), }) } @@ -880,21 +898,25 @@ impl<'a> Reader<'a> { let mut para: Vec = Vec::new(); let mut chars: Vec = Vec::new(); let mut owned: Vec<(usize, u32, u32)> = Vec::new(); + // (start, length, owner, cell) for each stretch of text. + let mut owners: Vec<(usize, usize, u32, u32)> = Vec::new(); for strand in strands { let Some(list) = self.chunk(strand, chunk::STRAND_DATA)? else { continue; }; let mut c = Cursor::new(&list); let n = c.u16()?; + let mut base = 0usize; for _ in 0..n { - let _len = c.u32()?; + let data_len = c.u32()? as usize; let data_uid = c.u32()?; let runs = self.required(data_uid, chunk::STRAND_RUNS)?; let mut r = Cursor::new(&runs); let kind = r.u32()?; r.skip(4)?; let count = r.u16()?; - let mut pos = 0usize; + let mut pos = base; + base += data_len; for _ in 0..count { let size = r.u32()? as usize; let rec = r.bytes(size)?; @@ -914,6 +936,11 @@ impl<'a> Reader<'a> { strand::TEXT => { text.extend(rc.segment_units(len)?); } + strand::TEXT_OWNER => { + let owner = rc.u32()?; + let cell = rc.u32()?; + owners.push((start, len, owner, cell)); + } strand::PARAGRAPH_STYLE | strand::CHARACTER_STYLE => { let style = rc.u32()?; let n = rc.u16()? as usize; @@ -931,20 +958,57 @@ impl<'a> Reader<'a> { } } let mut anchors: BTreeMap> = BTreeMap::new(); + let mut tables: BTreeMap = BTreeMap::new(); for (pos, cls, item) in owned { - if cls != class::ANCHOR { - continue; - } - for child in self.children(item, chunk::ANCHOR_CHILDREN)? { - if let Some(pi) = self.page_item(child, None)? { - anchors.entry(pos).or_default().push(pi); + match cls { + class::ANCHOR => { + for child in self.children(item, chunk::ANCHOR_CHILDREN)? { + if let Some(pi) = self.page_item(child, None)? { + anchors.entry(pos).or_default().push(pi); + } + } } + table::class::TABLE_ANCHOR => { + // A table that cannot be read is left out, with a + // warning, rather than failing the whole document. + match self.table_of_anchor(item) { + Ok(Some(t)) => { + tables.insert(pos, t); + } + Ok(None) => {} + Err(e) => self.warn(format!("story {uid}: table left out: {e}")), + } + } + _ => {} + } + } + let cuts: Vec = owners.iter().map(|o| o.0).collect(); + let all = split_runs(&text, ¶, &chars, &cuts); + // Text not owned by the story belongs to table cells. + let owner_at = |at: usize| { + owners + .iter() + .find(|o| at >= o.0 && at < o.0 + o.1) + .map(|o| (o.2, o.3)) + }; + let mut runs = Vec::new(); + for run in all { + match owner_at(run.start) { + Some((owner, cell)) if owner != uid => { + if let Some(t) = tables.values_mut().find(|t| t.uid == owner) + && let Some(c) = t.cells.iter_mut().find(|c| c.id == cell) + { + c.runs.push(run); + } + } + _ => runs.push(run), } } Ok(Story { uid, - runs: split_runs(&text, ¶, &chars), + runs, anchors, + tables, }) } } @@ -970,8 +1034,14 @@ fn find_string(data: &[u8], from: usize) -> Result { /// (counted in UTF-16 code units) into runs with both styles constant. type StyleRun = (usize, u32, Attrs); -fn split_runs(utf16: &[u16], para: &[StyleRun], chars: &[StyleRun]) -> Vec { +fn split_runs( + utf16: &[u16], + para: &[StyleRun], + chars: &[StyleRun], + extra: &[usize], +) -> Vec { let mut cuts: Vec = vec![0, utf16.len()]; + cuts.extend(extra.iter().map(|&c| c.min(utf16.len()))); for list in [para, chars] { let mut pos = 0; for (len, _, _) in list { @@ -997,6 +1067,7 @@ fn split_runs(utf16: &[u16], para: &[StyleRun], chars: &[StyleRun]) -> Vec = runs.iter().map(|r| r.text.as_str()).collect(); assert_eq!(texts, ["ab", "cd", "ef"]); diff --git a/src/model/table.rs b/src/model/table.rs new file mode 100644 index 0000000..35c3de0 --- /dev/null +++ b/src/model/table.rs @@ -0,0 +1,296 @@ +//! Tables. See `docs/format/tables.md`. + +use super::{Attrs, Reader, TextRun, Value}; +use crate::Error; +use crate::object::Cursor; + +pub mod class { + /// Owned by the U+0016 character where a table sits in its story. + pub const TABLE_ANCHOR: u32 = 0xB651; + pub const TABLE: u32 = 0xB608; + /// Owns the cell strand (row groups with cell records). + pub const CELL_STRAND_OWNER: u32 = 0xB606; +} + +pub mod chunk { + pub const ANCHOR_TABLE: u32 = 0xB67D; + pub const TABLE_SIZE: u32 = 0xB608; + pub const TABLE_ROWS: u32 = 0xB616; + pub const TABLE_COLUMNS: u32 = 0xB617; + pub const TABLE_PARTS: u32 = 0xB6FB; +} + +/// Attribute IDs in table data. +pub mod attr { + pub const COLUMN_WIDTH: u32 = 0xB60D; + pub const ROW_HEIGHT: u32 = 0xB60C; + pub const ROW_MIN_HEIGHT: u32 = 0xB66E; + /// 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. + pub const COVERED: u32 = 0xB614; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Row { + pub height: Option, + pub min_height: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Cell { + /// Cell ID, local to the table (IDML `Self` suffix `i`). + pub id: u32, + pub row: usize, + pub column: usize, + pub row_span: usize, + pub column_span: usize, + pub runs: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Table { + pub uid: u32, + pub header_rows: u32, + pub footer_rows: u32, + pub rows: Vec, + pub columns: Vec, + pub cells: Vec, +} + +/// Groups of rows or columns sharing attributes: u32 group count; per +/// group u32 count, u16, u16 attribute count, attributes, 8 bytes. +fn groups(data: &[u8]) -> Result, Error> { + let mut c = Cursor::new(data); + let n = c.u32()?; + let mut out = Vec::new(); + for _ in 0..n { + let count = c.u32()? as usize; + c.u16()?; + let na = c.u16()? as usize; + let attrs = Attrs::parse_text(&mut c, na)?; + c.skip(8)?; + out.push((count, attrs)); + } + Ok(out) +} + +fn f64_attr(a: &Attrs, id: u32) -> Option { + a.get(id).and_then(Value::as_f64) +} + +/// One grid position from the cell strand. +struct Position { + id: u32, + /// Text area width and height, for positions that start a cell. + size: Option<(f64, f64)>, + /// Covered by a merged cell. + covered: bool, +} + +impl Reader<'_> { + /// 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 { + return Ok(None); + }; + let uid = Cursor::new(&d).u32()?; + if self.class(uid) != Some(class::TABLE) { + return Ok(None); + } + self.table(uid).map(Some) + } + + fn table(&self, uid: u32) -> Result { + let size = self.required(uid, chunk::TABLE_SIZE)?; + let mut c = Cursor::new(&size); + let nrows = c.u32()? as usize; + let ncols = c.u32()? as usize; + let header_rows = c.u32()?; + let footer_rows = c.u32()?; + + let mut columns = Vec::with_capacity(ncols); + if let Some(d) = self.chunk(uid, chunk::TABLE_COLUMNS)? { + for (count, a) in groups(&d)? { + let w = f64_attr(&a, attr::COLUMN_WIDTH).unwrap_or(0.0); + columns.extend(std::iter::repeat_n(w, count)); + } + } + columns.resize(ncols, columns.last().copied().unwrap_or(0.0)); + let mut rows = Vec::with_capacity(nrows); + if let Some(d) = self.chunk(uid, chunk::TABLE_ROWS)? { + for (count, a) in groups(&d)? { + let row = Row { + height: f64_attr(&a, attr::ROW_HEIGHT), + min_height: f64_attr(&a, attr::ROW_MIN_HEIGHT), + }; + rows.extend(std::iter::repeat_n(row, count)); + } + } + rows.resize( + nrows, + Row { + height: None, + min_height: None, + }, + ); + + let grid = self.cell_grid(uid)?; + let cells = cells_from_grid(&grid, &rows, &columns); + Ok(Table { + uid, + header_rows, + footer_rows, + rows, + columns, + cells, + }) + } + + /// Grid positions by row, from the cell strand's row groups. + fn cell_grid(&self, table: u32) -> Result>, Error> { + let parts = self.required(table, chunk::TABLE_PARTS)?; + let mut c = Cursor::new(&parts); + let n = c.u32()?; + let mut owner = None; + for _ in 0..n { + let u = c.u32()?; + if c.u32()? == class::CELL_STRAND_OWNER { + owner = Some(u); + } + } + let Some(owner) = owner else { + return Ok(Vec::new()); + }; + let mut grid = Vec::new(); + let Some(list) = self.chunk(owner, super::chunk::STRAND_DATA)? else { + return Ok(grid); + }; + let mut lc = Cursor::new(&list); + let count = lc.u16()?; + for _ in 0..count { + lc.u32()?; + let data = self.required(lc.u32()?, super::chunk::STRAND_RUNS)?; + let mut r = Cursor::new(&data); + r.skip(8)?; + let groups = r.u16()?; + 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. + let sets = g.u32()?; + 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 nr = g.u32()?; + let mut ids = Vec::new(); + for _ in 0..nr { + let k = g.u32()?; + ids.push((0..k).map(|_| g.u32()).collect::, _>>()?); + } + let nrec = g.u32()?; + for (i, row_ids) in ids.into_iter().enumerate() { + if i as u32 >= nrec { + break; + } + let n = g.u16()? as usize; + let raw = raw_attrs(&mut g, n)?; + let row = row_ids + .into_iter() + .zip(raw) + .map(|(id, (aid, value))| Position { + id, + size: (aid == attr::CELL).then(|| cell_size(&value)).flatten(), + covered: aid == attr::COVERED, + }) + .collect(); + grid.push(row); + } + } + } + Ok(grid) + } +} + +/// Attribute records keeping the raw payload of their second value. +fn raw_attrs(c: &mut Cursor, n: usize) -> Result)>, Error> { + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let id = c.u32()?; + let size = c.u16()? as usize; + let payload = c.bytes(size)?; + let mut p = Cursor::new(payload); + let mut second = Vec::new(); + if size >= 2 { + let count = p.u16()?; + for i in 0..count { + p.u32()?; + let len = p.u16()? as usize; + let data = p.bytes(len)?; + if i == 1 { + second = data.to_vec(); + } + } + } + out.push((id, second)); + } + Ok(out) +} + +/// Text area width and height of a cell record. +fn cell_size(v: &[u8]) -> Option<(f64, f64)> { + let f = |o: usize| { + v.get(o..o + 8) + .map(|b| f64::from_le_bytes(b.try_into().unwrap())) + }; + Some((f(32)?, f(40)?)) +} + +/// Cells from the grid: a position with geometry starts a cell. Its text +/// area is its spanned width and height minus the insets, so its span is +/// the smallest number of columns (rows) whose sizes reach the text area. +fn cells_from_grid(grid: &[Vec], rows: &[Row], columns: &[f64]) -> Vec { + let mut cells = Vec::new(); + for (r, row) in grid.iter().enumerate() { + for (c, pos) in row.iter().enumerate() { + let Some((w, h)) = pos.size else { continue }; + let span = |sizes: &[f64], target: f64| -> usize { + let mut sum = 0.0; + for (k, s) in sizes.iter().enumerate() { + sum += s; + if sum >= target - 1e-3 { + return k + 1; + } + } + sizes.len().max(1) + }; + let heights: Vec = rows[r.min(rows.len())..] + .iter() + .map(|x| x.height.unwrap_or(0.0)) + .collect(); + // A cell that was never laid out has no geometry; then take the + // covered positions to its right as its span. + let column_span = if w > 0.0 { + span(&columns[c.min(columns.len())..], w) + } else { + 1 + row[c + 1..].iter().take_while(|p| p.covered).count() + }; + let row_span = if h > 0.0 { span(&heights, h) } else { 1 }; + cells.push(Cell { + id: pos.id, + row: r, + column: c, + row_span, + column_span, + runs: Vec::new(), + }); + } + } + cells +}