f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! The text map of a laid out document: the text of each story by paragraph, and the lines of
//! each page with their range of that text and the edges of their clusters, for a viewer that
//! selects, copies and searches the text of drawn pages.

use std::collections::HashMap;
use std::collections::hash_map::Entry;

use f_office_units::Length;

use crate::body::ParagraphId;
use crate::body::links::LinkTarget;
use crate::layout::{
    CellPlace, LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, RunSpan, StoryPart,
    TextCluster,
};
use crate::lines::EndHyphen;
use crate::text_blocks::Address;
use crate::text_links::RunMarks;

/// A story of the text map (**Story**): text that reads on by itself, and that a selection
/// stays in. The stories of one page compare in their reading order: the header, the body, the
/// endnotes, the frames, the text boxes, the footnotes and the footer, and the frames and the
/// text boxes each in the order of their layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TextStory {
    /// The header of a page.
    Header {
        /// The index of the page, from 0.
        page: usize,
    },
    /// The main text of the document.
    Body,
    /// The endnotes, in the order of their pages.
    Endnotes,
    /// The content of a frame of the body.
    Frame {
        /// The index of its page, from 0.
        page: usize,
        /// Its number among the frames and text boxes of the document, in the order of their
        /// layout.
        number: u32,
    },
    /// The text of a text box or a shape.
    TextBox {
        /// The index of its page, from 0.
        page: usize,
        /// Its number among the frames and text boxes of the document, in the order of their
        /// layout.
        number: u32,
    },
    /// The footnotes, in the order of their pages.
    Footnotes,
    /// The footer of a page.
    Footer {
        /// The index of the page, from 0.
        page: usize,
    },
}

impl TextStory {
    /// The stories that run over the pages of the document; the others lie on one page each.
    pub const RUNNING: [Self; 3] = [Self::Body, Self::Footnotes, Self::Endnotes];

    /// The story of a placed line.
    const fn of_placed(line: &PlacedLine) -> Self {
        Self::from_parts(line.page, line.story, line.part)
    }

    /// The story of a compact line. A frame or text box of a header, a footer or a footnote reads
    /// in that story.
    const fn of_compact(line: &CompactLine) -> Self {
        Self::from_parts(line.page, line.story, line.part)
    }

    const fn from_parts(page: usize, story: LineStory, part: StoryPart) -> Self {
        match (story, part) {
            (LineStory::Header, _) => Self::Header { page },
            (LineStory::Footer, _) => Self::Footer { page },
            (LineStory::Footnote, _) => Self::Footnotes,
            (LineStory::Body | LineStory::TextBox, StoryPart::Endnotes) => Self::Endnotes,
            (LineStory::Body | LineStory::TextBox, StoryPart::Frame(number)) => {
                Self::Frame { page, number }
            }
            (LineStory::Body | LineStory::TextBox, StoryPart::TextBox(number)) => {
                Self::TextBox { page, number }
            }
            (LineStory::Body, StoryPart::Own) => Self::Body,
            (LineStory::TextBox, StoryPart::Own) => Self::TextBox { page, number: 0 },
        }
    }
}

/// A paragraph of a story's text (**Story text**): the texts of its laid out lines joined, so
/// that a field gives its shown result, a list label is given as drawn, hidden text is left out
/// and an automatic hyphen is not in it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StoryParagraph {
    /// Its address, which every paragraph of a story has but a note separator's.
    pub address: Option<Address>,
    /// The table cell that it lies in, when it lies in one.
    pub cell: Option<CellPlace>,
    /// Its text: the characters of its glyphs, a tab as `\t`, a line, page or column break as
    /// `\n` and an inline object as U+FFFC.
    pub text: String,
    /// The hyperlinks in its text, in the order of their starts, a link before the links inside
    /// it.
    pub links: Vec<StoryLink>,
    /// The bookmarks that start in it, in order.
    pub bookmarks: Vec<StoryBookmark>,
}

/// A hyperlink in a paragraph's story text (**Story link**): the bytes of the text that show
/// it, from its first to its last glyph, where it goes and its tooltip.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct StoryLink {
    /// The first byte of the paragraph's text that shows it.
    pub start_byte: u32,
    /// The byte after the last that shows it.
    pub end_byte: u32,
    /// Where it goes.
    pub target: LinkTarget,
    /// Its tooltip, as the document gives it.
    pub tooltip: Option<String>,
}

