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/// Rectangles are `{ left, top, right, bottom }` in fractions of the canvas, `ink` is `null`
49/// when the text draws nothing, and `baselines` is `{ first, last }` in fractions of the canvas
50/// height. `fontSize` is the size drawn after `font_size_fit`, a fraction of the canvas's
51/// shorter side. `truncated` says `line_clamp` cut lines, and `overflow` that the drawn text
52/// still splits a word or is taller than `max_height`.
53///
54/// # Errors
55/// Returns [`MeasureError::Input`] for invalid generator JSON or an empty canvas, and
56/// [`MeasureError::Text`] for the text host's refusal.
57pub fn measure_text_json(
58    rasterizer: &TextRasterizer,
59    generator_json: &str,
60    width: u32,
61    height: u32,
62) -> Result<String, MeasureError> {
63    let generator: alpha2_model::Generator = serde_json::from_str(generator_json)
64        .map_err(|error| MeasureError::Input(format!("invalid text generator: {error}")))?;
65    if !generator.is_valid() {
66        return Err(MeasureError::Input(
67            "the text generator has a field out of range".into(),
68        ));
69    }
70    let alpha2_model::Generator::Text { text, style } = &generator else {
71        return Err(MeasureError::Input(
72            "only a text generator draws text".into(),
73        ));
74    };
75    let size = PictureSize::new(width, height)
76        .map_err(|error| MeasureError::Input(format!("invalid canvas size: {error}")))?;
77    let bounds =
78        crate::measure_text(rasterizer, &text.text(), style, size).map_err(MeasureError::Text)?;
79    Ok(serde_json::json!({
80        "layout": rect(bounds.layout),
81        "content": rect(bounds.content),
82        "ink": bounds.ink.map(rect),
83        "lineCount": bounds.line_count,
84        "baselines": baselines(bounds.baselines),
85        "fontSize": bounds.font_size,
86        "truncated": bounds.truncated,
87        "overflow": bounds.overflow,
88    })
89    .to_string())
90}
91
92/// Measures each node of the layout generator `generator_json` on a `width` by `height`
93/// picture at picture time `time` ([`crate::measure_layout`]).
94///
95/// Returns JSON `{ nodes }`, each node in preorder as
96/// `{ at, border, content, overflow, lineCount, baselines, fontSize, truncated }` with boxes in
97/// fractions of the picture. `lineCount` and `fontSize` (the size drawn, a fraction of the
98/// picture's shorter side) are `null` for non-text nodes, and `baselines` (`{ first, last }`,
99/// fractions of the picture height) also for empty text. `truncated` says `line_clamp` cut the
100/// node's lines; `overflow` is also true for a text the text host refuses to draw, such as a box
101/// over 16,384 pixels a side. `canvas` is the project canvas the generator's pixel lengths refer
102/// to, the picture's size when `None`.
103///
104/// # Errors
105/// Returns [`MeasureError::Input`] for an invalid layout generator on that canvas or an empty
106/// picture or canvas, and [`MeasureError::Text`] for the text host's refusal.
107pub fn measure_layout_json(
108    rasterizer: &TextRasterizer,
109    generator_json: &str,
110    width: u32,
111    height: u32,
112    time: MediaTime,
113    canvas: Option<(u32, u32)>,
114) -> Result<String, MeasureError> {
115    let generator: alpha2_model::Generator = serde_json::from_str(generator_json)
116        .map_err(|error| MeasureError::Input(format!("invalid layout generator: {error}")))?;
117    let size = PictureSize::new(width, height)
118        .map_err(|error| MeasureError::Input(format!("invalid canvas size: {error}")))?;
119    let (canvas_width, canvas_height) = canvas.unwrap_or((width, height));
120    PictureSize::new(canvas_width, canvas_height)
121        .map_err(|error| MeasureError::Input(format!("invalid project canvas: {error}")))?;
122    if let Err(issue) = generator.validate_on(canvas_width, canvas_height) {
123        return Err(MeasureError::Input(match issue {
124            alpha2_model::GeneratorIssue::Layout(issue) => {
125                format!("the layout generator {} {}", issue.at, issue.problem)
126            }
127            alpha2_model::GeneratorIssue::Shape(issue) => {
128                format!(
129                    "the layout generator's shape {} {}",
130                    issue.at, issue.problem
131                )
132            }
133            alpha2_model::GeneratorIssue::Invalid => {
134                "the layout generator has a field out of range".into()
135            }
136        }));
137    }
138    let alpha2_model::Generator::Layout { root } = &generator else {
139        return Err(MeasureError::Input(
140            "only a layout generator lays out boxes".into(),
141        ));
142    };
143    let bounds = crate::measure_layout(rasterizer, root, time, size, (canvas_width, canvas_height))
144        .map_err(MeasureError::Text)?;
145    let nodes = bounds
146        .nodes
147        .into_iter()
148        .map(|node| {
149            serde_json::json!({
150                "at": node.at,
151                "border": rect(node.border),
152                "content": rect(node.content),
153                "overflow": node.overflow,
154                "lineCount": node.line_count,
155                "baselines": node.baselines.map(baselines),
156                "fontSize": node.font_size,
157                "truncated": node.truncated,
158            })
159        })
160        .collect::<Vec<_>>();
161    Ok(serde_json::json!({ "nodes": nodes }).to_string())
162}
163
164#[cfg(test)]
165#[path = "json_tests.rs"]
166mod tests;