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/// Incremental batch of compact lines produced by one [`crate::IncrementalLayout::step`] slice.
245#[derive(Clone, Debug, Default)]
246pub struct TextMapDelta(Vec<CompactLine>);
247
248impl TextMapDelta {
249    /// Whether this delta contains no lines.
250    #[must_use]
251    pub fn is_empty(&self) -> bool {
252        self.0.is_empty()
253    }
254}
255
256/// Self-contained compact reading-order text index of a laid-out document: holds paragraph
257/// addresses, hyperlinks/bookmarks, and compact per-line text/cluster metadata without retaining
258/// full [`PlacedLine`] layout diagnostics.
259#[derive(Clone, Debug, Default)]
260pub struct TextMap {
261    addresses: HashMap<ParagraphId, Address>,
262    marks: HashMap<ParagraphId, RunMarks>,
263    lines: Vec<CompactLine>,
264}
265
266impl TextMap {
267    /// Initializes an empty [`TextMap`] from precomputed paragraph addresses and marks, ready to
268    /// receive [`TextMapDelta`] batches during incremental layout.
269    pub(crate) fn from_paragraphs(
270        (addresses, marks): (
271            HashMap<ParagraphId, Address>,
272            HashMap<ParagraphId, RunMarks>,
273        ),
274    ) -> Self {
275        Self {
276            addresses,
277            marks,
278            lines: Vec::new(),
279        }
280    }
281
282    /// Converts a newly placed batch of lines into a compact [`TextMapDelta`] without cloning any
283    /// lines from earlier slices.
284    pub(crate) fn delta_from_placed(placed: Vec<PlacedLine>) -> TextMapDelta {
285        let (upright, turned) = turned_apart(placed);
286        let mut turned = turned.into_iter().peekable();
287        let mut lines = Vec::with_capacity(upright.len() + turned.len());
288        for (index, line) in upright.into_iter().enumerate() {
289            while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
290                lines.push(CompactLine::from_owned(before));
291            }
292            lines.push(CompactLine::from_owned(line));
293        }
294        lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
295        TextMapDelta(lines)
296    }
297
298    /// Appends a [`TextMapDelta`] produced by an incremental layout slice in `O(delta)` time.
299    pub fn extend_delta(&mut self, delta: TextMapDelta) {
300        self.lines.extend(delta.0);
301    }
302
303    /// Builds a self-contained [`TextMap`] from `addresses`, `marks`, upright `lines`, and
304    /// `turned` lines (as returned by [`turned_apart`]), merged in reading order.
305    pub(crate) fn new(
306        (addresses, marks): (
307            HashMap<ParagraphId, Address>,
308            HashMap<ParagraphId, RunMarks>,
309        ),
310        upright: &[PlacedLine],
311        turned: Vec<(usize, PlacedLine)>,
312    ) -> Self {
313        let mut turned = turned.into_iter().peekable();
314        let mut lines = Vec::with_capacity(upright.len() + turned.len());
315        for (index, line) in upright.iter().enumerate() {
316            while let Some((_, before)) = turned.next_if(|&(at, _)| at <= index) {
317                lines.push(CompactLine::from_owned(before));
318            }
319            lines.push(CompactLine::from_ref(line));
320        }
321        lines.extend(turned.map(|(_, line)| CompactLine::from_owned(line)));
322        Self {
323            addresses,
324            marks,
325            lines,
326        }
327    }
328
329    /// The lines on `page` in reading order: the header, the body, the endnotes, the frames,
330    /// the text boxes, the footnotes and the footer, and the lines of each story in the order
331    /// of the layout, with table row cells reading in cell order.
332    #[must_use]
333    pub fn page(&self, page: usize) -> Vec<TextLine> {
334        self.pages(&[page]).pop().unwrap_or_default()
335    }
336
337    /// The lines of each page of `pages` in reading order, as [`Self::page`] gives them, from
338    /// one read of each story that has a line on one of them, so that a story that runs over
339    /// many pages, such as the body, is read once for all of them. A page that `pages` names
340    /// twice has its lines at its last place only.
341    #[must_use]
342    pub fn pages(&self, pages: &[usize]) -> Vec<Vec<TextLine>> {
343        let slots: HashMap<usize, usize> = pages
344            .iter()
345            .enumerate()
346            .map(|(slot, &page)| (page, slot))
347            .collect();
348        let mut stories: Vec<TextStory> = self
349            .lines
350            .iter()
351            .filter(|line| slots.contains_key(&line.page))
352            .map(TextStory::of_compact)
353            .collect();
354        stories.sort_unstable();
355        stories.dedup();
356        let mut maps = vec![Vec::new(); pages.len()];
357        for story in stories {
358            for (line, text_line) in self.read(story).lines {
359                if let Some(map) = slots.get(&line.page).and_then(|&slot| maps.get_mut(slot)) {
360                    map.push(text_line);
361                }
362            }
363        }
364        maps
365    }
366
367    /// The text of `story` by paragraph.
368    #[must_use]
369    pub fn story(&self, story: TextStory) -> Vec<StoryParagraph> {
370        self.read(story).paragraphs
371    }
372
373    /// Reads the lines of `story` into its paragraphs and text lines. The paragraphs come in the
374    /// order of their first lines, so the lines of a paragraph that another paragraph's lines
375    /// interrupt still join.
376    fn read(&self, story: TextStory) -> Read<'_> {
377        let mut read = Read::default();
378        let mut indices: HashMap<ParagraphId, usize> = HashMap::new();
379        // The paragraph and the run spans of each paragraph of `read`, in its text.
380        let mut spans: Vec<(ParagraphId, Vec<RunSpan>)> = Vec::new();
381        for line in self
382            .lines
383            .iter()
384            .filter(|line| TextStory::of_compact(line) == story)
385        {
386            let text = &line.text;
387            let paragraph = match indices.entry(line.paragraph) {
388                Entry::Occupied(entry) => *entry.get(),
389                Entry::Vacant(entry) => {
390                    read.paragraphs.push(StoryParagraph {
391                        address: self.addresses.get(&line.paragraph).cloned(),
392                        cell: line.cell,
393                        ..StoryParagraph::default()
394                    });
395                    spans.push((line.paragraph, Vec::new()));
396                    *entry.insert(read.paragraphs.len() - 1)
397                }
398            };
399            let Some(own) = read.paragraphs.get_mut(paragraph) else {
400                continue;
401            };
402            let start = text_offset(own.text.len());
403            own.text.push_str(&text.text);
404            if let Some((_, own_spans)) = spans.get_mut(paragraph) {
405                own_spans.extend(text.runs.iter().map(|span| RunSpan {
406                    start: span.start.saturating_add(start),
407                    end: span.end.saturating_add(start),
408                    run: span.run,
409                }));
410            }
411            read.lines
412                .push((line, text_line(line, text, (story, paragraph), start)));
413        }
414        for ((id, own_spans), own) in spans.iter().zip(&mut read.paragraphs) {
415            if let Some(marks) = self.marks.get(id) {
416                (own.links, own.bookmarks) = marks.placed(own_spans, text_offset(own.text.len()));
417            }
418        }
419        // The last line of a cell's last paragraph ends the cell.
420        let cells: Vec<Option<CellPlace>> = read.paragraphs.iter().map(|p| p.cell).collect();
421        for (_, text_line) in &mut read.lines {
422            let paragraph = text_line.paragraph;
423            let cell = cells.get(paragraph).copied().flatten();
424            let next = cells.get(paragraph + 1).copied().flatten();
425            if text_line.ends == LineTextEnd::Paragraph && cell.is_some() && next != cell {
426                text_line.ends = LineTextEnd::Cell;
427            }
428        }
429        read
430    }
431}
432
433/// The paragraphs and the text lines of one story, each line with the compact line that it is
434/// read from.
435#[derive(Default)]
436struct Read<'a> {
437    paragraphs: Vec<StoryParagraph>,
438    lines: Vec<(&'a CompactLine, TextLine)>,
439}
440
441/// The text line of `line`, whose text `text` starts at `start` in the text of the paragraph
442/// `paragraph` of `story`.
443fn text_line(
444    line: &CompactLine,
445    text: &LineText,
446    (story, paragraph): (TextStory, usize),
447    start: u32,
448) -> TextLine {
449    TextLine {
450        story,
451        paragraph,
452        start,
453        end: start + text_offset(text.text.len()),
454        top: line.top,
455        height: line.height,
456        baseline: line.baseline,
457        clusters: text
458            .clusters
459            .iter()
460            .map(|cluster| TextCluster {
461                start: start + cluster.start,
462                end: start + cluster.end,
463                ..*cluster
464            })
465            .collect(),
466        left: text.left,
467        ends: text.end,
468        hyphen: text.hyphen,
469        turn: text.turn,
470    }
471}
472
473/// The upright lines of `lines`, the lines of a layout pass in the order of the layout, and its
474/// turned lines, each with the index among the upright lines of the line before which it reads.
475/// The layout turns the turned cells of a row one after another, after its upright cells, so
476/// the lines of a turned cell read before the first earlier line of their story in a later cell
477/// of the row; with no such line, where the layout placed them.
478pub(crate) fn turned_apart(lines: Vec<PlacedLine>) -> (Vec<PlacedLine>, Vec<(usize, PlacedLine)>) {
479    let mut upright: Vec<PlacedLine> = Vec::with_capacity(lines.len());
480    let mut turned: Vec<(usize, PlacedLine)> = Vec::new();
481    let mut run: Vec<PlacedLine> = Vec::new();
482    for line in lines {
483        if line.upright() {
484            turned.extend(place_run(&upright, std::mem::take(&mut run)));
485            upright.push(line);
486        } else {
487            run.push(line);
488        }
489    }
490    turned.extend(place_run(&upright, run));
491    turned.sort_by_key(|&(before, _)| before);
492    (upright, turned)
493}
494
495/// The lines of `run`, turned lines that the layout placed one after another after the
496/// upright lines `upright`, each with the index of the upright line before which it reads. A
497/// line of a table nested in a turned cell reads with the cell, the cell of the run's table
498/// that the last line before it, or else the first line after it, lies in: the outer table,
499/// which starts before the tables nested in it, has the run's least number.
500fn place_run(upright: &[PlacedLine], run: Vec<PlacedLine>) -> Vec<(usize, PlacedLine)> {
501    let outer = run
502        .iter()
503        .filter_map(|line| line.cell)
504        .map(|cell| cell.table)
505        .min();
506    let of_outer = |line: &PlacedLine| {
507        line.cell
508            .filter(|cell| Some(cell.table) == outer)
509            .map(|cell| (cell, TextStory::of_placed(line)))
510    };
511    let mut frame = run.iter().find_map(of_outer);
512    let mut found: Option<((CellPlace, TextStory), usize)> = None;
513    let mut placed = Vec::with_capacity(run.len());
514    for line in run {
515        frame = of_outer(&line).or(frame);
516        let before = match (frame, found) {
517            (Some(cell), Some((known, before))) if known == cell => before,
518            (Some(cell), _) => {
519                let before = before_later_cells(upright, cell);
520                found = Some((cell, before));
521                before
522            }
523            (None, _) => upright.len(),
524        };
525        placed.push((before, line));
526    }
527    placed
528}
529
530/// The index among `upright` of the first line of `story` in a later cell of the row of `cell`
531/// than `cell`, searched back from the end to the first line of an earlier row of its table;
532/// the end when there is none.
533fn before_later_cells(upright: &[PlacedLine], (cell, story): (CellPlace, TextStory)) -> usize {
534    let mut before = upright.len();
535    for (index, other) in upright.iter().enumerate().rev() {
536        let Some(other_cell) = other.cell.filter(|_| TextStory::of_placed(other) == story) else {
537            continue;
538        };
539        if other_cell.table == cell.table && other_cell.row < cell.row {
540            break;
541        }
542        if other_cell.table == cell.table
543            && other_cell.row == cell.row
544            && other_cell.column > cell.column
545        {
546            before = index;
547        }
548    }
549    before
550}
551
552/// A byte offset of the text of a line or a paragraph, which is far shorter than 2^32 bytes.
553pub(crate) fn text_offset(bytes: usize) -> u32 {
554    u32::try_from(bytes).unwrap_or(u32::MAX)
555}