Skip to main content

alpha2_layout/
json.rs

1//! Measurements as JSON, in the form the wasm binding and the Python package return.
2
3use std::fmt;
4
5use alpha2_text::{TextRasterError, TextRasterizer};
6use alpha2_time::MediaTime;
7
8use crate::{Baselines, CanvasRect, PictureSize};
9
10/// Why a generator could not be measured.
11#[derive(Debug)]
12#[non_exhaustive]
13pub enum MeasureError {
14    /// Not a valid generator of the measured kind, or an empty picture.
15    Input(String),
16    /// The text host refused: no fonts, say.
17    Text(TextRasterError),
18}
19
20impl fmt::Display for MeasureError {
21    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            Self::Input(message) => formatter.write_str(message),
24            Self::Text(error) => write!(formatter, "text failed: {error}"),
25        }
26    }
27}
28
29impl std::error::Error for MeasureError {}
30
31fn baselines(baselines: Baselines) -> serde_json::Value {
32    serde_json::json!({ "first": baselines.first, "last": baselines.last })
33}
34
35fn rect(rect: CanvasRect) -> serde_json::Value {
36    serde_json::json!({
37        "left": rect.left,
38        "top": rect.top,
39        "right": rect.right,
40        "bottom": rect.bottom,
41    })
42}
43
44/// Measures the text generator `generator_json` on a `width` by `height` canvas
45/// ([`crate::measure_text`]).
46///
47/// Returns JSON `{ layout, content, ink, lineCount, baselines, fontSize, truncated, overflow }`,
48/// and `advanceHeadroom` (see [`crate::TextBounds::advance_headroom`]) when it is not 1.
49/// Rectangles are `{ left, top, right, bottom }` in fractions of the canvas, `ink` is `null`
50/// when the text draws nothing, and `baselines` is `{ first, last }` in fractions of the canvas
51/// height. `fontSize` is the size drawn after `font_size_fit`, a fraction of the canvas's
52/// shorter side. `truncated` says `line_clamp` cut lines, and `overflow` that the drawn text
53/// still splits a word or is taller than `max_height`.
54///
55/// # Errors
56/// Returns [`MeasureError::Input`] for invalid generator JSON or an empty canvas, and
57/// [`MeasureError::Text`] for the text host's refusal.
58pub fn measure_text_json(
59    rasterizer: &TextRasterizer,
60    generator_json: &str,
61    width: u32,
62    height: u32,
63) -> Result<String, MeasureError> {
64    let generator: alpha2_model::Generator = serde_json::from_str(generator_json)
65        .map_err(|error| MeasureError::Input(format!("invalid text generator: {error}")))?;
66    if !generator.is_valid() {
67        return Err(MeasureError::Input(
68            "the text generator has a field out of range".into(),
69        ));
70    }
71    let alpha2_model::Generator::Text { text, style } = &generator else {
72        return Err(MeasureError::Input(
73            "only a text generator draws text".into(),
74        ));
75    };
76    let size = PictureSize::new(width, height)
77        .map_err(|error| MeasureError::Input(format!("invalid canvas size: {error}")))?;
78    let bounds = crate::measure_text(
79        rasterizer,
80        &crate::TextAt::new(text, MediaTime::ZERO),
81        style,
82        size,
83    )
84    .map_err(MeasureError::Text)?;
85    let mut measured = serde_json::json!({
86        "layout": rect(bounds.layout),
87        "content": rect(bounds.content),
88        "ink": bounds.ink.map(rect),
89        "lineCount": bounds.line_count,
90        "baselines": baselines(bounds.baselines),
91        "fontSize": bounds.font_size,
92        "truncated": bounds.truncated,
93        "overflow": bounds.overflow,
94    });
95    with_headroom(&mut measured, Some(bounds.advance_headroom));
96    Ok(measured.to_string())
97}
98
99/// Adds `advanceHeadroom` to `measured` when animators reserve some.
100fn with_headroom(measured: &mut serde_json::Value, headroom: Option<f32>) {
101    if let Some(headroom) = headroom.filter(|headroom| *headroom > 1.0) {
102        measured["advanceHeadroom"] = serde_json::json!(headroom);
103    }
104}
105
106/// The unit a report counts a text's positions in: each binding's string unit.
107#[derive(Copy, Clone, Debug, Eq, PartialEq)]
108pub enum StringUnit {
109    /// UTF-8 bytes (Rust).
110    Utf8,
111    /// UTF-16 code units (JavaScript).
112    Utf16,
113    /// Unicode scalar values (Python).
114    CodePoints,
115}
116
117impl StringUnit {
118    /// The position of each UTF-8 byte offset of `text` in this unit, plus one for its end.
119    fn positions(self, text: &str) -> Vec<usize> {
120        let mut positions = vec![0; text.len() + 1];
121        let mut at = 0;
122        for (start, character) in text.char_indices() {
123            let width = match self {
124                Self::Utf8 => character.len_utf8(),
125                Self::Utf16 => character.len_utf16(),
126                Self::CodePoints => 1,
127            };
128            for slot in &mut positions[start..start + character.len_utf8()] {
129                *slot = at;
130            }
131            at += width;
132        }
133        positions[text.len()] = at;
134        positions
135    }
136}
137
138/// Reports where each line, word and cluster of the text generator `generator_json` lies on a
139/// `width` by `height` canvas ([`crate::text_layout`]), ranges in `unit`.
140///
141/// Returns JSON `{ fontSize, layout, lines, words, clusters }`: lines as `{ clusters: [first,
142/// end], box, em, baseline }`, words as `{ clusters, boxes, ink }`, clusters as `{ range:
143/// [start, end], run, word, line, space, ellipsis, fontSize, baseline, box, ink }`. Rectangles
144/// are `{ left, top, right, bottom }` in fractions of the canvas, baselines fractions of its
145/// height, font sizes fractions of its shorter side; `run`, `word` and `ink` may be `null`.
146///
147/// # Errors
148/// Returns [`MeasureError::Input`] for invalid generator JSON or an empty canvas, and
149/// [`MeasureError::Text`] for the text host's refusal.
150pub fn text_layout_json(
151    rasterizer: &TextRasterizer,
152    generator_json: &str,
153    width: u32,
154    height: u32,
155    unit: StringUnit,
156) -> Result<String, MeasureError> {
157    let generator: alpha2_model::Generator = serde_json::from_str(generator_json)
158        .map_err(|error| MeasureError::Input(format!("invalid text generator: {error}")))?;
159    if !generator.is_valid() {
160        return Err(MeasureError::Input(
161            "the text generator has a field out of range".into(),
162        ));
163    }
164    let alpha2_model::Generator::Text { text, style } = &generator else {
165        return Err(MeasureError::Input(
166            "only a text generator draws text".into(),
167        ));
168    };
169    let size = PictureSize::new(width, height)
170        .map_err(|error| MeasureError::Input(format!("invalid canvas size: {error}")))?;
171    let report = crate::text_layout(
172        rasterizer,
173        &crate::TextAt::new(text, MediaTime::ZERO),
174        style,
175        size,
176    )
177    .map_err(MeasureError::Text)?;
178    let positions = unit.positions(&text.text());
179    let at = |byte: usize| positions.get(byte).copied().unwrap_or(0);
180    let span = |range: &std::ops::Range<usize>| serde_json::json!([range.start, range.end]);
181    Ok(serde_json::json!({
182        "fontSize": report.font_size,
183        "layout": rect(report.layout),
184        "lines": report.lines.iter().map(|line| serde_json::json!({
185            "clusters": span(&line.clusters),
186            "box": rect(line.line_box),
187            "em": rect(line.em),
188            "baseline": line.baseline,
189        })).collect::<Vec<_>>(),
190        "words": report.words.iter().map(|word| serde_json::json!({
191            "clusters": span(&word.clusters),
192            "boxes": word.boxes.iter().copied().map(rect).collect::<Vec<_>>(),
193            "ink": word.ink.map(rect),
194        })).collect::<Vec<_>>(),
195        "clusters": report.clusters.iter().map(|cluster| serde_json::json!({
196            "range": [at(cluster.bytes.start), at(cluster.bytes.end)],
197            "run": cluster.run,
198            "word": cluster.word,
199            "line": cluster.line,
200            "space": cluster.space,
201            "ellipsis": cluster.ellipsis,
202            "fontSize": cluster.font_size,
203            "baseline": cluster.baseline,
204            "box": rect(cluster.cluster_box),
205            "ink": cluster.ink.map(rect),
206        })).collect::<Vec<_>>(),
207    })
208    .to_string())
209}
210
211/// Measures each node of the layout generator `generator_json` on a `width` by `height`
212/// picture at picture time `time` ([`crate::measure_layout`]).
213///
214/// Returns JSON `{ nodes }`, each node in preorder as
215/// `{ at, border, content, overflow, lineCount, baselines, fontSize, truncated }`, and
216/// `advanceHeadroom` for a text node whose animators reserve some, with boxes in
217/// fractions of the picture. `lineCount` and `fontSize` (the size drawn, a fraction of the
218/// picture's shorter side) are `null` for non-text nodes, and `baselines` (`{ first, last }`,
219/// fractions of the picture height) also for empty text. `truncated` says `line_clamp` cut the
220/// node's lines; `overflow` is also true for a text the text host refuses to draw, such as a box
221/// over 16,384 pixels a side. `canvas` is the project canvas the generator's pixel lengths refer
222/// to, the picture's size when `None`.
223///
224/// # Errors
225/// Returns [`MeasureError::Input`] for an invalid layout generator on that canvas or an empty
226/// picture or canvas, and [`MeasureError::Text`] for the text host's refusal.
227pub fn measure_layout_json(
228    rasterizer: &TextRasterizer,
229    generator_json: &str,
230    width: u32,
231    height: u32,
232    time: MediaTime,
233    canvas: Option<(u32, u32)>,
234) -> Result<String, MeasureError> {
235    let generator: alpha2_model::Generator = serde_json::from_str(generator_json)
236        .map_err(|error| MeasureError::Input(format!("invalid layout generator: {error}")))?;
237    let size = PictureSize::new(width, height)
238        .map_err(|error| MeasureError::Input(format!("invalid canvas size: {error}")))?;
239    let (canvas_width, canvas_height) = canvas.unwrap_or((width, height));
240    PictureSize::new(canvas_width, canvas_height)
241        .map_err(|error| MeasureError::Input(format!("invalid project canvas: {error}")))?;
242    if let Err(issue) = generator.validate_on(canvas_width, canvas_height) {
243        return Err(MeasureError::Input(match issue {
244            alpha2_model::GeneratorIssue::Layout(issue) => {
245                format!("the layout generator {} {}", issue.at, issue.problem)
246            }
247            alpha2_model::GeneratorIssue::Shape(issue) => {
248                format!(
249                    "the layout generator's shape {} {}",
250                    issue.at, issue.problem
251                )
252            }
253            alpha2_model::GeneratorIssue::Invalid
254            | alpha2_model::GeneratorIssue::TextRun { .. } => {
255                "the layout generator has a field out of range".into()
256            }
257        }));
258    }
259    let alpha2_model::Generator::Layout { root } = &generator else {
260        return Err(MeasureError::Input(
261            "only a layout generator lays out boxes".into(),
262        ));
263    };
264    let bounds = crate::measure_layout(rasterizer, root, time, size, (canvas_width, canvas_height))
265        .map_err(MeasureError::Text)?;
266    let nodes = bounds
267        .nodes
268        .into_iter()
269        .map(|node| {
270            let mut measured = serde_json::json!({
271                "at": node.at,
272                "border": rect(node.border),
273                "content": rect(node.content),
274                "overflow": node.overflow,
275                "lineCount": node.line_count,
276                "baselines": node.baselines.map(baselines),
277                "fontSize": node.font_size,
278                "truncated": node.truncated,
279            });
280            with_headroom(&mut measured, node.advance_headroom);
281            measured
282        })
283        .collect::<Vec<_>>();
284    Ok(serde_json::json!({ "nodes": nodes }).to_string())
285}
286
287#[cfg(test)]
288#[path = "json_tests.rs"]
289mod tests;