impl StoryLink {
    /// The link to `target` with the tooltip `tooltip` that the bytes `start_byte` to
    /// `end_byte` of a paragraph's text show.
    pub(crate) const fn new(
        start_byte: u32,
        end_byte: u32,
        target: LinkTarget,
        tooltip: Option<String>,
    ) -> Self {
        Self {
            start_byte,
            end_byte,
            target,
            tooltip,
        }
    }
}

/// A bookmark that starts in a paragraph's story text (**Story bookmark**), at a byte of it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct StoryBookmark {
    /// Its name.
    pub name: String,
    /// The byte of the paragraph's text where it starts: the first glyph after its start, or
    /// the end of the text.
    pub offset_byte: u32,
}

impl StoryBookmark {
    /// The bookmark `name` that starts at the byte `offset_byte` of a paragraph's text.
    pub(crate) const fn new(name: String, offset_byte: u32) -> Self {
        Self { name, offset_byte }
    }
}

/// A line of a page's text map: its story and paragraph, its range of the paragraph's text, its
/// line box and its clusters.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextLine {
    /// The story that it belongs to.
    pub story: TextStory,
    /// The index of its paragraph among the paragraphs of its story's text.
    pub paragraph: usize,
    /// The first byte of the paragraph's text that it shows.
    pub start: u32,
    /// The byte after the last that it shows.
    pub end: u32,
    /// The top of its line box on the page: of the line, not of its glyphs, so that the boxes of
    /// consecutive lines meet.
    pub top: Length,
    /// The height of its line box.
    pub height: Length,
    /// The offset of its baseline from its top.
    pub baseline: Length,
    /// Its clusters in visual order, from the left, each with its range of the paragraph's text.
    pub clusters: Vec<TextCluster>,
    /// The left edge of its text on the page: its first cluster's left edge, or for a line
    /// without a cluster, such as the line of an empty paragraph, where the line starts after
    /// its indent and alignment.
    pub left: Length,
    /// How it ends.
    pub ends: LineTextEnd,
    /// The hyphen that it draws at its end where a word breaks, at an automatic hyphenation
    /// point or a soft hyphen, which the text does not hold.
    pub hyphen: Option<EndHyphen>,
    /// For a line of a frame that turned onto the page, such as a line of a table cell with a
    /// turned text direction, how the frame lies on the page. Its top, left edge and cluster
    /// edges are then places of the frame.
    pub turn: Option<LineTurn>,
}

/// Compact per-line entry retained by [`TextMap`]: keeps only the 9 fields required for reading,
/// selecting, and searching text, dropping layout diagnostics (`steps`, `drawn`, `Fit`, rests).
#[derive(Clone, Debug)]
struct CompactLine {
    paragraph: ParagraphId,
    page: usize,
    story: LineStory,
    part: StoryPart,
    cell: Option<CellPlace>,
    top: Length,
    height: Length,
    baseline: Length,
    text: LineText,
}

impl CompactLine {
    fn from_ref(line: &PlacedLine) -> Self {
        Self {
            paragraph: line.paragraph,
            page: line.page,
            story: line.story,
            part: line.part,
            cell: line.cell,
            top: line.top,
            height: line.height,
            baseline: line.baseline,
            text: line.text.clone(),
        }
    }

    fn from_owned(line: PlacedLine) -> Self {
        Self {
            paragraph: line.paragraph,
            page: line.page,
            story: line.story,
            part: line.part,
            cell: line.cell,
            top: line.top,
            height: line.height,
            baseline: line.baseline,
            text: line.text,
        }
    }
}

/// Incremental batch of compact lines produced by one [`crate::IncrementalLayout::step`] slice.
#[derive(Clone, Debug, Default)]
pub struct TextMapDelta(Vec<CompactLine>);

impl TextMapDelta {
    /// Whether this delta contains no lines.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Self-contained compact reading-order text index of a laid-out document: holds paragraph
/// addresses, hyperlinks/bookmarks, and compact per-line text/cluster metadata without retaining
/// full [`PlacedLine`] layout diagnostics.
#[derive(Clone, Debug, Default)]
pub struct TextMap {
    addresses: HashMap<ParagraphId, Address>,
    marks: HashMap<ParagraphId, RunMarks>,
    lines: Vec<CompactLine>,
}

impl TextMap {
    /// Initializes an empty [`TextMap`] from precomputed paragraph addresses and marks, ready to
    /// receive [`TextMapDelta`] batches during incremental layout.
    pub(crate) fn from_paragraphs(
        (addresses, marks): (
            HashMap<ParagraphId, Address>,
            HashMap<ParagraphId, RunMarks>,
        ),
    ) -> Self {
        Self {
            addresses,
            marks,
            lines: Vec::new(),
        }
    }

