use super::floats::Float;
use super::page::DocStats;
use crate::common::geom::Rect;
use crate::model::Line;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OrderConfig {
pub min_gutter_em: f32,
pub line_band_ascent_em: f32,
pub line_band_descent_em: f32,
pub float_band_inset_pt: f32,
pub float_band_min_height_pt: f32,
pub float_gutter_inset_pt: f32,
pub same_row_distance_pt: f32,
pub float_weight_rows_count: usize,
pub min_items_to_split_count: usize,
pub min_column_width_ratio: f32,
pub min_column_rows_count: usize,
pub row_overlap_ratio: f32,
pub column_fit_tolerance_pt: f32,
pub max_split_depth_count: u32,
}
impl Default for OrderConfig {
fn default() -> Self {
Self {
min_gutter_em: 0.7,
line_band_ascent_em: 0.6,
line_band_descent_em: 0.1,
float_band_inset_pt: 1.0,
float_band_min_height_pt: 1.5,
float_gutter_inset_pt: 4.0,
same_row_distance_pt: 3.0,
float_weight_rows_count: 3,
min_items_to_split_count: 6,
min_column_width_ratio: 0.15,
min_column_rows_count: 3,
row_overlap_ratio: 0.5,
column_fit_tolerance_pt: 3.0,
max_split_depth_count: 8,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ItemRef {
Line(usize),
Float(usize),
}
#[derive(Debug, Clone)]
pub struct Leaf {
pub zone: usize,
pub zone_cols: usize,
pub col: usize,
pub rows: Vec<Vec<ItemRef>>,
pub bbox: Rect,
}
#[derive(Debug, Clone, Copy)]
struct OrderItem {
item: ItemRef,
bbox: Rect,
y0: f32,
y1: f32,
x_inset: f32,
}
enum Part {
Leaf(Vec<OrderItem>),
Split(Vec<Vec<OrderItem>>),
}
struct Splitter<'cfg> {
cfg: &'cfg OrderConfig,
min_gutter: f32,
}
impl Splitter<'_> {
fn columns(&self, items: Vec<OrderItem>) -> Vec<Vec<OrderItem>> {
if items.len() < self.cfg.min_items_to_split_count {
return vec![items];
}
let whole = extent(&items);
let mut candidates = gutters(&items, self.min_gutter);
candidates.sort_by(|a, b| (b.1 - b.0).total_cmp(&(a.1 - a.0)));
for (gap_start, gap_end) in candidates {
let mid = (gap_start + gap_end) * 0.5;
let (left, right): (Vec<OrderItem>, Vec<OrderItem>) = items.iter().partition(|item| item.bbox.cx() < mid);
let (left_extent, right_extent) = (extent(&left), extent(&right));
let wide_enough = left_extent.width() >= self.cfg.min_column_width_ratio * whole.width()
&& right_extent.width() >= self.cfg.min_column_width_ratio * whole.width();
if weight(&left, self.cfg) >= self.cfg.min_column_rows_count
&& weight(&right, self.cfg) >= self.cfg.min_column_rows_count
&& wide_enough
{
let mut out = self.columns(left);
out.extend(self.columns(right));
return out;
}
}
vec![items]
}
fn zones(&self, items: Vec<OrderItem>) -> Vec<Vec<OrderItem>> {
let mut zones: Vec<Vec<OrderItem>> = Vec::new();
let mut cur_has_gutter = false;
for band in bands(items) {
let band_gutter = !gutters(&band, self.min_gutter).is_empty();
match zones.last_mut() {
None => {
cur_has_gutter = band_gutter;
zones.push(band);
}
Some(zone) => {
if cur_has_gutter {
let mut merged = zone.clone();
merged.extend(band.iter().copied());
if !gutters(&merged, self.min_gutter).is_empty() {
*zone = merged;
} else {
cur_has_gutter = band_gutter;
zones.push(band);
}
} else if band_gutter {
cur_has_gutter = true;
zones.push(band);
} else {
zone.extend(band);
}
}
}
}
zones
}
fn partition(&self, items: Vec<OrderItem>) -> Vec<Part> {
let mut zones = self.zones(items);
self.attach_zones_above_columns(&mut zones);
let mut parts: Vec<Part> = Vec::new();
for zone in zones {
let cols = self.columns(zone);
if cols.len() == 1 {
let items = cols.into_iter().next().unwrap();
if let Some(Part::Leaf(prev)) = parts.last_mut() {
prev.extend(items);
} else {
parts.push(Part::Leaf(items));
}
} else {
parts.push(Part::Split(cols));
}
}
parts
}
fn attach_zones_above_columns(&self, zones: &mut Vec<Vec<OrderItem>>) {
let mut i = zones.len();
while i >= 2 {
i -= 1;
let cols = self.columns(zones[i].clone());
if cols.len() < 2 {
continue;
}
let prev_cols = self.columns(zones[i - 1].clone());
if prev_cols.len() >= 2 {
continue;
}
let bounds: Vec<Rect> = cols.iter().map(|column| extent(column)).collect();
let tolerance = self.cfg.column_fit_tolerance_pt;
let fits = zones[i - 1].iter().all(|item| {
bounds
.iter()
.any(|bound| item.bbox.x0 >= bound.x0 - tolerance && item.bbox.x1 <= bound.x1 + tolerance)
});
if fits {
let prev = zones.remove(i - 1);
zones[i - 1].splice(0..0, prev);
}
}
}
fn flatten(&self, items: Vec<OrderItem>, depth: u32, out: &mut Vec<Vec<OrderItem>>) {
if depth > self.cfg.max_split_depth_count {
out.push(items);
return;
}
for part in self.partition(items) {
match part {
Part::Leaf(items) => out.push(items),
Part::Split(cols) => {
for column in cols {
self.flatten(column, depth + 1, out);
}
}
}
}
}
}
pub fn order_page(lines: &[Line], floats: &[Float], stats: &DocStats, cfg: &OrderConfig) -> Vec<Leaf> {
let items = collect_items(lines, floats, cfg);
let splitter = Splitter {
cfg,
min_gutter: cfg.min_gutter_em * stats.body_size,
};
let mut leaves = Vec::new();
for (zone, part) in splitter.partition(items).into_iter().enumerate() {
match part {
Part::Leaf(items) => {
let bbox = extent(&items);
leaves.push(Leaf {
zone,
zone_cols: 1,
col: 0,
rows: rows(items, cfg),
bbox,
});
}
Part::Split(cols) => {
let n = cols.len();
for (col, column) in cols.into_iter().enumerate() {
let mut sub = Vec::new();
splitter.flatten(column, 1, &mut sub);
for items in sub {
let bbox = extent(&items);
leaves.push(Leaf {
zone,
zone_cols: n,
col,
rows: rows(items, cfg),
bbox,
});
}
}
}
}
}
leaves
}
fn collect_items(lines: &[Line], floats: &[Float], cfg: &OrderConfig) -> Vec<OrderItem> {
let mut items: Vec<OrderItem> = Vec::with_capacity(lines.len() + floats.len());
for (i, line) in lines.iter().enumerate() {
items.push(OrderItem {
item: ItemRef::Line(i),
bbox: line.bbox,
y0: line.baseline - cfg.line_band_ascent_em * line.size,
y1: line.baseline + cfg.line_band_descent_em * line.size,
x_inset: 0.0,
});
}
for (i, float) in floats.iter().enumerate() {
items.push(OrderItem {
item: ItemRef::Float(i),
bbox: float.bbox,
y0: float.bbox.y0 + cfg.float_band_inset_pt,
y1: (float.bbox.y1 - cfg.float_band_inset_pt).max(float.bbox.y0 + cfg.float_band_min_height_pt),
x_inset: cfg.float_gutter_inset_pt.min(float.bbox.width() * 0.5),
});
}
items
}
fn x_intervals(items: &[OrderItem]) -> Vec<(f32, f32)> {
let mut intervals: Vec<(f32, f32)> = items
.iter()
.map(|item| (item.bbox.x0 + item.x_inset, item.bbox.x1 - item.x_inset))
.collect();
intervals.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut out: Vec<(f32, f32)> = Vec::new();
for (start, end) in intervals {
match out.last_mut() {
Some(last) if start <= last.1 => last.1 = last.1.max(end),
_ => out.push((start, end)),
}
}
out
}
fn gutters(items: &[OrderItem], min_gutter: f32) -> Vec<(f32, f32)> {
let intervals = x_intervals(items);
intervals
.windows(2)
.filter(|pair| pair[1].0 - pair[0].1 >= min_gutter)
.map(|pair| (pair[0].1, pair[1].0))
.collect()
}
fn weight(items: &[OrderItem], cfg: &OrderConfig) -> usize {
let mut ys: Vec<f32> = Vec::new();
let mut floats = 0;
for item in items {
match item.item {
ItemRef::Line(_) => ys.push(item.bbox.cy()),
ItemRef::Float(_) => floats += 1,
}
}
ys.sort_by(|a, b| a.total_cmp(b));
let mut rows = 0;
let mut last = f32::NEG_INFINITY;
for y in ys {
if y - last > cfg.same_row_distance_pt {
rows += 1;
}
last = y;
}
rows + cfg.float_weight_rows_count * floats
}
fn extent(items: &[OrderItem]) -> Rect {
items.iter().fold(Rect::EMPTY, |acc, item| acc.union(&item.bbox))
}
fn bands(mut items: Vec<OrderItem>) -> Vec<Vec<OrderItem>> {
items.sort_by(|a, b| a.y0.total_cmp(&b.y0));
let mut out: Vec<Vec<OrderItem>> = Vec::new();
let mut cur_y1 = f32::NEG_INFINITY;
for item in items {
if out.is_empty() || item.y0 >= cur_y1 {
out.push(vec![item]);
cur_y1 = item.y1;
} else {
cur_y1 = cur_y1.max(item.y1);
out.last_mut().unwrap().push(item);
}
}
out
}
fn rows(mut items: Vec<OrderItem>, cfg: &OrderConfig) -> Vec<Vec<ItemRef>> {
items.sort_by(|a, b| a.bbox.cy().total_cmp(&b.bbox.cy()));
let mut out: Vec<(Rect, Vec<OrderItem>, bool)> = Vec::new();
for item in items {
let item_is_float = matches!(item.item, ItemRef::Float(_));
let joined = match out.last_mut() {
Some((row_box, row, row_has_float)) => {
let overlap = row_box.y_overlap(&item.bbox);
let is_float = item_is_float || *row_has_float;
if !is_float && overlap >= cfg.row_overlap_ratio * row_box.height().min(item.bbox.height()) {
*row_box = row_box.union(&item.bbox);
row.push(item);
true
} else {
false
}
}
None => false,
};
if !joined {
out.push((item.bbox, vec![item], item_is_float));
}
}
out.sort_by(|a, b| a.0.y0.total_cmp(&b.0.y0));
out.into_iter()
.map(|(_, mut row, _)| {
row.sort_by(|a, b| a.bbox.x0.total_cmp(&b.bbox.x0));
row.into_iter().map(|member| member.item).collect()
})
.collect()
}