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;
pub const LAYOUT_WRAP_SLACK: f32 = 1.0 / 64.0;
#[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
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct NodeRects {
pub border: [f32; 4],
pub padding: [f32; 4],
pub content: [f32; 4],
pub text_width: f32,
pub text_height: f32,
pub font_size: f32,
pub font_pixels: f32,
pub truncated: bool,
pub overflow: bool,
pub line_count: Option<u32>,
pub baselines: Option<[f32; 2]>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ResolvedLayout {
pub nodes: Vec<NodeRects>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutBounds {
pub nodes: Vec<NodeBounds>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct NodeBounds {
pub at: String,
pub border: CanvasRect,
pub content: CanvasRect,
pub overflow: bool,
pub line_count: Option<u32>,
pub font_size: Option<f32>,
pub truncated: bool,
pub baselines: Option<Baselines>,
}
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,
}
}
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(),
)
}
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(())
}
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(_) => {}
}
}
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(_) => {}
}
}
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()
}
#[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)
}
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(())
}
#[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(),
})
}