use std::borrow::Cow;
use std::rc::Rc;
use f_office_paint::{Item, Page, Rect, Rgb};
use f_office_units::Length;
use crate::body::{Block, Body, ParagraphId, Section, SectionStart, Sections};
use crate::note_setup::NoteLabel;
use crate::numbering::{NumberContext, Numbering};
use crate::table::Table;
use crate::text::{Shaper, ShaperState};
use super::columns;
use super::floating;
use super::frames;
use super::line;
use super::markup::{CommentMarkup, CommentMarkupState};
use super::measure;
use super::notes;
use super::output;
use super::page_items;
use super::paragraph::{HeldBorders, NewPageSpace, ParagraphChunkState, Previous};
use super::sections::SectionIndex;
use super::{
AlignedParts, Band, CellPlace, Column, Context, Layout, PageWraps, PlacedLine, Rest,
SectionLayout, Story, TableChain, TableTwips, TwipsRest, UpwardWrap, goes_on,
};
pub(crate) struct LayoutState {
numbering: Numbering,
device: crate::grid::Device,
section: Section,
shaper: ShaperState,
items: page_items::PageItems,
y: Length,
y_rest: i64,
y_twips: Option<TwipsRest>,
table_twips: TableTwips,
previous: Option<Previous>,
tops: [Length; 3],
bottoms: [Length; 3],
story: Option<Story>,
body_part: Rc<f_office_warnings::Name>,
output: output::PassOutput,
page_notes: notes::PageNotes,
endnote: Option<NoteLabel>,
comment_markup: CommentMarkupState,
page: Option<Section>,
story_notes: Length,
story_page: Option<usize>,
style_page: Option<(Rc<super::style_refs::StyledPages>, usize)>,
number_context: Option<NumberContext>,
bands: Vec<Band>,
hyphen_runs: Option<Vec<measure::HyphenRun>>,
squares: Vec<floating::Square>,
frame_boxes: Vec<frames::FrameBox>,
frame_places: Vec<(usize, Length)>,
same_baseline: Vec<floating::NarrowedPiece>,
line_floor: Option<Length>,
behind: Vec<(u64, Item)>,
front: Vec<(u64, Item)>,
column: Column,
columns: Vec<(Length, Length)>,
column_index: usize,
column_top: Length,
column_ends: Vec<Length>,
section_end_paragraph: Option<ParagraphId>,
balance: Option<columns::Balance>,
section_top: columns::SectionTop,
page_marks: Option<columns::PageMarks>,
fragment: Option<super::table::Fragment>,
cell_carried: bool,
cell_floor: Option<super::table::CellFloor>,
cell_top: Option<Length>,
cell_sides: Option<(Length, Length)>,
cell_prev_style: Option<String>,
table_prev_style: Option<String>,
body_floatings: usize,
cell_floatings: usize,
cell_upward_earlier: Vec<UpwardWrap>,
cell_upward_found: Vec<UpwardWrap>,
story_earlier_wraps: Option<Box<PageWraps>>,
started: bool,
after_break: bool,
alone_break: Option<Previous>,
section_previous: Option<Previous>,
table_chain: TableChain,
page_from_break: Option<usize>,
break_numbers: (usize, (i64, usize)),
grid_pitch: Option<Length>,
following_after: Option<Length>,
kept_tail: Option<usize>,
centered_middle: Option<line::centered::CenteredMiddle>,
line_band: Option<(Length, Length)>,
east_asian_axis: Option<Length>,
aligned_parts: Option<AlignedParts>,
glyph_places: Vec<(usize, Length)>,
own_space_before: Length,
first_space_before: Length,
held_borders: HeldBorders,
drawings_under_fill: Option<page_items::FillsEntry>,
new_page_space: NewPageSpace,
last_bar: Option<(usize, usize)>,
text_part: ((usize, usize), u32),
section_index: SectionIndex,
section_first_page: usize,
section_title_page: Option<usize>,
number_start: i64,
pending: Option<usize>,
table_number: usize,
cell_place: Option<CellPlace>,
}
#[derive(Default)]
pub(crate) struct BodyCursor {
section_index: usize,
section_begin: usize,
section_entered: bool,
chunk_index: usize,
joined_table: Option<Table>,
paragraph_chunk: Option<ParagraphChunkState>,
pub(crate) blocks_done: usize,
}
impl BodyCursor {
#[must_use]
pub(crate) const fn is_done(&self, section_count: usize) -> bool {
self.section_index >= section_count
}
}
impl<'a> Layout<'a> {
pub(crate) fn into_state(self) -> LayoutState {
LayoutState {
numbering: self.numbering,
device: self.device,
section: self.section,
shaper: self.shaper.into_state(),
items: self.items,
y: self.y,
y_rest: self.y_rest,
y_twips: self.y_twips,
table_twips: self.table_twips,
previous: self.previous,
tops: self.tops,
bottoms: self.bottoms,
story: self.story,
body_part: self.body_part,
output: self.output,
page_notes: self.page_notes,
endnote: self.endnote,
comment_markup: self.comment_markup.into_state(),
page: self.page,
story_notes: self.story_notes,
story_page: self.story_page,
style_page: self.style_page,
number_context: self.number_context,
bands: self.bands,
hyphen_runs: self.hyphen_runs,
squares: self.squares,
frame_boxes: self.frame_boxes,
frame_places: self.frame_places,
same_baseline: self.same_baseline,
line_floor: self.line_floor,
behind: self.behind,
front: self.front,
column: self.column,
columns: self.columns,
column_index: self.column_index,
column_top: self.column_top,
column_ends: self.column_ends,
section_end_paragraph: self.section_end_paragraph,
balance: self.balance,
section_top: self.section_top,
page_marks: self.page_marks,
fragment: self.fragment,
cell_carried: self.cell_carried,
cell_floor: self.cell_floor,
cell_top: self.cell_top,
cell_sides: self.cell_sides,
cell_prev_style: self.cell_prev_style,
table_prev_style: self.table_prev_style,
body_floatings: self.body_floatings,
cell_floatings: self.cell_floatings,
cell_upward_earlier: self.cell_upward_earlier,
cell_upward_found: self.cell_upward_found,
story_earlier_wraps: self.story_earlier_wraps,
started: self.started,
after_break: self.after_break,
alone_break: self.alone_break,
section_previous: self.section_previous,
table_chain: self.table_chain,
page_from_break: self.page_from_break,
break_numbers: self.break_numbers,
grid_pitch: self.grid_pitch,
following_after: self.following_after,
kept_tail: self.kept_tail,
centered_middle: self.centered_middle,
line_band: self.line_band,
east_asian_axis: self.east_asian_axis,
aligned_parts: self.aligned_parts,
glyph_places: self.glyph_places,
own_space_before: self.own_space_before,
first_space_before: self.first_space_before,
held_borders: self.held_borders,
drawings_under_fill: self.drawings_under_fill,
new_page_space: self.new_page_space,
last_bar: self.last_bar,
text_part: self.text_part,
section_index: self.section_index,
section_first_page: self.section_first_page,
section_title_page: self.section_title_page,
number_start: self.number_start,
pending: self.pending,
table_number: self.table_number,
cell_place: self.cell_place,
}
}
#[must_use]
pub(crate) fn from_state(
(context, stories): (&'a Context<'a>, &'a Context<'a>),
sections: &'a Sections<SectionLayout>,
fonts: &'a dyn crate::Fonts,
theme: &'a crate::styles::Theme,
table: &'a crate::styles::FontTable,
state: LayoutState,
) -> Self {
Self {
context,
stories,
styles: context.styles,
settings: context.settings,
numbering: state.numbering,
device: state.device,
sections: Cow::Borrowed(sections),
section: state.section,
shaper: Shaper::from_state(fonts, theme, table, state.shaper),
items: state.items,
y: state.y,
y_rest: state.y_rest,
y_twips: state.y_twips,
table_twips: state.table_twips,
previous: state.previous,
tops: state.tops,
bottoms: state.bottoms,
story: state.story,
body_part: state.body_part,
output: state.output,
page_notes: state.page_notes,
endnote: state.endnote,
comment_markup: CommentMarkup::from_state(&context.comments, state.comment_markup),
page: state.page,
story_notes: state.story_notes,
story_page: state.story_page,
style_page: state.style_page,
number_context: state.number_context,
bands: state.bands,
hyphen_runs: state.hyphen_runs,
squares: state.squares,
frame_boxes: state.frame_boxes,
frame_places: state.frame_places,
same_baseline: state.same_baseline,
line_floor: state.line_floor,
behind: state.behind,
front: state.front,
column: state.column,
columns: state.columns,
column_index: state.column_index,
column_top: state.column_top,
column_ends: state.column_ends,
section_end_paragraph: state.section_end_paragraph,
balance: state.balance,
section_top: state.section_top,
page_marks: state.page_marks,
fragment: state.fragment,
cell_carried: state.cell_carried,
cell_floor: state.cell_floor,
cell_top: state.cell_top,
cell_sides: state.cell_sides,
cell_prev_style: state.cell_prev_style,
table_prev_style: state.table_prev_style,
body_floatings: state.body_floatings,
cell_floatings: state.cell_floatings,
cell_upward_earlier: state.cell_upward_earlier,
cell_upward_found: state.cell_upward_found,
story_earlier_wraps: state.story_earlier_wraps,
started: state.started,
after_break: state.after_break,
alone_break: state.alone_break,
section_previous: state.section_previous,
table_chain: state.table_chain,
page_from_break: state.page_from_break,
break_numbers: state.break_numbers,
grid_pitch: state.grid_pitch,
following_after: state.following_after,
kept_tail: state.kept_tail,
centered_middle: state.centered_middle,
line_band: state.line_band,
east_asian_axis: state.east_asian_axis,
aligned_parts: state.aligned_parts,
glyph_places: state.glyph_places,
own_space_before: state.own_space_before,
first_space_before: state.first_space_before,
held_borders: state.held_borders,
drawings_under_fill: state.drawings_under_fill,
new_page_space: state.new_page_space,
last_bar: state.last_bar,
text_part: state.text_part,
section_index: state.section_index,
section_first_page: state.section_first_page,
section_title_page: state.section_title_page,
number_start: state.number_start,
pending: state.pending,
table_number: state.table_number,
cell_place: state.cell_place,
}
}
#[must_use]
pub(crate) fn finished_page_count(&self) -> usize {
self.output.pages.len()
}
#[must_use]
pub(crate) fn placed_lines(&self) -> &[PlacedLine] {
&self.output.placed
}
pub(crate) fn preview_page(
&mut self,
index: usize,
provisional_count: i64,
) -> Option<(Page, Vec<PlacedLine>)> {
let page = self.output.pages.get(index)?.clone();
let (items, lines) = if self.output.blank_pages.contains(&index) {
(Vec::new(), Vec::new())
} else {
let saved_warnings = self.output.warnings.clone();
let saved_story_warnings = self.output.story_warnings.clone();
let result = self.headers_and_footers(index, provisional_count);
self.output.warnings = saved_warnings;
self.output.story_warnings = saved_story_warnings;
result
};
let color = self.settings.page_color.map(|[r, g, b]| {
Item::Rect(Rect {
x: Length::ZERO,
y: Length::ZERO,
width: page.width(),
height: page.height(),
color: Rgb { r, g, b },
})
});
let stamped = page.map_items(|mut body| {
body.splice(0..0, color.into_iter().chain(items));
body
});
Some((stamped, lines))
}
fn budget_reached(
&self,
stop_pages: Option<usize>,
processed: usize,
max_blocks: usize,
) -> bool {
stop_pages.is_some_and(|n| self.output.pages.len() >= n) || processed >= max_blocks
}
pub(crate) fn step_body(
&mut self,
body: &Body,
cursor: &mut BodyCursor,
stop_pages: Option<usize>,
max_blocks: usize,
) {
let blocks = &body.blocks;
let section_count = self.sections.count();
let mut processed = 0usize;
while cursor.section_index < section_count {
if !self.step_one_section(blocks, cursor, stop_pages, max_blocks, &mut processed) {
return;
}
if self.budget_reached(stop_pages, processed, max_blocks) {
return;
}
}
}
fn step_one_section(
&mut self,
blocks: &[Block],
cursor: &mut BodyCursor,
stop_pages: Option<usize>,
max_blocks: usize,
processed: &mut usize,
) -> bool {
let index = cursor.section_index;
let Some((raw_end, start)) = self.sections.get(index).map(|s| (s.end, s.start)) else {
cursor.section_index += 1;
cursor.section_entered = false;
cursor.chunk_index = 0;
return true;
};
let end = raw_end.clamp(cursor.section_begin, blocks.len());
let part = blocks.get(cursor.section_begin..end).unwrap_or_default();
let continuous = self
.sections
.get(index + 1)
.is_some_and(|s| s.start == SectionStart::Continuous);
if !cursor.section_entered
&& self.enter_section(index, start, part, continuous, cursor, processed)
{
cursor.section_begin = end;
cursor.section_index += 1;
return true;
}
if !self.step_section_chunks(part, cursor, stop_pages, max_blocks, processed) {
return false;
}
self.leave_blocks();
if continuous && matches!(blocks.get(end), Some(Block::Paragraph(_))) {
self.hidden_section_end(part);
}
cursor.section_begin = end;
cursor.section_index += 1;
cursor.section_entered = false;
cursor.chunk_index = 0;
cursor.joined_table = None;
cursor.paragraph_chunk = None;
true
}
fn enter_section(
&mut self,
index: usize,
start: SectionStart,
part: &[Block],
continuous: bool,
cursor: &mut BodyCursor,
processed: &mut usize,
) -> bool {
if index > 0 {
self.start_section(index, start);
}
let section_count = self.sections.count();
self.section_end_paragraph = match part.last() {
Some(Block::Paragraph(paragraph)) if index + 1 < section_count => Some(paragraph.id),
_ => None,
};
if continuous && self.columns.len() > 1 {
self.balanced_blocks(part);
cursor.blocks_done += part.len();
*processed += part.len().max(1);
cursor.section_entered = false;
cursor.chunk_index = 0;
return true;
}
self.enter_blocks();
cursor.section_entered = true;
cursor.chunk_index = 0;
cursor.joined_table = None;
cursor.paragraph_chunk = None;
false
}
fn step_section_chunks(
&mut self,
part: &[Block],
cursor: &mut BodyCursor,
stop_pages: Option<usize>,
max_blocks: usize,
processed: &mut usize,
) -> bool {
let paragraphs_pred =
|a: &Block, b: &Block| matches!((a, b), (Block::Paragraph(_), Block::Paragraph(_)));
let chunks: Vec<&[Block]> = part.chunk_by(paragraphs_pred).collect();
while let Some(&chunk) = chunks.get(cursor.chunk_index) {
let ci = cursor.chunk_index;
let rest = Rest(chunks.get(ci + 1..).unwrap_or_default());
let next = chunks.get(ci + 1).and_then(|next| next.first());
if cursor.paragraph_chunk.is_none() {
self.note_chunk(ci);
}
if !self.step_one_chunk(chunk, rest, next, cursor, stop_pages, max_blocks, processed) {
return false;
}
cursor.chunk_index += 1;
if self.budget_reached(stop_pages, *processed, max_blocks) {
return false;
}
}
true
}
#[expect(
clippy::too_many_arguments,
reason = "chunk stepping forwards cursor, rest lookahead, and slice budget"
)]
fn step_one_chunk(
&mut self,
chunk: &[Block],
rest: Rest<'_>,
next: Option<&Block>,
cursor: &mut BodyCursor,
stop_pages: Option<usize>,
max_blocks: usize,
processed: &mut usize,
) -> bool {
if matches!(chunk.first(), Some(Block::Paragraph(_))) {
let group: Vec<_> = chunk
.iter()
.filter_map(|b| match b {
Block::Paragraph(p) => Some(p),
Block::Table(_) => None,
})
.collect();
let mut pstate = cursor
.paragraph_chunk
.take()
.unwrap_or_else(|| self.begin_paragraph_chunk(&group, 0));
let remaining = max_blocks.saturating_sub(*processed).max(1);
let (chunk_done, count) =
self.flow_step(&group, rest, &mut pstate, stop_pages, remaining);
cursor.blocks_done += count;
*processed += count;
if !chunk_done {
cursor.paragraph_chunk = Some(pstate);
return false;
}
return true;
}
for block in chunk {
if let Block::Table(table) = block {
let more = goes_on(table, next);
match cursor.joined_table.as_mut() {
Some(whole) => whole.rows.extend(table.rows.iter().cloned()),
None if more => cursor.joined_table = Some(table.clone()),
None => self.table(table, rest),
}
if let Some(whole) = cursor.joined_table.take_if(|_| !more) {
self.table(&whole, rest);
}
cursor.blocks_done += 1;
*processed += 1;
}
}
true
}
}