f-office 0.3.0

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Staged single-parse preparation (`PreparedDocument`) and resumable Page-1-first document
//! opening (`LayoutContinuation`) built on `f_office_docx::IncrementalLayout`.

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,
};

/// Progress summary returned by [`Document::begin_open_prepared`] and [`LayoutContinuation::step`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LayoutProgress {
    /// Total pages currently available on the [`Document`].
    pub page_count: usize,
    /// Zero-based indices of previously emitted pages whose content changed on finalization.
    pub invalidated_pages: Vec<usize>,
    /// Approximate body blocks processed in the active layout pass.
    pub blocks_done: usize,
    /// Total body blocks in the document.
    pub blocks_total: usize,
    /// Active layout pass (1 for initial streaming pass, 2+ for cross-reference/wrap passes).
    pub pass: u8,
    /// Whether all layout passes have completed and the [`Document`] holds final pages.
    pub complete: bool,
    /// Final accumulated warnings once `complete` is `true`, or `None` while layout is in progress.
    pub warnings: Option<Warnings>,
}

/// A DOCX file opened and parsed once, ready for fast font discovery and incremental layout.
#[derive(Debug)]
pub struct PreparedDocument {
    inner: PreparedDocx,
}

impl PreparedDocument {
    /// Opens and parses `docx` once for `options`.
    ///
    /// # Errors
    ///
    /// Returns an error when the package, XML, or configuration cannot be read.
    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)
    }

    /// Opens and parses a random-access DOCX `source` once for `options`.
    ///
    /// # Errors
    ///
    /// Returns an error when the package, XML, or configuration cannot be read.
    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 })
    }

    /// Quickly scans the parsed document for `(asked, tried)` font needs without running a dummy
    /// full-document layout pass.
    #[must_use]
    pub fn font_needs(&self) -> Vec<(Option<String>, Vec<String>)> {
        self.inner.font_needs()
    }

    /// Number of top-level blocks in the document body.
    #[must_use]
    pub fn block_count(&self) -> usize {
        self.inner.block_count()
    }
}

/// Resumable layout continuation driving remaining pages of an incrementally opened [`Document`].
#[derive(Debug)]
pub struct LayoutContinuation {
    inner: IncrementalLayout,
}

impl LayoutContinuation {
    /// Advances pagination by up to `max_new_pages` newly completed pages (on Pass 1) or
    /// `max_blocks` body blocks, appending newly finished pages directly onto `document`.
    ///
    /// # Errors
    ///
    /// Returns an error if lazy web-settings reading fails during finalization.
    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))
    }

    /// Fast-forwards all remaining layout slices to completion on `document`.
    ///
    /// # Errors
    ///
    /// Returns an error if lazy web-settings reading fails during finalization.
    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 {
    /// Begins opening a [`PreparedDocument`] incrementally, returning a drawable [`Document`] as
    /// soon as Page 1 is ready along with an optional [`LayoutContinuation`] if more pages or a
    /// second pass remain.
    ///
    /// # Errors
    ///
    /// Returns an error if layout fails.
    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,
                initial_text_blocks,
                text_block_pages,
                initial_text_map,
                text_map_delta,
                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 mut text_blocks = initial_text_blocks.unwrap_or_default();
                for (idx, span) in text_block_pages {
                    if let Some(block) = text_blocks.get_mut(idx) {
                        block.page_indices = Some(span);
                    }
                }
                let mut text_map = initial_text_map.unwrap_or_default();
                if let Some(delta) = text_map_delta {
                    text_map.extend_delta(delta);
                }
                let doc = Self {
                    list,
                    #[cfg(any(test, feature = "development"))]
                    lines: Vec::new(),
                    #[cfg(any(test, feature = "development"))]
                    tables: Vec::new(),
                    text_blocks,
                    text_map,
                    fidelity: crate::FidelityReport::default(),
                };
                let progress = LayoutProgress {
                    page_count,
                    invalidated_pages: Vec::new(),
                    blocks_done,
                    blocks_total,
                    pass,
                    complete: false,
                    warnings: None,
                };
                Ok((
                    Warned::new(doc, warnings),
                    Some(LayoutContinuation { inner: incremental }),
                    progress,
                ))
            }
            LayoutStep::Finished {
                laid_out,
                blocks_total,
                pass,
            } => {
                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: blocks_total,
                    blocks_total,
                    pass,
                    complete: true,
                    warnings: Some(warnings.clone()),
                };
                Ok((Warned::new(doc, warnings), None, progress))
            }
        }
    }
}

fn apply_step(document: &mut Document, step: LayoutStep) -> LayoutProgress {
    match step {
        LayoutStep::Progress {
            new_pages,
            initial_text_blocks,
            text_block_pages,
            initial_text_map,
            text_map_delta,
            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) = initial_text_blocks {
                document.text_blocks = tb;
            }
            for (idx, span) in text_block_pages {
                if let Some(block) = document.text_blocks.get_mut(idx) {
                    block.page_indices = Some(span);
                }
            }
            if let Some(tm) = initial_text_map {
                document.text_map = tm;
            }
            if let Some(delta) = text_map_delta {
                document.text_map.extend_delta(delta);
            }
            LayoutProgress {
                page_count: document.page_count(),
                invalidated_pages: Vec::new(),
                blocks_done,
                blocks_total,
                pass,
                complete: false,
                warnings: None,
            }
        }
        LayoutStep::Finished {
            laid_out,
            blocks_total,
            pass,
        } => {
            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: blocks_total,
                blocks_total,
                pass,
                complete: true,
                warnings: Some(warnings),
            }
        }
    }
}

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
}

pub(crate) 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,
        matched_fonts,
    } = laid_out.value;
    #[cfg(any(test, feature = "development"))]
    let f_office_docx::LaidOut {
        list,
        lines,
        text_blocks,
        text_map,
        tables,
        writer,
        matched_fonts,
    } = laid_out.value;
    let list = post_process_list(list, &writer, &mut warnings);
    let fidelity = crate::FidelityReport::from_parts(&matched_fonts, &warnings);
    let doc = Document {
        list,
        #[cfg(any(test, feature = "development"))]
        lines,
        #[cfg(any(test, feature = "development"))]
        tables,
        text_blocks,
        text_map,
        fidelity,
    };
    (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),
    }
}