Skip to main content

f_office_docx/layout/
line_text.rs

1//! The text that a placed line shows, with where each of its clusters lies on the page, for a
2//! viewer that selects, copies and searches the text of drawn pages.
3
4use f_office_paint::Turn;
5use f_office_units::Length;
6
7use crate::lines::{EndHyphen, Line, LineEnd, Piece};
8use crate::text::{AUTOMATIC_HYPHEN, LINE_END_HYPHEN, NON_BREAKING_HYPHEN, SOFT_HYPHEN};
9use crate::text_map::text_offset;
10
11/// The character that stands in a line's text for an inline object, the object replacement
12/// character.
13const OBJECT: char = '\u{FFFC}';
14
15/// The text that a placed line shows (**Line text**): its characters in the order of the text,
16/// its clusters in visual order with their edges on the page, its left edge, how it ends, and
17/// the hyphen that it shows at its end where a word breaks, which is not in its text. The texts of a paragraph's lines, joined
18/// in order, are the paragraph's text as the layout shows it: a field gives its shown result,
19/// a list label is given as drawn, and hidden text is left out.
20#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct LineText {
22    /// The characters in the order of the text: those of its glyphs, a tab as `\t`, a line,
23    /// page or column break as `\n` and an inline object as U+FFFC.
24    pub text: String,
25    /// The clusters in visual order, from the left.
26    pub clusters: Vec<TextCluster>,
27    /// The left edge of its text on the page: its first cluster's left edge, or for a line
28    /// without a cluster, such as the line of an empty paragraph, where the line starts after
29    /// its indent and alignment.
30    pub left: Length,
31    /// How the line ends.
32    pub end: LineTextEnd,
33    /// The hyphen that the line draws at its end where a word breaks, at an automatic
34    /// hyphenation point or a soft hyphen, which its text does not hold.
35    pub hyphen: Option<EndHyphen>,
36    /// For a line laid out upright in a frame that then turned onto the page, such as a line of
37    /// a table cell with a turned text direction, how the frame lies on the page. The line's
38    /// top, left edge and cluster edges are then places of the frame.
39    pub turn: Option<LineTurn>,
40    /// The parts of its text that show the glyphs of one run each, in the order of the text,
41    /// which the text map reads to find where a hyperlink's text and a bookmark lie.
42    pub(crate) runs: Vec<RunSpan>,
43}
44
45/// A part of a line's text from the first to the last glyph of one run of its paragraph
46/// (**Run span**): the tabs and breaks between those glyphs are in it, those after the last one
47/// are not.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub(crate) struct RunSpan {
50    /// The first byte of the line's text that it holds.
51    pub(crate) start: u32,
52    /// The byte after the last that it holds.
53    pub(crate) end: u32,
54    /// The index of the run among the runs of the paragraph; none for a list label.
55    pub(crate) run: Option<u32>,
56}
57
58/// How the upright frame of a turned line lies on the page (**Line turn**): a point of the
59/// frame lands on the page at `to`, plus its offset from `from` turned by `turn`.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct LineTurn {
62    /// The point of the frame that lands at `to`.
63    pub from: (Length, Length),
64    /// Where `from` lies on the page.
65    pub to: (Length, Length),
66    /// The turn of an offset in the frame onto the page.
67    pub turn: Turn,
68}
69
70/// A cluster of a line's text: one glyph or a tab with the ligature parts and combining marks
71/// that join it, the bytes of the line's text that it shows, and its edges on the page.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub struct TextCluster {
74    /// The first byte of the line's text that it shows.
75    pub start: u32,
76    /// The byte after the last that it shows.
77    pub end: u32,
78    /// Its left edge on the page.
79    pub left: Length,
80    /// Its right edge on the page.
81    pub right: Length,
82}
83
84/// How a line ends.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub enum LineTextEnd {
87    /// Before a word that the line does not hold, or inside one.
88    #[default]
89    Wrap,
90    /// At a line break.
91    LineBreak,
92    /// At a page break.
93    PageBreak,
94    /// At a column break.
95    ColumnBreak,
96    /// At the end of its paragraph.
97    Paragraph,
98    /// At the end of the last paragraph of a table cell, which only the text map tells apart
99    /// from the end of a paragraph.
100    Cell,
101}
102
103/// The text of `line`, which starts at `start` on the page and whose pieces lie in visual order
104/// at `edges`, the piece at each visual place being the piece of `line` that `order` names there
105/// (empty when the orders are the same); `last` when it is the last line of its paragraph.
106pub(super) fn line_text(
107    line: &Line,
108    (start, edges): (Length, &[(Length, Length)]),
109    order: &[usize],
110    last: bool,
111) -> LineText {
112    let visual_of = visual_places(order, line.placed.len());
113    let hyphen = line.hyphen.and_then(|_| {
114        line.placed
115            .iter()
116            .rposition(|placed| matches!(placed.piece, Piece::Glyph(_)))
117    });
118    let mut read = Reading::default();
119    for (own, placed) in line.placed.iter().enumerate() {
120        if let Some(ch) = piece_char(&placed.piece).filter(|_| Some(own) != hyphen) {
121            let visual = visual_of.get(own).copied().unwrap_or(own);
122            let joins = matches!(placed.piece, Piece::Glyph(glyph) if glyph.part)
123                || unicode_normalization::char::is_combining_mark(ch);
124            let edge = edges.get(visual).copied().unwrap_or_default();
125            let start = read.text.len();
126            read.add(ch, joins, (visual, edge));
127            if let Piece::Glyph(glyph) = placed.piece {
128                let run = (!glyph.label).then_some(glyph.place.run).flatten();
129                read.span(run, start);
130            }
131        }
132    }
133    let end = line_end(line.end, last);
134    let right = edges.iter().map(|&(_, right)| right).max();
135    LineText {
136        hyphen: line.hyphen,
137        ..read.close(end, right.unwrap_or(start))
138    }
139}
140
141/// For each piece of a line of `count` pieces, its place in visual order, where `order` gives
142/// the piece at each visual place, or is empty when the orders are the same.
143fn visual_places(order: &[usize], count: usize) -> Vec<usize> {
144    if order.is_empty() {
145        return (0..count).collect();
146    }
147    let mut visual_of = vec![0; count];
148    for (visual, &own) in order.iter().enumerate() {
149        if let Some(slot) = visual_of.get_mut(own) {
150            *slot = visual;
151        }
152    }
153    visual_of
154}
155
156/// How a line that ends at `end` ends its text, `last` when it is the last line of its
157/// paragraph.
158const fn line_end(end: LineEnd, last: bool) -> LineTextEnd {
159    match end {
160        _ if last => LineTextEnd::Paragraph,
161        LineEnd::Wrap | LineEnd::Split => LineTextEnd::Wrap,
162        LineEnd::Break(_) => LineTextEnd::LineBreak,
163        LineEnd::PageBreak => LineTextEnd::PageBreak,
164        LineEnd::ColumnBreak => LineTextEnd::ColumnBreak,
165    }
166}
167
168/// A line's text as it is read, with each cluster's place in visual order and the spans of its
169/// runs.
170#[derive(Default)]
171struct Reading {
172    text: String,
173    clusters: Vec<(usize, TextCluster)>,
174    runs: Vec<RunSpan>,
175}
176
177impl Reading {
178    /// Notes that the character just added at the byte `start` is a glyph of the run `run`: it
179    /// ends the span of the last glyph when that glyph has the same run, and else starts a span.
180    fn span(&mut self, run: Option<u32>, start: usize) {
181        let end = text_offset(self.text.len());
182        match self.runs.last_mut().filter(|span| span.run == run) {
183            Some(span) => span.end = end,
184            None => self.runs.push(RunSpan {
185                start: text_offset(start),
186                end,
187                run,
188            }),
189        }
190    }
191
192    /// Adds the character `ch` of the piece at the visual place `visual`, whose edges are
193    /// `edge`: to the last cluster when it `joins` it, and else as a cluster of its own.
194    fn add(&mut self, ch: char, joins: bool, (visual, (left, right)): (usize, (Length, Length))) {
195        let start = text_offset(self.text.len());
196        self.text.push(ch);
197        let end = text_offset(self.text.len());
198        match self.clusters.last_mut().filter(|_| joins) {
199            Some((_, cluster)) => {
200                cluster.end = end;
201                cluster.left = cluster.left.min(left);
202                cluster.right = cluster.right.max(right);
203            }
204            None => self.clusters.push((
205                visual,
206                TextCluster {
207                    start,
208                    end,
209                    left,
210                    right,
211                },
212            )),
213        }
214    }
215
216    /// The line's text, which ends at `end`, with its clusters in visual order. A break that
217    /// ends the line without a piece of its own still ends its text, with an empty cluster at
218    /// the line's right edge `right`, which is also the left edge of a line without a cluster.
219    fn close(mut self, end: LineTextEnd, right: Length) -> LineText {
220        self.clusters.sort_by_key(|&(visual, _)| visual);
221        let breaks = matches!(
222            end,
223            LineTextEnd::LineBreak | LineTextEnd::PageBreak | LineTextEnd::ColumnBreak
224        );
225        if breaks && !self.text.ends_with('\n') {
226            self.add('\n', false, (usize::MAX, (right, right)));
227        }
228        let clusters: Vec<TextCluster> = self
229            .clusters
230            .into_iter()
231            .map(|(_, cluster)| cluster)
232            .collect();
233        LineText {
234            text: self.text,
235            left: clusters.first().map_or(right, |cluster| cluster.left),
236            clusters,
237            end,
238            hyphen: None,
239            turn: None,
240            runs: self.runs,
241        }
242    }
243}
244
245/// The character that a piece gives a line's text, or none for a piece without text.
246fn piece_char(piece: &Piece) -> Option<char> {
247    match piece {
248        Piece::Glyph(glyph) => match glyph.ch {
249            NON_BREAKING_HYPHEN => Some('\u{2011}'),
250            SOFT_HYPHEN => Some('\u{AD}'),
251            AUTOMATIC_HYPHEN | LINE_END_HYPHEN => None,
252            ch => Some(ch),
253        },
254        Piece::Tab(_) | Piece::PositionTab(..) => Some('\t'),
255        Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak => Some('\n'),
256        Piece::Object { .. } | Piece::CheckBox { .. } => Some(OBJECT),
257        Piece::Note(_)
258        | Piece::NoteMarkEnd
259        | Piece::Comment(_)
260        | Piece::Anchor(_)
261        | Piece::Strut(_)
262        | Piece::Clear
263        | Piece::Rule { .. }
264        | Piece::Shift(_)
265        | Piece::Advance(_)
266        | Piece::Bar { .. }
267        | Piece::Vinculum { .. }
268        | Piece::Diagonal { .. } => None,
269    }
270}