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 alpha2_time::MediaTime;
5use serde::{Deserialize, Serialize};
6
7/// Most bytes of text in one caption cue or text generator.
8pub const MAX_TEXT_CONTENT_BYTES: usize = 4_096;
9
10/// Most bytes in a text style's font family name.
11pub const MAX_FONT_FAMILY_BYTES: usize = 256;
12
13/// Largest font size of a text generator, as a fraction of the canvas's shorter side.
14pub const MAX_TEXT_GENERATOR_FONT_SIZE: f32 = 1.0;
15
16/// The line heights text takes, as multiples of the font size.
17pub const LINE_HEIGHT_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;
18
19/// The letter spacings text takes, as fractions of the font size.
20pub const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;
21
22/// The font weights text takes, as CSS `font-weight` numbers.
23pub const FONT_WEIGHT_RANGE: std::ops::RangeInclusive<u16> = 1..=1000;
24
25/// Most strokes around one text.
26pub const MAX_TEXT_STROKES: usize = 8;
27
28/// Widest a text's strokes reach together (the sum of their widths), as a fraction of the
29/// font size.
30pub const MAX_TEXT_STROKE_EXTENT: f32 = 0.5;
31
32/// Most distinct `(family, weight, style)` selections one text draws in, counted after each
33/// run's style is applied.
34pub const MAX_TEXT_FONT_SELECTIONS: usize = 16;
35
36/// The range a run's `font_scale` takes, as multiples of the text's font size.
37pub const FONT_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.1..=10.0;
38
39/// Most shadows under one text.
40pub const MAX_TEXT_SHADOWS: usize = 4;
41
42/// Farthest a text shadow lies from its text on each axis, as a fraction of the font size.
43pub const MAX_TEXT_SHADOW_OFFSET: f32 = 1.0;
44
45/// Widest text shadow blur, as a fraction of the font size.
46pub const MAX_TEXT_SHADOW_BLUR: f32 = 1.0;
47
48/// Largest text background padding and radius, as a fraction of the font size.
49pub const MAX_TEXT_PADDING: f32 = 2.0;
50
51/// Widest text box border, as a fraction of the font size.
52pub const MAX_TEXT_BORDER_WIDTH: f32 = 0.5;
53
54/// Largest dash or gap of a text box border, as a fraction of the font size.
55pub const MAX_TEXT_DASH_ENTRY: f32 = 4.0;
56
57/// Largest magnitude of a text box border's dash offset, as a fraction of the font size.
58pub const MAX_TEXT_DASH_OFFSET: f32 = 16.0;
59/// Largest magnitude of a text's `position` or `anchor` coordinate, in canvas or text extents.
60pub const MAX_TEXT_POSITION: f32 = 1_024.0;
61
62/// Most bytes in a [`BlockEllipsis::String`].
63pub const MAX_BLOCK_ELLIPSIS_BYTES: usize = 64;
64
65/// Steps per unit of font size (a fraction of the shorter side) that a fitted font size takes
66/// between its bounds. Steps of `1 / 8192` are exact in `f32` and under a pixel at 8K.
67pub const FONT_SIZE_FIT_STEPS: f32 = 8_192.0;
68
69/// How text looks and where it lies, for caption cues or a text [`crate::Generator`].
70///
71/// The font size is a fraction of the canvas's shorter side, the wrapping width a fraction
72/// of the canvas width, and strokes, shadows and padding fractions of the font size. The
73/// engine draws with its host's registered fonts, `font_family` first, then the rest in
74/// fallback order.
75///
76/// Painting is bottom to top as in CSS: background boxes, shadows (last listed lowest),
77/// strokes (outermost lowest), fill, then color glyphs.
78#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
79#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
80#[serde(deny_unknown_fields)]
81pub struct TextStyle {
82    /// The family, as the font's name table gives it (typographic family, else family), matched
83    /// ASCII case-insensitively. Missing glyphs and unknown families fall back to the other fonts
84    /// in order; `None` uses the fallback order alone. Non-empty, at most
85    /// [`MAX_FONT_FAMILY_BYTES`] bytes.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub font_family: Option<String>,
88    /// Font size as a fraction of the canvas's shorter side: positive, at most
89    /// [`crate::MAX_CAPTION_FONT_SIZE`] on a caption track and [`MAX_TEXT_GENERATOR_FONT_SIZE`]
90    /// in a text generator.
91    #[serde(default = "default_font_size")]
92    pub font_size: f32,
93    /// What paints the glyphs; a color reads as a solid paint. Gradient positions are in the
94    /// text's layout box, `(0, 0)` top-left to `(1, 1)` bottom-right, and a radial radius is a
95    /// fraction of the box's shorter side. Default solid white.
96    #[serde(default = "white_paint")]
97    pub fill: Paint,
98    /// Baseline-to-baseline distance in font sizes, in `[0.5, 3]`. Each line's em box (0.8 font
99    /// sizes above the baseline, 0.2 below) is centred in a taller line.
100    #[serde(default = "default_line_height")]
101    pub line_height: f32,
102    /// Space after each character, as a fraction of the font size, in `[-0.5, 1]`, added as CSS
103    /// `letter-spacing` does: none after a line's last character or within cursive scripts such
104    /// as Arabic. A non-zero value turns optional ligatures off.
105    #[serde(default)]
106    pub letter_spacing: f32,
107    /// The weight in `[1, 1000]` used to match a family's faces, as CSS Fonts 4 matches
108    /// `font-weight`. Variable faces draw at it, clamped to their `wght` axis; no face is
109    /// synthetically emboldened.
110    #[serde(default = "default_font_weight")]
111    pub font_weight: u16,
112    /// The face style matched before weight, as CSS Fonts 4 matches `font-style`. A face that is
113    /// neither italic nor oblique is sheared by 14 degrees when one is asked; bitmap glyphs stay
114    /// upright. Default `normal`.
115    #[serde(default, skip_serializing_if = "FontStyle::is_normal")]
116    pub font_style: FontStyle,
117    /// A line under the glyphs, as CSS `text-decoration-line: underline`, placed by the font.
118    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119    pub underline: bool,
120    /// A line through the glyphs, as CSS `text-decoration-line: line-through`, placed by the
121    /// font.
122    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
123    pub line_through: bool,
124    /// How lines align within the text.
125    #[serde(default)]
126    pub align: TextAlign,
127    /// Width text wraps at, as a fraction of the canvas width, in `(0, 1]`.
128    #[serde(default = "default_max_width")]
129    pub max_width: f32,
130    /// Height the lines' box fits in, as a fraction of the canvas height, in `(0, 1]`, for
131    /// `font_size_fit` and `line_clamp`. Text taller than it still draws past it, as CSS
132    /// `max-height` lets a box with visible overflow. `None` sets no height.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub max_height: Option<f32>,
135    /// The range the font size is fitted in so the text fits its box. `None` draws at the
136    /// font size as set.
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub font_size_fit: Option<FontSizeFit>,
139    /// Where lines are cut and what ends a cut line, as CSS `line-clamp`. `None` cuts nothing.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub line_clamp: Option<LineClamp>,
142    /// Where on the canvas the text's anchor lies, `(0, 0)` top-left to `(1, 1)` bottom-right;
143    /// each coordinate within [`MAX_TEXT_POSITION`].
144    #[serde(default = "default_position")]
145    pub position: Vec2,
146    /// The point of the text, background included, placed at `position`; `(0.5, 1)` is its
147    /// bottom centre. Each coordinate within [`MAX_TEXT_POSITION`].
148    #[serde(default = "default_anchor")]
149    pub anchor: Vec2,
150    /// Bands around the glyphs, innermost first, each outside the one before. At most
151    /// [`MAX_TEXT_STROKES`], widths summing to at most [`MAX_TEXT_STROKE_EXTENT`].
152    #[serde(default, skip_serializing_if = "Vec::is_empty")]
153    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
154    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
155    pub strokes: Vec<TextStroke>,
156    /// Shadows of the glyphs and strokes, the first on top, as CSS `text-shadow` lists them. At
157    /// most [`MAX_TEXT_SHADOWS`].
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
160    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
161    pub shadows: Vec<TextShadow>,
162    /// A box behind each line.
163    #[serde(default)]
164    pub background: Option<TextBackground>,
165    /// A box over the timed run being said. Needs timed runs; without them it draws nothing.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub highlight: Option<TextHighlight>,
168    /// Per-character motion and color, applied in order, at most [`crate::MAX_TEXT_ANIMATORS`].
169    /// Keyframes are in the holder's time (since a caption cue's start, or a text generator's
170    /// picture time). They never re-break lines while they play; an animator whose advance
171    /// follows its scale makes the text wrap with room for its largest scale.
172    #[serde(default, skip_serializing_if = "Vec::is_empty")]
173    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
174    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
175    pub animators: Vec<TextAnimator>,
176    /// The units whose characters the animators scale and turn about one pivot.
177    #[serde(default, skip_serializing_if = "is_default")]
178    pub animator_grouping: crate::AnimatorGrouping,
179    /// Where in each group's box (the union of its characters' advances by their em boxes) the
180    /// pivot lies, fractions from its left and top in `[0, 1]`, as CSS `transform-origin`
181    /// percentages: `(0.5, 0.5)`, the default, is its centre, `(0.5, 0.8)` its baseline's centre
182    /// on one line. Not animated.
183    #[serde(
184        default = "default_animator_pivot",
185        skip_serializing_if = "is_default_animator_pivot"
186    )]
187    pub animator_pivot: Vec2,
188}
189
190fn is_default<T: Default + PartialEq>(value: &T) -> bool {
191    *value == T::default()
192}
193
194/// The centre of a group's box.
195pub(crate) const fn default_animator_pivot() -> Vec2 {
196    Vec2::new(0.5, 0.5)
197}
198
199#[allow(
200    clippy::trivially_copy_pass_by_ref,
201    reason = "serde passes a reference; the lint fires only where a pointer is as wide as a Vec2"
202)]
203pub(crate) fn is_default_animator_pivot(pivot: &Vec2) -> bool {
204    *pivot == default_animator_pivot()
205}
206
207/// Whether `pivot` lies in a group's box.
208pub(crate) fn valid_animator_pivot(pivot: Vec2) -> bool {
209    (0.0..=1.0).contains(&pivot.x) && (0.0..=1.0).contains(&pivot.y)
210}
211
212impl Default for TextStyle {
213    fn default() -> Self {
214        Self {
215            font_family: None,
216            font_size: default_font_size(),
217            fill: white_paint(),
218            line_height: default_line_height(),
219            letter_spacing: 0.0,
220            font_weight: default_font_weight(),
221            font_style: FontStyle::Normal,
222            underline: false,
223            line_through: false,
224            align: TextAlign::default(),
225            max_width: default_max_width(),
226            max_height: None,
227            font_size_fit: None,
228            line_clamp: None,
229            position: default_position(),
230            anchor: default_anchor(),
231            strokes: Vec::new(),
232            shadows: Vec::new(),
233            background: None,
234            highlight: None,
235            animators: Vec::new(),
236            animator_grouping: crate::AnimatorGrouping::Character,
237            animator_pivot: default_animator_pivot(),
238        }
239    }
240}
241
242const fn default_font_size() -> f32 {
243    0.05
244}
245
246const fn white_paint() -> Paint {
247    Paint::Solid {
248        color: Rgba::new(1.0, 1.0, 1.0, 1.0),
249    }
250}
251
252const fn default_line_height() -> f32 {
253    1.2
254}
255
256const fn default_font_weight() -> u16 {
257    400
258}
259
260const fn default_max_width() -> f32 {
261    0.9
262}
263
264const fn default_position() -> Vec2 {
265    Vec2::new(0.5, 0.92)
266}
267
268const fn default_anchor() -> Vec2 {
269    Vec2::new(0.5, 1.0)
270}
271
272/// The font sizes a text is fitted between, as fractions of the canvas's shorter side.
273///
274/// The text draws at the largest size in `[min, max]` at which no line breaks inside a word,
275/// the lines fit the box's height, and there are no more lines than `line_clamp.max_lines`.
276/// When no size fits, it draws at `min`. A `min` above `max` wins, as CSS `min-width` does.
277/// Sizes are tried by bisection over `max`, `min` and the multiples of `1 / 8192` between.
278#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
279#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
280#[serde(deny_unknown_fields)]
281pub struct FontSizeFit {
282    /// Smallest font size, positive. At most the holder's largest font size.
283    pub min: f32,
284    /// Largest font size, at least `min` and at most the holder's largest font size. `None`
285    /// is `font_size`, so the text only shrinks.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub max: Option<f32>,
288}
289
290impl FontSizeFit {
291    /// Whether both bounds are positive, in order, and at most `max_font_size`.
292    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
293        let size = |value: f32| value.is_finite() && value > 0.0 && value <= max_font_size;
294        size(self.min) && self.max.is_none_or(|max| size(max) && self.min <= max)
295    }
296}
297
298/// Lines past a clamp point are discarded, as CSS Overflow 4 `line-clamp` discards them.
299///
300/// The clamp point is after the last line within `max_lines` that fits the box's height, and
301/// never before the first line. Unlike CSS, the height counts without `max-lines: auto`, so
302/// clamped text stays inside a box that has one. A cut line is shortened to its last word end,
303/// else its last character, at which the ellipsis fits after it. Text animators count no unit
304/// for the ellipsis, which moves with the character before it.
305#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
307#[serde(deny_unknown_fields)]
308pub struct LineClamp {
309    /// Most lines, at least 1, as CSS `max-lines`. `None` cuts at the box's height alone.
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub max_lines: Option<u32>,
312    /// What ends the last kept line of cut text. Default `ellipsis`, as CSS `line-clamp` sets it.
313    #[serde(default)]
314    pub block_ellipsis: BlockEllipsis,
315}
316
317impl LineClamp {
318    pub(crate) fn is_valid(&self) -> bool {
319        self.max_lines != Some(0) && self.block_ellipsis.is_valid()
320    }
321}
322
323/// What ends a line that a clamp cuts, as CSS `block-ellipsis`.
324#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
325#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
326#[serde(rename_all = "snake_case")]
327pub enum BlockEllipsis {
328    /// No mark. The cut line keeps its own end.
329    NoEllipsis,
330    /// U+2026 HORIZONTAL ELLIPSIS.
331    #[default]
332    Ellipsis,
333    /// This text, 1 to [`MAX_BLOCK_ELLIPSIS_BYTES`] bytes with no control characters or line
334    /// and paragraph separators.
335    String(
336        /// The text drawn at the end of a cut line.
337        String,
338    ),
339}
340
341impl BlockEllipsis {
342    /// The text drawn at the end of a cut line, `None` for no mark.
343    #[must_use]
344    pub fn text(&self) -> Option<&str> {
345        match self {
346            Self::NoEllipsis => None,
347            Self::Ellipsis => Some("\u{2026}"),
348            Self::String(text) => Some(text),
349        }
350    }
351
352    fn is_valid(&self) -> bool {
353        match self {
354            Self::String(text) => {
355                !text.is_empty()
356                    && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
357                    && !text.chars().any(|character| {
358                        character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
359                    })
360            }
361            Self::NoEllipsis | Self::Ellipsis => true,
362        }
363    }
364}
365
366/// Which faces of a family text prefers, as CSS `font-style`.
367#[derive(
368    Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
369)]
370#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
371#[serde(rename_all = "snake_case")]
372pub enum FontStyle {
373    /// Upright faces, then oblique, then italic.
374    #[default]
375    Normal,
376    /// Italic faces, then oblique, then upright ones sheared.
377    Italic,
378    /// Oblique faces, then italic, then upright ones sheared.
379    Oblique,
380}
381
382impl FontStyle {
383    /// Whether this is `normal`.
384    #[must_use]
385    pub const fn is_normal(&self) -> bool {
386        matches!(self, Self::Normal)
387    }
388}
389
390/// How lines of text align within it.
391#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
392#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
393#[serde(rename_all = "snake_case")]
394pub enum TextAlign {
395    /// Left.
396    Start,
397    /// Centred.
398    #[default]
399    Center,
400    /// Right.
401    End,
402}
403
404/// A band around the glyphs and the strokes listed before it, drawn behind them.
405#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
406#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
407#[serde(deny_unknown_fields)]
408pub struct TextStroke {
409    /// Band color.
410    pub color: Rgba,
411    /// Band width as a fraction of the font size, positive; a text's strokes sum to at most
412    /// [`MAX_TEXT_STROKE_EXTENT`].
413    pub width: f32,
414}
415
416/// A shadow of a text's glyphs and strokes, behind them.
417#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
418#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
419#[serde(deny_unknown_fields)]
420pub struct TextShadow {
421    /// Shadow color.
422    pub color: Rgba,
423    /// Offset in font sizes, +x right, +y down; each component in `[-1, 1]`
424    /// ([`MAX_TEXT_SHADOW_OFFSET`]).
425    #[serde(default)]
426    pub offset: Vec2,
427    /// Blur radius in font sizes, as CSS `text-shadow` takes it (the Gaussian's standard
428    /// deviation is half of it). In `[0, 1]` ([`MAX_TEXT_SHADOW_BLUR`]).
429    #[serde(default)]
430    pub blur: f32,
431}
432
433/// A box behind each line of text, as CSS draws an inline box's background with
434/// `box-decoration-break: clone`: each line's box has its own padding, radius and border.
435#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
436#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
437#[serde(deny_unknown_fields)]
438pub struct TextBackground {
439    /// Box color.
440    pub color: Rgba,
441    /// Space between the text and the box edge, as fractions of the font size, each side in
442    /// `[0, 2]`.
443    #[serde(default)]
444    pub padding: TextInsets,
445    /// Every corner's radius, as a fraction of the font size, in `[0, 2]`; each box's radius is
446    /// capped at half its shorter side, as CSS `border-radius`. Default 0.
447    #[serde(default, skip_serializing_if = "is_zero")]
448    pub radius: f32,
449    /// A line inside the box's edge, as a CSS border. `None` draws none.
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub border: Option<TextBoxBorder>,
452    /// Which part of each line the box spans.
453    #[serde(default, skip_serializing_if = "is_default")]
454    pub extent: TextBoxExtent,
455}
456
457/// Which part of each line a text's background box spans, where tracking and pushing place its
458/// characters.
459#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
460#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
461#[serde(rename_all = "snake_case")]
462pub enum TextBoxExtent {
463    /// From the line's first character to its last that is not a hanging space.
464    #[default]
465    Line,
466    /// From the first to the last revealed character that is not white space: shown, not scaled
467    /// to nothing, and not hidden by a reveal. A line with none has no box; a text without
468    /// animators draws as `line`.
469    Revealed,
470    /// One box over the whole layout box, `max_width` wide and as tall as the lines.
471    Block,
472}
473
474/// A box over the timed run being said, sliding from run to run, drawn over the background
475/// boxes and under the glyphs. The run is the timed run that started last; before the first
476/// starts there is none.
477#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
478#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
479#[serde(deny_unknown_fields)]
480pub struct TextHighlight {
481    /// Box color.
482    pub color: Rgba,
483    /// Space between the run and the box edge, as a background's `padding`.
484    #[serde(default)]
485    pub padding: TextInsets,
486    /// Every corner's radius, as a background's `radius`.
487    #[serde(default, skip_serializing_if = "is_zero")]
488    pub radius: f32,
489    /// A line inside the box's edge, as a background's `border`.
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub border: Option<TextBoxBorder>,
492    /// How long the box takes to slide to the next run once it starts, at most
493    /// [`MAX_HIGHLIGHT_TRANSITION`]; 0 jumps. A change during a slide starts where the box is.
494    #[serde(default, skip_serializing_if = "is_default")]
495    pub transition: MediaTime,
496    /// The slide's timing curve.
497    #[serde(default = "linear", skip_serializing_if = "is_linear")]
498    pub easing: crate::Easing,
499    /// What the box does between a run's end and the next run's start.
500    #[serde(default, skip_serializing_if = "is_default")]
501    pub gap: HighlightGap,
502}
503
504/// What a highlight does after its run ends, before the next starts.
505#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
506#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
507#[serde(rename_all = "snake_case")]
508pub enum HighlightGap {
509    /// Stays on the run until the next starts or its holder ends.
510    #[default]
511    Hold,
512    /// Is drawn only while its run lasts; a run that starts after the last one ended takes the
513    /// box without sliding.
514    Hide,
515}
516
517/// Longest highlight transition.
518pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
519    MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);
520
521const fn linear() -> crate::Easing {
522    crate::Easing::Linear
523}
524
525fn is_linear(easing: &crate::Easing) -> bool {
526    matches!(easing, crate::Easing::Linear)
527}
528
529impl TextHighlight {
530    pub(crate) fn is_valid(&self) -> bool {
531        self.color.is_valid()
532            && self.padding.is_valid()
533            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
534            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
535            && self.transition >= MediaTime::ZERO
536            && self.transition <= MAX_HIGHLIGHT_TRANSITION
537            && self.easing.is_valid()
538    }
539}
540
541impl TextBackground {
542    /// A box of `color` with `padding` on every side, no radius and no border.
543    #[must_use]
544    pub const fn padded(color: Rgba, padding: f32) -> Self {
545        Self {
546            color,
547            padding: TextInsets::all(padding),
548            radius: 0.0,
549            border: None,
550            extent: TextBoxExtent::Line,
551        }
552    }
553
554    pub(crate) fn is_valid(&self) -> bool {
555        self.color.is_valid()
556            && self.padding.is_valid()
557            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
558            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
559    }
560}
561
562#[expect(
563    clippy::trivially_copy_pass_by_ref,
564    reason = "serde's skip_serializing_if passes a reference"
565)]
566fn is_zero(value: &f32) -> bool {
567    *value == 0.0
568}
569
570/// The border of a text box, drawn inside the box's edge.
571#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
572#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
573#[serde(deny_unknown_fields)]
574pub struct TextBoxBorder {
575    /// Width as a fraction of the font size, in `(0, 0.5]`.
576    pub width: f32,
577    /// Line color.
578    pub color: Rgba,
579    /// Dashes along the border's centre line; `None` draws it solid.
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    pub dash: Option<TextDash>,
582}
583
584impl TextBoxBorder {
585    fn is_valid(&self) -> bool {
586        self.width.is_finite()
587            && self.width > 0.0
588            && self.width <= MAX_TEXT_BORDER_WIDTH
589            && self.color.is_valid()
590            && self.dash.as_ref().is_none_or(TextDash::is_valid)
591    }
592}
593
594/// Dashes along a box border, as SVG `stroke-dasharray` and `stroke-dashoffset`: they start at
595/// the end of the top-left corner and run clockwise.
596#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
597#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
598#[serde(deny_unknown_fields)]
599pub struct TextDash {
600    /// Alternating dash and gap lengths, as fractions of the font size: one to
601    /// [`crate::MAX_DASH_ENTRIES`] entries in `[0, 4]`, not all zero. An odd count repeats once
602    /// more to pair up.
603    #[serde(deserialize_with = "dash_pattern")]
604    #[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
605    pub pattern: Vec<f32>,
606    /// How far into the pattern the border starts, in font sizes, in `[-16, 16]`.
607    #[serde(default, skip_serializing_if = "is_zero")]
608    pub offset: f32,
609}
610
611fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
612    let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
613    if pattern.is_empty() {
614        return Err(serde::de::Error::invalid_length(
615            0,
616            &"one to sixteen entries",
617        ));
618    }
619    Ok(pattern)
620}
621
622impl TextDash {
623    fn is_valid(&self) -> bool {
624        !self.pattern.is_empty()
625            && self.pattern.len() <= crate::MAX_DASH_ENTRIES
626            && self
627                .pattern
628                .iter()
629                .all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
630            && self.pattern.iter().any(|entry| *entry > 0.0)
631            && (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
632    }
633}
634
635/// A length on each side of a text box, as fractions of the font size.
636///
637/// Written as one number for every side, the CSS shorthand of one to four numbers (`"0.1 0.3"`:
638/// top first, clockwise), or the sides object, missing sides 0. Pixels are refused.
639#[derive(Copy, Clone, Debug, Default, PartialEq)]
640pub struct TextInsets {
641    /// Top side.
642    pub top: f32,
643    /// Right side.
644    pub right: f32,
645    /// Bottom side.
646    pub bottom: f32,
647    /// Left side.
648    pub left: f32,
649}
650
651impl TextInsets {
652    /// The same length on every side.
653    #[must_use]
654    pub const fn all(value: f32) -> Self {
655        Self {
656            top: value,
657            right: value,
658            bottom: value,
659            left: value,
660        }
661    }
662
663    /// The sides, top first, clockwise.
664    #[must_use]
665    pub const fn sides(self) -> [f32; 4] {
666        [self.top, self.right, self.bottom, self.left]
667    }
668
669    fn is_valid(self) -> bool {
670        self.sides()
671            .iter()
672            .all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
673    }
674
675    fn from_shorthand(values: &[f32]) -> Option<Self> {
676        let [top, right, bottom, left] = match *values {
677            [all] => [all; 4],
678            [vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
679            [top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
680            [top, right, bottom, left] => [top, right, bottom, left],
681            _ => return None,
682        };
683        Some(Self {
684            top,
685            right,
686            bottom,
687            left,
688        })
689    }
690}
691
692impl<'de> Deserialize<'de> for TextInsets {
693    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
694        #[derive(Deserialize)]
695        #[serde(untagged)]
696        enum Written {
697            Number(f32),
698            Shorthand(String),
699            Sides(std::collections::BTreeMap<String, f32>),
700        }
701        match Written::deserialize(deserializer)? {
702            Written::Number(value) => Ok(Self::all(value)),
703            Written::Shorthand(text) => text
704                .split(' ')
705                .filter(|token| !token.is_empty())
706                .map(str::parse::<f32>)
707                .collect::<Result<Vec<_>, _>>()
708                .ok()
709                .and_then(|values| Self::from_shorthand(&values))
710                .ok_or_else(|| {
711                    serde::de::Error::custom(format!(
712                        "text insets: expected one to four numbers, got {text:?}"
713                    ))
714                }),
715            Written::Sides(sides) => {
716                let mut insets = Self::default();
717                for (side, value) in sides {
718                    *match side.as_str() {
719                        "top" => &mut insets.top,
720                        "right" => &mut insets.right,
721                        "bottom" => &mut insets.bottom,
722                        "left" => &mut insets.left,
723                        _ => {
724                            return Err(serde::de::Error::unknown_field(
725                                &side,
726                                &["top", "right", "bottom", "left"],
727                            ));
728                        }
729                    } = value;
730                }
731                Ok(insets)
732            }
733        }
734    }
735}
736
737/// One number when every side is the same, else the sides object.
738impl Serialize for TextInsets {
739    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
740        use serde::ser::SerializeStruct;
741        let [top, right, bottom, left] = self.sides().map(f32::to_bits);
742        if top == right && top == bottom && top == left {
743            return serializer.serialize_f32(self.top);
744        }
745        let mut sides = serializer.serialize_struct("TextInsets", 4)?;
746        sides.serialize_field("top", &self.top)?;
747        sides.serialize_field("right", &self.right)?;
748        sides.serialize_field("bottom", &self.bottom)?;
749        sides.serialize_field("left", &self.left)?;
750        sides.end()
751    }
752}
753
754#[cfg(feature = "schema")]
755impl schemars::JsonSchema for TextInsets {
756    fn schema_name() -> std::borrow::Cow<'static, str> {
757        "TextInsets".into()
758    }
759
760    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
761        let number = r"-?(\d+\.?\d*|\.\d+)";
762        let side = |name: &str| {
763            schemars::json_schema!({
764                "description": format!("The {name} side, as a fraction of the font size."),
765                "type": "number",
766                "format": "float",
767            })
768        };
769        schemars::json_schema!({
770            "description": "A length on each side of a text box, as fractions of the font size: one number for every side, the CSS shorthand of one to four numbers (\"0.1 0.3\": top first, clockwise), or the sides object, missing sides 0.",
771            "anyOf": [
772                { "type": "number", "format": "float" },
773                { "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
774                {
775                    "type": "object",
776                    "properties": {
777                        "top": side("top"),
778                        "right": side("right"),
779                        "bottom": side("bottom"),
780                        "left": side("left"),
781                    },
782                    "additionalProperties": false,
783                },
784            ],
785        })
786    }
787}
788
789impl TextStyle {
790    /// Whether every field is in range, with the font size at most `max_font_size`.
791    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
792        let finite =
793            |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
794        self.font_family
795            .as_ref()
796            .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
797            && self.font_size > 0.0
798            && self.font_size <= max_font_size
799            && self.fill.is_valid()
800            && LINE_HEIGHT_RANGE.contains(&self.line_height)
801            && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
802            && FONT_WEIGHT_RANGE.contains(&self.font_weight)
803            && self.max_width > 0.0
804            && self.max_width <= 1.0
805            && self
806                .max_height
807                .is_none_or(|height| height > 0.0 && height <= 1.0)
808            && self
809                .font_size_fit
810                .is_none_or(|fit| fit.is_valid(max_font_size))
811            && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
812            && finite(self.position)
813            && finite(self.anchor)
814            && valid_strokes(&self.strokes)
815            && valid_shadows(&self.shadows)
816            && crate::text_animation::valid_animators(&self.animators, false)
817            && valid_animator_pivot(self.animator_pivot)
818            && self
819                .background
820                .as_ref()
821                .is_none_or(TextBackground::is_valid)
822            && self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
823    }
824}
825
826/// Whether `strokes` are at most [`MAX_TEXT_STROKES`] valid bands reaching at most
827/// [`MAX_TEXT_STROKE_EXTENT`] together.
828pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
829    strokes.len() <= MAX_TEXT_STROKES
830        && strokes
831            .iter()
832            .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
833        && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
834}
835
836/// Whether `shadows` are at most [`MAX_TEXT_SHADOWS`] shadows in range.
837pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
838    let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
839    shadows.len() <= MAX_TEXT_SHADOWS
840        && shadows.iter().all(|shadow| {
841            shadow.color.is_valid()
842                && offset(shadow.offset.x)
843                && offset(shadow.offset.y)
844                && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
845        })
846}