alpha2-layout 0.6.0

Text and layout boxes measures for alpha2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Layout generators: box trees laid out by CSS flexbox and grid with the engine's fonts.
//!
//! A layout is resolved where text is prepared, so its text is measured and drawn by the
//! same code. It is resolved in render pixels and rounded to whole pixels. A text node
//! breaks its lines at its unrounded content width plus [`LAYOUT_WRAP_SLACK`], both when
//! measured and when drawn.

mod resolve;

#[cfg(test)]
mod tests;

use crate::fit::{BoxedLines, boxed_lines, fit_font_size, pixels, text_clamp};
use crate::text::{TextDraw, layout_text_key, stroke_pixels, text_fill};
use crate::{Baselines, CanvasRect, PictureSize};
use alpha2_eval::{EvaluatedLayout, EvaluatedNode, EvaluatedText, LayoutPlan, NodeContent};
use alpha2_media::EmojiPolicy;
use alpha2_model::{LayoutNode, TextAlign};
use alpha2_text::{ShapedText, TextClamp, TextRasterError, TextRasterRequest, TextRasterizer};
use alpha2_time::MediaTime;
use std::sync::Arc;

pub use resolve::resolve;

/// Pixels added to a text node's wrapping width so float summation order cannot re-break a
/// text sized to its own max-content width. Lines and heights may overflow the box by less
/// than this.
pub const LAYOUT_WRAP_SLACK: f32 = 1.0 / 64.0;

/// The width a text node with content `width` pixels wide breaks its lines at. The slack never
/// takes a width the text host accepts past its limit.
#[allow(clippy::cast_precision_loss)]
pub(crate) fn wrap(width: f32) -> f32 {
    let limit = alpha2_text::MAX_TEXT_BOX as f32;
    let wrapped = (width + LAYOUT_WRAP_SLACK).max(1.0);
    if width <= limit {
        wrapped.min(limit)
    } else {
        wrapped
    }
}

/// One node's boxes in render pixels, `[left, top, right, bottom]`, whole pixels from the
/// picture's top-left.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct NodeRects {
    /// The border box.
    pub border: [f32; 4],
    /// The padding box.
    pub padding: [f32; 4],
    /// The content box.
    pub content: [f32; 4],
    /// The unrounded content width a text breaks at, before the slack.
    pub text_width: f32,
    /// The unrounded content height a text fits and is clamped in, before the slack.
    pub text_height: f32,
    /// A text node's font size as a fraction of the picture's shorter side, fitted when it
    /// has a `font_size_fit` ([`fit_texts`]). Zero for other nodes.
    pub font_size: f32,
    /// A text node's font size in pixels, as the text host draws it.
    pub font_pixels: f32,
    /// Whether a text node's `line_clamp` discarded lines.
    pub truncated: bool,
    /// Whether it overflows, as [`NodeBounds::overflow`] says.
    pub overflow: bool,
    /// A text node's line count, zero for empty text.
    pub line_count: Option<u32>,
    /// A text node's first and last baselines in pixels from the picture's top. `None` for
    /// other nodes and empty text.
    pub baselines: Option<[f32; 2]>,
}

/// Every node's boxes, in preorder ([`resolve`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ResolvedLayout {
    /// Each node, the root first.
    pub nodes: Vec<NodeRects>,
}

/// Where a layout's nodes lie ([`measure_layout`]), in preorder.
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutBounds {
    /// Each node, the root first.
    pub nodes: Vec<NodeBounds>,
}

/// Where one layout node's boxes lie, before its clip's transform and node visuals.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeBounds {
    /// Its path from the root, like `root.children[1]`.
    pub at: String,
    /// The border box, as fractions of the picture.
    pub border: CanvasRect,
    /// The content box, as fractions of the picture.
    pub content: CanvasRect,
    /// Whether its text, at its fitted size once clamped, is taller than its content box or
    /// splits a word, or an in-flow child reaches past its padding box. Also set for a text the
    /// text host refuses to draw, such as a box over 16,384 pixels a side; frames fail on it.
    pub overflow: bool,
    /// A text node's line count; `None` for other nodes.
    pub line_count: Option<u32>,
    /// A text node's font size as drawn, a fraction of the picture's shorter side. `None`
    /// for other nodes.
    pub font_size: Option<f32>,
    /// Whether a text node's `line_clamp` discarded lines.
    pub truncated: bool,
    /// A text node's first and last baselines as fractions of the picture height. `None` for
    /// other nodes and empty text.
    pub baselines: Option<Baselines>,
}

