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 pub advance_headroom: Option<f32>,
113}
114
115pub(crate) fn text_request(
118 text: &EvaluatedText,
119 font_size: f32,
120 max_width: f32,
121 clamp: Option<TextClamp>,
122 content_version: u64,
123) -> TextRasterRequest {
124 let base = alpha2_model::TextStyle {
125 font_family: text.font_family.clone(),
126 fill: text.fill.clone(),
127 letter_spacing: text.letter_spacing,
128 font_weight: text.font_weight,
129 strokes: text.strokes.clone(),
130 ..alpha2_model::TextStyle::default()
131 };
132 let spans = crate::text_spans(
133 &crate::TextAt::new(&text.content, alpha2_time::MediaTime::ZERO),
134 &base,
135 font_size,
136 );
137 TextRasterRequest {
138 text: text.content.text().into_owned(),
139 font_size,
140 max_width,
141 line_height: text.line_height,
142 align: match text.text_align {
143 TextAlign::Start => alpha2_media::TextAlign::Start,
144 TextAlign::Center => alpha2_media::TextAlign::Center,
145 TextAlign::End => alpha2_media::TextAlign::End,
146 },
147 fill: text_fill(&text.fill),
148 emoji_policy: EmojiPolicy::Color,
149 content_version,
150 strokes: stroke_pixels(&text.strokes, font_size),
151 background: None,
152 split_background: false,
153 font_family: text.font_family.clone(),
154 letter_spacing: text.letter_spacing * font_size,
155 font_weight: text.font_weight,
156 clamp,
157 spans,
158 advance_headroom: text.advance_headroom,
159 animator_grouping: crate::text::cluster_grouping(text.animator_grouping),
160 animator_pivot: [text.animator_pivot.x, text.animator_pivot.y],
161 highlight: None,
162 }
163}
164
165pub(crate) fn node_lines(
168 text: &EvaluatedText,
169 shaped: &ShapedText,
170 width: f32,
171 height: f32,
172) -> BoxedLines {
173 boxed_lines(
174 shaped,
175 alpha2_text::wrap_width(wrap(width), text.advance_headroom),
176 height + LAYOUT_WRAP_SLACK,
177 text.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
178 text.line_clamp.is_some(),
179 )
180}
181
182pub fn fit_texts(
189 layout: &EvaluatedLayout,
190 resolved: &mut ResolvedLayout,
191 size: PictureSize,
192 mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
193) -> Result<(), TextRasterError> {
194 let unit = size.unit();
195 let mut found = Vec::new();
196 text_nodes(&layout.root, &mut 0, &mut found);
197 for (node, text) in found {
198 let (Some(text), Some(rects)) = (text, resolved.nodes.get_mut(node)) else {
199 continue;
200 };
201 if text.font_size_fit.is_none() {
202 continue;
203 }
204 let (width, height) = (rects.text_width, rects.text_height);
205 let request = |pixels| text_request(text, pixels, 0.0, None, 1);
206 let fitted = fit_font_size(text.font_size, text.font_size_fit, unit, |pixels| {
207 Ok(node_lines(text, &*shape(&request(pixels))?, width, height).fits)
208 })?;
209 let lines = node_lines(text, &*shape(&request(fitted.font_pixels))?, width, height);
210 let top = rects.content[1];
211 rects.font_size = fitted.font_size;
212 rects.font_pixels = fitted.font_pixels;
213 rects.truncated = lines.truncated;
214 rects.line_count = Some(lines.lines.line_count);
215 rects.baselines = Some([
216 top + lines.lines.first_baseline,
217 top + lines.lines.last_baseline,
218 ]);
219 rects.overflow = lines.overflow;
220 }
221 Ok(())
222}
223
224fn text_nodes<'a>(
226 node: &'a EvaluatedNode,
227 index: &mut usize,
228 out: &mut Vec<(usize, Option<&'a EvaluatedText>)>,
229) {
230 let at = *index;
231 *index += 1;
232 match &node.content {
233 NodeContent::Text(text) => {
234 out.push((at, Some(&**text).filter(|text| !text.content.is_empty())));
235 }
236 NodeContent::Children(children) => {
237 for child in children {
238 text_nodes(child, index, out);
239 }
240 }
241 NodeContent::Empty | NodeContent::Shape(_) => {}
242 }
243}
244
245pub(crate) fn texts<'a>(node: &'a EvaluatedNode, out: &mut Vec<Option<&'a EvaluatedText>>) {
248 match &node.content {
249 NodeContent::Text(text) => out.push(Some(&**text).filter(|text| !text.content.is_empty())),
250 NodeContent::Children(children) => {
251 for child in children {
252 texts(child, out);
253 }
254 }
255 NodeContent::Empty | NodeContent::Shape(_) => {}
256 }
257}
258
259pub fn shape_texts(
265 layout: &EvaluatedLayout,
266 size: PictureSize,
267 mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
268) -> Result<Vec<Option<Arc<ShapedText>>>, TextRasterError> {
269 let unit = size.unit();
270 let mut list = Vec::new();
271 texts(&layout.root, &mut list);
272 list.into_iter()
273 .map(|text| {
274 text.map(|text| {
275 shape(&text_request(
276 text,
277 pixels(text.font_size, unit),
278 0.0,
279 None,
280 1,
281 ))
282 })
283 .transpose()
284 })
285 .collect()
286}
287
288#[must_use]
292pub fn layout_texts(
293 layout: &EvaluatedLayout,
294 resolved: &ResolvedLayout,
295 size: PictureSize,
296) -> (Vec<Option<u64>>, Vec<(u64, TextDraw)>) {
297 let unit = size.unit();
298 let mut found = Vec::new();
299 text_nodes(&layout.root, &mut 0, &mut found);
300 let mut keys = Vec::with_capacity(found.len());
301 let mut requests: Vec<(u64, TextDraw)> = Vec::new();
302 for (node, text) in found {
303 let Some(text) = text else {
304 keys.push(None);
305 continue;
306 };
307 let rects = resolved.nodes.get(node).copied().unwrap_or_default();
308 let font_size = if rects.font_pixels > 0.0 {
309 rects.font_pixels
310 } else {
311 pixels(text.font_size, unit)
312 };
313 let clamp = text
314 .line_clamp
315 .as_ref()
316 .map(|clamp| text_clamp(clamp, rects.text_height + LAYOUT_WRAP_SLACK));
317 let mut request = text_request(text, font_size, wrap(rects.text_width), clamp, 1);
318 let shadows = crate::text::shadow_pixels(&text.shadows, request.font_size);
319 let key = layout_text_key(&request, &shadows, &text.animators);
320 request.content_version = key;
321 if !requests.iter().any(|(held, _)| *held == key) {
322 let animation = (!text.animators.is_empty()).then(|| crate::TextAnimation {
323 animators: text.animators.clone(),
324 runs: Vec::new(),
325 time: layout.time,
326 });
327 requests.push((
328 key,
329 TextDraw {
330 request,
331 shadows,
332 animation,
333 },
334 ));
335 }
336 keys.push(Some(key));
337 }
338 (keys, requests)
339}
340
341fn mark_refused_texts(
344 rasterizer: &TextRasterizer,
345 layout: &EvaluatedLayout,
346 resolved: &mut ResolvedLayout,
347 size: PictureSize,
348) -> Result<(), TextRasterError> {
349 let (keys, requests) = layout_texts(layout, resolved, size);
350 let mut refused = Vec::new();
351 for (key, draw) in &requests {
352 match rasterizer.measure(&draw.request) {
353 Ok(_) => {}
354 Err(TextRasterError::InvalidRequest | TextRasterError::TooLarge) => refused.push(*key),
355 Err(error) => return Err(error),
356 }
357 }
358 if refused.is_empty() {
359 return Ok(());
360 }
361 let mut found = Vec::new();
362 text_nodes(&layout.root, &mut 0, &mut found);
363 for ((node, _), key) in found.into_iter().zip(keys) {
364 if key.is_some_and(|key| refused.contains(&key))
365 && let Some(rects) = resolved.nodes.get_mut(node)
366 {
367 rects.overflow = true;
368 }
369 }
370 Ok(())
371}
372
373#[allow(clippy::cast_precision_loss)]
383pub fn measure_layout(
384 rasterizer: &TextRasterizer,
385 root: &LayoutNode,
386 time: MediaTime,
387 size: PictureSize,
388 canvas: (u32, u32),
389) -> Result<LayoutBounds, TextRasterError> {
390 let evaluated = LayoutPlan::new(root, canvas).evaluate(time);
391 let shaped = shape_texts(&evaluated, size, |request| {
392 rasterizer.shape(request).map(Arc::new)
393 })?;
394 let mut resolved = resolve(&evaluated, size, &shaped);
395 fit_texts(&evaluated, &mut resolved, size, |request| {
396 rasterizer.shape(request).map(Arc::new)
397 })?;
398 mark_refused_texts(rasterizer, &evaluated, &mut resolved, size)?;
399 let (width, height) = (size.width() as f32, size.height() as f32);
400 let rect = |[left, top, right, bottom]: [f32; 4]| CanvasRect {
401 left: left / width,
402 top: top / height,
403 right: right / width,
404 bottom: bottom / height,
405 };
406 let mut paths = Vec::new();
407 root.walk(|at, _| paths.push(at.to_owned()));
408 let mut texts = Vec::new();
409 text_nodes(&evaluated.root, &mut 0, &mut texts);
410 let mut headrooms = vec![None; resolved.nodes.len()];
411 for (index, text) in texts {
412 if let Some(slot) = headrooms.get_mut(index) {
413 *slot = Some(text.map_or(1.0, |text| text.advance_headroom));
414 }
415 }
416 Ok(LayoutBounds {
417 nodes: paths
418 .into_iter()
419 .zip(&resolved.nodes)
420 .zip(headrooms)
421 .map(|((at, node), advance_headroom)| NodeBounds {
422 at,
423 border: rect(node.border),
424 content: rect(node.content),
425 overflow: node.overflow,
426 line_count: node.line_count,
427 font_size: node.line_count.map(|_| node.font_size),
428 truncated: node.truncated,
429 baselines: node.baselines.map(|[first, last]| Baselines {
430 first: first / height,
431 last: last / height,
432 }),
433 advance_headroom,
434 })
435 .collect(),
436 })
437}