Skip to main content

alpha2_layout/layout/
mod.rs

1//! Layout generators: box trees laid out by CSS flexbox and grid with the engine's fonts.
2//!
3//! A layout is resolved where text is prepared, so its text is measured and drawn by the
4//! same code. It is resolved in render pixels and rounded to whole pixels. A text node
5//! breaks its lines at its unrounded content width plus [`LAYOUT_WRAP_SLACK`], both when
6//! measured and when drawn.
7
8mod 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
25/// Pixels added to a text node's wrapping width so float summation order cannot re-break a
26/// text sized to its own max-content width. Lines and heights may overflow the box by less
27/// than this.
28pub const LAYOUT_WRAP_SLACK: f32 = 1.0 / 64.0;
29
30/// The width a text node with content `width` pixels wide breaks its lines at. The slack never
31/// takes a width the text host accepts past its limit.
32#[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/// One node's boxes in render pixels, `[left, top, right, bottom]`, whole pixels from the
44/// picture's top-left.
45#[derive(Copy, Clone, Debug, Default, PartialEq)]
46pub struct NodeRects {
47    /// The border box.
48    pub border: [f32; 4],
49    /// The padding box.
50    pub padding: [f32; 4],
51    /// The content box.
52    pub content: [f32; 4],
53    /// The unrounded content width a text breaks at, before the slack.
54    pub text_width: f32,
55    /// The unrounded content height a text fits and is clamped in, before the slack.
56    pub text_height: f32,
57    /// A text node's font size as a fraction of the picture's shorter side, fitted when it
58    /// has a `font_size_fit` ([`fit_texts`]). Zero for other nodes.
59    pub font_size: f32,
60    /// A text node's font size in pixels, as the text host draws it.
61    pub font_pixels: f32,
62    /// Whether a text node's `line_clamp` discarded lines.
63    pub truncated: bool,
64    /// Whether it overflows, as [`NodeBounds::overflow`] says.
65    pub overflow: bool,
66    /// A text node's line count, zero for empty text.
67    pub line_count: Option<u32>,
68    /// A text node's first and last baselines in pixels from the picture's top. `None` for
69    /// other nodes and empty text.
70    pub baselines: Option<[f32; 2]>,
71}
72
73/// Every node's boxes, in preorder ([`resolve`]).
74#[derive(Clone, Debug, Default, PartialEq)]
75pub struct ResolvedLayout {
76    /// Each node, the root first.
77    pub nodes: Vec<NodeRects>,
78}
79
80/// Where a layout's nodes lie ([`measure_layout`]), in preorder.
81#[derive(Clone, Debug, PartialEq)]
82pub struct LayoutBounds {
83    /// Each node, the root first.
84    pub nodes: Vec<NodeBounds>,
85}
86
87/// Where one layout node's boxes lie, before its clip's transform and node visuals.
88#[derive(Clone, Debug, PartialEq)]
89pub struct NodeBounds {
90    /// Its path from the root, like `root.children[1]`.
91    pub at: String,
92    /// The border box, as fractions of the picture.
93    pub border: CanvasRect,
94    /// The content box, as fractions of the picture.
95    pub content: CanvasRect,
96    /// Whether its text, at its fitted size once clamped, is taller than its content box or
97    /// splits a word, or an in-flow child reaches past its padding box. Also set for a text the
98    /// text host refuses to draw, such as a box over 16,384 pixels a side; frames fail on it.
99    pub overflow: bool,
100    /// A text node's line count; `None` for other nodes.
101    pub line_count: Option<u32>,
102    /// A text node's font size as drawn, a fraction of the picture's shorter side. `None`
103    /// for other nodes.
104    pub font_size: Option<f32>,
105    /// Whether a text node's `line_clamp` discarded lines.
106    pub truncated: bool,
107    /// A text node's first and last baselines as fractions of the picture height. `None` for
108    /// other nodes and empty text.
109    pub baselines: Option<Baselines>,
110}
111
112/// The text host request for a layout's text at `font_size` pixels, wrapped at `max_width`
113/// and cut by `clamp`.
114pub(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
144/// How `shaped` lies in a text node's content box `width` by `height` unrounded pixels, cut
145/// by its clamp. Both sides take [`LAYOUT_WRAP_SLACK`] more.
146pub(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
161/// Fits the font size of each text node with a `font_size_fit` to its content box in
162/// `resolved` ([`resolve`]), with lines from `shape`, and updates its font size, lines and
163/// overflow. The boxes keep the sizes they were laid out at.
164///
165/// # Errors
166/// Returns the first refusal of `shape`.
167pub 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
203/// Each text node's preorder index and its text, `None` for empty text.
204fn 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
224/// Each text node's text in preorder; `None` for empty text, which measures and draws
225/// nothing.
226pub(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
238/// Shapes each text node's text in preorder with `shape` on a picture of `size`, as
239/// [`resolve`] lays them out.
240///
241/// # Errors
242/// Returns the first refusal of `shape`.
243pub 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/// Each text node's store key in preorder (`None` for empty text), and each distinct key's
268/// raster request at its font size in `resolved`, wrapped at its unrounded content width plus
269/// the slack and clamped in its content height plus the slack.
270#[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
320/// Marks as overflowing each text node whose raster request (as [`layout_texts`] builds it) the
321/// text host refuses, since frames cannot draw it.
322fn 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/// Where each node of a valid layout tree lies on a picture of `size` at picture time
353/// `time`, laid out with `rasterizer`'s fonts exactly as a frame is.
354///
355/// `canvas` is the project canvas the tree's pixel lengths refer to. Rects are layout boxes,
356/// before the clip's transform and node visuals. An invalid tree gives unspecified rects but
357/// never panics.
358///
359/// # Errors
360/// Returns the text host's refusal of a text: no fonts, or a size out of range.
361#[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}