Skip to main content

alpha2_model/
text.rs

1//! Styled text: what caption tracks and text generators draw.
2
3use crate::{Paint, Rgba, TextAnimator, Vec2};
4use serde::{Deserialize, Serialize};
5
6/// Most bytes of text in one caption cue or text generator.
7pub const MAX_TEXT_CONTENT_BYTES: usize = 4_096;
8
9/// Most bytes in a text style's font family name.
10pub const MAX_FONT_FAMILY_BYTES: usize = 256;
11
12/// Largest font size of a text generator, as a fraction of the canvas's shorter side.
13pub const MAX_TEXT_GENERATOR_FONT_SIZE: f32 = 1.0;
14
15/// The line heights text takes, as multiples of the font size.
16pub const LINE_HEIGHT_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;
17
18/// The letter spacings text takes, as fractions of the font size.
19pub const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;
20
21/// The font weights text takes, as CSS `font-weight` numbers.
22pub const FONT_WEIGHT_RANGE: std::ops::RangeInclusive<u16> = 1..=1000;
23
24/// Most strokes around one text.
25pub const MAX_TEXT_STROKES: usize = 4;
26
27/// Widest a text's strokes reach together (the sum of their widths), as a fraction of the
28/// font size.
29pub const MAX_TEXT_STROKE_EXTENT: f32 = 0.5;
30
31/// Most shadows under one text.
32pub const MAX_TEXT_SHADOWS: usize = 4;
33
34/// Farthest a text shadow lies from its text on each axis, as a fraction of the font size.
35pub const MAX_TEXT_SHADOW_OFFSET: f32 = 1.0;
36
37/// Widest text shadow blur, as a fraction of the font size.
38pub const MAX_TEXT_SHADOW_BLUR: f32 = 1.0;
39
40/// Largest text background padding, as a fraction of the font size.
41pub const MAX_TEXT_PADDING: f32 = 2.0;
42/// Largest magnitude of a text's `position` or `anchor` coordinate, in canvas or text extents.
43pub const MAX_TEXT_POSITION: f32 = 1_024.0;
44
45/// Most bytes in a [`BlockEllipsis::String`].
46pub const MAX_BLOCK_ELLIPSIS_BYTES: usize = 64;
47
48/// Steps per unit of font size (a fraction of the shorter side) that a fitted font size takes
49/// between its bounds. Steps of `1 / 8192` are exact in `f32` and under a pixel at 8K.
50pub const FONT_SIZE_FIT_STEPS: f32 = 8_192.0;
51
52/// How text looks and where it lies, for caption cues or a text [`crate::Generator`].
53///
54/// The font size is a fraction of the canvas's shorter side, the wrapping width a fraction
55/// of the canvas width, and strokes, shadows and padding fractions of the font size. The
56/// engine draws with its host's registered fonts, `font_family` first, then the rest in
57/// fallback order.
58///
59/// Painting is bottom to top as in CSS: background boxes, shadows (last listed lowest),
60/// strokes (outermost lowest), fill, then color glyphs.
61#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
62#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
63#[serde(deny_unknown_fields)]
64pub struct TextStyle {
65    /// The family, as the font's name table gives it (typographic family, else family), matched
66    /// ASCII case-insensitively. Missing glyphs and unknown families fall back to the other fonts
67    /// in order; `None` uses the fallback order alone. Non-empty, at most
68    /// [`MAX_FONT_FAMILY_BYTES`] bytes.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub font_family: Option<String>,
71    /// Font size as a fraction of the canvas's shorter side: positive, at most
72    /// [`crate::MAX_CAPTION_FONT_SIZE`] on a caption track and [`MAX_TEXT_GENERATOR_FONT_SIZE`]
73    /// in a text generator.
74    #[serde(default = "default_font_size")]
75    pub font_size: f32,
76    /// What paints the glyphs; a color reads as a solid paint. Gradient positions are in the
77    /// text's layout box, `(0, 0)` top-left to `(1, 1)` bottom-right, and a radial radius is a
78    /// fraction of the box's shorter side. Default solid white.
79    #[serde(default = "white_paint")]
80    pub fill: Paint,
81    /// Baseline-to-baseline distance in font sizes, in `[0.5, 3]`. Each line's em box (0.8 font
82    /// sizes above the baseline, 0.2 below) is centred in a taller line.
83    #[serde(default = "default_line_height")]
84    pub line_height: f32,
85    /// Space after each character, as a fraction of the font size, in `[-0.5, 1]`, added as CSS
86    /// `letter-spacing` does: none after a line's last character or within cursive scripts such
87    /// as Arabic. A non-zero value turns optional ligatures off.
88    #[serde(default)]
89    pub letter_spacing: f32,
90    /// The weight in `[1, 1000]` used to match a family's faces, as CSS Fonts 4 matches
91    /// `font-weight`. Variable faces draw at it, clamped to their `wght` axis; no face is
92    /// synthetically emboldened.
93    #[serde(default = "default_font_weight")]
94    pub font_weight: u16,
95    /// How lines align within the text.
96    #[serde(default)]
97    pub align: TextAlign,
98    /// Width text wraps at, as a fraction of the canvas width, in `(0, 1]`.
99    #[serde(default = "default_max_width")]
100    pub max_width: f32,
101    /// Height the lines' box fits in, as a fraction of the canvas height, in `(0, 1]`, for
102    /// `font_size_fit` and `line_clamp`. Text taller than it still draws past it, as CSS
103    /// `max-height` lets a box with visible overflow. `None` sets no height.
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub max_height: Option<f32>,
106    /// The range the font size is fitted in so the text fits its box. `None` draws at the
107    /// font size as set.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub font_size_fit: Option<FontSizeFit>,
110    /// Where lines are cut and what ends a cut line, as CSS `line-clamp`. `None` cuts nothing.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub line_clamp: Option<LineClamp>,
113    /// Where on the canvas the text's anchor lies, `(0, 0)` top-left to `(1, 1)` bottom-right;
114    /// each coordinate within [`MAX_TEXT_POSITION`].
115    #[serde(default = "default_position")]
116    pub position: Vec2,
117    /// The point of the text, background included, placed at `position`; `(0.5, 1)` is its
118    /// bottom centre. Each coordinate within [`MAX_TEXT_POSITION`].
119    #[serde(default = "default_anchor")]
120    pub anchor: Vec2,
121    /// Bands around the glyphs, innermost first, each outside the one before. At most
122    /// [`MAX_TEXT_STROKES`], widths summing to at most [`MAX_TEXT_STROKE_EXTENT`].
123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
124    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
125    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
126    pub strokes: Vec<TextStroke>,
127    /// Shadows of the glyphs and strokes, the first on top, as CSS `text-shadow` lists them. At
128    /// most [`MAX_TEXT_SHADOWS`].
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
131    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
132    pub shadows: Vec<TextShadow>,
133    /// A box behind each line.
134    #[serde(default)]
135    pub background: Option<TextBackground>,
136    /// Per-character motion and color, applied in order, at most [`crate::MAX_TEXT_ANIMATORS`].
137    /// Keyframes are in the holder's time (since a caption cue's start, or a text generator's
138    /// picture time). They never change line layout.
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
141    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
142    pub animators: Vec<TextAnimator>,
143}
144
145impl Default for TextStyle {
146    fn default() -> Self {
147        Self {
148            font_family: None,
149            font_size: default_font_size(),
150            fill: white_paint(),
151            line_height: default_line_height(),
152            letter_spacing: 0.0,
153            font_weight: default_font_weight(),
154            align: TextAlign::default(),
155            max_width: default_max_width(),
156            max_height: None,
157            font_size_fit: None,
158            line_clamp: None,
159            position: default_position(),
160            anchor: default_anchor(),
161            strokes: Vec::new(),
162            shadows: Vec::new(),
163            background: None,
164            animators: Vec::new(),
165        }
166    }
167}
168
169const fn default_font_size() -> f32 {
170    0.05
171}
172
173const fn white_paint() -> Paint {
174    Paint::Solid {
175        color: Rgba::new(1.0, 1.0, 1.0, 1.0),
176    }
177}
178
179const fn default_line_height() -> f32 {
180    1.2
181}
182
183const fn default_font_weight() -> u16 {
184    400
185}
186
187const fn default_max_width() -> f32 {
188    0.9
189}
190
191const fn default_position() -> Vec2 {
192    Vec2::new(0.5, 0.92)
193}
194
195const fn default_anchor() -> Vec2 {
196    Vec2::new(0.5, 1.0)
197}
198
199/// The font sizes a text is fitted between, as fractions of the canvas's shorter side.
200///
201/// The text draws at the largest size in `[min, max]` at which no line breaks inside a word,
202/// the lines fit the box's height, and there are no more lines than `line_clamp.max_lines`.
203/// When no size fits, it draws at `min`. A `min` above `max` wins, as CSS `min-width` does.
204/// Sizes are tried by bisection over `max`, `min` and the multiples of `1 / 8192` between.
205#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
206#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
207#[serde(deny_unknown_fields)]
208pub struct FontSizeFit {
209    /// Smallest font size, positive. At most the holder's largest font size.
210    pub min: f32,
211    /// Largest font size, at least `min` and at most the holder's largest font size. `None`
212    /// is `font_size`, so the text only shrinks.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub max: Option<f32>,
215}
216
217impl FontSizeFit {
218    /// Whether both bounds are positive, in order, and at most `max_font_size`.
219    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
220        let size = |value: f32| value.is_finite() && value > 0.0 && value <= max_font_size;
221        size(self.min) && self.max.is_none_or(|max| size(max) && self.min <= max)
222    }
223}
224
225/// Lines past a clamp point are discarded, as CSS Overflow 4 `line-clamp` discards them.
226///
227/// The clamp point is after the last line within `max_lines` that fits the box's height, and
228/// never before the first line. Unlike CSS, the height counts without `max-lines: auto`, so
229/// clamped text stays inside a box that has one. A cut line is shortened to its last word end,
230/// else its last character, at which the ellipsis fits after it. Text animators count no unit
231/// for the ellipsis, which moves with the character before it.
232#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
233#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
234#[serde(deny_unknown_fields)]
235pub struct LineClamp {
236    /// Most lines, at least 1, as CSS `max-lines`. `None` cuts at the box's height alone.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub max_lines: Option<u32>,
239    /// What ends the last kept line of cut text. Default `ellipsis`, as CSS `line-clamp` sets it.
240    #[serde(default)]
241    pub block_ellipsis: BlockEllipsis,
242}
243
244impl LineClamp {
245    pub(crate) fn is_valid(&self) -> bool {
246        self.max_lines != Some(0) && self.block_ellipsis.is_valid()
247    }
248}
249
250/// What ends a line that a clamp cuts, as CSS `block-ellipsis`.
251#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
252#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
253#[serde(rename_all = "snake_case")]
254pub enum BlockEllipsis {
255    /// No mark. The cut line keeps its own end.
256    NoEllipsis,
257    /// U+2026 HORIZONTAL ELLIPSIS.
258    #[default]
259    Ellipsis,
260    /// This text, 1 to [`MAX_BLOCK_ELLIPSIS_BYTES`] bytes with no control characters or line
261    /// and paragraph separators.
262    String(String),
263}
264
265impl BlockEllipsis {
266    /// The text drawn at the end of a cut line, `None` for no mark.
267    #[must_use]
268    pub fn text(&self) -> Option<&str> {
269        match self {
270            Self::NoEllipsis => None,
271            Self::Ellipsis => Some("\u{2026}"),
272            Self::String(text) => Some(text),
273        }
274    }
275
276    fn is_valid(&self) -> bool {
277        match self {
278            Self::String(text) => {
279                !text.is_empty()
280                    && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
281                    && !text.chars().any(|character| {
282                        character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
283                    })
284            }
285            Self::NoEllipsis | Self::Ellipsis => true,
286        }
287    }
288}
289
290/// How lines of text align within it.
291#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
292#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
293#[serde(rename_all = "snake_case")]
294pub enum TextAlign {
295    /// Left.
296    Start,
297    /// Centred.
298    #[default]
299    Center,
300    /// Right.
301    End,
302}
303
304/// A band around the glyphs and the strokes listed before it, drawn behind them.
305#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
307#[serde(deny_unknown_fields)]
308pub struct TextStroke {
309    /// Band color.
310    pub color: Rgba,
311    /// Band width as a fraction of the font size, positive; a text's strokes sum to at most
312    /// [`MAX_TEXT_STROKE_EXTENT`].
313    pub width: f32,
314}
315
316/// A shadow of a text's glyphs and strokes, behind them.
317#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
318#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
319#[serde(deny_unknown_fields)]
320pub struct TextShadow {
321    /// Shadow color.
322    pub color: Rgba,
323    /// Offset in font sizes, +x right, +y down; each component in `[-1, 1]`
324    /// ([`MAX_TEXT_SHADOW_OFFSET`]).
325    #[serde(default)]
326    pub offset: Vec2,
327    /// Blur radius in font sizes, as CSS `text-shadow` takes it (the Gaussian's standard
328    /// deviation is half of it). In `[0, 1]` ([`MAX_TEXT_SHADOW_BLUR`]).
329    #[serde(default)]
330    pub blur: f32,
331}
332
333/// A box behind each line of text.
334#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
336#[serde(deny_unknown_fields)]
337pub struct TextBackground {
338    /// Box color.
339    pub color: Rgba,
340    /// Space between the text and the box edge, as a fraction of the font size, in `[0, 2]`.
341    #[serde(default)]
342    pub padding: f32,
343}
344
345impl TextStyle {
346    /// Whether every field is in range, with the font size at most `max_font_size`.
347    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
348        let finite =
349            |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
350        self.font_family
351            .as_ref()
352            .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
353            && self.font_size > 0.0
354            && self.font_size <= max_font_size
355            && self.fill.is_valid()
356            && LINE_HEIGHT_RANGE.contains(&self.line_height)
357            && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
358            && FONT_WEIGHT_RANGE.contains(&self.font_weight)
359            && self.max_width > 0.0
360            && self.max_width <= 1.0
361            && self
362                .max_height
363                .is_none_or(|height| height > 0.0 && height <= 1.0)
364            && self
365                .font_size_fit
366                .is_none_or(|fit| fit.is_valid(max_font_size))
367            && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
368            && finite(self.position)
369            && finite(self.anchor)
370            && valid_strokes(&self.strokes)
371            && valid_shadows(&self.shadows)
372            && crate::text_animation::valid_animators(&self.animators, false)
373            && self.background.is_none_or(|background| {
374                background.color.is_valid()
375                    && (0.0..=MAX_TEXT_PADDING).contains(&background.padding)
376            })
377    }
378}
379
380/// Whether `strokes` are at most [`MAX_TEXT_STROKES`] valid bands reaching at most
381/// [`MAX_TEXT_STROKE_EXTENT`] together.
382pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
383    strokes.len() <= MAX_TEXT_STROKES
384        && strokes
385            .iter()
386            .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
387        && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
388}
389
390/// Whether `shadows` are at most [`MAX_TEXT_SHADOWS`] shadows in range.
391pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
392    let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
393    shadows.len() <= MAX_TEXT_SHADOWS
394        && shadows.iter().all(|shadow| {
395            shadow.color.is_valid()
396                && offset(shadow.offset.x)
397                && offset(shadow.offset.y)
398                && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
399        })
400}