use crate::model::table::Table;
use crate::renderer::hwpunit_to_px;
use std::collections::{BTreeSet, VecDeque};
const BOUNDARY_TOLERANCE_HU: i32 = 2;
pub(super) struct StoredCellSpans {
col_count: usize,
spacing: f64,
tolerance: f64,
spans: Vec<(usize, usize, f64)>,
}
impl StoredCellSpans {
pub(super) fn collect(
table: &Table,
col_count: usize,
invalid_rows: &BTreeSet<u16>,
dpi: f64,
width_scale: f64,
) -> Option<Self> {
if col_count == 0 {
return None;
}
let spacing = hwpunit_to_px(i32::from(table.cell_spacing), dpi);
let mut spans = Vec::new();
for cell in &table.cells {
if invalid_rows.contains(&cell.row) || cell.width == 0 || cell.col_span == 0 {
continue;
}
let start = cell.col as usize;
let end = start + cell.col_span as usize;
if end > col_count {
return None;
}
let width = hwpunit_to_px(
table.physical_cell_width_hu(cell).min(i32::MAX as u32) as i32,
dpi,
) * width_scale;
spans.push((start, end, width + spacing));
}
if spans.is_empty() {
return None;
}
Some(Self {
col_count,
spacing,
tolerance: hwpunit_to_px(BOUNDARY_TOLERANCE_HU, dpi) * width_scale.max(1.0),
spans,
})
}
pub(super) fn satisfied_by(&self, col_widths: &[f64]) -> bool {
if col_widths.len() != self.col_count {
return false;
}
let mut boundary = Vec::with_capacity(self.col_count + 1);
boundary.push(0.0);
for width in col_widths {
boundary.push(boundary.last().copied().unwrap_or(0.0) + width + self.spacing);
}
self.spans.iter().all(|&(start, end, length)| {
(boundary[end] - boundary[start] - length).abs() <= self.tolerance
})
}
pub(super) fn solve(&self) -> Option<Vec<f64>> {
let mut adjacency: Vec<Vec<(usize, f64)>> = vec![Vec::new(); self.col_count + 1];
for &(start, end, length) in &self.spans {
adjacency[start].push((end, length));
adjacency[end].push((start, -length));
}
let mut boundary: Vec<Option<f64>> = vec![None; self.col_count + 1];
boundary[0] = Some(0.0);
let mut queue = VecDeque::from([0usize]);
while let Some(node) = queue.pop_front() {
let base = boundary[node]?;
for &(next, length) in &adjacency[node] {
let value = base + length;
match boundary[next] {
Some(existing) if (existing - value).abs() > self.tolerance => return None,
Some(_) => {}
None => {
boundary[next] = Some(value);
queue.push_back(next);
}
}
}
}
boundary[self.col_count]?;
let mut resolved = vec![0.0f64; self.col_count + 1];
let mut prev_known = 0usize;
for (index, value) in boundary.iter().enumerate().skip(1) {
let Some(value) = *value else {
continue;
};
let start = resolved[prev_known];
let gap = (index - prev_known) as f64;
for step in 1..=index - prev_known {
resolved[prev_known + step] = start + (value - start) * step as f64 / gap;
}
prev_known = index;
}
let col_widths: Vec<f64> = resolved
.windows(2)
.map(|pair| pair[1] - pair[0] - self.spacing)
.collect();
if col_widths.iter().any(|&width| width <= 0.0) || !self.satisfied_by(&col_widths) {
return None;
}
Some(col_widths)
}
}