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    /// The most a text node's animators can widen its advances; its lines break at its content
111    /// width over this. `None` for other nodes.
112    pub advance_headroom: Option<f32>,
113}
114
115/// The text host request for a layout's text at `font_size` pixels, wrapped at `max_width`
116/// and cut by `clamp`.
117pub(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
165/// How `shaped` lies in a text node's content box `width` by `height` unrounded pixels, cut
166/// by its clamp. Both sides take [`LAYOUT_WRAP_SLACK`] more.
167pub(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
182/// Fits the font size of each text node with a `font_size_fit` to its content box in
183/// `resolved` ([`resolve`]), with lines from `shape`, and updates its font size, lines and
184/// overflow. The boxes keep the sizes they were laid out at.
185///
186/// # Errors
187/// Returns the first refusal of `shape`.
188pub 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
224/// Each text node's preorder index and its text, `None` for empty text.
225fn 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
245/// Each text node's text in preorder; `None` for empty text, which measures and draws
246/// nothing.
247pub(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
259/// Shapes each text node's text in preorder with `shape` on a picture of `size`, as
260/// [`resolve`] lays them out.
261///
262/// # Errors
263/// Returns the first refusal of `shape`.
264pub 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/// Each text node's store key in preorder (`None` for empty text), and each distinct key's
289/// raster request at its font size in `resolved`, wrapped at its unrounded content width plus
290/// the slack and clamped in its content height plus the slack.
291#[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
341/// Marks as overflowing each text node whose raster request (as [`layout_texts`] builds it) the
342/// text host refuses, since frames cannot draw it.
343fn 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/// Where each node of a valid layout tree lies on a picture of `size` at picture time
374/// `time`, laid out with `rasterizer`'s fonts exactly as a frame is.
375///
376/// `canvas` is the project canvas the tree's pixel lengths refer to. Rects are layout boxes,
377/// before the clip's transform and node visuals. An invalid tree gives unspecified rects but
378/// never panics.
379///
380/// # Errors
381/// Returns the text host's refusal of a text: no fonts, or a size out of range.
382#[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}