1mod resolve;
9
10#[cfg(test)]
11mod tests;
12
13use crate::fit::{BoxedLines, boxed_lines, fit_font_size, pixels, text_clamp};
14use crate::text::{TextDraw, layout_text_key, stroke_pixels, text_fill};
15use crate::{Baselines, CanvasRect, PictureSize};
16use alpha2_eval::{EvaluatedLayout, EvaluatedNode, EvaluatedText, LayoutPlan, NodeContent};
17use alpha2_media::EmojiPolicy;
18use alpha2_model::{LayoutNode, TextAlign};
19use alpha2_text::{ShapedText, TextClamp, TextRasterError, TextRasterRequest, TextRasterizer};
20use alpha2_time::MediaTime;
21use std::sync::Arc;
22
23pub use resolve::resolve;
24
25pub const LAYOUT_WRAP_SLACK: f32 = 1.0 / 64.0;
29
30#[allow(clippy::cast_precision_loss)]
33pub(crate) fn wrap(width: f32) -> f32 {
34 let limit = alpha2_text::MAX_TEXT_BOX as f32;
35 let wrapped = (width + LAYOUT_WRAP_SLACK).max(1.0);
36 if width <= limit {
37 wrapped.min(limit)
38 } else {
39 wrapped
40 }
41}
42
43#[derive(Copy, Clone, Debug, Default, PartialEq)]
46pub struct NodeRects {
47 pub border: [f32; 4],
49 pub padding: [f32; 4],
51 pub content: [f32; 4],
53 pub text_width: f32,
55 pub text_height: f32,
57 pub font_size: f32,
60 pub font_pixels: f32,
62 pub truncated: bool,
64 pub overflow: bool,
66 pub line_count: Option<u32>,
68 pub baselines: Option<[f32; 2]>,
71}
72
73#[derive(Clone, Debug, Default, PartialEq)]
75pub struct ResolvedLayout {
76 pub nodes: Vec<NodeRects>,
78}
79
80#[derive(Clone, Debug, PartialEq)]
82pub struct LayoutBounds {
83 pub nodes: Vec<NodeBounds>,
85}
86
87#[derive(Clone, Debug, PartialEq)]
89pub struct NodeBounds {
90 pub at: String,
92 pub border: CanvasRect,
94 pub content: CanvasRect,
96 pub overflow: bool,
100 pub line_count: Option<u32>,
102 pub font_size: Option<f32>,
105 pub truncated: bool,
107 pub baselines: Option<Baselines>,
110}
111
112pub(crate) fn text_request(
115 text: &EvaluatedText,
116 font_size: f32,
117 max_width: f32,
118 clamp: Option<TextClamp>,
119 content_version: u64,
120) -> TextRasterRequest {
121 TextRasterRequest {
122 text: text.content.clone(),
123 font_size,
124 max_width,
125 line_height: text.line_height,
126 align: match text.text_align {
127 TextAlign::Start => alpha2_media::TextAlign::Start,
128 TextAlign::Center => alpha2_media::TextAlign::Center,
129 TextAlign::End => alpha2_media::TextAlign::End,
130 },
131 fill: text_fill(&text.fill),
132 emoji_policy: EmojiPolicy::Color,
133 content_version,
134 strokes: stroke_pixels(&text.strokes, font_size),
135 background: None,
136 split_background: false,
137 font_family: text.font_family.clone(),
138 letter_spacing: text.letter_spacing * font_size,
139 font_weight: text.font_weight,
140 clamp,
141 }
142}
143
144pub(crate) fn node_lines(
147 text: &EvaluatedText,
148 shaped: &ShapedText,
149 width: f32,
150 height: f32,
151) -> BoxedLines {
152 boxed_lines(
153 shaped,
154 wrap(width),
155 height + LAYOUT_WRAP_SLACK,
156 text.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
157 text.line_clamp.is_some(),
158 )
159}
160
161pub fn fit_texts(
168 layout: &EvaluatedLayout,
169 resolved: &mut ResolvedLayout,
170 size: PictureSize,
171 mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
172) -> Result<(), TextRasterError> {
173 let unit = size.unit();
174 let mut found = Vec::new();
175 text_nodes(&layout.root, &mut 0, &mut found);
176 for (node, text) in found {
177 let (Some(text), Some(rects)) = (text, resolved.nodes.get_mut(node)) else {
178 continue;
179 };
180 if text.font_size_fit.is_none() {
181 continue;
182 }
183 let (width, height) = (rects.text_width, rects.text_height);
184 let request = |pixels| text_request(text, pixels, 0.0, None, 1);
185 let fitted = fit_font_size(text.font_size, text.font_size_fit, unit, |pixels| {
186 Ok(node_lines(text, &*shape(&request(pixels))?, width, height).fits)
187 })?;
188 let lines = node_lines(text, &*shape(&request(fitted.font_pixels))?, width, height);
189 let top = rects.content[1];
190 rects.font_size = fitted.font_size;
191 rects.font_pixels = fitted.font_pixels;
192 rects.truncated = lines.truncated;
193 rects.line_count = Some(lines.lines.line_count);
194 rects.baselines = Some([
195 top + lines.lines.first_baseline,
196 top + lines.lines.last_baseline,
197 ]);
198 rects.overflow = lines.overflow;
199 }
200 Ok(())
201}
202
203fn text_nodes<'a>(
205 node: &'a EvaluatedNode,
206 index: &mut usize,
207 out: &mut Vec<(usize, Option<&'a EvaluatedText>)>,
208) {
209 let at = *index;
210 *index += 1;
211 match &node.content {
212 NodeContent::Text(text) => {
213 out.push((at, Some(&**text).filter(|text| !text.content.is_empty())));
214 }
215 NodeContent::Children(children) => {
216 for child in children {
217 text_nodes(child, index, out);
218 }
219 }
220 NodeContent::Empty | NodeContent::Shape(_) => {}
221 }
222}
223
224pub(crate) fn texts<'a>(node: &'a EvaluatedNode, out: &mut Vec<Option<&'a EvaluatedText>>) {
227 match &node.content {
228 NodeContent::Text(text) => out.push(Some(&**text).filter(|text| !text.content.is_empty())),
229 NodeContent::Children(children) => {
230 for child in children {
231 texts(child, out);
232 }
233 }
234 NodeContent::Empty | NodeContent::Shape(_) => {}
235 }
236}
237
238pub fn shape_texts(
244 layout: &EvaluatedLayout,
245 size: PictureSize,
246 mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
247) -> Result<Vec<Option<Arc<ShapedText>>>, TextRasterError> {
248 let unit = size.unit();
249 let mut list = Vec::new();
250 texts(&layout.root, &mut list);
251 list.into_iter()
252 .map(|text| {
253 text.map(|text| {
254 shape(&text_request(
255 text,
256 pixels(text.font_size, unit),
257 0.0,
258 None,
259 1,
260 ))
261 })
262 .transpose()
263 })
264 .collect()
265}
266
267#[must_use]
271pub fn layout_texts(
272 layout: &EvaluatedLayout,
273 resolved: &ResolvedLayout,
274 size: PictureSize,
275) -> (Vec<Option<u64>>, Vec<(u64, TextDraw)>) {
276 let unit = size.unit();
277 let mut found = Vec::new();
278 text_nodes(&layout.root, &mut 0, &mut found);
279 let mut keys = Vec::with_capacity(found.len());
280 let mut requests: Vec<(u64, TextDraw)> = Vec::new();
281 for (node, text) in found {
282 let Some(text) = text else {
283 keys.push(None);
284 continue;
285 };
286 let rects = resolved.nodes.get(node).copied().unwrap_or_default();
287 let font_size = if rects.font_pixels > 0.0 {
288 rects.font_pixels
289 } else {
290 pixels(text.font_size, unit)
291 };
292 let clamp = text
293 .line_clamp
294 .as_ref()
295 .map(|clamp| text_clamp(clamp, rects.text_height + LAYOUT_WRAP_SLACK));
296 let mut request = text_request(text, font_size, wrap(rects.text_width), clamp, 1);
297 let shadows = crate::text::shadow_pixels(&text.shadows, request.font_size);
298 let key = layout_text_key(&request, &shadows, &text.animators);
299 request.content_version = key;
300 if !requests.iter().any(|(held, _)| *held == key) {
301 let animation = (!text.animators.is_empty()).then(|| crate::TextAnimation {
302 animators: text.animators.clone(),
303 runs: Vec::new(),
304 time: layout.time,
305 });
306 requests.push((
307 key,
308 TextDraw {
309 request,
310 shadows,
311 animation,
312 },
313 ));
314 }
315 keys.push(Some(key));
316 }
317 (keys, requests)
318}
319
320fn mark_refused_texts(
323 rasterizer: &TextRasterizer,
324 layout: &EvaluatedLayout,
325 resolved: &mut ResolvedLayout,
326 size: PictureSize,
327) -> Result<(), TextRasterError> {
328 let (keys, requests) = layout_texts(layout, resolved, size);
329 let mut refused = Vec::new();
330 for (key, draw) in &requests {
331 match rasterizer.measure(&draw.request) {
332 Ok(_) => {}
333 Err(TextRasterError::InvalidRequest | TextRasterError::TooLarge) => refused.push(*key),
334 Err(error) => return Err(error),
335 }
336 }
337 if refused.is_empty() {
338 return Ok(());
339 }
340 let mut found = Vec::new();
341 text_nodes(&layout.root, &mut 0, &mut found);
342 for ((node, _), key) in found.into_iter().zip(keys) {
343 if key.is_some_and(|key| refused.contains(&key))
344 && let Some(rects) = resolved.nodes.get_mut(node)
345 {
346 rects.overflow = true;
347 }
348 }
349 Ok(())
350}
351
352#[allow(clippy::cast_precision_loss)]
362pub fn measure_layout(
363 rasterizer: &TextRasterizer,
364 root: &LayoutNode,
365 time: MediaTime,
366 size: PictureSize,
367 canvas: (u32, u32),
368) -> Result<LayoutBounds, TextRasterError> {
369 let evaluated = LayoutPlan::new(root, canvas).evaluate(time);
370 let shaped = shape_texts(&evaluated, size, |request| {
371 rasterizer.shape(request).map(Arc::new)
372 })?;
373 let mut resolved = resolve(&evaluated, size, &shaped);
374 fit_texts(&evaluated, &mut resolved, size, |request| {
375 rasterizer.shape(request).map(Arc::new)
376 })?;
377 mark_refused_texts(rasterizer, &evaluated, &mut resolved, size)?;
378 let (width, height) = (size.width() as f32, size.height() as f32);
379 let rect = |[left, top, right, bottom]: [f32; 4]| CanvasRect {
380 left: left / width,
381 top: top / height,
382 right: right / width,
383 bottom: bottom / height,
384 };
385 let mut paths = Vec::new();
386 root.walk(|at, _| paths.push(at.to_owned()));
387 Ok(LayoutBounds {
388 nodes: paths
389 .into_iter()
390 .zip(&resolved.nodes)
391 .map(|(at, node)| NodeBounds {
392 at,
393 border: rect(node.border),
394 content: rect(node.content),
395 overflow: node.overflow,
396 line_count: node.line_count,
397 font_size: node.line_count.map(|_| node.font_size),
398 truncated: node.truncated,
399 baselines: node.baselines.map(|[first, last]| Baselines {
400 first: first / height,
401 last: last / height,
402 }),
403 })
404 .collect(),
405 })
406}