    /// Converts a newly placed batch of lines into a compact [`TextMapDelta`] without cloning any
    /// lines from earlier slices.
    pub(crate) fn delta_from_placed(placed: Vec<PlacedLine>) -> TextMapDelta {
        let (upright, turned) = turned_apart(placed);
        let mut turned = turned.into_iter().peekable();
        let mut lines = Vec::with_capacity(upright.len() + turned.len());
        for (index, line) in upright.into_iter().enumerate() {
            while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
                lines.push(CompactLine::from_owned(before));
            }
            lines.push(CompactLine::from_owned(line));
        }
        lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
        TextMapDelta(lines)
    }

    /// Appends a [`TextMapDelta`] produced by an incremental layout slice in `O(delta)` time.
    pub fn extend_delta(&mut self, delta: TextMapDelta) {
        self.lines.extend(delta.0);
    }

    /// Builds a self-contained [`TextMap`] from `addresses`, `marks`, upright `lines`, and
    /// `turned` lines (as returned by [`turned_apart`]), merged in reading order.
    pub(crate) fn new(
        (addresses, marks): (
            HashMap<ParagraphId, Address>,
            HashMap<ParagraphId, RunMarks>,
        ),
        upright: &[PlacedLine],
        turned: Vec<(usize, PlacedLine)>,
    ) -> Self {
        let mut turned = turned.into_iter().peekable();
        let mut lines = Vec::with_capacity(upright.len() + turned.len());
        for (index, line) in upright.iter().enumerate() {
            while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
                lines.push(CompactLine::from_owned(before));
            }
            lines.push(CompactLine::from_ref(line));
        }
        lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
        Self {
            addresses,
            marks,
            lines,
        }
    }

    /// The lines on `page` in reading order: the header, the body, the endnotes, the frames,
    /// the text boxes, the footnotes and the footer, and the lines of each story in the order
    /// of the layout, with table row cells reading in cell order.
    #[must_use]
    pub fn page(&self, page: usize) -> Vec<TextLine> {
        self.pages(&[page]).pop().unwrap_or_default()
    }

    /// The lines of each page of `pages` in reading order, as [`Self::page`] gives them, from
    /// one read of each story that has a line on one of them, so that a story that runs over
    /// many pages, such as the body, is read once for all of them. A page that `pages` names
    /// twice has its lines at its last place only.
    #[must_use]
    pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
        let slots: HashMap<usize, usize> = pages
            .iter()
            .enumerate()
            .map(|(slot, &page)| (page, slot))
            .collect();
        let mut stories: Vec<TextStory> = self
            .lines
            .iter()
            .filter(|line| slots.contains_key(&line.page))
            .map(TextStory::of_compact)
            .collect();
        stories.sort_unstable();
        stories.dedup();
        let mut maps = vec![Vec::new(); pages.len()];
        for story in stories {
            for (line, text_line) in self.read(story).lines {
                if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
                    map.push(text_line);
                }
            }
        }
        maps
    }

    /// The text of `story` by paragraph.
    #[must_use]
    pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
        self.read(story).paragraphs
    }

    /// Reads the lines of `story` into its paragraphs and text lines. The paragraphs come in the
    /// order of their first lines, so the lines of a paragraph that another paragraph's lines
    /// interrupt still join.
    fn read(&self, story: TextStory) -> Read<'_> {
        let mut read = Read::default();
        let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
        // The paragraph and the run spans of each paragraph of `read`, in its text.
        let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
        for line in self
            .lines
            .iter()
            .filter(|line| TextStory::of_compact(line) == story)
        {
            let text = &line.text;
            let paragraph = match indices.entry(line.paragraph) {
                Entry::Occupied(entry) => *entry.get(),
                Entry::Vacant(entry) => {
                    read.paragraphs.push(StoryParagraph {
                        address: self.addresses.get(&line.paragraph).cloned(),
                        cell: line.cell,
                        ..StoryParagraph::default()
                    });
                    spans.push((line.paragraph, Vec::new()));
                    *entry.insert(read.paragraphs.len() - 1)
                }
            };
            let Some(own) = read.paragraphs.get_mut(paragraph) else {
                continue;
            };
            let start = text_offset(own.text.len());
            own.text.push_str(&text.text);
            if let Some((_, own_spans)) = spans.get_mut(paragraph) {
                own_spans.extend(text.runs.iter().map(|span| RunSpan {
                    start: span.start.saturating_add(start),
                    end: span.end.saturating_add(start),
                    run: span.run,
                }));
            }
            read.lines
                .push((line, text_line(line, text, (story, paragraph), start)));
        }
        for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
            if let Some(marks) = self.marks.get(id) {
                (own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
            }
        }
        // The last line of a cell's last paragraph ends the cell.
        let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
        for (_, text_line) in &mut read.lines {
            let paragraph = text_line.paragraph;
            let cell = cells.get(paragraph).copied().flatten();
            let next = cells.get(paragraph + 1).copied().flatten();
            if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
                text_line.ends = LineTextEnd::Cell;
            }
        }
        read
    }
}

