alpha2-model 0.9.0

Versioned project and timeline model for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Styled text: what caption tracks and text generators draw.

use crate::{Paint, Rgba, TextAnimator, Vec2};
use alpha2_time::MediaTime;
use serde::{Deserialize, Serialize};

/// Most bytes of text in one caption cue or text generator.
pub const MAX_TEXT_CONTENT_BYTES: usize = 4_096;

/// Most bytes in a text style's font family name.
pub const MAX_FONT_FAMILY_BYTES: usize = 256;

/// Largest font size of a text generator, as a fraction of the canvas's shorter side.
pub const MAX_TEXT_GENERATOR_FONT_SIZE: f32 = 1.0;

/// The line heights text takes, as multiples of the font size.
pub const LINE_HEIGHT_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;

/// The letter spacings text takes, as fractions of the font size.
pub const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;

/// The font weights text takes, as CSS `font-weight` numbers.
pub const FONT_WEIGHT_RANGE: std::ops::RangeInclusive<u16> = 1..=1000;

/// Most strokes around one text.
pub const MAX_TEXT_STROKES: usize = 8;

/// Widest a text's strokes reach together (the sum of their widths), as a fraction of the
/// font size.
pub const MAX_TEXT_STROKE_EXTENT: f32 = 0.5;

/// Most distinct `(family, weight, style)` selections one text draws in, counted after each
/// run's style is applied.
pub const MAX_TEXT_FONT_SELECTIONS: usize = 16;

/// The range a run's `font_scale` takes, as multiples of the text's font size.
pub const FONT_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.1..=10.0;

/// Most shadows under one text.
pub const MAX_TEXT_SHADOWS: usize = 4;

/// Farthest a text shadow lies from its text on each axis, as a fraction of the font size.
pub const MAX_TEXT_SHADOW_OFFSET: f32 = 1.0;

/// Widest text shadow blur, as a fraction of the font size.
pub const MAX_TEXT_SHADOW_BLUR: f32 = 1.0;

/// Largest text background padding and radius, as a fraction of the font size.
pub const MAX_TEXT_PADDING: f32 = 2.0;

/// Widest text box border, as a fraction of the font size.
pub const MAX_TEXT_BORDER_WIDTH: f32 = 0.5;

/// Largest dash or gap of a text box border, as a fraction of the font size.
pub const MAX_TEXT_DASH_ENTRY: f32 = 4.0;

/// Largest magnitude of a text box border's dash offset, as a fraction of the font size.
pub const MAX_TEXT_DASH_OFFSET: f32 = 16.0;
/// Largest magnitude of a text's `position` or `anchor` coordinate, in canvas or text extents.
pub const MAX_TEXT_POSITION: f32 = 1_024.0;

/// Most bytes in a [`BlockEllipsis::String`].
pub const MAX_BLOCK_ELLIPSIS_BYTES: usize = 64;

/// Steps per unit of font size (a fraction of the shorter side) that a fitted font size takes
/// between its bounds. Steps of `1 / 8192` are exact in `f32` and under a pixel at 8K.
pub const FONT_SIZE_FIT_STEPS: f32 = 8_192.0;

