Skip to main content

alpha2_layout/
report.rs

1//! Where a text's lines, words and clusters lie: the static layout the text host draws.
2
3use std::ops::Range;
4
5use alpha2_model::TextStyle;
6use alpha2_text::{TextRasterError, TextRasterizer};
7
8use crate::{CanvasRect, PictureSize, TextAt};
9
10/// A text's layout on a canvas, rectangles in fractions of the canvas, before the clip's
11/// transform: no animator states, no tracking or pushing, at the fitted size and after the
12/// clamp.
13#[derive(Clone, Debug, PartialEq)]
14pub struct TextLayoutReport {
15    /// The base size drawn, a fraction of the canvas's shorter side.
16    pub font_size: f32,
17    /// The layout box, as [`crate::TextBounds::layout`].
18    pub layout: CanvasRect,
19    /// Lines, top to bottom.
20    pub lines: Vec<LineReport>,
21    /// UAX #29 words holding a letter or digit, in order.
22    pub words: Vec<WordReport>,
23    /// Grapheme clusters in logical order.
24    pub clusters: Vec<ClusterReport>,
25}
26
27/// One line of a [`TextLayoutReport`].
28#[derive(Clone, Debug, PartialEq)]
29pub struct LineReport {
30    /// Its clusters, as indices into [`TextLayoutReport::clusters`].
31    pub clusters: Range<usize>,
32    /// Its line box: the line height times its largest size tall, its advance (without hanging
33    /// spaces) wide.
34    pub line_box: CanvasRect,
35    /// The em box of its largest size over the same advance.
36    pub em: CanvasRect,
37    /// Its baseline, a fraction of the canvas height.
38    pub baseline: f32,
39}
40
41/// One word of a [`TextLayoutReport`].
42#[derive(Clone, Debug, PartialEq)]
43pub struct WordReport {
44    /// Its clusters, as indices into [`TextLayoutReport::clusters`].
45    pub clusters: Range<usize>,
46    /// Its advance by its em box, one rectangle per line it lies on.
47    pub boxes: Vec<CanvasRect>,
48    /// The union of its clusters' ink, `None` when none draws.
49    pub ink: Option<CanvasRect>,
50}
51
52/// One cluster of a [`TextLayoutReport`].
53#[derive(Clone, Debug, PartialEq)]
54pub struct ClusterReport {
55    /// Its UTF-8 byte range in the text; the ellipsis has an empty one, at the cut.
56    pub bytes: Range<usize>,
57    /// The run holding its first byte, `None` for a plain string.
58    pub run: Option<usize>,
59    /// Its word, `None` for spaces, punctuation and the ellipsis.
60    pub word: Option<u32>,
61    /// Its line.
62    pub line: u32,
63    /// Whether it holds only white space.
64    pub space: bool,
65    /// Whether it is the ellipsis of a clamped text.
66    pub ellipsis: bool,
67    /// Its size, a fraction of the canvas's shorter side.
68    pub font_size: f32,
69    /// Its line's baseline, a fraction of the canvas height.
70    pub baseline: f32,
71    /// Its advance by its own em box.
72    pub cluster_box: CanvasRect,
73    /// The bounds of what it draws, strokes included, at most a pixel loose; `None` when it
74    /// draws nothing.
75    pub ink: Option<CanvasRect>,
76}
77
78/// The layout of `text` in `style` on a canvas of `size`, laid out with `rasterizer`'s fonts
79/// and placed as a frame places it.
80///
81/// # Errors
82/// Returns the text host's refusal: no fonts, or a style out of range.
83pub fn text_layout(
84    rasterizer: &TextRasterizer,
85    text: &TextAt<'_>,
86    style: &TextStyle,
87    size: PictureSize,
88) -> Result<TextLayoutReport, TextRasterError> {
89    let placed = crate::text::place(rasterizer, text, style, size)?;
90    let layout = rasterizer.layout_with_ink(&placed.request)?;
91    let unit = size.unit();
92    let rect = |bounds: [f32; 4]| placed.rect(bounds);
93    let baseline = |pixels: f32| (placed.origin[1] + pixels) / placed.canvas[1];
94    let em = |baseline: f32, size: f32| [baseline - 0.8 * size, baseline + 0.2 * size];
95    let run_ends = text
96        .content
97        .runs()
98        .iter()
99        .scan(0, |end, run| {
100            *end += run.text.len();
101            Some(*end)
102        })
103        .collect::<Vec<_>>();
104    let clusters = layout
105        .clusters
106        .iter()
107        .map(|cluster| {
108            let [top, bottom] = em(cluster.baseline, cluster.font_size);
109            ClusterReport {
110                bytes: cluster.bytes.clone(),
111                run: (!run_ends.is_empty()).then(|| {
112                    run_ends
113                        .partition_point(|end| *end <= cluster.bytes.start)
114                        .min(run_ends.len() - 1)
115                }),
116                word: cluster.word,
117                line: cluster.line,
118                space: cluster.is_space,
119                ellipsis: cluster.ellipsis,
120                font_size: cluster.font_size / unit,
121                baseline: baseline(cluster.baseline),
122                cluster_box: rect([cluster.x, top, cluster.x + cluster.advance, bottom]),
123                ink: cluster.ink.map(rect),
124            }
125        })
126        .collect::<Vec<_>>();
127    let lines = layout
128        .lines
129        .iter()
130        .map(|line| {
131            let [em_top, em_bottom] = em(line.baseline, line.size);
132            let (left, right) = (line.left, line.left + line.width);
133            LineReport {
134                clusters: line.clusters.clone(),
135                line_box: rect([
136                    left,
137                    line.box_top,
138                    right,
139                    line.box_top + placed.request.line_height * line.size,
140                ]),
141                em: rect([left, em_top, right, em_bottom]),
142                baseline: baseline(line.baseline),
143            }
144        })
145        .collect();
146    let words = words_of(&layout, &clusters, &rect);
147    Ok(TextLayoutReport {
148        font_size: placed.font_size,
149        layout: placed.layout,
150        lines,
151        words,
152        clusters,
153    })
154}
155
156/// The words of `layout`, their boxes per line by `rect`, their ink from `clusters`.
157fn words_of(
158    layout: &alpha2_text::TextLayout,
159    clusters: &[ClusterReport],
160    rect: &impl Fn([f32; 4]) -> CanvasRect,
161) -> Vec<WordReport> {
162    let em = |baseline: f32, size: f32| [baseline - 0.8 * size, baseline + 0.2 * size];
163    let mut words = Vec::<WordReport>::new();
164    for (index, cluster) in layout.clusters.iter().enumerate() {
165        let Some(word) = cluster.word else {
166            continue;
167        };
168        let word = usize::try_from(word).unwrap_or(usize::MAX);
169        while words.len() <= word {
170            words.push(WordReport {
171                clusters: index..index,
172                boxes: Vec::new(),
173                ink: None,
174            });
175        }
176        let entry = &mut words[word];
177        if entry.clusters.is_empty() {
178            entry.clusters.start = index;
179        }
180        entry.clusters.end = index + 1;
181    }
182    for word in &mut words {
183        let members = &layout.clusters[word.clusters.clone()];
184        let mut line_of = None;
185        let mut fragment: Option<[f32; 4]> = None;
186        let mut fragments = Vec::new();
187        for cluster in members.iter().filter(|cluster| cluster.word.is_some()) {
188            let [top, bottom] = em(cluster.baseline, cluster.font_size);
189            let piece = [cluster.x, top, cluster.x + cluster.advance, bottom];
190            if line_of != Some(cluster.line) {
191                fragments.extend(fragment.take());
192                line_of = Some(cluster.line);
193            }
194            fragment = Some(fragment.map_or(piece, |held| {
195                [
196                    held[0].min(piece[0]),
197                    held[1].min(piece[1]),
198                    held[2].max(piece[2]),
199                    held[3].max(piece[3]),
200                ]
201            }));
202        }
203        fragments.extend(fragment);
204        word.boxes = fragments.into_iter().map(rect).collect();
205        word.ink = clusters[word.clusters.clone()]
206            .iter()
207            .filter_map(|cluster| cluster.ink)
208            .reduce(|held, ink| CanvasRect {
209                left: held.left.min(ink.left),
210                top: held.top.min(ink.top),
211                right: held.right.max(ink.right),
212                bottom: held.bottom.max(ink.bottom),
213            });
214    }
215    words
216}