use std::sync::Arc;
use f_office_docx::{IncrementalLayout, LayoutStep, PreparedDocx};
use f_office_fonts::FontDb;
use f_office_opc::Package;
use f_office_paint::DisplayList;
use crate::{
ArtPictures, Document, Error, Options, RandomAccessRead, Warned, Warning, Warnings, pictures,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LayoutProgress {
pub page_count: usize,
pub invalidated_pages: Vec<usize>,
pub blocks_done: usize,
pub blocks_total: usize,
pub pass: u8,
pub complete: bool,
}
#[derive(Debug)]
pub struct PreparedDocument {
inner: PreparedDocx,
}
impl PreparedDocument {
pub fn open(docx: &[u8], options: &Options) -> Result<Self, Error> {
let package = f_office_docx::timing::span("open", || Package::open(docx, &options.limits))
.map_err(Error::Package)?;
Self::from_package(package, options)
}
pub fn open_source(
source: Arc<dyn RandomAccessRead>,
options: &Options,
) -> Result<Self, Error> {
let package =
f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
.map_err(Error::Package)?;
Self::from_package(package, options)
}
fn from_package(package: Package, options: &Options) -> Result<Self, Error> {
let inner = PreparedDocx::open(package, &options.layout()).map_err(map_docx_error)?;
Ok(Self { inner })
}
#[must_use]
pub fn font_needs(&self) -> Vec<(Option<String>, Vec<String>)> {
self.inner.font_needs()
}
#[must_use]
pub fn block_count(&self) -> usize {
self.inner.block_count()
}
}
#[derive(Debug)]
pub struct LayoutContinuation {
inner: IncrementalLayout,
}
impl LayoutContinuation {
pub fn step(
&mut self,
document: &mut Document,
fonts: &FontDb,
art: &ArtPictures,
max_new_pages: Option<usize>,
max_blocks: usize,
) -> Result<LayoutProgress, Error> {
let step = self
.inner
.step((fonts, art), max_new_pages, max_blocks)
.map_err(map_docx_error)?;
Ok(apply_step(document, step))
}
pub fn finish(
mut self,
document: &mut Document,
fonts: &FontDb,
art: &ArtPictures,
) -> Result<LayoutProgress, Error> {
let mut invalidated = Vec::new();
loop {
let progress = self.step(document, fonts, art, None, usize::MAX)?;
for page in progress.invalidated_pages {
if !invalidated.contains(&page) {
invalidated.push(page);
}
}
if progress.complete {
return Ok(LayoutProgress {
invalidated_pages: invalidated,
..progress
});
}
}
}
}
impl Document {
pub fn begin_open_prepared(
prepared: PreparedDocument,
fonts: &FontDb,
art: &ArtPictures,
) -> Result<(Warned<Self>, Option<LayoutContinuation>, LayoutProgress), Error> {
let mut incremental = prepared.inner.into_incremental();
let step = incremental
.step((fonts, art), Some(1), usize::MAX)
.map_err(map_docx_error)?;
match step {
LayoutStep::Progress {
new_pages,
text_blocks,
text_map,
writer,
blocks_done,
blocks_total,
pass,
..
} => {
let mut warnings = Warnings::new();
let list = post_process_list(DisplayList::new(new_pages), &writer, &mut warnings);
let page_count = list.pages().len();
let doc = Self {
list,
#[cfg(any(test, feature = "development"))]
lines: Vec::new(),
#[cfg(any(test, feature = "development"))]
tables: Vec::new(),
text_blocks: text_blocks.unwrap_or_default(),
text_map: text_map.unwrap_or_default(),
};
let progress = LayoutProgress {
page_count,
invalidated_pages: Vec::new(),
blocks_done,
blocks_total,
pass,
complete: false,
};
Ok((
Warned::new(doc, warnings),
Some(LayoutContinuation { inner: incremental }),
progress,
))
}
LayoutStep::Finished(laid_out) => {
let (doc, warnings) = finish_laid_out(laid_out);
let page_count = doc.page_count();
let progress = LayoutProgress {
page_count,
invalidated_pages: Vec::new(),
blocks_done: page_count,
blocks_total: page_count,
pass: 1,
complete: true,
};
Ok((Warned::new(doc, warnings), None, progress))
}
}
}
}
fn apply_step(document: &mut Document, step: LayoutStep) -> LayoutProgress {
match step {
LayoutStep::Progress {
new_pages,
text_blocks,
text_map,
writer,
blocks_done,
blocks_total,
pass,
..
} => {
if !new_pages.is_empty() {
let mut warnings = Warnings::new();
let batch = post_process_list(DisplayList::new(new_pages), &writer, &mut warnings);
let mut pages = std::mem::replace(&mut document.list, DisplayList::new(Vec::new()))
.into_pages();
pages.extend(batch.into_pages());
document.list = DisplayList::new(pages);
}
if let Some(tb) = text_blocks {
document.text_blocks = tb;
}
if let Some(tm) = text_map {
document.text_map = tm;
}
LayoutProgress {
page_count: document.page_count(),
invalidated_pages: Vec::new(),
blocks_done,
blocks_total,
pass,
complete: false,
}
}
LayoutStep::Finished(laid_out) => {
let (final_doc, _warnings) = finish_laid_out(laid_out);
let invalidated_pages: Vec<usize> = document
.list
.pages()
.iter()
.zip(final_doc.list.pages())
.enumerate()
.filter_map(|(idx, (old, new))| (old != new).then_some(idx))
.collect();
*document = final_doc;
let page_count = document.page_count();
LayoutProgress {
page_count,
invalidated_pages,
blocks_done: page_count,
blocks_total: page_count,
pass: 1,
complete: true,
}
}
}
}
fn post_process_list(
mut list: DisplayList,
writer: &f_office_paint::Writer,
warnings: &mut Warnings,
) -> DisplayList {
writer.finish(&mut list);
list = pictures::write_pictures_again(
list,
pictures::Rewriting {
quality: writer.jpeg_quality(),
jpeg_share: writer.jpeg_share(),
jpeg_sample: writer.jpeg_sample(),
crop: writer.picture_crop(),
alpha_mix: writer.alpha_mix(),
resampling: &|pixels, palette, image| {
writer.resampled_size(pixels, (image.width, image.height), palette)
},
},
warnings,
);
writer.place_pictures(&mut list);
list
}
fn finish_laid_out(
laid_out: f_office_docx::Warned<f_office_docx::LaidOut>,
) -> (Document, Warnings) {
let mut warnings = laid_out.warnings.map(Warning::Docx);
#[cfg(not(any(test, feature = "development")))]
let f_office_docx::LaidOut {
list,
lines: _,
text_blocks,
text_map,
tables: _,
writer,
} = laid_out.value;
#[cfg(any(test, feature = "development"))]
let f_office_docx::LaidOut {
list,
lines,
text_blocks,
text_map,
tables,
writer,
} = laid_out.value;
let list = post_process_list(list, &writer, &mut warnings);
let doc = Document {
list,
#[cfg(any(test, feature = "development"))]
lines,
#[cfg(any(test, feature = "development"))]
tables,
text_blocks,
text_map,
};
(doc, warnings)
}
fn map_docx_error(error: f_office_docx::Error) -> Error {
match error {
f_office_docx::Error::Configuration(error) => Error::Configuration(error),
error => Error::Docx(error),
}
}