/// The text host request for a layout's text at `font_size` pixels, wrapped at `max_width`
/// and cut by `clamp`.
pub(crate) fn text_request(
    text: &EvaluatedText,
    font_size: f32,
    max_width: f32,
    clamp: Option<TextClamp>,
    content_version: u64,
) -> TextRasterRequest {
    TextRasterRequest {
        text: text.content.clone(),
        font_size,
        max_width,
        line_height: text.line_height,
        align: match text.text_align {
            TextAlign::Start => alpha2_media::TextAlign::Start,
            TextAlign::Center => alpha2_media::TextAlign::Center,
            TextAlign::End => alpha2_media::TextAlign::End,
        },
        fill: text_fill(&text.fill),
        emoji_policy: EmojiPolicy::Color,
        content_version,
        strokes: stroke_pixels(&text.strokes, font_size),
        background: None,
        split_background: false,
        font_family: text.font_family.clone(),
        letter_spacing: text.letter_spacing * font_size,
        font_weight: text.font_weight,
        clamp,
    }
}

/// How `shaped` lies in a text node's content box `width` by `height` unrounded pixels, cut
/// by its clamp. Both sides take [`LAYOUT_WRAP_SLACK`] more.
pub(crate) fn node_lines(
    text: &EvaluatedText,
    shaped: &ShapedText,
    width: f32,
    height: f32,
) -> BoxedLines {
    boxed_lines(
        shaped,
        wrap(width),
        height + LAYOUT_WRAP_SLACK,
        text.line_clamp.as_ref().and_then(|clamp| clamp.max_lines),
        text.line_clamp.is_some(),
    )
}

/// Fits the font size of each text node with a `font_size_fit` to its content box in
/// `resolved` ([`resolve`]), with lines from `shape`, and updates its font size, lines and
/// overflow. The boxes keep the sizes they were laid out at.
///
/// # Errors
/// Returns the first refusal of `shape`.
pub fn fit_texts(
    layout: &EvaluatedLayout,
    resolved: &mut ResolvedLayout,
    size: PictureSize,
    mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
) -> Result<(), TextRasterError> {
    let unit = size.unit();
    let mut found = Vec::new();
    text_nodes(&layout.root, &mut 0, &mut found);
    for (node, text) in found {
        let (Some(text), Some(rects)) = (text, resolved.nodes.get_mut(node)) else {
            continue;
        };
        if text.font_size_fit.is_none() {
            continue;
        }
        let (width, height) = (rects.text_width, rects.text_height);
        let request = |pixels| text_request(text, pixels, 0.0, None, 1);
        let fitted = fit_font_size(text.font_size, text.font_size_fit, unit, |pixels| {
            Ok(node_lines(text, &*shape(&request(pixels))?, width, height).fits)
        })?;
        let lines = node_lines(text, &*shape(&request(fitted.font_pixels))?, width, height);
        let top = rects.content[1];
        rects.font_size = fitted.font_size;
        rects.font_pixels = fitted.font_pixels;
        rects.truncated = lines.truncated;
        rects.line_count = Some(lines.lines.line_count);
        rects.baselines = Some([
            top + lines.lines.first_baseline,
            top + lines.lines.last_baseline,
        ]);
        rects.overflow = lines.overflow;
    }
    Ok(())
}

/// Each text node's preorder index and its text, `None` for empty text.
fn text_nodes<'a>(
    node: &'a EvaluatedNode,
    index: &mut usize,
    out: &mut Vec<(usize, Option<&'a EvaluatedText>)>,
) {
    let at = *index;
    *index += 1;
    match &node.content {
        NodeContent::Text(text) => {
            out.push((at, Some(&**text).filter(|text| !text.content.is_empty())));
        }
        NodeContent::Children(children) => {
            for child in children {
                text_nodes(child, index, out);
            }
        }
        NodeContent::Empty | NodeContent::Shape(_) => {}
    }
}

/// Each text node's text in preorder; `None` for empty text, which measures and draws
/// nothing.
pub(crate) fn texts<'a>(node: &'a EvaluatedNode, out: &mut Vec<Option<&'a EvaluatedText>>) {
    match &node.content {
        NodeContent::Text(text) => out.push(Some(&**text).filter(|text| !text.content.is_empty())),
        NodeContent::Children(children) => {
            for child in children {
                texts(child, out);
            }
        }
        NodeContent::Empty | NodeContent::Shape(_) => {}
    }
}

/// Shapes each text node's text in preorder with `shape` on a picture of `size`, as
/// [`resolve`] lays them out.
///
/// # Errors
/// Returns the first refusal of `shape`.
pub fn shape_texts(
    layout: &EvaluatedLayout,
    size: PictureSize,
    mut shape: impl FnMut(&TextRasterRequest) -> Result<Arc<ShapedText>, TextRasterError>,
) -> Result<Vec<Option<Arc<ShapedText>>>, TextRasterError> {
    let unit = size.unit();
    let mut list = Vec::new();
    texts(&layout.root, &mut list);
    list.into_iter()
        .map(|text| {
            text.map(|text| {
                shape(&text_request(
                    text,
                    pixels(text.font_size, unit),
                    0.0,
                    None,
                    1,
                ))
            })
            .transpose()
        })
        .collect()
}

