1use std::ops::Range;
4
5use alpha2_model::TextStyle;
6use alpha2_text::{TextRasterError, TextRasterizer};
7
8use crate::{CanvasRect, PictureSize, TextAt};
9
10#[derive(Clone, Debug, PartialEq)]
14pub struct TextLayoutReport {
15 pub font_size: f32,
17 pub layout: CanvasRect,
19 pub lines: Vec<LineReport>,
21 pub words: Vec<WordReport>,
23 pub clusters: Vec<ClusterReport>,
25}
26
27#[derive(Clone, Debug, PartialEq)]
29pub struct LineReport {
30 pub clusters: Range<usize>,
32 pub line_box: CanvasRect,
35 pub em: CanvasRect,
37 pub baseline: f32,
39}
40
41#[derive(Clone, Debug, PartialEq)]
43pub struct WordReport {
44 pub clusters: Range<usize>,
46 pub boxes: Vec<CanvasRect>,
48 pub ink: Option<CanvasRect>,
50}
51
52#[derive(Clone, Debug, PartialEq)]
54pub struct ClusterReport {
55 pub bytes: Range<usize>,
57 pub run: Option<usize>,
59 pub word: Option<u32>,
61 pub line: u32,
63 pub space: bool,
65 pub ellipsis: bool,
67 pub font_size: f32,
69 pub baseline: f32,
71 pub cluster_box: CanvasRect,
73 pub ink: Option<CanvasRect>,
76}
77
78pub 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
156fn 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}