/// How text looks and where it lies, for caption cues or a text [`crate::Generator`].
///
/// The font size is a fraction of the canvas's shorter side, the wrapping width a fraction
/// of the canvas width, and strokes, shadows and padding fractions of the font size. The
/// engine draws with its host's registered fonts, `font_family` first, then the rest in
/// fallback order.
///
/// Painting is bottom to top as in CSS: background boxes, shadows (last listed lowest),
/// strokes (outermost lowest), fill, then color glyphs.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextStyle {
    /// The family, as the font's name table gives it (typographic family, else family), matched
    /// ASCII case-insensitively. Missing glyphs and unknown families fall back to the other fonts
    /// in order; `None` uses the fallback order alone. Non-empty, at most
    /// [`MAX_FONT_FAMILY_BYTES`] bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_family: Option<String>,
    /// Font size as a fraction of the canvas's shorter side: positive, at most
    /// [`crate::MAX_CAPTION_FONT_SIZE`] on a caption track and [`MAX_TEXT_GENERATOR_FONT_SIZE`]
    /// in a text generator.
    #[serde(default = "default_font_size")]
    pub font_size: f32,
    /// What paints the glyphs; a color reads as a solid paint. Gradient positions are in the
    /// text's layout box, `(0, 0)` top-left to `(1, 1)` bottom-right, and a radial radius is a
    /// fraction of the box's shorter side. Default solid white.
    #[serde(default = "white_paint")]
    pub fill: Paint,
    /// Baseline-to-baseline distance in font sizes, in `[0.5, 3]`. Each line's em box (0.8 font
    /// sizes above the baseline, 0.2 below) is centred in a taller line.
    #[serde(default = "default_line_height")]
    pub line_height: f32,
    /// Space after each character, as a fraction of the font size, in `[-0.5, 1]`, added as CSS
    /// `letter-spacing` does: none after a line's last character or within cursive scripts such
    /// as Arabic. A non-zero value turns optional ligatures off.
    #[serde(default)]
    pub letter_spacing: f32,
    /// The weight in `[1, 1000]` used to match a family's faces, as CSS Fonts 4 matches
    /// `font-weight`. Variable faces draw at it, clamped to their `wght` axis; no face is
    /// synthetically emboldened.
    #[serde(default = "default_font_weight")]
    pub font_weight: u16,
    /// The face style matched before weight, as CSS Fonts 4 matches `font-style`. A face that is
    /// neither italic nor oblique is sheared by 14 degrees when one is asked; bitmap glyphs stay
    /// upright. Default `normal`.
    #[serde(default, skip_serializing_if = "FontStyle::is_normal")]
    pub font_style: FontStyle,
    /// A line under the glyphs, as CSS `text-decoration-line: underline`, placed by the font.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub underline: bool,
    /// A line through the glyphs, as CSS `text-decoration-line: line-through`, placed by the
    /// font.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub line_through: bool,
    /// How lines align within the text.
    #[serde(default)]
    pub align: TextAlign,
    /// Width text wraps at, as a fraction of the canvas width, in `(0, 1]`.
    #[serde(default = "default_max_width")]
    pub max_width: f32,
    /// Height the lines' box fits in, as a fraction of the canvas height, in `(0, 1]`, for
    /// `font_size_fit` and `line_clamp`. Text taller than it still draws past it, as CSS
    /// `max-height` lets a box with visible overflow. `None` sets no height.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_height: Option<f32>,
    /// The range the font size is fitted in so the text fits its box. `None` draws at the
    /// font size as set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font_size_fit: Option<FontSizeFit>,
    /// Where lines are cut and what ends a cut line, as CSS `line-clamp`. `None` cuts nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_clamp: Option<LineClamp>,
    /// Where on the canvas the text's anchor lies, `(0, 0)` top-left to `(1, 1)` bottom-right;
    /// each coordinate within [`MAX_TEXT_POSITION`].
    #[serde(default = "default_position")]
    pub position: Vec2,
    /// The point of the text, background included, placed at `position`; `(0.5, 1)` is its
    /// bottom centre. Each coordinate within [`MAX_TEXT_POSITION`].
    #[serde(default = "default_anchor")]
    pub anchor: Vec2,
    /// Bands around the glyphs, innermost first, each outside the one before. At most
    /// [`MAX_TEXT_STROKES`], widths summing to at most [`MAX_TEXT_STROKE_EXTENT`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
    pub strokes: Vec<TextStroke>,
    /// Shadows of the glyphs and strokes, the first on top, as CSS `text-shadow` lists them. At
    /// most [`MAX_TEXT_SHADOWS`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
    pub shadows: Vec<TextShadow>,
    /// A box behind each line.
    #[serde(default)]
    pub background: Option<TextBackground>,
    /// A box over the timed run being said. Needs timed runs; without them it draws nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub highlight: Option<TextHighlight>,
    /// Per-character motion and color, applied in order, at most [`crate::MAX_TEXT_ANIMATORS`].
    /// Keyframes are in the holder's time (since a caption cue's start, or a text generator's
    /// picture time). They never re-break lines while they play; an animator whose advance
    /// follows its scale makes the text wrap with room for its largest scale.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
    pub animators: Vec<TextAnimator>,
    /// The units whose characters the animators scale and turn about one pivot.
    #[serde(default, skip_serializing_if = "is_default")]
    pub animator_grouping: crate::AnimatorGrouping,
    /// Where in each group's box (the union of its characters' advances by their em boxes) the
    /// pivot lies, fractions from its left and top in `[0, 1]`, as CSS `transform-origin`
    /// percentages: `(0.5, 0.5)`, the default, is its centre, `(0.5, 0.8)` its baseline's centre
    /// on one line. Not animated.
    #[serde(
        default = "default_animator_pivot",
        skip_serializing_if = "is_default_animator_pivot"
    )]
    pub animator_pivot: Vec2,
}

fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

/// The centre of a group's box.
pub(crate) const fn default_animator_pivot() -> Vec2 {
    Vec2::new(0.5, 0.5)
}

#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde passes a reference; the lint fires only where a pointer is as wide as a Vec2"
)]
pub(crate) fn is_default_animator_pivot(pivot: &Vec2) -> bool {
    *pivot == default_animator_pivot()
}

/// Whether `pivot` lies in a group's box.
pub(crate) fn valid_animator_pivot(pivot: Vec2) -> bool {
    (0.0..=1.0).contains(&pivot.x) && (0.0..=1.0).contains(&pivot.y)
}

impl Default for TextStyle {
    fn default() -> Self {
        Self {
            font_family: None,
            font_size: default_font_size(),
            fill: white_paint(),
            line_height: default_line_height(),
            letter_spacing: 0.0,
            font_weight: default_font_weight(),
            font_style: FontStyle::Normal,
            underline: false,
            line_through: false,
            align: TextAlign::default(),
            max_width: default_max_width(),
            max_height: None,
            font_size_fit: None,
            line_clamp: None,
            position: default_position(),
            anchor: default_anchor(),
            strokes: Vec::new(),
            shadows: Vec::new(),
            background: None,
            highlight: None,
            animators: Vec::new(),
            animator_grouping: crate::AnimatorGrouping::Character,
            animator_pivot: default_animator_pivot(),
        }
    }
}

const fn default_font_size() -> f32 {
    0.05
}

const fn white_paint() -> Paint {
    Paint::Solid {
        color: Rgba::new(1.0, 1.0, 1.0, 1.0),
    }
}

const fn default_line_height() -> f32 {
    1.2
}

const fn default_font_weight() -> u16 {
    400
}

const fn default_max_width() -> f32 {
    0.9
}

const fn default_position() -> Vec2 {
    Vec2::new(0.5, 0.92)
}

const fn default_anchor() -> Vec2 {
    Vec2::new(0.5, 1.0)
}

/// The font sizes a text is fitted between, as fractions of the canvas's shorter side.
///
/// The text draws at the largest size in `[min, max]` at which no line breaks inside a word,
/// the lines fit the box's height, and there are no more lines than `line_clamp.max_lines`.
/// When no size fits, it draws at `min`. A `min` above `max` wins, as CSS `min-width` does.
/// Sizes are tried by bisection over `max`, `min` and the multiples of `1 / 8192` between.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FontSizeFit {
    /// Smallest font size, positive. At most the holder's largest font size.
    pub min: f32,
    /// Largest font size, at least `min` and at most the holder's largest font size. `None`
    /// is `font_size`, so the text only shrinks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<f32>,
}

impl FontSizeFit {
    /// Whether both bounds are positive, in order, and at most `max_font_size`.
    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
        let size = |value: f32| value.is_finite() && value > 0.0 && value <= max_font_size;
        size(self.min) && self.max.is_none_or(|max| size(max) && self.min <= max)
    }
}

/// Lines past a clamp point are discarded, as CSS Overflow 4 `line-clamp` discards them.
///
/// The clamp point is after the last line within `max_lines` that fits the box's height, and
/// never before the first line. Unlike CSS, the height counts without `max-lines: auto`, so
/// clamped text stays inside a box that has one. A cut line is shortened to its last word end,
/// else its last character, at which the ellipsis fits after it. Text animators count no unit
/// for the ellipsis, which moves with the character before it.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LineClamp {
    /// Most lines, at least 1, as CSS `max-lines`. `None` cuts at the box's height alone.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_lines: Option<u32>,
    /// What ends the last kept line of cut text. Default `ellipsis`, as CSS `line-clamp` sets it.
    #[serde(default)]
    pub block_ellipsis: BlockEllipsis,
}

impl LineClamp {
    pub(crate) fn is_valid(&self) -> bool {
        self.max_lines != Some(0) && self.block_ellipsis.is_valid()
    }
}

