use super::{ColumnGeometry, WrapRows};
use crate::graphics::{Border, BoxPaint, Clip, DisplayItem, Rect};
use crate::layout::TextLine;
use crate::layout::pagination::{FRAGMENTATION_TOLERANCE_PT, overflows};
use crate::style::ColumnFill;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Run<'b> {
pub top: f32,
pub bottom: f32,
pub breaks: &'b [f32],
pub cloned: [f32; 2],
pub repeated: [f32; 2],
}
impl Run<'_> {
pub(in crate::layout) fn whole(height: f32) -> Self {
Self {
top: 0.0,
bottom: height,
breaks: &[],
cloned: [0.0; 2],
repeated: [0.0; 2],
}
}
fn height(&self) -> f32 {
self.bottom - self.top + self.repeated[0] + self.repeated[1]
}
}
pub(in crate::layout) fn line_breaks(
line_boxes: &[[f32; 2]],
monolithic: impl IntoIterator<Item = [f32; 2]>,
[orphans, widows]: [usize; 2],
end: f32,
) -> Vec<f32> {
let mut bottoms: Vec<f32> = line_boxes.iter().map(|[_, bottom]| *bottom).collect();
bottoms.sort_by(f32::total_cmp);
let mut extents: Vec<[f32; 2]> = line_boxes.iter().copied().chain(monolithic).collect();
extents.sort_by(|a, b| a[0].total_cmp(&b[0]));
let mut spans: Vec<[f32; 2]> = Vec::with_capacity(extents.len());
for [top, bottom] in extents {
match spans.last_mut() {
Some(span) if top < span[1] => span[1] = span[1].max(bottom),
_ => spans.push([top, bottom]),
}
}
let cuts = |offset: f32| {
let after = spans.partition_point(|span| span[0] < offset);
after > 0 && offset < spans[after - 1][1]
};
let total = bottoms.len();
let mut breaks: Vec<f32> = bottoms
.iter()
.copied()
.filter(|&offset| {
let before = bottoms.partition_point(|&bottom| bottom <= offset);
before >= orphans && total - before >= widows && !cuts(offset)
})
.chain([end])
.collect();
breaks.sort_by(f32::total_cmp);
breaks.dedup();
breaks
}
pub(in crate::layout) fn slice_clip(window: Rect) -> DisplayItem {
DisplayItem::PushClip(Clip {
rect: window,
radii: crate::graphics::Radii::default(),
outline: None,
axes: [false, true],
reference_box: None,
})
}
pub(in crate::layout) fn windowed(
items: &[DisplayItem],
lines: &[TextLine],
[top, bottom]: [f32; 2],
) -> (Vec<DisplayItem>, Vec<TextLine>) {
if items
.iter()
.any(|item| matches!(item, DisplayItem::Scene(_)))
{
return (items.to_vec(), lines.to_vec());
}
let mut kept = vec![None; lines.len()];
let mut kept_lines = Vec::new();
let mut output = Vec::with_capacity(items.len());
let mut open = Vec::new();
for item in items {
match item {
DisplayItem::Pop => {
open.pop();
}
DisplayItem::PushTransform(_) | DisplayItem::PushProjection(_) => open.push(true),
item if item.is_push() => open.push(false),
DisplayItem::Text { line } => {
let source = &lines[*line];
if !open.contains(&true)
&& (source.baseline + source.height <= top
|| source.baseline - source.height >= bottom)
{
continue;
}
let index = *kept[*line].get_or_insert_with(|| {
kept_lines.push(source.clone());
kept_lines.len() - 1
});
output.push(DisplayItem::Text { line: index });
continue;
}
_ => {}
}
output.push(item.clone());
}
(output, kept_lines)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(in crate::layout) struct Slice {
pub run: usize,
pub top: f32,
pub bottom: f32,
pub repeated: [f32; 2],
pub y: f32,
}
impl Slice {
pub(in crate::layout) fn height(&self) -> f32 {
self.bottom - self.top + self.repeated[0] + self.repeated[1]
}
}
#[derive(Clone, Debug, Default)]
pub(in crate::layout) struct ColumnBox {
pub row: usize,
pub index: usize,
pub slices: Vec<Slice>,
pub extent: f32,
}
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct Plan {
pub count: usize,
pub height: Option<f32>,
pub definite: bool,
pub fill: ColumnFill,
pub wrap: Option<WrapRows>,
}
#[derive(Clone, Debug)]
pub(in crate::layout) struct Distribution {
pub columns: Vec<ColumnBox>,
pub rows: Vec<f32>,
pub row_gap: f32,
pub overflows: bool,
}
impl Distribution {
pub(in crate::layout) fn of(runs: &[Run<'_>], plan: Plan) -> Self {
let mut distribution = Self {
columns: Vec::new(),
rows: Vec::new(),
row_gap: plan.wrap.map_or(0.0, |wrap| wrap.gap),
overflows: false,
};
let Some(start) = Cursor::start(runs) else {
return distribution;
};
let balanced = plan.fill != ColumnFill::Auto;
if let Some(wrap) = plan.wrap {
let mut next = Some(start);
while let Some(cursor) = next {
let row = fill(runs, cursor, wrap.height, Some(plan.count));
next = row.end;
let row = if next.is_none() && balanced {
balance(runs, cursor, plan.count, Some(wrap.height))
} else {
row
};
distribution.push_row(row, wrap.height);
}
return distribution;
}
let Some(height) = plan.height else {
let row = balance(runs, start, plan.count, None);
let extent = row.extent();
distribution.push_row(row, extent);
return distribution;
};
let sequential = fill(runs, start, height, None);
let fits = sequential.columns.len() <= plan.count && !sequential.forced;
let row = if fits && balanced {
balance(runs, start, plan.count, Some(height))
} else {
sequential
};
let extent = if plan.definite { height } else { row.extent() };
distribution.push_row(row, extent);
distribution.overflows |= !fits;
distribution
}
fn push_row(&mut self, filled: Filled, height: f32) {
let row = self.rows.len();
self.overflows |= filled.forced;
self.columns.extend(
filled
.columns
.into_iter()
.map(|column| ColumnBox { row, ..column }),
);
self.rows.push(height);
}
pub(in crate::layout) fn height(&self) -> f32 {
self.rows.iter().sum::<f32>() + self.row_gap * self.rows.len().saturating_sub(1) as f32
}
pub(in crate::layout) fn row_offset(&self, row: usize) -> f32 {
self.rows[..row].iter().sum::<f32>() + self.row_gap * row as f32
}
pub(in crate::layout) fn placed(
&self,
geometry: ColumnGeometry,
) -> impl Iterator<Item = (Slice, [f32; 2])> + '_ {
self.columns.iter().flat_map(move |column| {
let [x, y] = [geometry.left(column.index), self.row_offset(column.row)];
column
.slices
.iter()
.map(move |slice| (*slice, [x, y + slice.y]))
})
}
pub(in crate::layout) fn held(&self, count: usize, extent: f32) -> f32 {
self.columns
.iter()
.filter(|column| {
column.index < count
&& !overflows(self.row_offset(column.row) + self.rows[column.row], extent)
})
.filter_map(|column| column.slices.last())
.map(|slice| slice.bottom)
.fold(0.0, f32::max)
}
pub(in crate::layout) fn rules(
&self,
geometry: &ColumnGeometry,
rule: Border,
origin: [f32; 2],
) -> Vec<BoxPaint> {
if rule.used_width() <= 0.0 {
return Vec::new();
}
self.columns
.windows(2)
.filter(|pair| {
pair[0].row == pair[1].row && pair.iter().all(|column| !column.slices.is_empty())
})
.map(|pair| {
let row = pair[0].row;
super::rule_paint(
rule,
origin[0] + geometry.rule_x(pair[0].index),
origin[1] + self.row_offset(row),
self.rows[row],
)
})
.collect()
}
}
#[derive(Clone, Copy, Debug)]
struct Cursor {
run: usize,
top: f32,
repeated: f32,
}
impl Cursor {
fn start(runs: &[Run<'_>]) -> Option<Self> {
runs.first().map(|run| Self {
run: 0,
top: run.top,
repeated: run.repeated[0],
})
}
}
struct Filled {
columns: Vec<ColumnBox>,
end: Option<Cursor>,
forced: bool,
}
impl Filled {
fn extent(&self) -> f32 {
self.columns
.iter()
.map(|column| column.extent)
.fold(0.0, f32::max)
}
}
fn fill(runs: &[Run<'_>], mut cursor: Cursor, height: f32, limit: Option<usize>) -> Filled {
let mut columns = vec![ColumnBox::default()];
let mut forced = false;
loop {
let run = &runs[cursor.run];
let column = columns.last_mut().expect("a column is open");
let room = height - column.extent;
let whole = run.bottom - cursor.top + cursor.repeated + run.repeated[1];
let first = run.breaks.partition_point(|&offset| offset <= cursor.top);
let candidates = &run.breaks[first
..run
.breaks
.partition_point(|&offset| offset < run.bottom)
.max(first)];
let slice = if overflows(whole, room) {
let fitting = candidates.partition_point(|&offset| {
!overflows(offset - cursor.top + cursor.repeated + run.cloned[1], room)
});
if fitting > 0 {
Some((candidates[fitting - 1], run.cloned[1]))
} else if column.slices.is_empty() {
forced = true;
Some(
candidates
.first()
.map_or((run.bottom, run.repeated[1]), |&offset| {
(offset, run.cloned[1])
}),
)
} else {
None
}
} else {
Some((run.bottom, run.repeated[1]))
};
if let Some((bottom, end)) = slice {
let slice = Slice {
run: cursor.run,
top: cursor.top,
bottom,
repeated: [cursor.repeated, end],
y: column.extent,
};
column.extent += slice.height();
column.slices.push(slice);
if bottom >= run.bottom {
let Some(next) = runs.get(cursor.run + 1) else {
return Filled {
columns,
end: None,
forced,
};
};
cursor = Cursor {
run: cursor.run + 1,
top: next.top,
repeated: next.repeated[0],
};
continue;
}
cursor.top = bottom;
cursor.repeated = run.cloned[0];
}
if limit.is_some_and(|limit| columns.len() >= limit) {
return Filled {
columns,
end: Some(cursor),
forced,
};
}
columns.push(ColumnBox {
index: columns.len(),
..ColumnBox::default()
});
}
}
fn balance(runs: &[Run<'_>], cursor: Cursor, count: usize, cap: Option<f32>) -> Filled {
let current = &runs[cursor.run];
let total = current.bottom - cursor.top
+ cursor.repeated
+ current.repeated[1]
+ runs[cursor.run + 1..].iter().map(Run::height).sum::<f32>();
let mut high = cap.map_or(total, |cap| cap.min(total));
let holds = |height: f32| {
let filled = fill(runs, cursor, height, Some(count));
(filled.end.is_none() && !filled.forced).then_some(filled)
};
let Some(mut best) = holds(high) else {
return fill(runs, cursor, high, Some(count));
};
if count == 1 {
return best;
}
let mut low = 0.0;
while high - low > FRAGMENTATION_TOLERANCE_PT {
let middle = low + (high - low) / 2.0;
if middle == low || middle == high {
break;
}
match holds(middle) {
Some(filled) => {
high = middle;
best = filled;
}
None => low = middle,
}
}
best
}