use std::ops::RangeInclusive;
use std::rc::Rc;
use f_office_fonts::FontDb;
use f_office_opc::Package;
use f_office_paint::{DisplayList, Page};
use f_office_units::count_factor;
use crate::body::{Block, Content, Paragraph};
use crate::font_choice::FontChoice;
use crate::layout::{
BodyCursor, Context, EarlierPass, Layout, LayoutState, Pass, list_label_props, mark_run_props,
};
use crate::numbering::Numbering;
use crate::pass_loop::{PassDecision, PassLoop};
use crate::props::{ListLevel, ListRef, MarkChange, RunProps};
use crate::styles::{Styles, TableStyle};
use crate::text::{Shaper, ShaperSettings};
use crate::text_addresses::StoryParagraphs;
use crate::text_blocks::{IncrementalTextBlocks, TextBlock};
use crate::text_map::{TextMap, TextMapDelta};
use crate::web_settings::{HtmlDivs, HtmlDivsCache};
use crate::{ArtPictures, Error, LaidOut, Options, ParsedDocx, Warned, profile, text_addresses};
pub struct PreparedDocx {
package: Package,
profile: profile::Profile,
parsed: ParsedDocx,
}
impl std::fmt::Debug for PreparedDocx {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PreparedDocx")
.field("main", &self.parsed.main)
.field("blocks", &self.parsed.body.blocks.len())
.finish_non_exhaustive()
}
}
impl PreparedDocx {
pub fn open(package: Package, options: &Options) -> Result<Self, Error> {
let profile = options.profile().map_err(Error::Configuration)?;
let parsed = ParsedDocx::parse(&package, options, &profile)?;
Ok(Self {
package,
profile,
parsed,
})
}
#[must_use]
pub fn block_count(&self) -> usize {
self.parsed.body.blocks.len()
}
#[must_use]
pub fn font_needs(&self) -> Vec<(Option<String>, Vec<String>)> {
let empty = FontDb::default();
let font_choice = FontChoice::of(&empty, &self.profile);
let shaper_settings = ShaperSettings::of(
&self.parsed.settings,
&self.parsed.quirks,
self.parsed.device.dot_size(),
);
let shaper = Shaper::new(
&font_choice,
&self.parsed.theme,
&self.parsed.table,
&shaper_settings,
);
let mut collected = CollectedNeeds::default();
let mut numbering = (*self.parsed.numbering).clone();
scan_blocks(
&self.parsed.body.blocks,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
for index in 0..self.parsed.sections.count() {
if let Some(section) = self.parsed.sections.get(index) {
for story in [
section.headers.default.as_ref(),
section.headers.first.as_ref(),
section.headers.even.as_ref(),
section.footers.default.as_ref(),
section.footers.first.as_ref(),
section.footers.even.as_ref(),
]
.into_iter()
.flatten()
{
scan_blocks(
&story.blocks,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
}
}
}
for notes in [&self.parsed.notes, &self.parsed.endnotes] {
if notes.by_id.is_empty() {
continue;
}
scan_blocks(
¬es.separator,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
scan_blocks(
¬es.continuation,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
for blocks in notes.by_id.values() {
scan_blocks(
blocks,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
}
}
for comment in self.parsed.comments.by_id.values() {
scan_blocks(
&comment.blocks,
&self.parsed.styles,
None,
&mut numbering,
&shaper,
&mut collected,
);
}
collected.into_ordered()
}
#[must_use]
pub fn into_incremental(self) -> IncrementalLayout {
IncrementalLayout::new(self)
}
}
#[derive(Default)]
struct CollectedNeeds {
text: Vec<(Option<String>, Vec<String>)>,
marks: Vec<(Option<String>, Vec<String>)>,
}
impl CollectedNeeds {
fn into_ordered(mut self) -> Vec<(Option<String>, Vec<String>)> {
for need in self.marks {
if !self.text.contains(&need) {
self.text.push(need);
}
}
self.text
}
}
fn has_explicit_font(props: &RunProps) -> bool {
props.font_ascii.is_some()
|| props.font_hansi.is_some()
|| props.font_cs.is_some()
|| props.font_east_asia.is_some()
}
fn scan_blocks(
blocks: &[Block],
styles: &Styles,
table_style: Option<&TableStyle>,
numbering: &mut Numbering,
shaper: &Shaper<'_>,
out: &mut CollectedNeeds,
) {
for block in blocks {
match block {
Block::Paragraph(paragraph) => {
scan_paragraph(paragraph, styles, table_style, numbering, shaper, out);
}
Block::Table(table) => {
let resolved_table = styles.table(table.props.style.as_deref());
for row in &table.rows {
for cell in &row.cells {
scan_blocks(
&cell.blocks,
styles,
Some(&resolved_table),
numbering,
shaper,
out,
);
}
}
}
}
}
}
fn scan_paragraph(
paragraph: &Paragraph,
styles: &Styles,
table_style: Option<&TableStyle>,
numbering: &mut Numbering,
shaper: &Shaper<'_>,
out: &mut CollectedNeeds,
) {
let (mut para_props, base_run) =
styles.paragraph(paragraph.props.style.as_deref(), table_style);
para_props.apply(¶graph.props);
let mark_run = mark_run_props(styles, &base_run, ¶_props);
shaper.collect_run_needs(&mark_run, "", &mut out.marks);
collect_list_label_needs(
paragraph,
(¶_props, &mark_run),
(styles, table_style),
numbering,
shaper,
out,
);
for run in ¶graph.runs {
scan_run(run, &base_run, styles, numbering, shaper, out);
}
}
fn collect_list_label_needs(
paragraph: &Paragraph,
(para_props, mark_run): (&crate::props::ParaProps, &RunProps),
(styles, table_style): (&Styles, Option<&TableStyle>),
numbering: &mut Numbering,
shaper: &Shaper<'_>,
out: &mut CollectedNeeds,
) {
let flags = paragraph.props.flags();
if flags.section_end || flags.continuous_end {
return;
}
let ilvl = para_props
.numbering_level
.unwrap_or(ListLevel::FIRST)
.index();
let list = para_props.numbering.and_then(ListRef::id).zip(ilvl);
let original_list = match ¶graph.props.original {
Some(original) => {
let props = styles.paragraph_properties_without_list_level(original, table_style);
let orig_ilvl = props.numbering_level.unwrap_or(ListLevel::FIRST).index();
props.numbering.and_then(ListRef::id).zip(orig_ilvl)
}
None => list,
};
let change = paragraph.props.mark_change;
let new = list.filter(|_| change != Some(MarkChange::Deleted));
let original = original_list.filter(|_| change != Some(MarkChange::Inserted));
let Some(label) = numbering.next_label(new, original) else {
return;
};
if label.picture || label.text.is_empty() {
return;
}
let rtl = para_props.bidi.unwrap_or(false);
let label_props = list_label_props(shaper, &label, mark_run, rtl);
shaper.collect_run_needs(&label_props, &label.text, &mut out.text);
}
fn scan_run(
run: &crate::body::Run,
base_run: &RunProps,
styles: &Styles,
numbering: &mut Numbering,
shaper: &Shaper<'_>,
out: &mut CollectedNeeds,
) {
let mut resolved = base_run.clone();
if let Some(style_id) = run.style.as_deref() {
styles.apply_character(&mut resolved, style_id);
}
resolved.apply(&run.props);
let mut text = String::new();
let mut has_visible_item = false;
let mut needs_math = resolved.math == Some(true);
for item in &run.content {
let (visible, math) = scan_run_item(item, styles, numbering, shaper, &mut text, out);
has_visible_item |= visible;
needs_math |= math;
}
if needs_math {
shaper.collect_math_needs(&resolved, &mut out.text);
}
if has_visible_item {
shaper.collect_run_needs(&resolved, &text, &mut out.text);
} else if has_explicit_font(&run.props) {
shaper.collect_run_needs(&resolved, "", &mut out.marks);
}
}
fn scan_run_item(
item: &Content,
styles: &Styles,
numbering: &mut Numbering,
shaper: &Shaper<'_>,
text: &mut String,
out: &mut CollectedNeeds,
) -> (bool, bool) {
match item {
Content::Text(s) => {
text.push_str(s);
(!s.is_empty(), false)
}
Content::PageNumber
| Content::PageCount
| Content::CheckBox(_)
| Content::Date(_)
| Content::DocProperty(_)
| Content::StyleRef(_)
| Content::PageRef(_)
| Content::NumberRef(_)
| Content::If(_)
| Content::FootnoteReference(_, _)
| Content::FootnoteMark
| Content::EndnoteReference(_, _)
| Content::EndnoteMark
| Content::Tab
| Content::PositionTab { .. } => (true, false),
Content::Drawing(drawing) => {
scan_blocks(&drawing.shape.blocks, styles, None, numbering, shaper, out);
for (_, _, child) in &drawing.shape.parts {
scan_blocks(&child.blocks, styles, None, numbering, shaper, out);
}
(false, false)
}
Content::Floating(floating) => {
scan_blocks(&floating.blocks, styles, None, numbering, shaper, out);
for (_, _, child) in &floating.parts {
scan_blocks(&child.blocks, styles, None, numbering, shaper, out);
}
(false, false)
}
Content::Stack(_)
| Content::Grown(_)
| Content::Radical(_)
| Content::Accent(_)
| Content::Matrix(_)
| Content::MathBar(_)
| Content::MathSlash(_)
| Content::MathLimit(_)
| Content::GroupChr(_)
| Content::MathBox(_)
| Content::Scripts(_) => (false, true),
_ => (false, false),
}
}
pub enum LayoutStep {
Progress {
new_pages: Vec<Page>,
total_pages: usize,
initial_text_blocks: Option<Vec<TextBlock>>,
text_block_pages: Vec<(usize, RangeInclusive<usize>)>,
initial_text_map: Option<TextMap>,
text_map_delta: Option<TextMapDelta>,
writer: f_office_paint::Writer,
blocks_done: usize,
blocks_total: usize,
pass: u8,
},
Finished {
laid_out: Warned<LaidOut>,
blocks_total: usize,
pass: u8,
},
}
pub struct IncrementalLayout {
prepared: PreparedDocx,
state: Option<LayoutState>,
cursor: BodyCursor,
earlier: EarlierPass,
html_divs_cache: HtmlDivsCache,
pass_loop: PassLoop,
emitted_pages: usize,
indexed_body_lines: usize,
story_paragraphs: Option<StoryParagraphs>,
initial_text_blocks: Option<Vec<TextBlock>>,
initial_text_map: Option<TextMap>,
text_block_tracker: IncrementalTextBlocks,
finished: bool,
}
impl std::fmt::Debug for IncrementalLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IncrementalLayout")
.field("pass_number", &self.pass_loop.pass_number())
.field("emitted_pages", &self.emitted_pages)
.field("blocks_done", &self.cursor.blocks_done)
.field("finished", &self.finished)
.finish_non_exhaustive()
}
}
impl IncrementalLayout {
#[must_use]
pub fn new(prepared: PreparedDocx) -> Self {
let parsed = &prepared.parsed;
let story_paragraphs = text_addresses::story_paragraphs(
&parsed.body.blocks,
&parsed.sections,
(&parsed.notes, &parsed.endnotes),
);
let initial_text_map = TextMap::from_paragraphs(story_paragraphs.clone());
let toc = parsed.body.table_of_contents.as_ref();
let (initial_text_blocks, text_block_tracker) =
IncrementalTextBlocks::new(&parsed.body.blocks, (&parsed.styles, toc));
Self {
prepared,
state: None,
cursor: BodyCursor::default(),
earlier: EarlierPass::default(),
html_divs_cache: None,
pass_loop: PassLoop::new(),
emitted_pages: 0,
indexed_body_lines: 0,
story_paragraphs: Some(story_paragraphs),
initial_text_blocks: Some(initial_text_blocks),
initial_text_map: Some(initial_text_map),
text_block_tracker,
finished: false,
}
}
#[must_use]
pub const fn is_finished(&self) -> bool {
self.finished
}
pub fn step(
&mut self,
(fonts, art): (&FontDb, &ArtPictures),
max_new_pages: Option<usize>,
max_blocks: usize,
) -> Result<LayoutStep, Error> {
let parsed = &self.prepared.parsed;
let blocks_total = parsed.body.blocks.len();
let font_choice = FontChoice::of(fonts, &self.prepared.profile);
let html_divs = HtmlDivs::from_cache(
&self.prepared.package,
parsed.web_part.clone(),
(&parsed.paragraph_ids, parsed.reader),
self.html_divs_cache.take(),
);
let context = Context {
main: &parsed.main,
styles: &parsed.styles,
settings: &parsed.settings,
html_divs: &html_divs,
numbering: Rc::clone(&parsed.numbering),
notes: Rc::clone(&parsed.notes),
endnotes: Rc::clone(&parsed.endnotes),
comments: Rc::clone(&parsed.comments),
device: parsed.device,
quirks: parsed.quirks,
now: parsed.now,
properties: std::sync::Arc::clone(&parsed.properties),
zone_minutes: parsed.zone_minutes,
earlier: std::mem::take(&mut self.earlier),
deleted_cell_label: parsed.deleted_cell_label,
art,
};
let stories = context.for_stories();
let shaper_settings =
ShaperSettings::of(&parsed.settings, &parsed.quirks, parsed.device.dot_size());
let mut layout = if let Some(state) = self.state.take() {
Layout::from_state(
(&context, &stories),
&parsed.sections,
&font_choice,
&parsed.theme,
&parsed.table,
state,
)
} else {
let shaper = Shaper::new(&font_choice, &parsed.theme, &parsed.table, &shaper_settings);
let mut fresh = Layout::new((&context, &stories), &parsed.sections, shaper);
fresh.begin_body(&parsed.body);
fresh
};
let active_pass = self.pass_loop.pass_number();
let stop_pages = if active_pass == 1 {
max_new_pages.map(|n| self.emitted_pages.saturating_add(n))
} else {
None
};
layout.step_body(&parsed.body, &mut self.cursor, stop_pages, max_blocks);
if !self.cursor.is_done(parsed.sections.count()) {
let preview = collect_mid_pass_preview(
active_pass,
&mut self.emitted_pages,
&mut self.indexed_body_lines,
&mut self.initial_text_blocks,
&mut self.initial_text_map,
&mut self.text_block_tracker,
&mut layout,
&font_choice,
);
self.state = Some(layout.into_state());
self.earlier = context.earlier;
self.html_divs_cache = html_divs.into_cache();
return Ok(LayoutStep::Progress {
new_pages: preview.new_pages,
total_pages: self.emitted_pages,
initial_text_blocks: preview.initial_text_blocks,
text_block_pages: preview.text_block_pages,
initial_text_map: preview.initial_text_map,
text_map_delta: preview.text_map_delta,
writer: self.prepared.profile.writer(),
blocks_done: self.cursor.blocks_done.min(blocks_total),
blocks_total,
pass: active_pass,
});
}
let mut pass = layout.finish_body_pass();
let earlier_done = context.earlier;
let html_divs_cache = html_divs.into_cache();
self.finish_pass(fonts, earlier_done, html_divs_cache, &mut pass)
}
fn finish_pass(
&mut self,
fonts: &FontDb,
earlier_done: EarlierPass,
html_divs_cache: HtmlDivsCache,
pass: &mut Pass,
) -> Result<LayoutStep, Error> {
let blocks_total = self.prepared.parsed.body.blocks.len();
let finished_pass = self.pass_loop.pass_number();
match self.pass_loop.advance(
&self.prepared.parsed.body,
&self.prepared.parsed.sections,
earlier_done,
pass,
) {
PassDecision::Continue(next_earlier) => {
let mut new_pages = Vec::new();
let mut initial_text_blocks = None;
let mut text_block_pages = Vec::new();
let mut initial_text_map = None;
let mut text_map_delta = None;
if finished_pass == 1 && pass.list.pages().len() > self.emitted_pages {
let prev_emitted = self.emitted_pages;
let raw = pass
.list
.pages()
.get(prev_emitted..)
.unwrap_or_default()
.to_vec();
let font_choice = FontChoice::of(fonts, &self.prepared.profile);
new_pages = font_choice
.draw_symbol_stand_ins(DisplayList::new(raw))
.into_pages();
self.emitted_pages = pass.list.pages().len();
let trailing_lines: Vec<crate::PlacedLine> = pass
.lines
.iter()
.filter(|line| line.page >= prev_emitted)
.cloned()
.collect();
initial_text_blocks = self.initial_text_blocks.take();
text_block_pages = self.text_block_tracker.update(&trailing_lines);
initial_text_map = self.initial_text_map.take();
let delta = TextMap::delta_from_placed(trailing_lines);
if !delta.is_empty() {
text_map_delta = Some(delta);
}
}
self.earlier = *next_earlier;
self.cursor = BodyCursor::default();
self.state = None;
self.html_divs_cache = html_divs_cache;
Ok(LayoutStep::Progress {
new_pages,
total_pages: self.emitted_pages,
initial_text_blocks,
text_block_pages,
initial_text_map,
text_map_delta,
writer: self.prepared.profile.writer(),
blocks_done: 0,
blocks_total,
pass: self.pass_loop.pass_number(),
})
}
PassDecision::Done => {
self.finish_final_pass(fonts, html_divs_cache, pass, blocks_total, finished_pass)
}
}
}
fn finish_final_pass(
&mut self,
fonts: &FontDb,
html_divs_cache: HtmlDivsCache,
pass: &mut Pass,
blocks_total: usize,
finished_pass: u8,
) -> Result<LayoutStep, Error> {
let mut taken = Pass {
list: std::mem::replace(&mut pass.list, DisplayList::new(Vec::new())),
wraps: std::mem::take(&mut pass.wraps),
bookmarks: std::mem::take(&mut pass.bookmarks),
bookmark_numbers: std::mem::take(&mut pass.bookmark_numbers),
styles: std::mem::take(&mut pass.styles),
note_places: std::mem::take(&mut pass.note_places),
later_anchors: std::mem::take(&mut pass.later_anchors),
note_heights: std::mem::take(&mut pass.note_heights),
notes_missed: pass.notes_missed,
lines: std::mem::take(&mut pass.lines),
tables: std::mem::take(&mut pass.tables),
warnings: std::mem::take(&mut pass.warnings),
font_notes: std::mem::take(&mut pass.font_notes),
};
self.pass_loop.merge_final_font_notes(&mut taken);
let parsed = &mut self.prepared.parsed;
let paragraphs = self.story_paragraphs.take().unwrap_or_else(|| {
text_addresses::story_paragraphs(
&parsed.body.blocks,
&parsed.sections,
(&parsed.notes, &parsed.endnotes),
)
});
let warnings = std::mem::take(&mut parsed.warnings);
let html_divs = HtmlDivs::from_cache(
&self.prepared.package,
parsed.web_part.clone(),
(&parsed.paragraph_ids, parsed.reader),
html_divs_cache,
);
let font_choice = FontChoice::of(fonts, &self.prepared.profile);
let laid_out = LaidOut::of(
taken,
(&parsed.body, &parsed.styles, paragraphs),
(html_divs, &font_choice, self.prepared.profile.writer()),
warnings,
)?;
let laid_out = laid_out.map(|lo| LaidOut {
list: font_choice.draw_symbol_stand_ins(lo.list),
..lo
});
self.finished = true;
Ok(LayoutStep::Finished {
laid_out,
blocks_total,
pass: finished_pass,
})
}
}
struct MidPassPreview {
new_pages: Vec<Page>,
initial_text_blocks: Option<Vec<TextBlock>>,
text_block_pages: Vec<(usize, RangeInclusive<usize>)>,
initial_text_map: Option<TextMap>,
text_map_delta: Option<TextMapDelta>,
}
#[expect(
clippy::too_many_arguments,
reason = "internal slice preview collector mutating disjoint incremental state fields"
)]
fn collect_mid_pass_preview(
pass_number: u8,
emitted_pages: &mut usize,
indexed_body_lines: &mut usize,
initial_text_blocks: &mut Option<Vec<TextBlock>>,
initial_text_map: &mut Option<TextMap>,
text_block_tracker: &mut IncrementalTextBlocks,
layout: &mut Layout<'_>,
font_choice: &FontChoice<'_>,
) -> MidPassPreview {
if pass_number != 1 || layout.finished_page_count() <= *emitted_pages {
return MidPassPreview {
new_pages: Vec::new(),
initial_text_blocks: None,
text_block_pages: Vec::new(),
initial_text_map: None,
text_map_delta: None,
};
}
let finished_now = layout.finished_page_count();
let provisional_count = count_factor(finished_now);
let mut new_pages = Vec::new();
let mut slice_header_footer_lines = Vec::new();
for idx in *emitted_pages..finished_now {
if let Some((page, header_footer_lines)) = layout.preview_page(idx, provisional_count) {
new_pages.push(page);
slice_header_footer_lines.extend(header_footer_lines);
}
}
let new_pages = font_choice
.draw_symbol_stand_ins(DisplayList::new(new_pages))
.into_pages();
*emitted_pages = finished_now;
let body_placed = layout.placed_lines();
let new_body_slice = body_placed.get(*indexed_body_lines..).unwrap_or_default();
let text_block_pages = text_block_tracker.update(new_body_slice);
let mut delta_lines =
Vec::with_capacity(new_body_slice.len() + slice_header_footer_lines.len());
delta_lines.extend(new_body_slice.iter().cloned());
delta_lines.extend(slice_header_footer_lines);
*indexed_body_lines = body_placed.len();
let delta = TextMap::delta_from_placed(delta_lines);
MidPassPreview {
new_pages,
initial_text_blocks: initial_text_blocks.take(),
text_block_pages,
initial_text_map: initial_text_map.take(),
text_map_delta: (!delta.is_empty()).then_some(delta),
}
}