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(String),
336}
337
338impl BlockEllipsis {
339    /// The text drawn at the end of a cut line, `None` for no mark.
340    #[must_use]
341    pub fn text(&self) -> Option<&str> {
342        match self {
343            Self::NoEllipsis => None,
344            Self::Ellipsis => Some("\u{2026}"),
345            Self::String(text) => Some(text),
346        }
347    }
348
349    fn is_valid(&self) -> bool {
350        match self {
351            Self::String(text) => {
352                !text.is_empty()
353                    && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
354                    && !text.chars().any(|character| {
355                        character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
356                    })
357            }
358            Self::NoEllipsis | Self::Ellipsis => true,
359        }
360    }
361}
362
363/// Which faces of a family text prefers, as CSS `font-style`.
364#[derive(
365    Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
366)]
367#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
368#[serde(rename_all = "snake_case")]
369pub enum FontStyle {
370    /// Upright faces, then oblique, then italic.
371    #[default]
372    Normal,
373    /// Italic faces, then oblique, then upright ones sheared.
374    Italic,
375    /// Oblique faces, then italic, then upright ones sheared.
376    Oblique,
377}
378
379impl FontStyle {
380    /// Whether this is `normal`.
381    #[must_use]
382    pub const fn is_normal(&self) -> bool {
383        matches!(self, Self::Normal)
384    }
385}
386
387/// How lines of text align within it.
388#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
389#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
390#[serde(rename_all = "snake_case")]
391pub enum TextAlign {
392    /// Left.
393    Start,
394    /// Centred.
395    #[default]
396    Center,
397    /// Right.
398    End,
399}
400
401/// A band around the glyphs and the strokes listed before it, drawn behind them.
402#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
403#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
404#[serde(deny_unknown_fields)]
405pub struct TextStroke {
406    /// Band color.
407    pub color: Rgba,
408    /// Band width as a fraction of the font size, positive; a text's strokes sum to at most
409    /// [`MAX_TEXT_STROKE_EXTENT`].
410    pub width: f32,
411}
412
413/// A shadow of a text's glyphs and strokes, behind them.
414#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
415#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
416#[serde(deny_unknown_fields)]
417pub struct TextShadow {
418    /// Shadow color.
419    pub color: Rgba,
420    /// Offset in font sizes, +x right, +y down; each component in `[-1, 1]`
421    /// ([`MAX_TEXT_SHADOW_OFFSET`]).
422    #[serde(default)]
423    pub offset: Vec2,
424    /// Blur radius in font sizes, as CSS `text-shadow` takes it (the Gaussian's standard
425    /// deviation is half of it). In `[0, 1]` ([`MAX_TEXT_SHADOW_BLUR`]).
426    #[serde(default)]
427    pub blur: f32,
428}
429
430/// A box behind each line of text, as CSS draws an inline box's background with
431/// `box-decoration-break: clone`: each line's box has its own padding, radius and border.
432#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
433#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
434#[serde(deny_unknown_fields)]
435pub struct TextBackground {
436    /// Box color.
437    pub color: Rgba,
438    /// Space between the text and the box edge, as fractions of the font size, each side in
439    /// `[0, 2]`.
440    #[serde(default)]
441    pub padding: TextInsets,
442    /// Every corner's radius, as a fraction of the font size, in `[0, 2]`; each box's radius is
443    /// capped at half its shorter side, as CSS `border-radius`. Default 0.
444    #[serde(default, skip_serializing_if = "is_zero")]
445    pub radius: f32,
446    /// A line inside the box's edge, as a CSS border. `None` draws none.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub border: Option<TextBoxBorder>,
449    /// Which part of each line the box spans.
450    #[serde(default, skip_serializing_if = "is_default")]
451    pub extent: TextBoxExtent,
452}
453
454/// Which part of each line a text's background box spans, where tracking and pushing place its
455/// characters.
456#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
457#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
458#[serde(rename_all = "snake_case")]
459pub enum TextBoxExtent {
460    /// From the line's first character to its last that is not a hanging space.
461    #[default]
462    Line,
463    /// From the first to the last revealed character that is not white space: shown, not scaled
464    /// to nothing, and not hidden by a reveal. A line with none has no box; a text without
465    /// animators draws as `line`.
466    Revealed,
467    /// One box over the whole layout box, `max_width` wide and as tall as the lines.
468    Block,
469}
470
471/// A box over the timed run being said, sliding from run to run, drawn over the background
472/// boxes and under the glyphs. The run is the timed run that started last; before the first
473/// starts there is none.
474#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
475#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
476#[serde(deny_unknown_fields)]
477pub struct TextHighlight {
478    /// Box color.
479    pub color: Rgba,
480    /// Space between the run and the box edge, as a background's `padding`.
481    #[serde(default)]
482    pub padding: TextInsets,
483    /// Every corner's radius, as a background's `radius`.
484    #[serde(default, skip_serializing_if = "is_zero")]
485    pub radius: f32,
486    /// A line inside the box's edge, as a background's `border`.
487    #[serde(default, skip_serializing_if = "Option::is_none")]
488    pub border: Option<TextBoxBorder>,
489    /// How long the box takes to slide to the next run once it starts, at most
490    /// [`MAX_HIGHLIGHT_TRANSITION`]; 0 jumps. A change during a slide starts where the box is.
491    #[serde(default, skip_serializing_if = "is_default")]
492    pub transition: MediaTime,
493    /// The slide's timing curve.
494    #[serde(default = "linear", skip_serializing_if = "is_linear")]
495    pub easing: crate::Easing,
496    /// What the box does between a run's end and the next run's start.
497    #[serde(default, skip_serializing_if = "is_default")]
498    pub gap: HighlightGap,
499}
500
501/// What a highlight does after its run ends, before the next starts.
502#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
503#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
504#[serde(rename_all = "snake_case")]
505pub enum HighlightGap {
506    /// Stays on the run until the next starts or its holder ends.
507    #[default]
508    Hold,
509    /// Is drawn only while its run lasts; a run that starts after the last one ended takes the
510    /// box without sliding.
511    Hide,
512}
513
514/// Longest highlight transition.
515pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
516    MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);
517
518const fn linear() -> crate::Easing {
519    crate::Easing::Linear
520}
521
522fn is_linear(easing: &crate::Easing) -> bool {
523    matches!(easing, crate::Easing::Linear)
524}
525
526impl TextHighlight {
527    pub(crate) fn is_valid(&self) -> bool {
528        self.color.is_valid()
529            && self.padding.is_valid()
530            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
531            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
532            && self.transition >= MediaTime::ZERO
533            && self.transition <= MAX_HIGHLIGHT_TRANSITION
534            && self.easing.is_valid()
535    }
536}
537
538impl TextBackground {
539    /// A box of `color` with `padding` on every side, no radius and no border.
540    #[must_use]
541    pub const fn padded(color: Rgba, padding: f32) -> Self {
542        Self {
543            color,
544            padding: TextInsets::all(padding),
545            radius: 0.0,
546            border: None,
547            extent: TextBoxExtent::Line,
548        }
549    }
550
551    pub(crate) fn is_valid(&self) -> bool {
552        self.color.is_valid()
553            && self.padding.is_valid()
554            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
555            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
556    }
557}
558
559#[expect(
560    clippy::trivially_copy_pass_by_ref,
561    reason = "serde's skip_serializing_if passes a reference"
562)]
563fn is_zero(value: &f32) -> bool {
564    *value == 0.0
565}
566
567/// The border of a text box, drawn inside the box's edge.
568#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
569#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
570#[serde(deny_unknown_fields)]
571pub struct TextBoxBorder {
572    /// Width as a fraction of the font size, in `(0, 0.5]`.
573    pub width: f32,
574    /// Line color.
575    pub color: Rgba,
576    /// Dashes along the border's centre line; `None` draws it solid.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub dash: Option<TextDash>,
579}
580
581impl TextBoxBorder {
582    fn is_valid(&self) -> bool {
583        self.width.is_finite()
584            && self.width > 0.0
585            && self.width <= MAX_TEXT_BORDER_WIDTH
586            && self.color.is_valid()
587            && self.dash.as_ref().is_none_or(TextDash::is_valid)
588    }
589}
590
591/// Dashes along a box border, as SVG `stroke-dasharray` and `stroke-dashoffset`: they start at
592/// the end of the top-left corner and run clockwise.
593#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
594#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
595#[serde(deny_unknown_fields)]
596pub struct TextDash {
597    /// Alternating dash and gap lengths, as fractions of the font size: one to
598    /// [`crate::MAX_DASH_ENTRIES`] entries in `[0, 4]`, not all zero. An odd count repeats once
599    /// more to pair up.
600    #[serde(deserialize_with = "dash_pattern")]
601    #[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
602    pub pattern: Vec<f32>,
603    /// How far into the pattern the border starts, in font sizes, in `[-16, 16]`.
604    #[serde(default, skip_serializing_if = "is_zero")]
605    pub offset: f32,
606}
607
608fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
609    let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
610    if pattern.is_empty() {
611        return Err(serde::de::Error::invalid_length(
612            0,
613            &"one to sixteen entries",
614        ));
615    }
616    Ok(pattern)
617}
618
619impl TextDash {
620    fn is_valid(&self) -> bool {
621        !self.pattern.is_empty()
622            && self.pattern.len() <= crate::MAX_DASH_ENTRIES
623            && self
624                .pattern
625                .iter()
626                .all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
627            && self.pattern.iter().any(|entry| *entry > 0.0)
628            && (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
629    }
630}
631
632/// A length on each side of a text box, as fractions of the font size.
633///
634/// Written as one number for every side, the CSS shorthand of one to four numbers (`"0.1 0.3"`:
635/// top first, clockwise), or the sides object, missing sides 0. Pixels are refused.
636#[derive(Copy, Clone, Debug, Default, PartialEq)]
637pub struct TextInsets {
638    /// Top side.
639    pub top: f32,
640    /// Right side.
641    pub right: f32,
642    /// Bottom side.
643    pub bottom: f32,
644    /// Left side.
645    pub left: f32,
646}
647
648impl TextInsets {
649    /// The same length on every side.
650    #[must_use]
651    pub const fn all(value: f32) -> Self {
652        Self {
653            top: value,
654            right: value,
655            bottom: value,
656            left: value,
657        }
658    }
659
660    /// The sides, top first, clockwise.
661    #[must_use]
662    pub const fn sides(self) -> [f32; 4] {
663        [self.top, self.right, self.bottom, self.left]
664    }
665
666    fn is_valid(self) -> bool {
667        self.sides()
668            .iter()
669            .all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
670    }
671
672    fn from_shorthand(values: &[f32]) -> Option<Self> {
673        let [top, right, bottom, left] = match *values {
674            [all] => [all; 4],
675            [vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
676            [top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
677            [top, right, bottom, left] => [top, right, bottom, left],
678            _ => return None,
679        };
680        Some(Self {
681            top,
682            right,
683            bottom,
684            left,
685        })
686    }
687}
688
689impl<'de> Deserialize<'de> for TextInsets {
690    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
691        #[derive(Deserialize)]
692        #[serde(untagged)]
693        enum Written {
694            Number(f32),
695            Shorthand(String),
696            Sides(std::collections::BTreeMap<String, f32>),
697        }
698        match Written::deserialize(deserializer)? {
699            Written::Number(value) => Ok(Self::all(value)),
700            Written::Shorthand(text) => text
701                .split(' ')
702                .filter(|token| !token.is_empty())
703                .map(str::parse::<f32>)
704                .collect::<Result<Vec<_>, _>>()
705                .ok()
706                .and_then(|values| Self::from_shorthand(&values))
707                .ok_or_else(|| {
708                    serde::de::Error::custom(format!(
709                        "text insets: expected one to four numbers, got {text:?}"
710                    ))
711                }),
712            Written::Sides(sides) => {
713                let mut insets = Self::default();
714                for (side, value) in sides {
715                    *match side.as_str() {
716                        "top" => &mut insets.top,
717                        "right" => &mut insets.right,
718                        "bottom" => &mut insets.bottom,
719                        "left" => &mut insets.left,
720                        _ => {
721                            return Err(serde::de::Error::unknown_field(
722                                &side,
723                                &["top", "right", "bottom", "left"],
724                            ));
725                        }
726                    } = value;
727                }
728                Ok(insets)
729            }
730        }
731    }
732}
733
734/// One number when every side is the same, else the sides object.
735impl Serialize for TextInsets {
736    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
737        use serde::ser::SerializeStruct;
738        let [top, right, bottom, left] = self.sides().map(f32::to_bits);
739        if top == right && top == bottom && top == left {
740            return serializer.serialize_f32(self.top);
741        }
742        let mut sides = serializer.serialize_struct("TextInsets", 4)?;
743        sides.serialize_field("top", &self.top)?;
744        sides.serialize_field("right", &self.right)?;
745        sides.serialize_field("bottom", &self.bottom)?;
746        sides.serialize_field("left", &self.left)?;
747        sides.end()
748    }
749}
750
751#[cfg(feature = "schema")]
752impl schemars::JsonSchema for TextInsets {
753    fn schema_name() -> std::borrow::Cow<'static, str> {
754        "TextInsets".into()
755    }
756
757    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
758        let number = r"-?(\d+\.?\d*|\.\d+)";
759        let side = schemars::json_schema!({ "type": "number", "format": "float" });
760        schemars::json_schema!({
761            "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.",
762            "anyOf": [
763                { "type": "number", "format": "float" },
764                { "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
765                {
766                    "type": "object",
767                    "properties": { "top": side, "right": side, "bottom": side, "left": side },
768                    "additionalProperties": false,
769                },
770            ],
771        })
772    }
773}
774
775impl TextStyle {
776    /// Whether every field is in range, with the font size at most `max_font_size`.
777    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
778        let finite =
779            |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
780        self.font_family
781            .as_ref()
782            .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
783            && self.font_size > 0.0
784            && self.font_size <= max_font_size
785            && self.fill.is_valid()
786            && LINE_HEIGHT_RANGE.contains(&self.line_height)
787            && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
788            && FONT_WEIGHT_RANGE.contains(&self.font_weight)
789            && self.max_width > 0.0
790            && self.max_width <= 1.0
791            && self
792                .max_height
793                .is_none_or(|height| height > 0.0 && height <= 1.0)
794            && self
795                .font_size_fit
796                .is_none_or(|fit| fit.is_valid(max_font_size))
797            && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
798            && finite(self.position)
799            && finite(self.anchor)
800            && valid_strokes(&self.strokes)
801            && valid_shadows(&self.shadows)
802            && crate::text_animation::valid_animators(&self.animators, false)
803            && valid_animator_pivot(self.animator_pivot)
804            && self
805                .background
806                .as_ref()
807                .is_none_or(TextBackground::is_valid)
808            && self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
809    }
810}
811
812/// Whether `strokes` are at most [`MAX_TEXT_STROKES`] valid bands reaching at most
813/// [`MAX_TEXT_STROKE_EXTENT`] together.
814pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
815    strokes.len() <= MAX_TEXT_STROKES
816        && strokes
817            .iter()
818            .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
819        && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
820}
821
822/// Whether `shadows` are at most [`MAX_TEXT_SHADOWS`] shadows in range.
823pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
824    let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
825    shadows.len() <= MAX_TEXT_SHADOWS
826        && shadows.iter().all(|shadow| {
827            shadow.color.is_valid()
828                && offset(shadow.offset.x)
829                && offset(shadow.offset.y)
830                && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
831        })
832}