/// The paragraphs and the text lines of one story, each line with the compact line that it is
/// read from.
#[derive(Default)]
struct Read<'a> {
    paragraphs: Vec<StoryParagraph>,
    lines: Vec<(&'a CompactLine, TextLine)>,
}

/// The text line of `line`, whose text `text` starts at `start` in the text of the paragraph
/// `paragraph` of `story`.
fn text_line(
    line: &CompactLine,
    text: &LineText,
    (story, paragraph): (TextStory, usize),
    start: u32,
) -> TextLine {
    TextLine {
        story,
        paragraph,
        start,
        end: start + text_offset(text.text.len()),
        top: line.top,
        height: line.height,
        baseline: line.baseline,
        clusters: text
            .clusters
            .iter()
            .map(|cluster| TextCluster {
                start: start + cluster.start,
                end: start + cluster.end,
                ..*cluster
            })
            .collect(),
        left: text.left,
        ends: text.end,
        hyphen: text.hyphen,
        turn: text.turn,
    }
}

/// The upright lines of `lines`, the lines of a layout pass in the order of the layout, and its
/// turned lines, each with the index among the upright lines of the line before which it reads.
/// The layout turns the turned cells of a row one after another, after its upright cells, so
/// the lines of a turned cell read before the first earlier line of their story in a later cell
/// of the row; with no such line, where the layout placed them.
pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
    let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
    let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
    let mut run: Vec<PlacedLine> = Vec::new();
    for line in lines {
        if line.upright() {
            turned.extend(place_run(&upright, std::mem::take(&mut run)));
            upright.push(line);
        } else {
            run.push(line);
        }
    }
    turned.extend(place_run(&upright, run));
    turned.sort_by_key(|&(before, _)| before);
    (upright, turned)
}

/// The lines of `run`, turned lines that the layout placed one after another after the
/// upright lines `upright`, each with the index of the upright line before which it reads. A
/// line of a table nested in a turned cell reads with the cell, the cell of the run's table
/// that the last line before it, or else the first line after it, lies in: the outer table,
/// which starts before the tables nested in it, has the run's least number.
fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
    let outer = run
        .iter()
        .filter_map(|line| line.cell)
        .map(|cell| cell.table)
        .min();
    let of_outer = |line: &PlacedLine| {
        line.cell
            .filter(|cell| Some(cell.table) == outer)
            .map(|cell| (cell, TextStory::of_placed(line)))
    };
    let mut frame = run.iter().find_map(of_outer);
    let mut found: Option<((CellPlace, TextStory), usize)> = None;
    let mut placed = Vec::with_capacity(run.len());
    for line in run {
        frame = of_outer(&line).or(frame);
        let before = match (frame, found) {
            (Some(cell), Some((known, before))) if known == cell => before,
            (Some(cell), _) => {
                let before = before_later_cells(upright, cell);
                found = Some((cell, before));
                before
            }
            (None, _) => upright.len(),
        };
        placed.push((before, line));
    }
    placed
}

/// The index among `upright` of the first line of `story` in a later cell of the row of `cell`
/// than `cell`, searched back from the end to the first line of an earlier row of its table;
/// the end when there is none.
fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
    let mut before = upright.len();
    for (index, other) in upright.iter().enumerate().rev() {
        let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
            continue;
        };
        if other_cell.table == cell.table && other_cell.row < cell.row {
            break;
        }
        if other_cell.table == cell.table
            && other_cell.row == cell.row
            && other_cell.column > cell.column
        {
            before = index;
        }
    }
    before
}

/// A byte offset of the text of a line or a paragraph, which is far shorter than 2^32 bytes.
pub(crate) fn text_offset(bytes: usize) -> u32 {
    u32::try_from(bytes).unwrap_or(u32::MAX)
}