Skip to main content

f_office/
incremental.rs

1//! Staged single-parse preparation (`PreparedDocument`) and resumable Page-1-first document
2//! opening (`LayoutContinuation`) built on `f_office_docx::IncrementalLayout`.
3
4use std::sync::Arc;
5
6use f_office_docx::{IncrementalLayout, LayoutStep, PreparedDocx};
7use f_office_fonts::FontDb;
8use f_office_opc::Package;
9use f_office_paint::DisplayList;
10
11use crate::{
12    ArtPictures, Document, Error, Options, RandomAccessRead, Warned, Warning, Warnings, pictures,
13};
14
15/// Progress summary returned by [`Document::begin_open_prepared`] and [`LayoutContinuation::step`].
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub struct LayoutProgress {
18    /// Total pages currently available on the [`Document`].
19    pub page_count: usize,
20    /// Zero-based indices of previously emitted pages whose content changed on finalization.
21    pub invalidated_pages: Vec<usize>,
22    /// Approximate body blocks processed in the active layout pass.
23    pub blocks_done: usize,
24    /// Total body blocks in the document.
25    pub blocks_total: usize,
26    /// Active layout pass (1 for initial streaming pass, 2+ for cross-reference/wrap passes).
27    pub pass: u8,
28    /// Whether all layout passes have completed and the [`Document`] holds final pages.
29    pub complete: bool,
30    /// Final accumulated warnings once `complete` is `true`, or `None` while layout is in progress.
31    pub warnings: Option<Warnings>,
32}
33
34/// A DOCX file opened and parsed once, ready for fast font discovery and incremental layout.
35#[derive(Debug)]
36pub struct PreparedDocument {
37    inner: PreparedDocx,
38}
39
40impl PreparedDocument {
41    /// Opens and parses `docx` once for `options`.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error when the package, XML, or configuration cannot be read.
46    pub fn open(docx: &[u8], options: &Options) -> Result<Self, Error> {
47        let package = f_office_docx::timing::span("open", || Package::open(docx, &options.limits))
48            .map_err(Error::Package)?;
49        Self::from_package(package, options)
50    }
51
52    /// Opens and parses a random-access DOCX `source` once for `options`.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error when the package, XML, or configuration cannot be read.
57    pub fn open_source(
58        source: Arc<dyn RandomAccessRead>,
59        options: &Options,
60    ) -> Result<Self, Error> {
61        let package =
62            f_office_docx::timing::span("open", || Package::open_source(source, &options.limits))
63                .map_err(Error::Package)?;
64        Self::from_package(package, options)
65    }
66
67    fn from_package(package: Package, options: &Options) -> Result<Self, Error> {
68        let inner = PreparedDocx::open(package, &options.layout()).map_err(map_docx_error)?;
69        Ok(Self { inner })
70    }
71
72    /// Quickly scans the parsed document for `(asked, tried)` font needs without running a dummy
73    /// full-document layout pass.
74    #[must_use]
75    pub fn font_needs(&self) -> Vec<(Option<String>, Vec<String>)> {
76        self.inner.font_needs()
77    }
78
79    /// Number of top-level blocks in the document body.
80    #[must_use]
81    pub fn block_count(&self) -> usize {
82        self.inner.block_count()
83    }
84}
85
86/// Resumable layout continuation driving remaining pages of an incrementally opened [`Document`].
87#[derive(Debug)]
88pub struct LayoutContinuation {
89    inner: IncrementalLayout,
90}
91
92impl LayoutContinuation {
93    /// Advances pagination by up to `max_new_pages` newly completed pages (on Pass 1) or
94    /// `max_blocks` body blocks, appending newly finished pages directly onto `document`.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error if lazy web-settings reading fails during finalization.
99    pub fn step(
100        &mut self,
101        document: &mut Document,
102        fonts: &FontDb,
103        art: &ArtPictures,
104        max_new_pages: Option<usize>,
105        max_blocks: usize,
106    ) -> Result<LayoutProgress, Error> {
107        let step = self
108            .inner
109            .step((fonts, art), max_new_pages, max_blocks)
110            .map_err(map_docx_error)?;
111        Ok(apply_step(document, step))
112    }
113
114    /// Fast-forwards all remaining layout slices to completion on `document`.
115    ///
116    /// # Errors
117    ///
118    /// Returns an error if lazy web-settings reading fails during finalization.
119    pub fn finish(
120        mut self,
121        document: &mut Document,
122        fonts: &FontDb,
123        art: &ArtPictures,
124    ) -> Result<LayoutProgress, Error> {
125        let mut invalidated = Vec::new();
126        loop {
127            let progress = self.step(document, fonts, art, None, usize::MAX)?;
128            for page in progress.invalidated_pages {
129                if !invalidated.contains(&page) {
130                    invalidated.push(page);
131                }
132            }
133            if progress.complete {
134                return Ok(LayoutProgress {
135                    invalidated_pages: invalidated,
136                    ..progress
137                });
138            }
139        }
140    }
141}
142
143impl Document {
144    /// Begins opening a [`PreparedDocument`] incrementally, returning a drawable [`Document`] as
145    /// soon as Page 1 is ready along with an optional [`LayoutContinuation`] if more pages or a
146    /// second pass remain.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if layout fails.
151    pub fn begin_open_prepared(
152        prepared: PreparedDocument,
153        fonts: &FontDb,
154        art: &ArtPictures,
155    ) -> Result<(Warned<Self>, Option<LayoutContinuation>, LayoutProgress), Error> {
156        let mut incremental = prepared.inner.into_incremental();
157        let step = incremental
158            .step((fonts, art), Some(1), usize::MAX)
159            .map_err(map_docx_error)?;
160        match step {
161            LayoutStep::Progress {
162                new_pages,
163                initial_text_blocks,
164                text_block_pages,
165                initial_text_map,
166                text_map_delta,
167                writer,
168                blocks_done,
169                blocks_total,
170                pass,
171                ..
172            } => {
173                let mut warnings = Warnings::new();
174                let list = post_process_list(DisplayList::new(new_pages), &writer, &mut warnings);
175                let page_count = list.pages().len();
176                let mut text_blocks = initial_text_blocks.unwrap_or_default();
177                for (idx, span) in text_block_pages {
178                    if let Some(block) = text_blocks.get_mut(idx) {
179                        block.page_indices = Some(span);
180                    }
181                }
182                let mut text_map = initial_text_map.unwrap_or_default();
183                if let Some(delta) = text_map_delta {
184                    text_map.extend_delta(delta);
185                }
186                let doc = Self {
187                    list,
188                    #[cfg(any(test, feature = "development"))]
189                    lines: Vec::new(),
190                    #[cfg(any(test, feature = "development"))]
191                    tables: Vec::new(),
192                    text_blocks,
193                    text_map,
194                    fidelity: crate::FidelityReport::default(),
195                };
196                let progress = LayoutProgress {
197                    page_count,
198                    invalidated_pages: Vec::new(),
199                    blocks_done,
200                    blocks_total,
201                    pass,
202                    complete: false,
203                    warnings: None,
204                };
205                Ok((
206                    Warned::new(doc, warnings),
207                    Some(LayoutContinuation { inner: incremental }),
208                    progress,
209                ))
210            }
211            LayoutStep::Finished {
212                laid_out,
213                blocks_total,
214                pass,
215            } => {
216                let (doc, warnings) = finish_laid_out(laid_out);
217                let page_count = doc.page_count();
218                let progress = LayoutProgress {
219                    page_count,
220                    invalidated_pages: Vec::new(),
221                    blocks_done: blocks_total,
222                    blocks_total,
223                    pass,
224                    complete: true,
225                    warnings: Some(warnings.clone()),
226                };
227                Ok((Warned::new(doc, warnings), None, progress))
228            }
229        }
230    }
231}
232
233fn apply_step(document: &mut Document, step: LayoutStep) -> LayoutProgress {
234    match step {
235        LayoutStep::Progress {
236            new_pages,
237            initial_text_blocks,
238            text_block_pages,
239            initial_text_map,
240            text_map_delta,
241            writer,
242            blocks_done,
243            blocks_total,
244            pass,
245            ..
246        } => {
247            if !new_pages.is_empty() {
248                let mut warnings = Warnings::new();
249                let batch = post_process_list(DisplayList::new(new_pages), &writer, &mut warnings);
250                let mut pages = std::mem::replace(&mut document.list, DisplayList::new(Vec::new()))
251                    .into_pages();
252                pages.extend(batch.into_pages());
253                document.list = DisplayList::new(pages);
254            }
255            if let Some(tb) = initial_text_blocks {
256                document.text_blocks = tb;
257            }
258            for (idx, span) in text_block_pages {
259                if let Some(block) = document.text_blocks.get_mut(idx) {
260                    block.page_indices = Some(span);
261                }
262            }
263            if let Some(tm) = initial_text_map {
264                document.text_map = tm;
265            }
266            if let Some(delta) = text_map_delta {
267                document.text_map.extend_delta(delta);
268            }
269            LayoutProgress {
270                page_count: document.page_count(),
271                invalidated_pages: Vec::new(),
272                blocks_done,
273                blocks_total,
274                pass,
275                complete: false,
276                warnings: None,
277            }
278        }
279        LayoutStep::Finished {
280            laid_out,
281            blocks_total,
282            pass,
283        } => {
284            let (final_doc, warnings) = finish_laid_out(laid_out);
285            let invalidated_pages: Vec<usize> = document
286                .list
287                .pages()
288                .iter()
289                .zip(final_doc.list.pages())
290                .enumerate()
291                .filter_map(|(idx, (old, new))| (old != new).then_some(idx))
292                .collect();
293            *document = final_doc;
294            let page_count = document.page_count();
295            LayoutProgress {
296                page_count,
297                invalidated_pages,
298                blocks_done: blocks_total,
299                blocks_total,
300                pass,
301                complete: true,
302                warnings: Some(warnings),
303            }
304        }
305    }
306}
307
308fn post_process_list(
309    mut list: DisplayList,
310    writer: &f_office_paint::Writer,
311    warnings: &mut Warnings,
312) -> DisplayList {
313    writer.finish(&mut list);
314    list = pictures::write_pictures_again(
315        list,
316        pictures::Rewriting {
317            quality: writer.jpeg_quality(),
318            jpeg_share: writer.jpeg_share(),
319            jpeg_sample: writer.jpeg_sample(),
320            crop: writer.picture_crop(),
321            alpha_mix: writer.alpha_mix(),
322            resampling: &|pixels, palette, image| {
323                writer.resampled_size(pixels, (image.width, image.height), palette)
324            },
325        },
326        warnings,
327    );
328    writer.place_pictures(&mut list);
329    list
330}
331
332pub(crate) fn finish_laid_out(
333    laid_out: f_office_docx::Warned<f_office_docx::LaidOut>,
334) -> (Document, Warnings) {
335    let mut warnings = laid_out.warnings.map(Warning::Docx);
336    #[cfg(not(any(test, feature = "development")))]
337    let f_office_docx::LaidOut {
338        list,
339        lines: _,
340        text_blocks,
341        text_map,
342        tables: _,
343        writer,
344        matched_fonts,
345    } = laid_out.value;
346    #[cfg(any(test, feature = "development"))]
347    let f_office_docx::LaidOut {
348        list,
349        lines,
350        text_blocks,
351        text_map,
352        tables,
353        writer,
354        matched_fonts,
355    } = laid_out.value;
356    let list = post_process_list(list, &writer, &mut warnings);
357    let fidelity = crate::FidelityReport::from_parts(&matched_fonts, &warnings);
358    let doc = Document {
359        list,
360        #[cfg(any(test, feature = "development"))]
361        lines,
362        #[cfg(any(test, feature = "development"))]
363        tables,
364        text_blocks,
365        text_map,
366        fidelity,
367    };
368    (doc, warnings)
369}
370
371fn map_docx_error(error: f_office_docx::Error) -> Error {
372    match error {
373        f_office_docx::Error::Configuration(error) => Error::Configuration(error),
374        error => Error::Docx(error),
375    }
376}