Skip to main content

f_office_docx/
text_map.rs

1//! The text map of a laid out document: the text of each story by paragraph, and the lines of
2//! each page with their range of that text and the edges of their clusters, for a viewer that
3//! selects, copies and searches the text of drawn pages.
4
5use std::collections::HashMap;
6use std::collections::hash_map::Entry;
7
8use f_office_units::Length;
9
10use crate::body::ParagraphId;
11use crate::body::links::LinkTarget;
12use crate::layout::{
13    CellPlace, LineStory, LineText, LineTextEnd, LineTurn, PlacedLine, RunSpan, StoryPart,
14    TextCluster,
15};
16use crate::lines::EndHyphen;
17use crate::text_blocks::Address;
18use crate::text_links::RunMarks;
19
20/// A story of the text map (**Story**): text that reads on by itself, and that a selection
21/// stays in. The stories of one page compare in their reading order: the header, the body, the
22/// endnotes, the frames, the text boxes, the footnotes and the footer, and the frames and the
23/// text boxes each in the order of their layout.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub enum TextStory {
26    /// The header of a page.
27    Header {
28        /// The index of the page, from 0.
29        page: usize,
30    },
31    /// The main text of the document.
32    Body,
33    /// The endnotes, in the order of their pages.
34    Endnotes,
35    /// The content of a frame of the body.
36    Frame {
37        /// The index of its page, from 0.
38        page: usize,
39        /// Its number among the frames and text boxes of the document, in the order of their
40        /// layout.
41        number: u32,
42    },
43    /// The text of a text box or a shape.
44    TextBox {
45        /// The index of its page, from 0.
46        page: usize,
47        /// Its number among the frames and text boxes of the document, in the order of their
48        /// layout.
49        number: u32,
50    },
51    /// The footnotes, in the order of their pages.
52    Footnotes,
53    /// The footer of a page.
54    Footer {
55        /// The index of the page, from 0.
56        page: usize,
57    },
58}
59
60impl TextStory {
61    /// The stories that run over the pages of the document; the others lie on one page each.
62    pub const RUNNING: [Self; 3] = [Self::Body, Self::Footnotes, Self::Endnotes];
63
64    /// The story of a placed line.
65    const fn of_placed(line: &PlacedLine) -> Self {
66        Self::from_parts(line.page, line.story, line.part)
67    }
68
69    /// The story of a compact line. A frame or text box of a header, a footer or a footnote reads
70    /// in that story.
71    const fn of_compact(line: &CompactLine) -> Self {
72        Self::from_parts(line.page, line.story, line.part)
73    }
74
75    const fn from_parts(page: usize, story: LineStory, part: StoryPart) -> Self {
76        match (story, part) {
77            (LineStory::Header, _) => Self::Header { page },
78            (LineStory::Footer, _) => Self::Footer { page },
79            (LineStory::Footnote, _) => Self::Footnotes,
80            (LineStory::Body | LineStory::TextBox, StoryPart::Endnotes) => Self::Endnotes,
81            (LineStory::Body | LineStory::TextBox, StoryPart::Frame(number)) => {
82                Self::Frame { page, number }
83            }
84            (LineStory::Body | LineStory::TextBox, StoryPart::TextBox(number)) => {
85                Self::TextBox { page, number }
86            }
87            (LineStory::Body, StoryPart::Own) => Self::Body,
88            (LineStory::TextBox, StoryPart::Own) => Self::TextBox { page, number: 0 },
89        }
90    }
91}
92
93/// A paragraph of a story's text (**Story text**): the texts of its laid out lines joined, so
94/// that a field gives its shown result, a list label is given as drawn, hidden text is left out
95/// and an automatic hyphen is not in it.
96#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct StoryParagraph {
98    /// Its address, which every paragraph of a story has but a note separator's.
99    pub address: Option<Address>,
100    /// The table cell that it lies in, when it lies in one.
101    pub cell: Option<CellPlace>,
102    /// Its text: the characters of its glyphs, a tab as `\t`, a line, page or column break as
103    /// `\n` and an inline object as U+FFFC.
104    pub text: String,
105    /// The hyperlinks in its text, in the order of their starts, a link before the links inside
106    /// it.
107    pub links: Vec<StoryLink>,
108    /// The bookmarks that start in it, in order.
109    pub bookmarks: Vec<StoryBookmark>,
110}
111
112/// A hyperlink in a paragraph's story text (**Story link**): the bytes of the text that show
113/// it, from its first to its last glyph, where it goes and its tooltip.
114#[derive(Clone, Debug, PartialEq, Eq)]
115#[non_exhaustive]
116pub struct StoryLink {
117    /// The first byte of the paragraph's text that shows it.
118    pub start_byte: u32,
119    /// The byte after the last that shows it.
120    pub end_byte: u32,
121    /// Where it goes.
122    pub target: LinkTarget,
123    /// Its tooltip, as the document gives it.
124    pub tooltip: Option<String>,
125}
126
127impl StoryLink {
128    /// The link to `target` with the tooltip `tooltip` that the bytes `start_byte` to
129    /// `end_byte` of a paragraph's text show.
130    pub(crate) const fn new(
131        start_byte: u32,
132        end_byte: u32,
133        target: LinkTarget,
134        tooltip: Option<String>,
135    ) -> Self {
136        Self {
137            start_byte,
138            end_byte,
139            target,
140            tooltip,
141        }
142    }
143}
144
145/// A bookmark that starts in a paragraph's story text (**Story bookmark**), at a byte of it.
146#[derive(Clone, Debug, PartialEq, Eq)]
147#[non_exhaustive]
148pub struct StoryBookmark {
149    /// Its name.
150    pub name: String,
151    /// The byte of the paragraph's text where it starts: the first glyph after its start, or
152    /// the end of the text.
153    pub offset_byte: u32,
154}
155
156impl StoryBookmark {
157    /// The bookmark `name` that starts at the byte `offset_byte` of a paragraph's text.
158    pub(crate) const fn new(name: String, offset_byte: u32) -> Self {
159        Self { name, offset_byte }
160    }
161}
162
163/// A line of a page's text map: its story and paragraph, its range of the paragraph's text, its
164/// line box and its clusters.
165#[derive(Clone, Debug, PartialEq, Eq)]
166pub struct TextLine {
167    /// The story that it belongs to.
168    pub story: TextStory,
169    /// The index of its paragraph among the paragraphs of its story's text.
170    pub paragraph: usize,
171    /// The first byte of the paragraph's text that it shows.
172    pub start: u32,
173    /// The byte after the last that it shows.
174    pub end: u32,
175    /// The top of its line box on the page: of the line, not of its glyphs, so that the boxes of
176    /// consecutive lines meet.
177    pub top: Length,
178    /// The height of its line box.
179    pub height: Length,
180    /// The offset of its baseline from its top.
181    pub baseline: Length,
182    /// Its clusters in visual order, from the left, each with its range of the paragraph's text.
183    pub clusters: Vec<TextCluster>,
184    /// The left edge of its text on the page: its first cluster's left edge, or for a line
185    /// without a cluster, such as the line of an empty paragraph, where the line starts after
186    /// its indent and alignment.
187    pub left: Length,
188    /// How it ends.
189    pub ends: LineTextEnd,
190    /// The hyphen that it draws at its end where a word breaks, at an automatic hyphenation
191    /// point or a soft hyphen, which the text does not hold.
192    pub hyphen: Option<EndHyphen>,
193    /// For a line of a frame that turned onto the page, such as a line of a table cell with a
194    /// turned text direction, how the frame lies on the page. Its top, left edge and cluster
195    /// edges are then places of the frame.
196    pub turn: Option<LineTurn>,
197}
198
199/// Compact per-line entry retained by [`TextMap`]: keeps only the 9 fields required for reading,
200/// selecting, and searching text, dropping layout diagnostics (`steps`, `drawn`, `Fit`, rests).
201#[derive(Clone, Debug)]
202struct CompactLine {
203    paragraph: ParagraphId,
204    page: usize,
205    story: LineStory,
206    part: StoryPart,
207    cell: Option<CellPlace>,
208    top: Length,
209    height: Length,
210    baseline: Length,
211    text: LineText,
212}
213
214impl CompactLine {
215    fn from_ref(line: &PlacedLine) -> Self {
216        Self {
217            paragraph: line.paragraph,
218            page: line.page,
219            story: line.story,
220            part: line.part,
221            cell: line.cell,
222            top: line.top,
223            height: line.height,
224            baseline: line.baseline,
225            text: line.text.clone(),
226        }
227    }
228
229    fn from_owned(line: PlacedLine) -> Self {
230        Self {
231            paragraph: line.paragraph,
232            page: line.page,
233            story: line.story,
234            part: line.part,
235            cell: line.cell,
236            top: line.top,
237            height: line.height,
238            baseline: line.baseline,
239            text: line.text,
240        }
241    }
242}
243
244/// Self-contained compact reading-order text index of a laid-out document: holds paragraph
245/// addresses, hyperlinks/bookmarks, and compact per-line text/cluster metadata without retaining
246/// full [`PlacedLine`] layout diagnostics.
247#[derive(Clone, Debug, Default)]
248pub struct TextMap {
249    addresses: HashMap<ParagraphId, Address>,
250    marks: HashMap<ParagraphId, RunMarks>,
251    lines: Vec<CompactLine>,
252}
253
254impl TextMap {
255    /// Builds a self-contained [`TextMap`] from `addresses`, `marks`, upright `lines`, and
256    /// `turned` lines (as returned by [`turned_apart`]), merged in reading order.
257    pub(crate) fn new(
258        (addresses, marks): (
259            HashMap<ParagraphId, Address>,
260            HashMap<ParagraphId, RunMarks>,
261        ),
262        upright: &[PlacedLine],
263        turned: Vec<(usize, PlacedLine)>,
264    ) -> Self {
265        let mut turned = turned.into_iter().peekable();
266        let mut lines = Vec::with_capacity(upright.len() + turned.len());
267        for (index, line) in upright.iter().enumerate() {
268            while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
269                lines.push(CompactLine::from_owned(before));
270            }
271            lines.push(CompactLine::from_ref(line));
272        }
273        lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
274        Self {
275            addresses,
276            marks,
277            lines,
278        }
279    }
280
281    /// The lines on `page` in reading order: the header, the body, the endnotes, the frames,
282    /// the text boxes, the footnotes and the footer, and the lines of each story in the order
283    /// of the layout, with table row cells reading in cell order.
284    #[must_use]
285    pub fn page(&self, page: usize) -> Vec<TextLine> {
286        self.pages(&[page]).pop().unwrap_or_default()
287    }
288
289    /// The lines of each page of `pages` in reading order, as [`Self::page`] gives them, from
290    /// one read of each story that has a line on one of them, so that a story that runs over
291    /// many pages, such as the body, is read once for all of them. A page that `pages` names
292    /// twice has its lines at its last place only.
293    #[must_use]
294    pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
295        let slots: HashMap<usize, usize> = pages
296            .iter()
297            .enumerate()
298            .map(|(slot, &page)| (page, slot))
299            .collect();
300        let mut stories: Vec<TextStory> = self
301            .lines
302            .iter()
303            .filter(|line| slots.contains_key(&line.page))
304            .map(TextStory::of_compact)
305            .collect();
306        stories.sort_unstable();
307        stories.dedup();
308        let mut maps = vec![Vec::new(); pages.len()];
309        for story in stories {
310            for (line, text_line) in self.read(story).lines {
311                if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
312                    map.push(text_line);
313                }
314            }
315        }
316        maps
317    }
318
319    /// The text of `story` by paragraph.
320    #[must_use]
321    pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
322        self.read(story).paragraphs
323    }
324
325    /// Reads the lines of `story` into its paragraphs and text lines. The paragraphs come in the
326    /// order of their first lines, so the lines of a paragraph that another paragraph's lines
327    /// interrupt still join.
328    fn read(&self, story: TextStory) -> Read<'_> {
329        let mut read = Read::default();
330        let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
331        // The paragraph and the run spans of each paragraph of `read`, in its text.
332        let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
333        for line in self
334            .lines
335            .iter()
336            .filter(|line| TextStory::of_compact(line) == story)
337        {
338            let text = &line.text;
339            let paragraph = match indices.entry(line.paragraph) {
340                Entry::Occupied(entry) => *entry.get(),
341                Entry::Vacant(entry) => {
342                    read.paragraphs.push(StoryParagraph {
343                        address: self.addresses.get(&line.paragraph).cloned(),
344                        cell: line.cell,
345                        ..StoryParagraph::default()
346                    });
347                    spans.push((line.paragraph, Vec::new()));
348                    *entry.insert(read.paragraphs.len() - 1)
349                }
350            };
351            let Some(own) = read.paragraphs.get_mut(paragraph) else {
352                continue;
353            };
354            let start = text_offset(own.text.len());
355            own.text.push_str(&text.text);
356            if let Some((_, own_spans)) = spans.get_mut(paragraph) {
357                own_spans.extend(text.runs.iter().map(|span| RunSpan {
358                    start: span.start.saturating_add(start),
359                    end: span.end.saturating_add(start),
360                    run: span.run,
361                }));
362            }
363            read.lines
364                .push((line, text_line(line, text, (story, paragraph), start)));
365        }
366        for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
367            if let Some(marks) = self.marks.get(id) {
368                (own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
369            }
370        }
371        // The last line of a cell's last paragraph ends the cell.
372        let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
373        for (_, text_line) in &mut read.lines {
374            let paragraph = text_line.paragraph;
375            let cell = cells.get(paragraph).copied().flatten();
376            let next = cells.get(paragraph + 1).copied().flatten();
377            if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
378                text_line.ends = LineTextEnd::Cell;
379            }
380        }
381        read
382    }
383}
384
385/// The paragraphs and the text lines of one story, each line with the compact line that it is
386/// read from.
387#[derive(Default)]
388struct Read<'a> {
389    paragraphs: Vec<StoryParagraph>,
390    lines: Vec<(&'a CompactLine, TextLine)>,
391}
392
393/// The text line of `line`, whose text `text` starts at `start` in the text of the paragraph
394/// `paragraph` of `story`.
395fn text_line(
396    line: &CompactLine,
397    text: &LineText,
398    (story, paragraph): (TextStory, usize),
399    start: u32,
400) -> TextLine {
401    TextLine {
402        story,
403        paragraph,
404        start,
405        end: start + text_offset(text.text.len()),
406        top: line.top,
407        height: line.height,
408        baseline: line.baseline,
409        clusters: text
410            .clusters
411            .iter()
412            .map(|cluster| TextCluster {
413                start: start + cluster.start,
414                end: start + cluster.end,
415                ..*cluster
416            })
417            .collect(),
418        left: text.left,
419        ends: text.end,
420        hyphen: text.hyphen,
421        turn: text.turn,
422    }
423}
424
425/// The upright lines of `lines`, the lines of a layout pass in the order of the layout, and its
426/// turned lines, each with the index among the upright lines of the line before which it reads.
427/// The layout turns the turned cells of a row one after another, after its upright cells, so
428/// the lines of a turned cell read before the first earlier line of their story in a later cell
429/// of the row; with no such line, where the layout placed them.
430pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
431    let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
432    let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
433    let mut run: Vec<PlacedLine> = Vec::new();
434    for line in lines {
435        if line.upright() {
436            turned.extend(place_run(&upright, std::mem::take(&mut run)));
437            upright.push(line);
438        } else {
439            run.push(line);
440        }
441    }
442    turned.extend(place_run(&upright, run));
443    turned.sort_by_key(|&(before, _)| before);
444    (upright, turned)
445}
446
447/// The lines of `run`, turned lines that the layout placed one after another after the
448/// upright lines `upright`, each with the index of the upright line before which it reads. A
449/// line of a table nested in a turned cell reads with the cell, the cell of the run's table
450/// that the last line before it, or else the first line after it, lies in: the outer table,
451/// which starts before the tables nested in it, has the run's least number.
452fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
453    let outer = run
454        .iter()
455        .filter_map(|line| line.cell)
456        .map(|cell| cell.table)
457        .min();
458    let of_outer = |line: &PlacedLine| {
459        line.cell
460            .filter(|cell| Some(cell.table) == outer)
461            .map(|cell| (cell, TextStory::of_placed(line)))
462    };
463    let mut frame = run.iter().find_map(of_outer);
464    let mut found: Option<((CellPlace, TextStory), usize)> = None;
465    let mut placed = Vec::with_capacity(run.len());
466    for line in run {
467        frame = of_outer(&line).or(frame);
468        let before = match (frame, found) {
469            (Some(cell), Some((known, before))) if known == cell => before,
470            (Some(cell), _) => {
471                let before = before_later_cells(upright, cell);
472                found = Some((cell, before));
473                before
474            }
475            (None, _) => upright.len(),
476        };
477        placed.push((before, line));
478    }
479    placed
480}
481
482/// The index among `upright` of the first line of `story` in a later cell of the row of `cell`
483/// than `cell`, searched back from the end to the first line of an earlier row of its table;
484/// the end when there is none.
485fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
486    let mut before = upright.len();
487    for (index, other) in upright.iter().enumerate().rev() {
488        let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
489            continue;
490        };
491        if other_cell.table == cell.table && other_cell.row < cell.row {
492            break;
493        }
494        if other_cell.table == cell.table
495            && other_cell.row == cell.row
496            && other_cell.column > cell.column
497        {
498            before = index;
499        }
500    }
501    before
502}
503
504/// A byte offset of the text of a line or a paragraph, which is far shorter than 2^32 bytes.
505pub(crate) fn text_offset(bytes: usize) -> u32 {
506    u32::try_from(bytes).unwrap_or(u32::MAX)
507}