/// What ends a line that a clamp cuts, as CSS `block-ellipsis`.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum BlockEllipsis {
    /// No mark. The cut line keeps its own end.
    NoEllipsis,
    /// U+2026 HORIZONTAL ELLIPSIS.
    #[default]
    Ellipsis,
    /// This text, 1 to [`MAX_BLOCK_ELLIPSIS_BYTES`] bytes with no control characters or line
    /// and paragraph separators.
    String(String),
}

impl BlockEllipsis {
    /// The text drawn at the end of a cut line, `None` for no mark.
    #[must_use]
    pub fn text(&self) -> Option<&str> {
        match self {
            Self::NoEllipsis => None,
            Self::Ellipsis => Some("\u{2026}"),
            Self::String(text) => Some(text),
        }
    }

    fn is_valid(&self) -> bool {
        match self {
            Self::String(text) => {
                !text.is_empty()
                    && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
                    && !text.chars().any(|character| {
                        character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
                    })
            }
            Self::NoEllipsis | Self::Ellipsis => true,
        }
    }
}

/// Which faces of a family text prefers, as CSS `font-style`.
#[derive(
    Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FontStyle {
    /// Upright faces, then oblique, then italic.
    #[default]
    Normal,
    /// Italic faces, then oblique, then upright ones sheared.
    Italic,
    /// Oblique faces, then italic, then upright ones sheared.
    Oblique,
}

impl FontStyle {
    /// Whether this is `normal`.
    #[must_use]
    pub const fn is_normal(&self) -> bool {
        matches!(self, Self::Normal)
    }
}

/// How lines of text align within it.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TextAlign {
    /// Left.
    Start,
    /// Centred.
    #[default]
    Center,
    /// Right.
    End,
}

/// A band around the glyphs and the strokes listed before it, drawn behind them.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextStroke {
    /// Band color.
    pub color: Rgba,
    /// Band width as a fraction of the font size, positive; a text's strokes sum to at most
    /// [`MAX_TEXT_STROKE_EXTENT`].
    pub width: f32,
}

/// A shadow of a text's glyphs and strokes, behind them.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextShadow {
    /// Shadow color.
    pub color: Rgba,
    /// Offset in font sizes, +x right, +y down; each component in `[-1, 1]`
    /// ([`MAX_TEXT_SHADOW_OFFSET`]).
    #[serde(default)]
    pub offset: Vec2,
    /// Blur radius in font sizes, as CSS `text-shadow` takes it (the Gaussian's standard
    /// deviation is half of it). In `[0, 1]` ([`MAX_TEXT_SHADOW_BLUR`]).
    #[serde(default)]
    pub blur: f32,
}

/// A box behind each line of text, as CSS draws an inline box's background with
/// `box-decoration-break: clone`: each line's box has its own padding, radius and border.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextBackground {
    /// Box color.
    pub color: Rgba,
    /// Space between the text and the box edge, as fractions of the font size, each side in
    /// `[0, 2]`.
    #[serde(default)]
    pub padding: TextInsets,
    /// Every corner's radius, as a fraction of the font size, in `[0, 2]`; each box's radius is
    /// capped at half its shorter side, as CSS `border-radius`. Default 0.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub radius: f32,
    /// A line inside the box's edge, as a CSS border. `None` draws none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border: Option<TextBoxBorder>,
    /// Which part of each line the box spans.
    #[serde(default, skip_serializing_if = "is_default")]
    pub extent: TextBoxExtent,
}

/// Which part of each line a text's background box spans, where tracking and pushing place its
/// characters.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TextBoxExtent {
    /// From the line's first character to its last that is not a hanging space.
    #[default]
    Line,
    /// From the first to the last revealed character that is not white space: shown, not scaled
    /// to nothing, and not hidden by a reveal. A line with none has no box; a text without
    /// animators draws as `line`.
    Revealed,
    /// One box over the whole layout box, `max_width` wide and as tall as the lines.
    Block,
}

/// A box over the timed run being said, sliding from run to run, drawn over the background
/// boxes and under the glyphs. The run is the timed run that started last; before the first
/// starts there is none.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextHighlight {
    /// Box color.
    pub color: Rgba,
    /// Space between the run and the box edge, as a background's `padding`.
    #[serde(default)]
    pub padding: TextInsets,
    /// Every corner's radius, as a background's `radius`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub radius: f32,
    /// A line inside the box's edge, as a background's `border`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub border: Option<TextBoxBorder>,
    /// How long the box takes to slide to the next run once it starts, at most
    /// [`MAX_HIGHLIGHT_TRANSITION`]; 0 jumps. A change during a slide starts where the box is.
    #[serde(default, skip_serializing_if = "is_default")]
    pub transition: MediaTime,
    /// The slide's timing curve.
    #[serde(default = "linear", skip_serializing_if = "is_linear")]
    pub easing: crate::Easing,
    /// What the box does between a run's end and the next run's start.
    #[serde(default, skip_serializing_if = "is_default")]
    pub gap: HighlightGap,
}