/// Each text node's store key in preorder (`None` for empty text), and each distinct key's
/// raster request at its font size in `resolved`, wrapped at its unrounded content width plus
/// the slack and clamped in its content height plus the slack.
#[must_use]
pub fn layout_texts(
    layout: &EvaluatedLayout,
    resolved: &ResolvedLayout,
    size: PictureSize,
) -> (Vec<Option<u64>>, Vec<(u64, TextDraw)>) {
    let unit = size.unit();
    let mut found = Vec::new();
    text_nodes(&layout.root, &mut 0, &mut found);
    let mut keys = Vec::with_capacity(found.len());
    let mut requests: Vec<(u64, TextDraw)> = Vec::new();
    for (node, text) in found {
        let Some(text) = text else {
            keys.push(None);
            continue;
        };
        let rects = resolved.nodes.get(node).copied().unwrap_or_default();
        let font_size = if rects.font_pixels > 0.0 {
            rects.font_pixels
        } else {
            pixels(text.font_size, unit)
        };
        let clamp = text
            .line_clamp
            .as_ref()
            .map(|clamp| text_clamp(clamp, rects.text_height + LAYOUT_WRAP_SLACK));
        let mut request = text_request(text, font_size, wrap(rects.text_width), clamp, 1);
        let shadows = crate::text::shadow_pixels(&text.shadows, request.font_size);
        let key = layout_text_key(&request, &shadows, &text.animators);
        request.content_version = key;
        if !requests.iter().any(|(held, _)| *held == key) {
            let animation = (!text.animators.is_empty()).then(|| crate::TextAnimation {
                animators: text.animators.clone(),
                runs: Vec::new(),
                time: layout.time,
            });
            requests.push((
                key,
                TextDraw {
                    request,
                    shadows,
                    animation,
                },
            ));
        }
        keys.push(Some(key));
    }
    (keys, requests)
}

/// Marks as overflowing each text node whose raster request (as [`layout_texts`] builds it) the
/// text host refuses, since frames cannot draw it.
fn mark_refused_texts(
    rasterizer: &TextRasterizer,
    layout: &EvaluatedLayout,
    resolved: &mut ResolvedLayout,
    size: PictureSize,
) -> Result<(), TextRasterError> {
    let (keys, requests) = layout_texts(layout, resolved, size);
    let mut refused = Vec::new();
    for (key, draw) in &requests {
        match rasterizer.measure(&draw.request) {
            Ok(_) => {}
            Err(TextRasterError::InvalidRequest | TextRasterError::TooLarge) => refused.push(*key),
            Err(error) => return Err(error),
        }
    }
    if refused.is_empty() {
        return Ok(());
    }
    let mut found = Vec::new();
    text_nodes(&layout.root, &mut 0, &mut found);
    for ((node, _), key) in found.into_iter().zip(keys) {
        if key.is_some_and(|key| refused.contains(&key))
            && let Some(rects) = resolved.nodes.get_mut(node)
        {
            rects.overflow = true;
        }
    }
    Ok(())
}

/// Where each node of a valid layout tree lies on a picture of `size` at picture time
/// `time`, laid out with `rasterizer`'s fonts exactly as a frame is.
///
/// `canvas` is the project canvas the tree's pixel lengths refer to. Rects are layout boxes,
/// before the clip's transform and node visuals. An invalid tree gives unspecified rects but
/// never panics.
///
/// # Errors
/// Returns the text host's refusal of a text: no fonts, or a size out of range.
#[allow(clippy::cast_precision_loss)]
pub fn measure_layout(
    rasterizer: &TextRasterizer,
    root: &LayoutNode,
    time: MediaTime,
    size: PictureSize,
    canvas: (u32, u32),
) -> Result<LayoutBounds, TextRasterError> {
    let evaluated = LayoutPlan::new(root, canvas).evaluate(time);
    let shaped = shape_texts(&evaluated, size, |request| {
        rasterizer.shape(request).map(Arc::new)
    })?;
    let mut resolved = resolve(&evaluated, size, &shaped);
    fit_texts(&evaluated, &mut resolved, size, |request| {
        rasterizer.shape(request).map(Arc::new)
    })?;
    mark_refused_texts(rasterizer, &evaluated, &mut resolved, size)?;
    let (width, height) = (size.width() as f32, size.height() as f32);
    let rect = |[left, top, right, bottom]: [f32; 4]| CanvasRect {
        left: left / width,
        top: top / height,
        right: right / width,
        bottom: bottom / height,
    };
    let mut paths = Vec::new();
    root.walk(|at, _| paths.push(at.to_owned()));
    Ok(LayoutBounds {
        nodes: paths
            .into_iter()
            .zip(&resolved.nodes)
            .map(|(at, node)| NodeBounds {
                at,
                border: rect(node.border),
                content: rect(node.content),
                overflow: node.overflow,
                line_count: node.line_count,
                font_size: node.line_count.map(|_| node.font_size),
                truncated: node.truncated,
                baselines: node.baselines.map(|[first, last]| Baselines {
                    first: first / height,
                    last: last / height,
                }),
            })
            .collect(),
    })
}