use crate::analysis::lines::{LinesConfig, split_at_positions};
use crate::common::geom::{Rect, median};
use crate::model::Align;
use crate::model::Line;
const BIN_PT: f32 = 0.5;
const NUMBER_UNITS: &str = "MKBGkx";
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TablesConfig {
pub min_pieces_count: usize,
pub default_size_pt: f32,
pub max_glyph_height_em: f32,
pub row_break_em: f32,
pub min_rows_count: usize,
pub band_rule_min_ratio: f32,
pub continuation_gap_ratio: f32,
pub band_min_count: usize,
pub multiline_bands_tenths: usize,
pub band_max_lines_count: usize,
pub merged_figure_cells_min_count: usize,
pub band_rules_min_count: usize,
pub continuation_max_dy_em: f32,
pub continuation_min_lowercase_count: usize,
pub continuation_lowercase_tenths: usize,
pub min_corridor_em: f32,
pub min_clear_corridor_em: f32,
pub min_numeric_corridor_em: f32,
pub numeric_corridor_min_rows_count: usize,
pub multi_row_split_min_rows_count: usize,
pub aligned_word_tolerance_pt: f32,
pub aligned_words_min_count: usize,
pub split_unaligned_min_words_count: usize,
pub numeric_row_min_tenths: usize,
pub numeric_rivers_min_rows_count: usize,
pub strict_corridor_below_rows_count: usize,
pub corridor_crossing_ratio: f32,
pub column_split_passes_count: usize,
pub split_min_rows_count: usize,
pub split_min_multi_rows_count: usize,
pub split_min_multi_rows_tenths: usize,
pub split_crossing_ratio: f32,
pub split_min_side_rows_count: usize,
pub cell_edge_inset_pt: f32,
pub default_pitch_em: f32,
pub floating_label_max_pitch_ratio: f32,
pub edge_pad_em: f32,
pub region_slack_pt: f32,
pub first_row_top_em: f32,
pub row_boundary_raise_em: f32,
pub last_row_bottom_em: f32,
pub rule_row_offset_em: f32,
pub heavy_rule_min_width_pt: f32,
pub rule_column_cover_ratio: f32,
pub full_rule_min_cols_tenths: usize,
pub snap_min_below_em: f32,
pub snap_min_above_em: f32,
pub vrule_text_slack_pt: f32,
pub vrule_max_offset_em: f32,
pub vrule_top_slack_em: f32,
pub vrule_bottom_slack_em: f32,
pub min_cells_count: usize,
pub min_multi_cell_rows_tenths: usize,
pub spanning_cells_divisor: usize,
pub align_tolerance_pt: f32,
pub max_header_rows_count: usize,
}
impl Default for TablesConfig {
fn default() -> Self {
Self {
min_pieces_count: 4,
default_size_pt: 9.0,
max_glyph_height_em: 2.4,
row_break_em: 0.45,
min_rows_count: 2,
band_rule_min_ratio: 0.5,
continuation_gap_ratio: 1.35,
band_min_count: 3,
multiline_bands_tenths: 5,
band_max_lines_count: 12,
merged_figure_cells_min_count: 2,
band_rules_min_count: 3,
continuation_max_dy_em: 1.6,
continuation_min_lowercase_count: 2,
continuation_lowercase_tenths: 4,
min_corridor_em: 0.4,
min_clear_corridor_em: 0.1,
min_numeric_corridor_em: 0.15,
numeric_corridor_min_rows_count: 2,
multi_row_split_min_rows_count: 2,
aligned_word_tolerance_pt: 0.6,
aligned_words_min_count: 2,
split_unaligned_min_words_count: 4,
numeric_row_min_tenths: 8,
numeric_rivers_min_rows_count: 3,
strict_corridor_below_rows_count: 4,
corridor_crossing_ratio: 0.15,
column_split_passes_count: 3,
split_min_rows_count: 4,
split_min_multi_rows_count: 2,
split_min_multi_rows_tenths: 3,
split_crossing_ratio: 0.34,
split_min_side_rows_count: 2,
cell_edge_inset_pt: 0.5,
default_pitch_em: 1.2,
floating_label_max_pitch_ratio: 0.75,
edge_pad_em: 0.5,
region_slack_pt: 2.0,
first_row_top_em: 1.05,
row_boundary_raise_em: 0.3,
last_row_bottom_em: 0.55,
rule_row_offset_em: 0.3,
heavy_rule_min_width_pt: 0.7,
rule_column_cover_ratio: 0.5,
full_rule_min_cols_tenths: 9,
snap_min_below_em: 0.1,
snap_min_above_em: 0.5,
vrule_text_slack_pt: 0.5,
vrule_max_offset_em: 4.0,
vrule_top_slack_em: 0.3,
vrule_bottom_slack_em: 0.5,
min_cells_count: 6,
min_multi_cell_rows_tenths: 5,
spanning_cells_divisor: 3,
align_tolerance_pt: 0.3,
max_header_rows_count: 4,
}
}
}
#[derive(Debug, Clone)]
pub struct GridCell {
pub col: usize,
pub colspan: usize,
pub rowspan: usize,
pub lines: Vec<Line>,
}
#[derive(Debug, Clone)]
pub struct Grid {
pub bbox: Rect,
pub n_cols: usize,
pub col_bounds: Vec<f32>,
pub col_text: Vec<(f32, f32)>,
pub col_align: Vec<Align>,
pub row_bounds: Vec<f32>,
pub row_baselines: Vec<f32>,
pub rows: Vec<Vec<GridCell>>,
pub rule_above: Vec<Vec<u8>>,
pub rule_bottom: Vec<u8>,
pub rule_left: Vec<Vec<bool>>,
pub rule_right: Vec<bool>,
pub header_rows: usize,
pub size: f32,
}
struct TableText<'line> {
pieces: Vec<&'line Line>,
rows: Vec<Vec<&'line Line>>,
multiline: bool,
size: f32,
x_min: f32,
x_max: f32,
}
#[derive(Clone, Copy)]
struct CorridorBins {
run: usize,
clear: usize,
numeric_run: usize,
numeric_rows: usize,
words: bool,
}
struct RowPiece {
line: Line,
centred: bool,
}
struct Corridor {
start: f32,
end: f32,
at: f32,
}
struct Word {
x0: f32,
x1: f32,
numeric: bool,
}
struct HorizontalRules {
rule_above: Vec<Vec<u8>>,
rule_bottom: Vec<u8>,
full_rule_at: Vec<bool>,
snapped: Vec<Option<f32>>,
}
struct VerticalRules {
rule_left: Vec<Vec<bool>>,
rule_right: Vec<bool>,
}
struct CellCounts {
total: usize,
spanning: usize,
multi_cell_rows: usize,
rows: usize,
}
pub fn extract_grid(
region: Rect,
lines: &[Line],
hrules: &[(Rect, f32)],
vrules: &[Rect],
cfg: &TablesConfig,
lines_cfg: &LinesConfig,
) -> Option<Grid> {
grid_from_lines(region, lines, hrules, vrules, true, cfg, lines_cfg)
.or_else(|| grid_from_lines(region, lines, hrules, vrules, false, cfg, lines_cfg))
}
fn grid_from_lines(
region: Rect,
lines: &[Line],
hrules: &[(Rect, f32)],
vrules: &[Rect],
merge_lines: bool,
cfg: &TablesConfig,
lines_cfg: &LinesConfig,
) -> Option<Grid> {
let text = table_text(lines, hrules, merge_lines, cfg)?;
let size = text.size;
let separators = find_columns(&text, cfg)?;
let n_cols = separators.len() + 1;
let mut grid_rows = build_cells(&text.rows, text.multiline, &separators, cfg, lines_cfg);
let mut baselines: Vec<f32> = text.rows.iter().map(|row| row_baseline(row, text.multiline)).collect();
let mut last_baselines: Vec<f32> = text.rows.iter().map(|row| last_baseline(row)).collect();
let floating = if text.multiline {
Vec::new()
} else {
take_floating_labels(&mut grid_rows, &mut baselines, size, cfg)
};
if !text.multiline {
last_baselines = baselines.clone();
}
let n_rows = grid_rows.len();
if n_rows < cfg.min_rows_count {
return None;
}
let mut col_bounds = column_bounds(region, hrules, &separators, &text, cfg);
let mut row_bounds = row_bounds(&baselines, &last_baselines, size, cfg);
let horizontal = horizontal_rules(hrules, &col_bounds, &baselines, size, cfg);
snap_row_bounds(
&mut row_bounds,
&horizontal.snapped,
&baselines,
&last_baselines,
size,
cfg,
);
let vertical = vertical_rules(vrules, &text.pieces, &mut col_bounds, &baselines, size, cfg);
place_floating_labels(floating, &mut grid_rows, &baselines, &horizontal.rule_above)?;
if !is_plausible(&grid_rows, n_cols, cfg) {
return None;
}
let (col_text, col_align) = column_geometry(&grid_rows, n_cols, cfg);
let header_rows = (1..n_rows)
.find(|&k| horizontal.full_rule_at[k])
.filter(|&k| k <= cfg.max_header_rows_count)
.unwrap_or(0);
let bbox = Rect::new(col_bounds[0], row_bounds[0], col_bounds[n_cols], row_bounds[n_rows]);
Some(Grid {
bbox,
n_cols,
col_bounds,
col_text,
col_align,
row_bounds,
row_baselines: baselines,
rows: grid_rows,
rule_above: horizontal.rule_above,
rule_bottom: horizontal.rule_bottom,
rule_left: vertical.rule_left,
rule_right: vertical.rule_right,
header_rows,
size,
})
}
fn table_text<'line>(
lines: &'line [Line],
hrules: &[(Rect, f32)],
merge_lines: bool,
cfg: &TablesConfig,
) -> Option<TableText<'line>> {
let pieces: Vec<&Line> = lines.iter().filter(|line| !line.glyphs.is_empty()).collect();
if pieces.len() < cfg.min_pieces_count {
return None;
}
let sizes: Vec<f32> = pieces.iter().map(|line| line.size).collect();
let size = median(&sizes, cfg.default_size_pt);
if pieces.iter().any(|line| {
line.glyphs
.iter()
.any(|glyph| glyph.ink.height() > cfg.max_glyph_height_em * line.size.max(size))
}) {
return None;
}
let rows = group_rows(&pieces, size, cfg)?;
let x_min = pieces.iter().map(|line| line.bbox.x0).fold(f32::INFINITY, f32::min);
let x_max = pieces.iter().map(|line| line.bbox.x1).fold(f32::NEG_INFINITY, f32::max);
let merged = if merge_lines {
merge_continuation_rows(&rows, hrules, (x_min, x_max), size, cfg)
} else {
None
};
let (rows, multiline) = match merged {
Some(merged) => (merged, true),
None => (rows, false),
};
Some(TableText {
pieces,
rows,
multiline,
size,
x_min,
x_max,
})
}
fn group_rows<'line>(pieces: &[&'line Line], size: f32, cfg: &TablesConfig) -> Option<Vec<Vec<&'line Line>>> {
let mut order: Vec<&Line> = pieces.to_vec();
order.sort_by(|a, b| a.baseline.total_cmp(&b.baseline));
let mut rows: Vec<Vec<&Line>> = Vec::new();
let mut row_y = f32::NEG_INFINITY;
for line in order {
if rows.is_empty() || line.baseline - row_y > cfg.row_break_em * size {
rows.push(vec![line]);
row_y = line.baseline;
} else {
rows.last_mut().unwrap().push(line);
}
}
if rows.len() < cfg.min_rows_count {
return None;
}
for row in rows.iter_mut() {
row.sort_by(|a, b| a.bbox.x0.total_cmp(&b.bbox.x0));
}
Some(rows)
}
fn merge_continuation_rows<'line>(
rows: &[Vec<&'line Line>],
hrules: &[(Rect, f32)],
text_extent: (f32, f32),
size: f32,
cfg: &TablesConfig,
) -> Option<Vec<Vec<&'line Line>>> {
if rows.len() < 2 {
return None;
}
let baselines: Vec<f32> = rows.iter().map(|row| row_baseline(row, false)).collect();
let min_rule = cfg.band_rule_min_ratio * (text_extent.1 - text_extent.0);
let rule_ys: Vec<f32> = hrules
.iter()
.filter(|(rule, _)| rule.width() >= min_rule)
.map(|(rule, _)| rule.cy())
.collect();
let gaps: Vec<f32> = baselines.windows(2).map(|pair| pair[1] - pair[0]).collect();
let ruled: Vec<bool> = (0..gaps.len())
.map(|k| rule_ys.iter().any(|&y| y > baselines[k] && y < baselines[k + 1]))
.collect();
let by_rules = ruled.iter().filter(|&&is_ruled| is_ruled).count() >= cfg.band_rules_min_count;
let mut inner: Vec<f32> = (0..gaps.len()).filter(|&k| !ruled[k]).map(|k| gaps[k]).collect();
inner.sort_by(|a, b| a.total_cmp(b));
let pitch = inner.get(inner.len() / 2).copied().unwrap_or(f32::INFINITY);
let breaks: Vec<bool> = (0..gaps.len())
.map(|k| {
if by_rules {
ruled[k]
} else {
gaps[k] > cfg.continuation_gap_ratio * pitch.max(cfg.row_break_em * size)
}
})
.collect();
let mut bands: Vec<Vec<&Line>> = vec![rows[0].clone()];
let mut piece_counts: Vec<Vec<usize>> = vec![vec![rows[0].len()]];
for (k, row) in rows.iter().enumerate().skip(1) {
if breaks[k - 1] {
bands.push(row.clone());
piece_counts.push(vec![row.len()]);
} else {
bands.last_mut()?.extend(row.iter().copied());
piece_counts.last_mut()?.push(row.len());
}
}
let line_counts: Vec<usize> = piece_counts.iter().map(Vec::len).collect();
let multi = line_counts.iter().filter(|&&count| count > 1).count();
let ragged = piece_counts
.iter()
.filter(|counts| counts.len() > 1 && counts.iter().any(|&count| count != counts[0]))
.count();
let plausible = bands.len() >= cfg.band_min_count
&& multi * 10 >= bands.len() * cfg.multiline_bands_tenths
&& ragged * 2 >= multi
&& line_counts.iter().all(|&count| count <= cfg.band_max_lines_count)
&& !stacked_numbers(&bands)
&& continues_text(&bands, size, cfg);
plausible.then(|| {
for band in bands.iter_mut() {
band.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
}
bands
})
}
fn stacked_numbers(bands: &[Vec<&Line>]) -> bool {
bands.iter().any(|band| {
let numbers: Vec<&&Line> = band.iter().filter(|line| is_number(line.text().trim())).collect();
numbers.iter().enumerate().any(|(i, line)| {
numbers[i + 1..]
.iter()
.any(|other| other.bbox.x_overlap(&line.bbox) > 0.0 && (other.baseline - line.baseline).abs() > 0.0)
})
})
}
fn continues_text(bands: &[Vec<&Line>], size: f32, cfg: &TablesConfig) -> bool {
let (mut under, mut lowercase) = (0usize, 0usize);
for band in bands {
for line in band {
let has_line_above = band.iter().any(|other| {
let dy = line.baseline - other.baseline;
dy > cfg.row_break_em * size
&& dy <= cfg.continuation_max_dy_em * size
&& other.bbox.x_overlap(&line.bbox) > 0.0
});
if !has_line_above {
continue;
}
under += 1;
let starts_lowercase = line
.glyphs
.iter()
.find(|glyph| !glyph.text.trim().is_empty())
.is_some_and(|glyph| glyph.text.chars().next().is_some_and(char::is_lowercase));
lowercase += starts_lowercase as usize;
}
}
lowercase >= cfg.continuation_min_lowercase_count && lowercase * 10 >= under * cfg.continuation_lowercase_tenths
}
fn row_baseline(row: &[&Line], multiline: bool) -> f32 {
if multiline {
return row.iter().map(|line| line.baseline).fold(f32::INFINITY, f32::min);
}
median(&row.iter().map(|line| line.baseline).collect::<Vec<_>>(), 0.0)
}
fn last_baseline(row: &[&Line]) -> f32 {
row.iter().map(|line| line.baseline).fold(f32::NEG_INFINITY, f32::max)
}
fn table_corridors(text: &TableText, min_bins: CorridorBins, cfg: &TablesConfig) -> Vec<f32> {
let rows = &text.rows;
let n_all = rows.len();
let tolerance = if n_all < cfg.strict_corridor_below_rows_count {
0
} else {
((n_all as f32 * cfg.corridor_crossing_ratio) as u16).max(1)
};
let mut corridors = find_corridors(rows, text.x_min, text.x_max, tolerance, min_bins);
for river in numeric_rivers(rows, text, min_bins, cfg) {
let known = corridors
.iter()
.any(|corridor| corridor.start - BIN_PT <= river.end && river.start <= corridor.end + BIN_PT);
if !known {
corridors.push(river);
}
}
for corridor in corridors.iter_mut() {
if !cuts_word(rows, corridor.at) {
continue;
}
if let Some(clear) = clearest_point(rows, corridor.start, corridor.end, true)
&& !cuts_word(rows, clear)
{
corridor.at = clear;
}
}
let mut separators: Vec<f32> = corridors.iter().map(|corridor| corridor.at).collect();
separators.sort_by(|a, b| a.total_cmp(b));
separators
}
fn find_columns(text: &TableText, cfg: &TablesConfig) -> Option<Vec<f32>> {
let rows = &text.rows;
let min_bins = CorridorBins {
run: ((cfg.min_corridor_em * text.size / BIN_PT) as usize).max(1),
clear: ((cfg.min_clear_corridor_em * text.size / BIN_PT) as usize).max(1),
numeric_run: ((cfg.min_numeric_corridor_em * text.size / BIN_PT) as usize).max(1),
numeric_rows: cfg.numeric_corridor_min_rows_count,
words: false,
};
let mut separators = table_corridors(text, min_bins, cfg);
if separators.is_empty() {
return None;
}
for _ in 0..cfg.column_split_passes_count {
let mut bounds = vec![text.x_min - 1.0];
bounds.extend(separators.iter().copied());
bounds.push(text.x_max + 1.0);
let mut added = Vec::new();
for pair in bounds.windows(2) {
split_column(rows, pair[0], pair[1], min_bins, cfg, &mut added);
}
if added.is_empty() {
break;
}
separators.extend(added);
separators.sort_by(|a, b| a.total_cmp(b));
}
Some(separators)
}
fn cuts_word(rows: &[Vec<&Line>], x: f32) -> bool {
rows.iter()
.flatten()
.flat_map(|line| piece_words(line))
.any(|word| word.x0 < x && x < word.x1)
}
fn numeric_rivers(rows: &[Vec<&Line>], text: &TableText, min_bins: CorridorBins, cfg: &TablesConfig) -> Vec<Corridor> {
let numeric_rows: Vec<Vec<&Line>> = rows
.iter()
.filter(|row| {
let words: Vec<Word> = row.iter().flat_map(|line| piece_words(line)).collect();
let numeric = words.iter().filter(|word| word.numeric).count();
numeric >= 2 && numeric * 10 >= words.len() * cfg.numeric_row_min_tenths
})
.cloned()
.collect();
if numeric_rows.len() < cfg.numeric_rivers_min_rows_count {
return Vec::new();
}
let by_words = CorridorBins {
words: true,
..min_bins
};
find_corridors(&numeric_rows, text.x_min, text.x_max, 0, by_words)
.into_iter()
.map(|corridor| Corridor {
at: clearest_point(&numeric_rows, corridor.start, corridor.end, true).unwrap_or(corridor.at),
..corridor
})
.collect()
}
fn split_column(
rows: &[Vec<&Line>],
left: f32,
right: f32,
min_bins: CorridorBins,
cfg: &TablesConfig,
added: &mut Vec<f32>,
) {
let known = added.len();
split_column_by_share(rows, left, right, min_bins, cfg, added);
if added.len() == known {
split_column_by_multi_rows(rows, left, right, min_bins, cfg, added);
}
}
fn split_column_by_share(
rows: &[Vec<&Line>],
left: f32,
right: f32,
min_bins: CorridorBins,
cfg: &TablesConfig,
added: &mut Vec<f32>,
) {
let inside = |line: &&&Line| line.bbox.cx() >= left && line.bbox.cx() <= right;
let with: usize = rows.iter().filter(|row| row.iter().any(|line| inside(&line))).count();
let multi: usize = rows.iter().filter(|row| row.iter().filter(inside).count() >= 2).count();
if with < cfg.split_min_rows_count
|| multi < cfg.split_min_multi_rows_count
|| multi * 10 < with * cfg.split_min_multi_rows_tenths
{
return;
}
let lo = rows
.iter()
.flatten()
.filter(inside)
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
let hi = rows
.iter()
.flatten()
.filter(inside)
.map(|line| line.bbox.x1)
.fold(f32::NEG_INFINITY, f32::max);
let local = ((with as f32 * cfg.split_crossing_ratio) as u16).max(1);
for split in find_separators(rows, lo, hi, local, min_bins) {
let crossing = rows
.iter()
.filter(|row| {
row.iter()
.any(|line| inside(&line) && line.bbox.x0 < split && line.bbox.x1 > split)
})
.count();
let left_rows = rows
.iter()
.filter(|row| row.iter().any(|line| inside(&line) && line.bbox.x1 <= split))
.count();
let right_rows = rows
.iter()
.filter(|row| row.iter().any(|line| inside(&line) && line.bbox.x0 >= split))
.count();
if left_rows > crossing
&& right_rows > crossing
&& left_rows >= cfg.split_min_side_rows_count
&& right_rows >= cfg.split_min_side_rows_count
{
added.push(split);
}
}
}
fn split_column_by_multi_rows(
rows: &[Vec<&Line>],
left: f32,
right: f32,
min_bins: CorridorBins,
cfg: &TablesConfig,
added: &mut Vec<f32>,
) {
let multi_rows: Vec<Vec<&Line>> = rows
.iter()
.map(|row| {
row.iter()
.copied()
.filter(|line| line.bbox.cx() >= left && line.bbox.cx() <= right)
.collect::<Vec<_>>()
})
.filter(|row| row.len() >= 2)
.collect();
if multi_rows.len() < cfg.multi_row_split_min_rows_count {
return;
}
let lo = multi_rows
.iter()
.flatten()
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
let hi = multi_rows
.iter()
.flatten()
.map(|line| line.bbox.x1)
.fold(f32::NEG_INFINITY, f32::max);
for corridor in find_corridors(&multi_rows, lo, hi, 0, min_bins) {
let split = clearest_point(rows, corridor.start, corridor.end, false).unwrap_or(corridor.at);
let straddling = multi_rows
.iter()
.filter(|row| row.iter().any(|line| line.bbox.x1 <= split) && row.iter().any(|line| line.bbox.x0 >= split))
.count();
let (numeric, with_both) = numeric_sides(&multi_rows, split, split);
if straddling >= cfg.multi_row_split_min_rows_count && numeric >= 1 && numeric * 2 >= with_both {
added.push(split);
}
}
}
fn clearest_point(rows: &[Vec<&Line>], start: f32, end: f32, by_words: bool) -> Option<f32> {
let n_bins = ((end - start) / BIN_PT).ceil() as usize + 1;
let mut crossing = vec![0u16; n_bins];
for row in rows {
let mut covered = vec![false; n_bins];
for (left, right) in row.iter().flat_map(|line| piece_extents(line, by_words)) {
if right < start || left > end {
continue;
}
let first_bin = ((left - start) / BIN_PT).floor().max(0.0) as usize;
let last_bin = (((right - start) / BIN_PT).ceil().max(0.0) as usize).min(n_bins - 1);
for flag in &mut covered[first_bin..=last_bin.max(first_bin)] {
*flag = true;
}
}
for (bin, flag) in covered.iter().enumerate() {
crossing[bin] += *flag as u16;
}
}
let (best, best_len) = emptiest_stretch(&crossing, 0, n_bins);
(best_len > 0).then_some(start + (best as f32 + best_len as f32 * 0.5) * BIN_PT)
}
fn find_separators(rows: &[Vec<&Line>], x0: f32, x1: f32, tolerance: u16, min_bins: CorridorBins) -> Vec<f32> {
find_corridors(rows, x0, x1, tolerance, min_bins)
.into_iter()
.map(|corridor| corridor.at)
.collect()
}
fn find_corridors(rows: &[Vec<&Line>], x0: f32, x1: f32, tolerance: u16, min_bins: CorridorBins) -> Vec<Corridor> {
let crossing = crossing_counts(rows, x0, x1, min_bins.words);
let n_bins = crossing.len();
let mut corridors = Vec::new();
let mut i = 0;
while i < n_bins {
if crossing[i] > tolerance {
i += 1;
continue;
}
let start = i;
while i < n_bins && crossing[i] <= tolerance {
i += 1;
}
if start == 0 || i >= n_bins || i - start < min_bins.numeric_run {
continue;
}
let narrow = i - start < min_bins.run;
if narrow && !numbers_on_both_sides(rows, x0 + start as f32 * BIN_PT, x0 + i as f32 * BIN_PT, min_bins) {
continue;
}
let (best, best_len) = emptiest_stretch(&crossing, start, i);
if best_len >= min_bins.clear {
corridors.push(Corridor {
start: x0 + start as f32 * BIN_PT,
end: x0 + i as f32 * BIN_PT,
at: x0 + (best as f32 + best_len as f32 * 0.5) * BIN_PT,
});
}
}
corridors
}
fn crossing_counts(rows: &[Vec<&Line>], x0: f32, x1: f32, by_words: bool) -> Vec<u16> {
let n_bins = ((x1 - x0) / BIN_PT).ceil() as usize + 1;
let mut crossing = vec![0u16; n_bins];
for row in rows {
let mut covered = vec![false; n_bins];
for line in row {
if line.bbox.cx() < x0 || line.bbox.cx() > x1 {
continue;
}
for (left, right) in piece_extents(line, by_words) {
let first_bin = ((left - x0) / BIN_PT).floor().max(0.0) as usize;
let last_bin = (((right - x0) / BIN_PT).ceil().max(0.0) as usize).min(n_bins - 1);
if first_bin <= last_bin {
for flag in &mut covered[first_bin..=last_bin] {
*flag = true;
}
}
}
}
for (i, flag) in covered.iter().enumerate() {
crossing[i] += *flag as u16;
}
}
crossing
}
fn piece_extents(line: &Line, by_words: bool) -> Vec<(f32, f32)> {
if by_words {
piece_words(line).iter().map(|word| (word.x0, word.x1)).collect()
} else {
piece_stretches(line)
}
}
fn piece_stretches(line: &Line) -> Vec<(f32, f32)> {
let mut stretches: Vec<(f32, f32)> = Vec::new();
let mut previous_numeric = false;
for word in piece_words(line) {
match stretches.last_mut() {
Some(stretch) if !(previous_numeric && word.numeric) => stretch.1 = word.x1,
_ => stretches.push((word.x0, word.x1)),
}
previous_numeric = word.numeric;
}
stretches
}
fn piece_words(line: &Line) -> Vec<Word> {
let mut words: Vec<(f32, f32, String)> = Vec::new();
let mut open = false;
for glyph in &line.glyphs {
if glyph.text.trim().is_empty() {
open = false;
continue;
}
match words.last_mut() {
Some(word) if open && !glyph.space_before => {
word.0 = word.0.min(glyph.x0);
word.1 = word.1.max(glyph.x1);
word.2.push_str(&glyph.text);
}
_ => words.push((glyph.x0, glyph.x1, glyph.text.clone())),
}
open = true;
}
words
.into_iter()
.map(|(x0, x1, text)| Word {
x0,
x1,
numeric: is_number(&text),
})
.collect()
}
fn is_number(word: &str) -> bool {
let digits = word.trim_end_matches(|ch| NUMBER_UNITS.contains(ch));
digits
.chars()
.next()
.is_some_and(|ch| ch.is_ascii_digit() || "+-−~<>≈.".contains(ch))
&& digits.chars().any(|ch| ch.is_ascii_digit())
&& digits
.chars()
.all(|ch| ch.is_ascii_digit() || ".,%±+-−~*†‡<>≈eE".contains(ch))
}
fn numbers_on_both_sides(rows: &[Vec<&Line>], xa: f32, xb: f32, min_bins: CorridorBins) -> bool {
let (numeric, with_both) = numeric_sides(rows, xa, xb);
numeric >= min_bins.numeric_rows && numeric * 2 > with_both
}
fn numeric_sides(rows: &[Vec<&Line>], xa: f32, xb: f32) -> (usize, usize) {
let (mut numeric, mut with_both) = (0, 0);
for row in rows {
let words: Vec<Word> = row.iter().flat_map(|line| piece_words(line)).collect();
let left = words
.iter()
.filter(|word| word.x1 <= xa + BIN_PT)
.max_by(|a, b| a.x1.total_cmp(&b.x1));
let right = words
.iter()
.filter(|word| word.x0 >= xb - BIN_PT)
.min_by(|a, b| a.x0.total_cmp(&b.x0));
if let (Some(left), Some(right)) = (left, right) {
with_both += 1;
numeric += (left.numeric && right.numeric) as usize;
}
}
(numeric, with_both)
}
fn emptiest_stretch(crossing: &[u16], start: usize, end: usize) -> (usize, usize) {
let lowest = crossing[start..end].iter().copied().min().unwrap();
let (mut best, mut best_len, mut k) = (start, 0, start);
while k < end {
if crossing[k] == lowest {
let run_start = k;
while k < end && crossing[k] == lowest {
k += 1;
}
if k - run_start > best_len {
best = run_start;
best_len = k - run_start;
}
} else {
k += 1;
}
}
(best, best_len)
}
fn build_cells(
rows: &[Vec<&Line>],
multiline: bool,
separators: &[f32],
cfg: &TablesConfig,
lines_cfg: &LinesConfig,
) -> Vec<Vec<GridCell>> {
let col_of = |x: f32| separators.iter().filter(|&&separator| separator <= x).count();
let words: Vec<Vec<Word>> = rows
.iter()
.map(|row| row.iter().flat_map(|line| piece_words(line)).collect())
.collect();
let mut grid_rows: Vec<Vec<GridCell>> = Vec::with_capacity(rows.len());
for (row_idx, row) in rows.iter().enumerate() {
let others: Vec<&Word> = words
.iter()
.enumerate()
.filter(|(other_idx, _)| *other_idx != row_idx)
.flat_map(|(_, other)| other.iter())
.collect();
let pieces: Vec<RowPiece> = row
.iter()
.flat_map(|line| split_tight_cells(line, separators, &others, cfg, lines_cfg))
.collect();
let mut cells: Vec<GridCell> = Vec::new();
let mut placed: Vec<(usize, usize, &Line)> = pieces
.iter()
.map(|RowPiece { line, centred }| {
if *centred {
let col = col_of(line.bbox.cx());
(col, col, line)
} else {
let first_col = col_of(line.bbox.x0 + cfg.cell_edge_inset_pt);
(
first_col,
col_of(line.bbox.x1 - cfg.cell_edge_inset_pt).max(first_col),
line,
)
}
})
.collect();
if multiline {
placed.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.baseline.total_cmp(&b.2.baseline)));
}
for (first_col, last_col, line) in placed {
match cells.last_mut() {
Some(prev) if first_col < prev.col + prev.colspan => {
prev.colspan = prev.colspan.max(last_col + 1 - prev.col);
prev.lines.push(line.clone());
}
_ => cells.push(GridCell {
col: first_col,
colspan: last_col - first_col + 1,
rowspan: 1,
lines: vec![line.clone()],
}),
}
}
grid_rows.push(cells);
}
grid_rows
}
fn split_tight_cells(
line: &Line,
separators: &[f32],
others: &[&Word],
cfg: &TablesConfig,
lines_cfg: &LinesConfig,
) -> Vec<RowPiece> {
let crossed: Vec<f32> = separators
.iter()
.copied()
.filter(|&separator| {
separator > line.bbox.x0 + cfg.cell_edge_inset_pt && separator < line.bbox.x1 - cfg.cell_edge_inset_pt
})
.collect();
let words = piece_words(line);
let whole = || {
vec![RowPiece {
line: line.clone(),
centred: false,
}]
};
let pieces = |cuts: &[f32], centred: bool| {
split_at_positions(line, cuts, lines_cfg)
.into_iter()
.map(|line| RowPiece { line, centred })
.collect()
};
if crossed.is_empty() || words.len() != crossed.len() + 1 {
return whole();
}
let in_spaces = crossed
.iter()
.enumerate()
.all(|(i, &separator)| words[i].x1 <= separator && separator <= words[i + 1].x0);
let own_column = |(i, word): (usize, &Word)| {
let centre = (word.x0 + word.x1) * 0.5;
(i == 0 || crossed[i - 1] < centre) && (i == crossed.len() || centre < crossed[i])
};
let labels = words.len() >= cfg.split_unaligned_min_words_count && words.iter().enumerate().all(own_column);
let lined_up = |word: &Word| {
let tolerance = cfg.aligned_word_tolerance_pt;
let aligned = others
.iter()
.filter(|other| (other.x0 - word.x0).abs() <= tolerance || (other.x1 - word.x1).abs() <= tolerance)
.count();
aligned >= cfg.aligned_words_min_count
};
if labels && !in_spaces {
let cuts: Vec<f32> = words.windows(2).map(|pair| (pair[0].x1 + pair[1].x0) * 0.5).collect();
pieces(&cuts, true)
} else if in_spaces && (labels || words.iter().all(lined_up)) {
pieces(&crossed, false)
} else {
whole()
}
}
fn take_floating_labels(
grid_rows: &mut Vec<Vec<GridCell>>,
baselines: &mut Vec<f32>,
size: f32,
cfg: &TablesConfig,
) -> Vec<(f32, GridCell)> {
let pitch = {
let gaps: Vec<f32> = baselines.windows(2).map(|pair| pair[1] - pair[0]).collect();
median(&gaps, cfg.default_pitch_em * size)
};
let max_distance = cfg.floating_label_max_pitch_ratio * pitch;
let mut floating: Vec<(f32, GridCell)> = Vec::new();
let mut k = 0;
while k < grid_rows.len() {
let lone = grid_rows[k].len() == 1 && grid_rows[k][0].colspan == 1;
let near_prev = k > 0 && baselines[k] - baselines[k - 1] < max_distance;
let near_next = k + 1 < grid_rows.len() && baselines[k + 1] - baselines[k] < max_distance;
if lone && near_prev && near_next && grid_rows.len() > 2 {
let cell = grid_rows.remove(k).pop().unwrap();
floating.push((baselines.remove(k), cell));
} else {
k += 1;
}
}
floating
}
fn column_bounds(
region: Rect,
hrules: &[(Rect, f32)],
separators: &[f32],
text: &TableText,
cfg: &TablesConfig,
) -> Vec<f32> {
let rule_x0 = hrules.iter().map(|rule| rule.0.x0).fold(f32::INFINITY, f32::min);
let rule_x1 = hrules.iter().map(|rule| rule.0.x1).fold(f32::NEG_INFINITY, f32::max);
let pad = cfg.edge_pad_em * text.size;
let left_edge = if rule_x0.is_finite() {
rule_x0.min(text.x_min)
} else {
text.x_min - pad
};
let right_edge = if rule_x1.is_finite() {
rule_x1.max(text.x_max)
} else {
text.x_max + pad
};
let mut col_bounds = Vec::with_capacity(separators.len() + 2);
col_bounds.push(left_edge.max(region.x0 - cfg.region_slack_pt));
col_bounds.extend(separators.iter().copied());
col_bounds.push(right_edge.min(region.x1 + cfg.region_slack_pt));
col_bounds
}
fn row_bounds(baselines: &[f32], last_baselines: &[f32], size: f32, cfg: &TablesConfig) -> Vec<f32> {
let n_rows = baselines.len();
let mut row_bounds = Vec::with_capacity(n_rows + 1);
row_bounds.push(baselines[0] - cfg.first_row_top_em * size);
for k in 1..n_rows {
row_bounds.push((last_baselines[k - 1] + baselines[k]) * 0.5 - cfg.row_boundary_raise_em * size);
}
row_bounds.push(last_baselines[n_rows - 1] + cfg.last_row_bottom_em * size);
row_bounds
}
fn horizontal_rules(
hrules: &[(Rect, f32)],
col_bounds: &[f32],
baselines: &[f32],
size: f32,
cfg: &TablesConfig,
) -> HorizontalRules {
let n_rows = baselines.len();
let n_cols = col_bounds.len() - 1;
let boundary_of = |y: f32| {
baselines
.iter()
.filter(|&&baseline| baseline - cfg.rule_row_offset_em * size < y)
.count()
};
let mut rules = HorizontalRules {
rule_above: vec![vec![0u8; n_cols]; n_rows],
rule_bottom: vec![0u8; n_cols],
full_rule_at: vec![false; n_rows + 1],
snapped: vec![None; n_rows + 1],
};
for (rule, stroke_width) in hrules {
let y = rule.cy();
let k = boundary_of(y);
let weight = if *stroke_width >= cfg.heavy_rule_min_width_pt {
2
} else {
1
};
let mut covered = 0;
for col in 0..n_cols {
let (col_x0, col_x1) = (col_bounds[col], col_bounds[col + 1]);
if rule.x1.min(col_x1) - rule.x0.max(col_x0) >= cfg.rule_column_cover_ratio * (col_x1 - col_x0) {
covered += 1;
if k < n_rows {
rules.rule_above[k][col] = rules.rule_above[k][col].max(weight);
} else {
rules.rule_bottom[col] = rules.rule_bottom[col].max(weight);
}
}
}
if covered * 10 >= n_cols * cfg.full_rule_min_cols_tenths {
rules.full_rule_at[k] = true;
}
if covered > 0 {
rules.snapped[k] = Some(y);
}
}
rules
}
fn snap_row_bounds(
row_bounds: &mut [f32],
snapped: &[Option<f32>],
baselines: &[f32],
last_baselines: &[f32],
size: f32,
cfg: &TablesConfig,
) {
let n_rows = baselines.len();
for k in 0..=n_rows {
if let Some(y) = snapped[k] {
let lo = if k == 0 {
f32::NEG_INFINITY
} else {
last_baselines[k - 1] + cfg.snap_min_below_em * size
};
let hi = if k == n_rows {
f32::INFINITY
} else {
baselines[k] - cfg.snap_min_above_em * size
};
if y > lo && y < hi {
row_bounds[k] = y;
}
}
}
}
fn vertical_rules(
vrules: &[Rect],
pieces: &[&Line],
col_bounds: &mut [f32],
baselines: &[f32],
size: f32,
cfg: &TablesConfig,
) -> VerticalRules {
let n_rows = baselines.len();
let n_cols = col_bounds.len() - 1;
let mut rules = VerticalRules {
rule_left: vec![vec![false; n_cols]; n_rows],
rule_right: vec![false; n_rows],
};
for vrule in vrules {
let x = vrule.cx();
let (j, dist) = col_bounds
.iter()
.enumerate()
.map(|(j, bound)| (j, (bound - x).abs()))
.min_by(|a, b| a.1.total_cmp(&b.1))
.unwrap();
let gap_ok = j == 0 || j == n_cols || {
let left_text = pieces
.iter()
.filter(|line| line.bbox.x1 <= x + cfg.vrule_text_slack_pt)
.count();
let right_text = pieces
.iter()
.filter(|line| line.bbox.x0 >= x - cfg.vrule_text_slack_pt)
.count();
left_text > 0 && right_text > 0 && dist < cfg.vrule_max_offset_em * size
};
if !gap_ok {
continue;
}
let mut any = false;
for (row, &baseline) in baselines.iter().enumerate() {
if baseline >= vrule.y0 - cfg.vrule_top_slack_em * size
&& baseline - cfg.vrule_bottom_slack_em * size <= vrule.y1
{
any = true;
if j < n_cols {
rules.rule_left[row][j] = true;
} else {
rules.rule_right[row] = true;
}
}
}
if any && j > 0 && j < n_cols {
col_bounds[j] = x;
}
}
rules
}
fn place_floating_labels(
floating: Vec<(f32, GridCell)>,
grid_rows: &mut [Vec<GridCell>],
baselines: &[f32],
rule_above: &[Vec<u8>],
) -> Option<()> {
let n_rows = grid_rows.len();
for (y, mut cell) in floating {
let col = cell.col;
let pos = baselines
.iter()
.filter(|&&baseline| baseline < y)
.count()
.clamp(1, n_rows - 1);
let ruled = |k: usize| k == 0 || k == n_rows || rule_above[k][col] > 0;
let group_start = (0..=pos).rev().find(|&k| ruled(k)).unwrap_or(0);
let group_end = (pos..=n_rows).find(|&k| ruled(k)).unwrap_or(n_rows);
let spanning = |rows: &[Vec<GridCell>], row: usize| {
(0..row).rev().find_map(|start| {
rows[start]
.iter()
.position(|other| {
other.col <= col && col < other.col + other.colspan && start + other.rowspan > row
})
.map(|index| (start, index))
})
};
let free = |row: usize| {
!grid_rows[row]
.iter()
.any(|other| other.col <= col && col < other.col + other.colspan)
&& spanning(grid_rows, row).is_none()
};
if group_end - group_start >= 2 && (group_start..group_end).all(free) {
cell.rowspan = group_end - group_start;
grid_rows[group_start].push(cell);
grid_rows[group_start].sort_by_key(|other| other.col);
} else {
let near = if pos < n_rows && (baselines[pos] - y).abs() < (y - baselines[pos - 1]).abs() {
pos
} else {
pos - 1
};
if let Some((start, index)) = spanning(grid_rows, near) {
grid_rows[start][index].lines.extend(cell.lines);
continue;
}
let target = [near, pos.min(n_rows - 1), pos - 1]
.into_iter()
.find(|&row| free(row))?;
grid_rows[target].push(cell);
grid_rows[target].sort_by_key(|other| other.col);
}
}
Some(())
}
fn is_plausible(grid_rows: &[Vec<GridCell>], n_cols: usize, cfg: &TablesConfig) -> bool {
let counts = CellCounts {
total: grid_rows.iter().map(|row| row.len()).sum(),
spanning: grid_rows.iter().flatten().filter(|cell| cell.colspan > 1).count(),
multi_cell_rows: grid_rows.iter().filter(|row| row.len() >= 2).count(),
rows: grid_rows.len(),
};
has_enough_cells(&counts, cfg)
&& has_enough_multi_cell_rows(&counts, cfg)
&& has_few_spanning_cells(&counts, cfg)
&& every_column_used(grid_rows, n_cols)
&& !has_merged_figures(grid_rows, cfg)
}
fn has_enough_cells(counts: &CellCounts, cfg: &TablesConfig) -> bool {
counts.total >= cfg.min_cells_count
}
fn has_enough_multi_cell_rows(counts: &CellCounts, cfg: &TablesConfig) -> bool {
counts.multi_cell_rows * 10 >= counts.rows * cfg.min_multi_cell_rows_tenths
}
fn has_few_spanning_cells(counts: &CellCounts, cfg: &TablesConfig) -> bool {
counts.spanning * cfg.spanning_cells_divisor <= counts.total
}
fn every_column_used(grid_rows: &[Vec<GridCell>], n_cols: usize) -> bool {
let mut used = vec![0usize; n_cols];
for cell in grid_rows.iter().flatten() {
if cell.colspan == 1 {
used[cell.col] += 1;
}
}
!used.contains(&0)
}
fn has_merged_figures(grid_rows: &[Vec<GridCell>], cfg: &TablesConfig) -> bool {
let merged = grid_rows
.iter()
.flatten()
.filter(|cell| {
cell.lines.len() >= 2
&& cell.lines.windows(2).all(|pair| {
(pair[1].baseline - pair[0].baseline).abs() < cfg.row_break_em * pair[0].size
&& pair.iter().all(|line| ends_like_figure(&line.text()))
})
})
.count();
merged >= cfg.merged_figure_cells_min_count
}
fn ends_like_figure(text: &str) -> bool {
let text = text.trim();
text.chars()
.next()
.is_some_and(|ch| ch.is_ascii_digit() || "+-−±~<>≈".contains(ch))
&& text.chars().last().is_some_and(|ch| ch.is_ascii_digit())
}
fn column_geometry(grid_rows: &[Vec<GridCell>], n_cols: usize, cfg: &TablesConfig) -> (Vec<(f32, f32)>, Vec<Align>) {
let mut col_text = vec![(f32::INFINITY, f32::NEG_INFINITY); n_cols];
let mut samples: Vec<Vec<(f32, f32)>> = vec![Vec::new(); n_cols];
for cell in grid_rows.iter().flatten().filter(|cell| cell.colspan == 1) {
let x0 = cell.lines.iter().map(|line| line.bbox.x0).fold(f32::INFINITY, f32::min);
let x1 = cell
.lines
.iter()
.map(|line| line.bbox.x1)
.fold(f32::NEG_INFINITY, f32::max);
col_text[cell.col].0 = col_text[cell.col].0.min(x0);
col_text[cell.col].1 = col_text[cell.col].1.max(x1);
samples[cell.col].push((x0, x1));
}
let col_align: Vec<Align> = samples
.iter()
.enumerate()
.map(|(col, extents)| column_align(col, extents, cfg))
.collect();
(col_text, col_align)
}
fn column_align(col: usize, extents: &[(f32, f32)], cfg: &TablesConfig) -> Align {
if extents.len() < 2 {
return if col == 0 { Align::Left } else { Align::Center };
}
let left = spread(extents.iter().map(|extent| extent.0).collect());
let right = spread(extents.iter().map(|extent| extent.1).collect());
let centre = spread(extents.iter().map(|extent| (extent.0 + extent.1) * 0.5).collect());
if left <= centre + cfg.align_tolerance_pt && left <= right {
Align::Left
} else if right < centre - cfg.align_tolerance_pt {
Align::Right
} else {
Align::Center
}
}
fn spread(values: Vec<f32>) -> f32 {
let lo = values.iter().copied().fold(f32::INFINITY, f32::min);
let hi = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
hi - lo
}