/// What a highlight does after its run ends, before the next starts.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum HighlightGap {
    /// Stays on the run until the next starts or its holder ends.
    #[default]
    Hold,
    /// Is drawn only while its run lasts; a run that starts after the last one ended takes the
    /// box without sliding.
    Hide,
}

/// Longest highlight transition.
pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
    MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);

const fn linear() -> crate::Easing {
    crate::Easing::Linear
}

fn is_linear(easing: &crate::Easing) -> bool {
    matches!(easing, crate::Easing::Linear)
}

impl TextHighlight {
    pub(crate) fn is_valid(&self) -> bool {
        self.color.is_valid()
            && self.padding.is_valid()
            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
            && self.transition >= MediaTime::ZERO
            && self.transition <= MAX_HIGHLIGHT_TRANSITION
            && self.easing.is_valid()
    }
}

impl TextBackground {
    /// A box of `color` with `padding` on every side, no radius and no border.
    #[must_use]
    pub const fn padded(color: Rgba, padding: f32) -> Self {
        Self {
            color,
            padding: TextInsets::all(padding),
            radius: 0.0,
            border: None,
            extent: TextBoxExtent::Line,
        }
    }

    pub(crate) fn is_valid(&self) -> bool {
        self.color.is_valid()
            && self.padding.is_valid()
            && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
            && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
    }
}

#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if passes a reference"
)]
fn is_zero(value: &f32) -> bool {
    *value == 0.0
}

/// The border of a text box, drawn inside the box's edge.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextBoxBorder {
    /// Width as a fraction of the font size, in `(0, 0.5]`.
    pub width: f32,
    /// Line color.
    pub color: Rgba,
    /// Dashes along the border's centre line; `None` draws it solid.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dash: Option<TextDash>,
}

impl TextBoxBorder {
    fn is_valid(&self) -> bool {
        self.width.is_finite()
            && self.width > 0.0
            && self.width <= MAX_TEXT_BORDER_WIDTH
            && self.color.is_valid()
            && self.dash.as_ref().is_none_or(TextDash::is_valid)
    }
}

/// Dashes along a box border, as SVG `stroke-dasharray` and `stroke-dashoffset`: they start at
/// the end of the top-left corner and run clockwise.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextDash {
    /// Alternating dash and gap lengths, as fractions of the font size: one to
    /// [`crate::MAX_DASH_ENTRIES`] entries in `[0, 4]`, not all zero. An odd count repeats once
    /// more to pair up.
    #[serde(deserialize_with = "dash_pattern")]
    #[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
    pub pattern: Vec<f32>,
    /// How far into the pattern the border starts, in font sizes, in `[-16, 16]`.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub offset: f32,
}

fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
    let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
    if pattern.is_empty() {
        return Err(serde::de::Error::invalid_length(
            0,
            &"one to sixteen entries",
        ));
    }
    Ok(pattern)
}

impl TextDash {
    fn is_valid(&self) -> bool {
        !self.pattern.is_empty()
            && self.pattern.len() <= crate::MAX_DASH_ENTRIES
            && self
                .pattern
                .iter()
                .all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
            && self.pattern.iter().any(|entry| *entry > 0.0)
            && (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
    }
}

/// A length on each side of a text box, as fractions of the font size.
///
/// Written as 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. Pixels are refused.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct TextInsets {
    /// Top side.
    pub top: f32,
    /// Right side.
    pub right: f32,
    /// Bottom side.
    pub bottom: f32,
    /// Left side.
    pub left: f32,
}

