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