Skip to main content

alpha2_model/
text_animation.rs

1//! Text content as runs, and text animators: per-character motion and color held by a text
2//! style.
3//!
4//! A run's style changes its layout as CSS inline boxes do; animators never change layout. An
5//! animator gives each grapheme cluster a selection in `[0, 1]` and moves, scales,
6//! turns, fades or recolors it in proportion, as After Effects' text animators do.
7
8use std::borrow::Cow;
9
10use alpha2_time::MediaTime;
11use serde::{Deserialize, Serialize};
12
13use crate::animation::{valid_keyframes, valid_scalar_values};
14use crate::{Animated, FontStyle, Paint, Rgba, TextStroke, Vec2};
15
16/// Most runs one text holds.
17pub const MAX_TEXT_RUNS: usize = 512;
18
19/// Most classes one run carries.
20pub const MAX_RUN_CLASSES: usize = 8;
21
22/// Most bytes of one class name.
23pub const MAX_CLASS_NAME_BYTES: usize = 64;
24
25/// Most animators one text style holds.
26pub const MAX_TEXT_ANIMATORS: usize = 8;
27
28/// How far a Range selector in index units reaches past either end: `[-N, 2N]` units for
29/// `N` of this.
30pub const MAX_RANGE_INDEX: f32 = 4_096.0;
31
32/// The range a percent Range selector's start, end and offset take.
33pub const RANGE_PERCENT: std::ops::RangeInclusive<f32> = -100.0..=200.0;
34
35/// Largest magnitude of a text animator's offset on each axis, in font sizes.
36pub const MAX_ANIMATOR_OFFSET: f32 = 1_024.0;
37/// The range an animator's scale takes on each axis.
38pub const ANIMATOR_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.0..=10.0;
39/// Widest feather of a text reveal's edge, in font sizes.
40pub const MAX_REVEAL_FEATHER: f32 = 1.0;
41
42/// A text: one string, or runs whose texts joined are the text.
43///
44/// Written as `"Hello"` or `[{ "text": "Hel" }, { "text": "lo", "class": ["key"] }]`.
45#[derive(Clone, Debug, PartialEq, Serialize)]
46#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
47#[serde(untagged)]
48pub enum TextContent {
49    /// One string; `\n` starts a line.
50    Plain(String),
51    /// Runs in order; their texts joined are the text.
52    Runs(#[cfg_attr(feature = "schema", schemars(length(max = MAX_TEXT_RUNS)))] Vec<TextRun>),
53}
54
55// Read by the JSON type rather than as an untagged enum, which would buffer the whole value and
56// hide why runs were refused.
57impl<'de> Deserialize<'de> for TextContent {
58    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
59        struct Content;
60
61        impl<'de> serde::de::Visitor<'de> for Content {
62            type Value = TextContent;
63
64            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65                formatter.write_str("a string or a sequence of runs")
66            }
67
68            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<TextContent, E> {
69                Ok(TextContent::Plain(text.to_owned()))
70            }
71
72            fn visit_string<E: serde::de::Error>(self, text: String) -> Result<TextContent, E> {
73                Ok(TextContent::Plain(text))
74            }
75
76            fn visit_seq<A: serde::de::SeqAccess<'de>>(
77                self,
78                seq: A,
79            ) -> Result<TextContent, A::Error> {
80                crate::bounded::seq::<_, _, MAX_TEXT_RUNS>(
81                    serde::de::value::SeqAccessDeserializer::new(seq),
82                )
83                .map(TextContent::Runs)
84            }
85        }
86
87        deserializer.deserialize_any(Content)
88    }
89}
90
91impl Default for TextContent {
92    fn default() -> Self {
93        Self::Plain(String::new())
94    }
95}
96
97impl From<String> for TextContent {
98    fn from(text: String) -> Self {
99        Self::Plain(text)
100    }
101}
102
103impl From<&str> for TextContent {
104    fn from(text: &str) -> Self {
105        Self::Plain(text.to_owned())
106    }
107}
108
109/// Compares the whole text, runs joined, with a string.
110impl PartialEq<str> for TextContent {
111    fn eq(&self, other: &str) -> bool {
112        self.text() == other
113    }
114}
115
116impl PartialEq<&str> for TextContent {
117    fn eq(&self, other: &&str) -> bool {
118        self.text() == *other
119    }
120}
121
122impl TextContent {
123    /// The whole text: the string, or the runs' texts joined.
124    #[must_use]
125    pub fn text(&self) -> Cow<'_, str> {
126        match self {
127            Self::Plain(text) => Cow::Borrowed(text),
128            Self::Runs(runs) => Cow::Owned(runs.iter().map(|run| run.text.as_str()).collect()),
129        }
130    }
131
132    /// The runs, none for a plain string.
133    #[must_use]
134    pub fn runs(&self) -> &[TextRun] {
135        match self {
136            Self::Plain(_) => &[],
137            Self::Runs(runs) => runs,
138        }
139    }
140
141    /// Bytes of the whole text.
142    #[must_use]
143    pub fn len(&self) -> usize {
144        match self {
145            Self::Plain(text) => text.len(),
146            Self::Runs(runs) => runs.iter().map(|run| run.text.len()).sum(),
147        }
148    }
149
150    /// Whether the whole text is empty.
151    #[must_use]
152    pub fn is_empty(&self) -> bool {
153        self.len() == 0
154    }
155
156    /// Whether the text is non-empty and within `max_bytes`, has at most [`MAX_TEXT_RUNS`] runs,
157    /// and every run has non-empty text, at most [`MAX_RUN_CLASSES`] valid class names, and a
158    /// time span that starts at or after zero and before it ends.
159    pub(crate) fn is_valid(&self, max_bytes: usize) -> bool {
160        !self.is_empty()
161            && self.len() <= max_bytes
162            && self.runs().len() <= MAX_TEXT_RUNS
163            && self.runs().iter().all(TextRun::is_valid)
164    }
165
166    /// Whether any run has a style.
167    #[must_use]
168    pub fn has_run_styles(&self) -> bool {
169        self.runs().iter().any(|run| run.style.is_some())
170    }
171
172    /// Whether a run's `font_scale` changes over time, so the text lays out again as it does.
173    #[must_use]
174    pub fn varies(&self) -> bool {
175        self.runs().iter().any(|run| {
176            run.style
177                .as_ref()
178                .and_then(|style| style.font_scale.as_ref())
179                .is_some_and(Animated::varies)
180        })
181    }
182
183    pub(crate) fn invalid_run_style(&self, base: FontSelection<'_>) -> Option<usize> {
184        let mut selections = Vec::new();
185        for (index, run) in self.runs().iter().enumerate() {
186            let style = run.style.as_ref();
187            if style.is_some_and(|style| !style.is_valid()) {
188                return Some(index);
189            }
190            let selection = TextRunStyle::selection(style, base);
191            if !selections.contains(&selection) {
192                if selections.len() == crate::MAX_TEXT_FONT_SELECTIONS {
193                    return Some(index);
194                }
195                selections.push(selection);
196            }
197        }
198        None
199    }
200}
201
202/// A run's changes to its holder's text style, as an inline box's own CSS properties. Each
203/// field set replaces the holder's value for the run's characters; a field left out keeps it.
204/// A change of family, weight, style, size or letter spacing shapes the run apart and can move
205/// line breaks; fill, strokes, background and decorations only paint.
206#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
207#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
208#[serde(deny_unknown_fields)]
209pub struct TextRunStyle {
210    /// The family, as a text style's `font_family`; `null` draws from the fallback order alone.
211    #[serde(
212        default,
213        skip_serializing_if = "Option::is_none",
214        with = "crate::caption::double_option"
215    )]
216    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
217    pub font_family: Option<Option<String>>,
218    /// The weight in `[1, 1000]`, as a text style's `font_weight`.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub font_weight: Option<u16>,
221    /// The face style, as a text style's `font_style`.
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub font_style: Option<FontStyle>,
224    /// The run's size as a multiple of the text's font size, in `[0.1, 10]`, as CSS
225    /// `font-size: <n>em`. Lines are laid out again when it changes; keyframes are in the
226    /// holder's time.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub font_scale: Option<Animated<f32>>,
229    /// Space after each character, as a fraction of the run's size, in `[-0.5, 1]`.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub letter_spacing: Option<f32>,
232    /// What paints the run's glyphs; gradient positions are in the text's layout box, as the
233    /// text's fill.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub fill: Option<Paint>,
236    /// The run's bands, as a text style's `strokes`, widths in fractions of the run's size.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
239    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
240    pub strokes: Option<Vec<TextStroke>>,
241    /// A box behind the run on each line, its advances wide and its em box tall, as CSS
242    /// `background-color` paints an inline box.
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub background_color: Option<Rgba>,
245    /// See [`crate::TextStyle::underline`].
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub underline: Option<bool>,
248    /// See [`crate::TextStyle::line_through`].
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub line_through: Option<bool>,
251}
252
253impl TextRunStyle {
254    /// `base` with every face, spacing, paint and decoration field this style sets replaced.
255    /// The size stays the base's: `font_scale` multiplies it where the run is laid out, and
256    /// `background_color` has no text-wide counterpart.
257    #[must_use]
258    pub fn apply(&self, base: &crate::TextStyle) -> crate::TextStyle {
259        let mut style = base.clone();
260        if let Some(family) = &self.font_family {
261            style.font_family.clone_from(family);
262        }
263        if let Some(weight) = self.font_weight {
264            style.font_weight = weight;
265        }
266        if let Some(font_style) = self.font_style {
267            style.font_style = font_style;
268        }
269        if let Some(spacing) = self.letter_spacing {
270            style.letter_spacing = spacing;
271        }
272        if let Some(fill) = &self.fill {
273            style.fill = fill.clone();
274        }
275        if let Some(strokes) = &self.strokes {
276            style.strokes.clone_from(strokes);
277        }
278        if let Some(underline) = self.underline {
279            style.underline = underline;
280        }
281        if let Some(line_through) = self.line_through {
282            style.line_through = line_through;
283        }
284        style
285    }
286
287    pub(crate) fn is_valid(&self) -> bool {
288        self.font_family.as_ref().is_none_or(|family| {
289            family.as_ref().is_none_or(|family| {
290                !family.is_empty() && family.len() <= crate::MAX_FONT_FAMILY_BYTES
291            })
292        }) && self
293            .font_weight
294            .is_none_or(|weight| crate::FONT_WEIGHT_RANGE.contains(&weight))
295            && self.font_scale.as_ref().is_none_or(|scale| {
296                scale.data().is_none()
297                    && valid_scalar_values(scale, |value| crate::FONT_SCALE_RANGE.contains(&value))
298            })
299            && self
300                .letter_spacing
301                .is_none_or(|spacing| crate::LETTER_SPACING_RANGE.contains(&spacing))
302            && self.fill.as_ref().is_none_or(Paint::is_valid)
303            && self
304                .strokes
305                .as_deref()
306                .is_none_or(crate::text::valid_strokes)
307            && self.background_color.is_none_or(Rgba::is_valid)
308    }
309
310    /// Whether the run takes only fields a layout text's run may: no keyframed font scale.
311    #[must_use]
312    pub const fn is_static(&self) -> bool {
313        !matches!(
314            self.font_scale,
315            Some(Animated::Keyframes { .. } | Animated::Split { .. } | Animated::Data(_))
316        )
317    }
318
319    fn selection(
320        style: Option<&Self>,
321        base: FontSelection<'_>,
322    ) -> (Option<String>, u16, FontStyle) {
323        let family = match style.and_then(|style| style.font_family.as_ref()) {
324            Some(family) => family.as_deref(),
325            None => base.family,
326        };
327        (
328            family.map(str::to_ascii_lowercase),
329            style
330                .and_then(|style| style.font_weight)
331                .unwrap_or(base.weight),
332            style
333                .and_then(|style| style.font_style)
334                .unwrap_or(base.style),
335        )
336    }
337}
338
339#[derive(Copy, Clone, Debug)]
340pub(crate) struct FontSelection<'a> {
341    pub(crate) family: Option<&'a str>,
342    pub(crate) weight: u16,
343    pub(crate) style: FontStyle,
344}
345
346impl<'a> FontSelection<'a> {
347    pub(crate) fn of(style: &'a crate::TextStyle) -> Self {
348        Self {
349            family: style.font_family.as_deref(),
350            weight: style.font_weight,
351            style: style.font_style,
352        }
353    }
354}
355
356/// A piece of a text with its own style, that animators' Class and Timing selectors can pick.
357#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
358#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
359#[serde(deny_unknown_fields)]
360pub struct TextRun {
361    /// Non-empty; `\n` starts a line. A grapheme cluster spanning two runs belongs to the run
362    /// holding its first byte.
363    pub text: String,
364    /// Names Class selectors match, each 1 to 64 bytes of `A-Z`, `a-z`, `0-9`, `_` and `-`; at
365    /// most [`MAX_RUN_CLASSES`].
366    #[serde(default, skip_serializing_if = "Vec::is_empty")]
367    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_RUN_CLASSES }>")]
368    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_RUN_CLASSES)))]
369    pub class: Vec<String>,
370    /// When the run is said, from the holder's start (a caption cue's start, or a text
371    /// generator's picture time zero).
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub time: Option<RunTime>,
374    /// Changes to the holder's style for this run's characters.
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub style: Option<TextRunStyle>,
377}
378
379impl TextRun {
380    fn is_valid(&self) -> bool {
381        !self.text.is_empty()
382            && self.class.len() <= MAX_RUN_CLASSES
383            && self.class.iter().all(|name| valid_class_name(name))
384            && self
385                .time
386                .is_none_or(|time| time.start.ticks() >= 0 && time.start < time.end)
387    }
388}
389
390/// Whether `name` is a class name a run or a Class selector may carry.
391#[must_use]
392pub fn valid_class_name(name: &str) -> bool {
393    !name.is_empty()
394        && name.len() <= MAX_CLASS_NAME_BYTES
395        && name
396            .bytes()
397            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
398}
399
400/// A run's time span.
401#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
402#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
403#[serde(deny_unknown_fields)]
404pub struct RunTime {
405    /// When it starts.
406    pub start: MediaTime,
407    /// When it ends; after `start`.
408    pub end: MediaTime,
409}
410
411/// One animator: what it selects, and what it does to what it selects.
412#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
413#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
414#[serde(deny_unknown_fields)]
415pub struct TextAnimator {
416    /// Gives each character its selection, in `[0, 1]`.
417    pub selector: TextSelector,
418    /// Applied to each character in proportion to its selection.
419    #[serde(default)]
420    pub properties: TextAnimatorProperties,
421}
422
423/// How an animator selects characters.
424#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
425#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
426#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
427pub enum TextSelector {
428    /// A range over the text's units, shaped at its ends, like After Effects' range selector.
429    Range {
430        /// What the range counts: characters (the default), non-space characters, words, or lines.
431        #[serde(default)]
432        based_on: TextUnit,
433        /// Whether start, end and offset are percents of the units (the default) or unit indices.
434        #[serde(default)]
435        units: RangeUnits,
436        /// Where the range starts: `[-100, 200]` percent, or `[-N, 2N]` units for `N` of
437        /// [`MAX_RANGE_INDEX`]. Default 0.
438        #[serde(default = "zero")]
439        start: Animated<f32>,
440        /// Where it ends, in the same range. Default 100.
441        #[serde(default = "hundred")]
442        end: Animated<f32>,
443        /// Added to start and end, in the same range. Default 0.
444        #[serde(default = "zero")]
445        offset: Animated<f32>,
446        /// How selection rises and falls across the range.
447        #[serde(default)]
448        shape: RangeShape,
449        /// The selection's scale, in `[0, 1]`. Default 1.
450        #[serde(default = "one")]
451        amount: Animated<f32>,
452    },
453    /// Characters of timed runs, by the run's time against the current time.
454    Timing {
455        /// Which runs it selects: those not yet said, being said, or said.
456        state: RunState,
457        /// How long the state takes to fade in and out; zero switches.
458        #[serde(default)]
459        ramp: MediaTime,
460        /// Splits each run's span over its characters in order, sweeping the run character by
461        /// character.
462        #[serde(default)]
463        sweep: bool,
464    },
465    /// Characters of runs that carry a class.
466    Class {
467        /// The class name.
468        class: String,
469    },
470}
471
472const fn zero() -> Animated<f32> {
473    Animated::Constant { value: 0.0 }
474}
475
476const fn hundred() -> Animated<f32> {
477    Animated::Constant { value: 100.0 }
478}
479
480const fn one() -> Animated<f32> {
481    Animated::Constant { value: 1.0 }
482}
483
484/// The units a Range selector counts.
485#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
486#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
487#[serde(rename_all = "snake_case")]
488pub enum TextUnit {
489    /// Grapheme clusters, spaces included.
490    #[default]
491    Characters,
492    /// Grapheme clusters that are not white space.
493    CharactersExcludingSpaces,
494    /// UAX #29 words that hold a letter or digit; a CJK ideograph is a word.
495    Words,
496    /// Laid-out lines.
497    Lines,
498}
499
500/// What a Range selector's start, end and offset count in.
501#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
502#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
503#[serde(rename_all = "snake_case")]
504pub enum RangeUnits {
505    /// Percents of the units.
506    #[default]
507    Percent,
508    /// Unit indices.
509    Index,
510}
511
512/// How selection rises and falls across a Range selector's range.
513#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
514#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
515#[serde(rename_all = "snake_case")]
516pub enum RangeShape {
517    /// Fully selected inside the range, partly at fractional ends.
518    #[default]
519    Square,
520    /// Rising from the start to the end.
521    RampUp,
522    /// Falling from the start to the end.
523    RampDown,
524    /// Rising to the middle, falling after it.
525    Triangle,
526    /// A half circle over the range.
527    Round,
528    /// The triangle eased by smoothstep.
529    Smooth,
530}
531
532/// Which runs a Timing selector selects.
533#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
534#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
535#[serde(rename_all = "snake_case")]
536pub enum RunState {
537    /// Runs whose time has not started.
538    Upcoming,
539    /// Runs whose time holds the current time.
540    Active,
541    /// Runs whose time has ended.
542    Spoken,
543}
544
545/// What an animator does to each character, in proportion to its selection. A property left
546/// out does nothing.
547#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
548#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
549#[serde(deny_unknown_fields)]
550pub struct TextAnimatorProperties {
551    /// Moves the character, in font sizes, +y down.
552    #[serde(default, skip_serializing_if = "Option::is_none")]
553    pub offset: Option<Animated<Vec2>>,
554    /// Scales the character about its centre; 1 is none. Each axis in `[0, 10]`. The scales of
555    /// several animators multiply, and the product is at most 10 on each axis.
556    #[serde(default, skip_serializing_if = "Option::is_none")]
557    pub scale: Option<Animated<Vec2>>,
558    /// Turns the character about its centre, clockwise degrees.
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub rotation_degrees: Option<Animated<f32>>,
561    /// The opacity a fully selected character takes, in `[0, 1]`.
562    #[serde(default, skip_serializing_if = "Option::is_none")]
563    pub opacity: Option<Animated<f32>>,
564    /// The fill color a fully selected character takes; a gradient fill is mixed toward it.
565    #[serde(default, skip_serializing_if = "Option::is_none")]
566    pub fill: Option<Animated<Rgba>>,
567    /// The color every stroke of a fully selected character takes.
568    #[serde(default, skip_serializing_if = "Option::is_none")]
569    pub stroke: Option<Animated<Rgba>>,
570    /// Space added after the character, in font sizes, in `[-0.5, 1]`, as letter spacing adds
571    /// it. Lines are not re-broken.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub tracking: Option<Animated<f32>>,
574    /// Whether the character's advance follows this animator's horizontal scale, pushing the
575    /// characters after it along its line, which is re-aligned; lines are not re-broken, and the
576    /// text wraps with room for the largest scale this can reach. Needs `scale`.
577    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
578    pub advance_follows_scale: bool,
579    /// Wipes the character's unit (its group, as `animator_grouping` gives) in along a straight
580    /// edge, cutting its fill, strokes and color glyphs alike; a fully selected unit shows
581    /// `progress` of itself.
582    #[serde(default, skip_serializing_if = "Option::is_none")]
583    pub reveal: Option<TextReveal>,
584}
585
586/// A straight edge that shows a unit up to it, as a linear wipe: across the unit's box (its
587/// advances by its em boxes, outset by its strokes) in the direction `angle_degrees`.
588#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
589#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
590#[serde(deny_unknown_fields)]
591pub struct TextReveal {
592    /// How much of a fully selected unit shows, in `[0, 1]`: 0 hides it, 1 shows it whole. A unit
593    /// selected by `w` shows `1 + w (progress - 1)`. Default 0.
594    #[serde(default = "zero")]
595    pub progress: Animated<f32>,
596    /// The direction the edge travels, clockwise degrees with y down: 0 reveals left to right,
597    /// 90 top to bottom. Default 0.
598    #[serde(default = "zero")]
599    pub angle_degrees: Animated<f32>,
600    /// The edge's softness in font sizes, in `[0, MAX_REVEAL_FEATHER]`; 0 is a one-pixel
601    /// antialiased step. Default 0.
602    #[serde(default = "zero")]
603    pub feather: Animated<f32>,
604}
605
606impl TextReveal {
607    fn is_valid(&self) -> bool {
608        valid_scalar_values(&self.progress, |value| (0.0..=1.0).contains(&value))
609            && valid_scalar_values(&self.angle_degrees, |_| true)
610            && valid_scalar_values(&self.feather, |value| {
611                (0.0..=MAX_REVEAL_FEATHER).contains(&value)
612            })
613    }
614}
615
616/// The units whose clusters scale and turn about one pivot, as After Effects' Anchor Point
617/// Grouping.
618#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
619#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
620#[serde(rename_all = "snake_case")]
621pub enum AnimatorGrouping {
622    /// Each grapheme cluster about its own pivot.
623    #[default]
624    Character,
625    /// Each UAX #29 word holding a letter or digit; a cluster in no word is its own group.
626    Word,
627    /// Each line.
628    Line,
629    /// The whole text.
630    All,
631}
632
633impl TextAnimatorProperties {
634    /// Whether no property is set: the animator does nothing.
635    #[must_use]
636    pub const fn is_empty(&self) -> bool {
637        self.offset.is_none()
638            && self.scale.is_none()
639            && self.rotation_degrees.is_none()
640            && self.opacity.is_none()
641            && self.fill.is_none()
642            && self.stroke.is_none()
643            && self.tracking.is_none()
644            && self.reveal.is_none()
645    }
646
647    fn is_valid(&self) -> bool {
648        let vec2 = |animation: &Animated<Vec2>, check: &dyn Fn(f32) -> bool| match animation {
649            Animated::Constant { value } => check(value.x) && check(value.y),
650            Animated::Keyframes {
651                keyframes,
652                before,
653                after,
654            } => {
655                valid_keyframes(keyframes, *before, *after)
656                    && keyframes
657                        .iter()
658                        .all(|keyframe| check(keyframe.value.x) && check(keyframe.value.y))
659            }
660            Animated::Split { channels } => {
661                crate::animation::valid_channels(channels, 2..=2, check)
662            }
663            Animated::Data(_) => true,
664        };
665        let color = |animation: &Animated<Rgba>| match animation {
666            Animated::Constant { value } => value.is_valid(),
667            Animated::Keyframes {
668                keyframes,
669                before,
670                after,
671            } => {
672                valid_keyframes(keyframes, *before, *after)
673                    && keyframes.iter().all(|key| key.value.is_valid())
674            }
675            Animated::Data(_) | Animated::Split { .. } => false,
676        };
677        self.offset
678            .as_ref()
679            .is_none_or(|offset| vec2(offset, &|value| value.abs() <= MAX_ANIMATOR_OFFSET))
680            && self.scale.as_ref().is_none_or(|scale| {
681                vec2(scale, &|value| {
682                    value.is_finite() && ANIMATOR_SCALE_RANGE.contains(&value)
683                })
684            })
685            && self
686                .rotation_degrees
687                .as_ref()
688                .is_none_or(|rotation| valid_scalar_values(rotation, |_| true))
689            && self.opacity.as_ref().is_none_or(|opacity| {
690                valid_scalar_values(opacity, |value| (0.0..=1.0).contains(&value))
691            })
692            && self.fill.as_ref().is_none_or(color)
693            && self.stroke.as_ref().is_none_or(color)
694            && self.tracking.as_ref().is_none_or(|tracking| {
695                valid_scalar_values(tracking, |value| {
696                    crate::LETTER_SPACING_RANGE.contains(&value)
697                })
698            })
699            && (!self.advance_follows_scale || self.scale.is_some())
700            && self.reveal.as_ref().is_none_or(TextReveal::is_valid)
701    }
702}
703
704impl TextSelector {
705    fn is_valid(&self) -> bool {
706        match self {
707            Self::Range {
708                units,
709                start,
710                end,
711                offset,
712                amount,
713                ..
714            } => {
715                let range = match units {
716                    RangeUnits::Percent => RANGE_PERCENT,
717                    RangeUnits::Index => -MAX_RANGE_INDEX..=2.0 * MAX_RANGE_INDEX,
718                };
719                [start, end, offset]
720                    .into_iter()
721                    .all(|value| valid_scalar_values(value, |value| range.contains(&value)))
722                    && valid_scalar_values(amount, |value| (0.0..=1.0).contains(&value))
723            }
724            Self::Timing { ramp, .. } => ramp.ticks() >= 0,
725            Self::Class { class } => valid_class_name(class),
726        }
727    }
728}
729
730/// Whether `animators` are at most [`MAX_TEXT_ANIMATORS`] valid animators, using only Range
731/// selectors when `range_only`.
732pub(crate) fn valid_animators(animators: &[TextAnimator], range_only: bool) -> bool {
733    animators.len() <= MAX_TEXT_ANIMATORS
734        && animators.iter().all(|animator| {
735            animator.selector.is_valid()
736                && animator.properties.is_valid()
737                && (!range_only || matches!(animator.selector, TextSelector::Range { .. }))
738        })
739}
740
741/// Whether any value of `animators` has keyframes or data.
742pub(crate) fn animators_have_keyframes(animators: &[TextAnimator]) -> bool {
743    let mut keyed = false;
744    for_each_keyed_animator(animators, "", &mut |_, _| keyed = true);
745    keyed
746}
747
748/// Calls `visit` with each keyed value of `animators` under `at`, for the lint's keyframe
749/// walk.
750pub(crate) fn for_each_keyed_animator(
751    animators: &[TextAnimator],
752    at: &str,
753    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
754) {
755    use crate::animation::visit_keyed;
756    for (index, animator) in animators.iter().enumerate() {
757        let at = format!("{at}[{index}]");
758        if let TextSelector::Range {
759            start,
760            end,
761            offset,
762            amount,
763            ..
764        } = &animator.selector
765        {
766            visit_keyed(&format!("{at}.selector.start"), start, visit);
767            visit_keyed(&format!("{at}.selector.end"), end, visit);
768            visit_keyed(&format!("{at}.selector.offset"), offset, visit);
769            visit_keyed(&format!("{at}.selector.amount"), amount, visit);
770        }
771        let properties = &animator.properties;
772        let at = format!("{at}.properties");
773        if let Some(value) = &properties.offset {
774            visit_keyed(&format!("{at}.offset"), value, visit);
775        }
776        if let Some(value) = &properties.scale {
777            visit_keyed(&format!("{at}.scale"), value, visit);
778        }
779        if let Some(value) = &properties.rotation_degrees {
780            visit_keyed(&format!("{at}.rotation_degrees"), value, visit);
781        }
782        if let Some(value) = &properties.opacity {
783            visit_keyed(&format!("{at}.opacity"), value, visit);
784        }
785        if let Some(value) = &properties.fill {
786            visit_keyed(&format!("{at}.fill"), value, visit);
787        }
788        if let Some(value) = &properties.stroke {
789            visit_keyed(&format!("{at}.stroke"), value, visit);
790        }
791        if let Some(value) = &properties.tracking {
792            visit_keyed(&format!("{at}.tracking"), value, visit);
793        }
794        if let Some(reveal) = &properties.reveal {
795            visit_keyed(&format!("{at}.reveal.progress"), &reveal.progress, visit);
796            visit_keyed(
797                &format!("{at}.reveal.angle_degrees"),
798                &reveal.angle_degrees,
799                visit,
800            );
801            visit_keyed(&format!("{at}.reveal.feather"), &reveal.feather, visit);
802        }
803    }
804}