impl TextInsets {
    /// The same length on every side.
    #[must_use]
    pub const fn all(value: f32) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }

    /// The sides, top first, clockwise.
    #[must_use]
    pub const fn sides(self) -> [f32; 4] {
        [self.top, self.right, self.bottom, self.left]
    }

    fn is_valid(self) -> bool {
        self.sides()
            .iter()
            .all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
    }

    fn from_shorthand(values: &[f32]) -> Option<Self> {
        let [top, right, bottom, left] = match *values {
            [all] => [all; 4],
            [vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
            [top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
            [top, right, bottom, left] => [top, right, bottom, left],
            _ => return None,
        };
        Some(Self {
            top,
            right,
            bottom,
            left,
        })
    }
}

impl<'de> Deserialize<'de> for TextInsets {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Written {
            Number(f32),
            Shorthand(String),
            Sides(std::collections::BTreeMap<String, f32>),
        }
        match Written::deserialize(deserializer)? {
            Written::Number(value) => Ok(Self::all(value)),
            Written::Shorthand(text) => text
                .split(' ')
                .filter(|token| !token.is_empty())
                .map(str::parse::<f32>)
                .collect::<Result<Vec<_>, _>>()
                .ok()
                .and_then(|values| Self::from_shorthand(&values))
                .ok_or_else(|| {
                    serde::de::Error::custom(format!(
                        "text insets: expected one to four numbers, got {text:?}"
                    ))
                }),
            Written::Sides(sides) => {
                let mut insets = Self::default();
                for (side, value) in sides {
                    *match side.as_str() {
                        "top" => &mut insets.top,
                        "right" => &mut insets.right,
                        "bottom" => &mut insets.bottom,
                        "left" => &mut insets.left,
                        _ => {
                            return Err(serde::de::Error::unknown_field(
                                &side,
                                &["top", "right", "bottom", "left"],
                            ));
                        }
                    } = value;
                }
                Ok(insets)
            }
        }
    }
}

/// One number when every side is the same, else the sides object.
impl Serialize for TextInsets {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let [top, right, bottom, left] = self.sides().map(f32::to_bits);
        if top == right && top == bottom && top == left {
            return serializer.serialize_f32(self.top);
        }
        let mut sides = serializer.serialize_struct("TextInsets", 4)?;
        sides.serialize_field("top", &self.top)?;
        sides.serialize_field("right", &self.right)?;
        sides.serialize_field("bottom", &self.bottom)?;
        sides.serialize_field("left", &self.left)?;
        sides.end()
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for TextInsets {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "TextInsets".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let number = r"-?(\d+\.?\d*|\.\d+)";
        let side = schemars::json_schema!({ "type": "number", "format": "float" });
        schemars::json_schema!({
            "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.",
            "anyOf": [
                { "type": "number", "format": "float" },
                { "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
                {
                    "type": "object",
                    "properties": { "top": side, "right": side, "bottom": side, "left": side },
                    "additionalProperties": false,
                },
            ],
        })
    }
}

impl TextStyle {
    /// Whether every field is in range, with the font size at most `max_font_size`.
    pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
        let finite =
            |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
        self.font_family
            .as_ref()
            .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
            && self.font_size > 0.0
            && self.font_size <= max_font_size
            && self.fill.is_valid()
            && LINE_HEIGHT_RANGE.contains(&self.line_height)
            && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
            && FONT_WEIGHT_RANGE.contains(&self.font_weight)
            && self.max_width > 0.0
            && self.max_width <= 1.0
            && self
                .max_height
                .is_none_or(|height| height > 0.0 && height <= 1.0)
            && self
                .font_size_fit
                .is_none_or(|fit| fit.is_valid(max_font_size))
            && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
            && finite(self.position)
            && finite(self.anchor)
            && valid_strokes(&self.strokes)
            && valid_shadows(&self.shadows)
            && crate::text_animation::valid_animators(&self.animators, false)
            && valid_animator_pivot(self.animator_pivot)
            && self
                .background
                .as_ref()
                .is_none_or(TextBackground::is_valid)
            && self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
    }
}

/// Whether `strokes` are at most [`MAX_TEXT_STROKES`] valid bands reaching at most
/// [`MAX_TEXT_STROKE_EXTENT`] together.
pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
    strokes.len() <= MAX_TEXT_STROKES
        && strokes
            .iter()
            .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
        && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
}

/// Whether `shadows` are at most [`MAX_TEXT_SHADOWS`] shadows in range.
pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
    let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
    shadows.len() <= MAX_TEXT_SHADOWS
        && shadows.iter().all(|shadow| {
            shadow.color.is_valid()
                && offset(shadow.offset.x)
                && offset(shadow.offset.y)
                && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
        })
}