use f_office_paint::{Item, Rect, Rgb};
use f_office_units::Length;
use crate::body::{Block, Section};
use crate::params::{COLUMN_SEPARATOR_WIDTH, MAX_BALANCE_TRIALS};
use crate::quirks::Quirks;
use crate::warnings::Limit;
use super::{Layout, decisions};
#[derive(Clone, Copy, Debug)]
pub(super) struct Balance {
pub(super) limit: Length,
pub(super) overflowed: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct BlockStart {
pub(super) chunk: usize,
pub(super) paragraph: usize,
}
#[derive(Default)]
pub(super) struct PageMarks {
depth: usize,
chunk: usize,
first: Option<(usize, BlockStart, Mark)>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum SectionTop {
#[default]
Placed,
Pending,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Trials {
Fit,
NoFit,
Limit,
}
pub(super) struct Mark {
row: RowMark,
behind: usize,
front: usize,
bands: usize,
squares: usize,
frame_boxes: usize,
page_notes: super::notes::PageNotes,
previous: Option<super::Previous>,
y: Length,
y_rest: i64,
y_twips: Option<super::TwipsRest>,
started: bool,
after_break: bool,
alone_break: Option<super::Previous>,
column: super::Column,
column_index: usize,
column_top: Length,
column_ends: Vec<Length>,
output: OutputMark,
}
pub(super) struct RowMark {
pub(super) items: usize,
pub(super) lines: usize,
clips: usize,
region_fills: usize,
numbering: crate::numbering::Numbering,
tables: usize,
pictures: usize,
drawings: usize,
styled: Option<super::style_refs::RecordMark>,
chapter_number: Option<i64>,
section_previous: Option<super::Previous>,
table_chain: super::TableChain,
markup_mark: super::markup::MarkupMark,
found: (usize, usize),
found_later: usize,
bookmarks: usize,
bookmark_numbers: usize,
}
struct OutputMark {
pages: usize,
endnotes: usize,
note_numbers: super::notes::NoteNumbers,
warnings: crate::Warnings,
story_warnings: Vec<(super::output::StoryKey, crate::Warnings)>,
}
impl OutputMark {
fn of(output: &super::output::PassOutput) -> Self {
let super::output::PassOutput {
pages,
endnotes,
notes,
warnings,
story_warnings,
placed: _,
pictures: _,
drawings: _,
tables: _,
styled: _,
chapter_number: _,
found: _,
found_later: _,
found_bookmarks: _,
found_numbers: _,
page_infos: _,
body_areas: _,
margin_notes: _,
blank_pages: _,
style_pages: _,
line_count: _,
table_columns: _,
story_parts: _,
} = output;
Self {
pages: pages.len(),
endnotes: endnotes.len(),
note_numbers: notes.clone(),
warnings: warnings.clone(),
story_warnings: story_warnings.clone(),
}
}
}
impl Layout<'_> {
pub(super) fn set_columns(&mut self) {
self.columns = areas(&self.section, &self.context.quirks);
self.column_index = 0;
self.column_top = self.y;
self.column_ends.clear();
if let Some(&(left, width)) = self.columns.first() {
self.column.left = left;
self.column.origin = left;
self.column.width = width;
}
}
pub(super) fn paint_column_separators(&mut self) {
if !self.section.columns.separator || self.columns.len() < 2 || self.story.is_some() {
return;
}
let lines = decisions::column_separators(&self.context.quirks, || self.separator_lines());
self.items.extend(lines.into_iter().flatten());
}
fn separator_lines(&self) -> Vec<Item> {
let page = self.output.pages.len();
let mut bottoms: Vec<Option<Length>> = vec![None; self.columns.len()];
let lines = self.output.placed.iter().rev();
for line in lines.take_while(|line| line.page == page) {
let counts = line.story == super::LineStory::Body
&& line.area == super::LineArea::OutsideTables
&& line.top >= self.column_top
&& !(Some(line.paragraph) == self.section_end_paragraph && line.drawn.is_empty());
let column = self
.columns
.iter()
.position(|&(left, _)| left == line.column_left);
if let Some(bottom) = column
.filter(|_| counts)
.and_then(|index| bottoms.get_mut(index))
{
let end = line.top + line.height;
*bottom = Some(bottom.map_or(end, |b| b.max(end)));
}
}
let Some(lowest) = bottoms.iter().flatten().copied().reduce(Length::max) else {
return Vec::new();
};
let device = &self.device;
let width = device.snap(COLUMN_SEPARATOR_WIDTH);
let (top, bottom) = (device.snap(self.column_top), device.snap(lowest));
self.columns
.iter()
.zip(&bottoms)
.zip(self.columns.iter().zip(&bottoms).skip(1))
.filter(|((_, a), (_, b))| a.is_some() && b.is_some())
.map(|((&first, _), (&second, _))| {
let (left, right) = if first.0 <= second.0 {
(first, second)
} else {
(second, first)
};
let middle = (left.0 + left.1 + right.0).div_toward_zero(2);
Item::Rect(Rect {
x: device.snap(middle - width.div_toward_zero(2)),
y: top,
width,
height: bottom - top,
color: Rgb::BLACK,
})
})
.collect()
}
pub(super) fn first_column(&mut self) {
self.column_index = 0;
self.column_top = self.y;
self.column_ends.clear();
if let Some(&(left, width)) = self.columns.first().filter(|_| self.column.cell.is_none()) {
self.column.left = left;
self.column.origin = left;
self.column.width = width;
}
}
pub(super) fn next_column(&mut self) {
self.end_column();
if let Some(&(left, width)) = self.columns.get(self.column_index + 1) {
self.place_column_notes();
self.column_index += 1;
self.column.left = left;
self.column.origin = left;
self.column.width = width;
self.move_to(self.column_top);
} else if let Some(balance) = self.balance.as_mut() {
balance.overflowed = true;
self.move_to(self.column_top);
} else {
self.new_page();
}
}
pub(super) fn next_area_top(&self) -> Length {
if self.column_index + 1 < self.columns.len() {
self.column_top
} else {
self.page_top(self.output.pages.len() + 1)
}
}
fn end_column(&mut self) {
if self.column_ends.len() <= self.column_index {
self.column_ends
.resize(self.column_index + 1, self.column_top);
}
if let Some(end) = self.column_ends.get_mut(self.column_index) {
*end = (*end).max(self.y);
}
}
pub(super) fn balanced_blocks(&mut self, blocks: &[Block]) {
let section_mark = self.mark();
let count = i64::try_from(self.columns.len()).unwrap_or(1);
if count >= 2 {
self.page_marks =
decisions::balanced_last_page(&self.context.quirks, PageMarks::default());
}
self.plain_blocks(blocks, BlockStart::default());
let marks = self.page_marks.take();
if count < 2 {
return;
}
let page = self.output.pages.len();
let (mark, start) = if page == section_mark.output.pages {
(section_mark, BlockStart::default())
} else {
match marks
.and_then(|marks| marks.first)
.filter(|(on, ..)| *on == page)
{
Some((_, start, mark)) => (mark, start),
None => return,
}
};
self.end_column();
let top = self.column_top;
let bottom = self.page_bottom();
let after = self
.hidden_end(blocks)
.map_or(Length::ZERO, |(after, _)| after);
let step = self.limit_step(&mark, after);
let limit = top + self.mean_height(top);
let trials = self.balance(&mark, (blocks, start), (limit, step, bottom));
if trials != Trials::Fit {
self.rewind(&mark);
self.plain_blocks(blocks, start);
}
if trials == Trials::Limit {
self.output.warnings.push(crate::Warning::LimitReached {
part: (*self.body_part).clone(),
limit: Limit::BalanceTrials,
});
}
if let Some((_, props)) = self.hidden_end(blocks) {
self.section_previous = Some(super::Previous::of(&props));
}
self.end_column();
let end = self.column_ends.iter().copied().fold(self.y, Length::max);
if end > self.y {
self.move_to(end);
}
}
fn balance(
&mut self,
mark: &Mark,
blocks: (&[Block], BlockStart),
(mut limit, step, bottom): (Length, Length, Length),
) -> Trials {
for _ in 0..MAX_BALANCE_TRIALS {
if self.limited_blocks(mark, blocks, limit) {
return Trials::Fit;
}
if step <= Length::ZERO || limit >= bottom {
return Trials::NoFit;
}
limit += step;
}
Trials::Limit
}
pub(super) fn hidden_end(
&mut self,
blocks: &[Block],
) -> Option<(Length, crate::props::ParaProps)> {
let Some(Block::Paragraph(paragraph)) = blocks.last() else {
return None;
};
let numbering = self.numbering.clone();
let resolved = self.resolve(paragraph);
self.numbering = numbering;
if !self.shows_nothing(paragraph, &resolved) {
return None;
}
let after = super::paragraph::gap_parts(self.previous.as_ref(), &resolved.props).after;
Some((after, resolved.props))
}
fn mean_height(&self, top: Length) -> Length {
let filled = self.columns.iter().zip(&self.column_ends);
let area: i128 = filled
.map(|(&(_, width), &end)| i128::from((end - top).units()) * i128::from(width.units()))
.sum();
let widths: i128 = self
.columns
.iter()
.map(|&(_, width)| i128::from(width.units()))
.sum();
Length::from_units(f_office_units::saturated(area / widths.max(1)))
}
fn limit_step(&self, mark: &Mark, after: Length) -> Length {
let lines = self.output.placed.get(mark.row.lines..).unwrap_or_default();
let upright = lines.iter().filter(|line| line.upright());
let heights = upright.flat_map(|line| [line.height, line.before]);
let heights = heights.chain([after]);
let smallest = heights
.filter(|&height| height > Length::ZERO)
.min()
.unwrap_or(Length::ZERO);
smallest.up_to_whole(Length::UNITS_PER_POINT)
}
fn plain_blocks(&mut self, blocks: &[Block], start: BlockStart) {
if start == BlockStart::default() {
self.section_top = SectionTop::Pending;
}
self.blocks_from(blocks, start);
self.section_top = SectionTop::Placed;
if let Some((after, _)) = self.hidden_end(blocks) {
self.y += after;
if let Some(balance) = self.balance.as_mut()
&& self.y > balance.limit
{
balance.overflowed = true;
}
}
}
pub(super) fn leave_column(&mut self, before: Length) -> Length {
if self.columns.len() > 1 {
self.y -= before;
}
let page = self.output.pages.len();
self.next_column();
if self.new_page_space == super::NewPageSpace::Goes {
let new_page = self.output.pages.len() != page;
let at_page_top = self.column_top <= self.page_top(page);
if new_page || decisions::column_top_space_goes(&self.context.quirks, at_page_top) {
return Length::ZERO;
}
}
self.y += before;
before
}
fn limited_blocks(
&mut self,
mark: &Mark,
(blocks, start): (&[Block], BlockStart),
limit: Length,
) -> bool {
self.rewind(mark);
self.balance = Some(Balance {
limit,
overflowed: false,
});
self.plain_blocks(blocks, start);
let overflowed = self.balance.take().is_some_and(|b| b.overflowed);
!overflowed && self.output.pages.len() == mark.output.pages
}
pub(super) fn enter_blocks(&mut self) {
if let Some(marks) = self.page_marks.as_mut() {
marks.depth += 1;
}
}
pub(super) fn leave_blocks(&mut self) {
if let Some(marks) = self.page_marks.as_mut() {
marks.depth = marks.depth.saturating_sub(1);
}
}
pub(super) fn note_chunk(&mut self, chunk: usize) {
if let Some(marks) = self.page_marks.as_mut().filter(|marks| marks.depth == 1) {
marks.chunk = chunk;
}
}
pub(super) fn keeps_page_marks(&self) -> bool {
self.page_marks
.as_ref()
.is_some_and(|marks| marks.depth == 1)
}
pub(super) fn note_paragraph_start(
&mut self,
paragraph: usize,
run_start: Option<&(crate::numbering::Numbering, super::TableChain)>,
) {
let page = self.output.pages.len();
let Some(run_start) = run_start else {
return;
};
let Some(chunk) = self
.page_marks
.as_ref()
.filter(|marks| marks.depth == 1)
.filter(|marks| marks.first.as_ref().is_none_or(|(on, ..)| *on != page))
.map(|marks| marks.chunk)
else {
return;
};
let mut mark = self.mark();
mark.row.numbering = run_start.0.clone();
mark.row.table_chain = run_start.1;
if let Some(marks) = self.page_marks.as_mut() {
marks.first = Some((page, BlockStart { chunk, paragraph }, mark));
}
}
#[expect(
clippy::too_many_lines,
reason = "one line for each field of the layout, which the mark sorts by name"
)]
pub(super) fn mark(&self) -> Mark {
let Self {
behind,
front,
bands,
squares,
frame_boxes,
page_notes,
previous,
y,
y_rest,
y_twips,
started,
after_break,
alone_break,
column,
column_index,
column_top,
column_ends,
output,
items: _,
table_twips: _,
numbering: _,
section_previous: _,
table_chain: _,
comment_markup: _,
context: _,
body_part: _,
stories: _,
styles: _,
settings: _,
story: _,
page: _,
story_notes: _,
style_page: _,
sections: _,
device: _,
section: _,
tops: _,
bottoms: _,
story_page: _,
columns: _,
section_end_paragraph: _,
page_from_break: _,
section_index: _,
section_first_page: _,
section_title_page: _,
number_start: _,
pending: _,
number_context: _,
hyphen_runs: _,
table_number: _,
cell_place: _,
cell_top: _,
cell_sides: _,
cell_carried: _,
balance: _,
endnote: _,
fragment: _,
cell_floor: _,
frame_places: _,
grid_pitch: _,
following_after: _,
kept_tail: _,
centered_middle: _,
line_band: _,
east_asian_axis: _,
aligned_parts: _,
glyph_places: _,
own_space_before: _,
first_space_before: _,
held_borders: _,
new_page_space: _,
text_part: _,
same_baseline: _,
line_floor: _,
last_bar: _,
drawings_under_fill: _,
section_top: _,
page_marks: _,
shaper: _,
break_numbers: _,
} = self;
Mark {
row: self.row_mark(),
behind: behind.len(),
front: front.len(),
bands: bands.len(),
squares: squares.len(),
frame_boxes: frame_boxes.len(),
page_notes: page_notes.clone(),
previous: previous.clone(),
y: *y,
y_rest: *y_rest,
y_twips: *y_twips,
started: *started,
after_break: *after_break,
alone_break: alone_break.clone(),
column: column.clone(),
column_index: *column_index,
column_top: *column_top,
column_ends: column_ends.clone(),
output: OutputMark::of(output),
}
}
pub(super) fn rewind(&mut self, mark: &Mark) {
let Mark {
row,
behind,
front,
bands,
squares,
frame_boxes,
page_notes,
previous,
y,
y_rest,
y_twips,
started,
after_break,
alone_break,
column,
column_index,
column_top,
column_ends,
output,
} = mark;
let OutputMark {
endnotes,
note_numbers,
warnings,
story_warnings,
pages: _,
} = output;
self.back_to_row_mark(row);
self.behind.truncate(*behind);
self.front.truncate(*front);
self.bands.truncate(*bands);
self.squares.truncate(*squares);
self.frame_boxes.truncate(*frame_boxes);
self.page_notes = page_notes.clone();
self.previous.clone_from(previous);
self.y = *y;
self.y_rest = *y_rest;
self.y_twips = *y_twips;
self.started = *started;
self.after_break = *after_break;
self.alone_break.clone_from(alone_break);
self.column = column.clone();
self.column_index = *column_index;
self.column_top = *column_top;
self.column_ends.clone_from(column_ends);
self.output.endnotes.truncate(*endnotes);
self.output.notes = note_numbers.clone();
self.output.warnings.clone_from(warnings);
self.output.story_warnings.clone_from(story_warnings);
}
pub(super) fn row_mark(&self) -> RowMark {
RowMark {
items: self.items.len(),
lines: self.output.placed.len(),
clips: self.items.clip_count(),
region_fills: self.items.region_fill_count(),
numbering: self.numbering.clone(),
tables: self.output.tables,
pictures: self.output.pictures.len(),
drawings: self.output.drawings.len(),
styled: self
.output
.styled
.as_ref()
.map(super::style_refs::Record::mark),
chapter_number: self.output.chapter_number,
section_previous: self.section_previous.clone(),
table_chain: self.table_chain,
markup_mark: self.comment_markup.mark(),
found: self.output.found.counts(),
found_later: self.output.found_later.len(),
bookmarks: self.output.found_bookmarks.count(),
bookmark_numbers: self.output.found_numbers.count(),
}
}
pub(super) fn back_to_row_mark(&mut self, mark: &RowMark) {
let RowMark {
items,
lines,
clips,
region_fills,
numbering,
tables,
pictures,
drawings,
styled,
chapter_number,
section_previous,
table_chain,
markup_mark,
found,
found_later,
bookmarks,
bookmark_numbers,
} = mark;
self.items.take_back_region_fills(*region_fills);
self.items.cut(*items);
self.items.truncate_clips(*clips);
self.output.placed.truncate(*lines);
self.numbering.clone_from(numbering);
self.output.tables = *tables;
self.output.pictures.truncate(*pictures);
self.output.drawings.truncate(*drawings);
self.back_to_styled(*styled, *chapter_number);
self.section_previous.clone_from(section_previous);
self.table_chain = *table_chain;
self.comment_markup.rewind(markup_mark);
self.output.found.take_back(*found);
self.output.found_later.truncate(*found_later);
self.output.found_bookmarks.take_back(*bookmarks);
self.output.found_numbers.take_back(*bookmark_numbers);
}
}
pub(super) fn areas(section: &Section, quirks: &Quirks) -> Vec<(Length, Length)> {
let width = section.width - section.left - section.right;
let areas = section.columns.areas(section.left, width, |exact| {
decisions::equal_column_width(quirks, exact)
});
if !section.right_to_left {
return areas;
}
let right = section.left + width;
decisions::mirrored_columns(quirks, || {
areas
.iter()
.map(|&(left, column)| (section.left + right - left - column, column))
.collect()
})
.unwrap_or(areas)
}