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//! Runs never change layout; the joined text is shaped and broken into lines like the plain
5//! string. An 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, Rgba, 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
40/// A text: one string, or runs whose texts joined are the text.
41///
42/// Written as `"Hello"` or `[{ "text": "Hel" }, { "text": "lo", "class": ["key"] }]`.
43#[derive(Clone, Debug, PartialEq, Serialize)]
44#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
45#[serde(untagged)]
46pub enum TextContent {
47    /// One string; `\n` starts a line.
48    Plain(String),
49    /// Runs in order; their texts joined are the text.
50    Runs(#[cfg_attr(feature = "schema", schemars(length(max = MAX_TEXT_RUNS)))] Vec<TextRun>),
51}
52
53// Read by the JSON type rather than as an untagged enum, which would buffer the whole value and
54// hide why runs were refused.
55impl<'de> Deserialize<'de> for TextContent {
56    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
57        struct Content;
58
59        impl<'de> serde::de::Visitor<'de> for Content {
60            type Value = TextContent;
61
62            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63                formatter.write_str("a string or a sequence of runs")
64            }
65
66            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<TextContent, E> {
67                Ok(TextContent::Plain(text.to_owned()))
68            }
69
70            fn visit_string<E: serde::de::Error>(self, text: String) -> Result<TextContent, E> {
71                Ok(TextContent::Plain(text))
72            }
73
74            fn visit_seq<A: serde::de::SeqAccess<'de>>(
75                self,
76                seq: A,
77            ) -> Result<TextContent, A::Error> {
78                crate::bounded::seq::<_, _, MAX_TEXT_RUNS>(
79                    serde::de::value::SeqAccessDeserializer::new(seq),
80                )
81                .map(TextContent::Runs)
82            }
83        }
84
85        deserializer.deserialize_any(Content)
86    }
87}
88
89impl Default for TextContent {
90    fn default() -> Self {
91        Self::Plain(String::new())
92    }
93}
94
95impl From<String> for TextContent {
96    fn from(text: String) -> Self {
97        Self::Plain(text)
98    }
99}
100
101impl From<&str> for TextContent {
102    fn from(text: &str) -> Self {
103        Self::Plain(text.to_owned())
104    }
105}
106
107/// Compares the whole text, runs joined, with a string.
108impl PartialEq<str> for TextContent {
109    fn eq(&self, other: &str) -> bool {
110        self.text() == other
111    }
112}
113
114impl PartialEq<&str> for TextContent {
115    fn eq(&self, other: &&str) -> bool {
116        self.text() == *other
117    }
118}
119
120impl TextContent {
121    /// The whole text: the string, or the runs' texts joined.
122    #[must_use]
123    pub fn text(&self) -> Cow<'_, str> {
124        match self {
125            Self::Plain(text) => Cow::Borrowed(text),
126            Self::Runs(runs) => Cow::Owned(runs.iter().map(|run| run.text.as_str()).collect()),
127        }
128    }
129
130    /// The runs, none for a plain string.
131    #[must_use]
132    pub fn runs(&self) -> &[TextRun] {
133        match self {
134            Self::Plain(_) => &[],
135            Self::Runs(runs) => runs,
136        }
137    }
138
139    /// Bytes of the whole text.
140    #[must_use]
141    pub fn len(&self) -> usize {
142        match self {
143            Self::Plain(text) => text.len(),
144            Self::Runs(runs) => runs.iter().map(|run| run.text.len()).sum(),
145        }
146    }
147
148    /// Whether the whole text is empty.
149    #[must_use]
150    pub fn is_empty(&self) -> bool {
151        self.len() == 0
152    }
153
154    /// Whether the text is non-empty and within `max_bytes`, has at most [`MAX_TEXT_RUNS`] runs,
155    /// and every run has non-empty text, at most [`MAX_RUN_CLASSES`] valid class names, and a
156    /// time span that starts at or after zero and before it ends.
157    pub(crate) fn is_valid(&self, max_bytes: usize) -> bool {
158        !self.is_empty()
159            && self.len() <= max_bytes
160            && self.runs().len() <= MAX_TEXT_RUNS
161            && self.runs().iter().all(TextRun::is_valid)
162    }
163}
164
165/// A piece of a text that animators' Class and Timing selectors can pick.
166#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
168#[serde(deny_unknown_fields)]
169pub struct TextRun {
170    /// Non-empty; `\n` starts a line. A grapheme cluster spanning two runs belongs to the run
171    /// holding its first byte.
172    pub text: String,
173    /// Names Class selectors match, each 1 to 64 bytes of `A-Z`, `a-z`, `0-9`, `_` and `-`; at
174    /// most [`MAX_RUN_CLASSES`].
175    #[serde(default, skip_serializing_if = "Vec::is_empty")]
176    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_RUN_CLASSES }>")]
177    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_RUN_CLASSES)))]
178    pub class: Vec<String>,
179    /// When the run is said, from the holder's start (a caption cue's start, or a text
180    /// generator's picture time zero).
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub time: Option<RunTime>,
183}
184
185impl TextRun {
186    fn is_valid(&self) -> bool {
187        !self.text.is_empty()
188            && self.class.len() <= MAX_RUN_CLASSES
189            && self.class.iter().all(|name| valid_class_name(name))
190            && self
191                .time
192                .is_none_or(|time| time.start.ticks() >= 0 && time.start < time.end)
193    }
194}
195
196/// Whether `name` is a class name a run or a Class selector may carry.
197#[must_use]
198pub fn valid_class_name(name: &str) -> bool {
199    !name.is_empty()
200        && name.len() <= MAX_CLASS_NAME_BYTES
201        && name
202            .bytes()
203            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
204}
205
206/// A run's time span.
207#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
208#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
209#[serde(deny_unknown_fields)]
210pub struct RunTime {
211    /// When it starts.
212    pub start: MediaTime,
213    /// When it ends; after `start`.
214    pub end: MediaTime,
215}
216
217/// One animator: what it selects, and what it does to what it selects.
218#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
220#[serde(deny_unknown_fields)]
221pub struct TextAnimator {
222    /// Gives each character its selection, in `[0, 1]`.
223    pub selector: TextSelector,
224    /// Applied to each character in proportion to its selection.
225    #[serde(default)]
226    pub properties: TextAnimatorProperties,
227}
228
229/// How an animator selects characters.
230#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
231#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
232#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
233pub enum TextSelector {
234    /// A range over the text's units, shaped at its ends, like After Effects' range selector.
235    Range {
236        /// What the range counts: characters (the default), non-space characters, words, or lines.
237        #[serde(default)]
238        based_on: TextUnit,
239        /// Whether start, end and offset are percents of the units (the default) or unit indices.
240        #[serde(default)]
241        units: RangeUnits,
242        /// Where the range starts: `[-100, 200]` percent, or `[-N, 2N]` units for `N` of
243        /// [`MAX_RANGE_INDEX`]. Default 0.
244        #[serde(default = "zero")]
245        start: Animated<f32>,
246        /// Where it ends, in the same range. Default 100.
247        #[serde(default = "hundred")]
248        end: Animated<f32>,
249        /// Added to start and end, in the same range. Default 0.
250        #[serde(default = "zero")]
251        offset: Animated<f32>,
252        /// How selection rises and falls across the range.
253        #[serde(default)]
254        shape: RangeShape,
255        /// The selection's scale, in `[0, 1]`. Default 1.
256        #[serde(default = "one")]
257        amount: Animated<f32>,
258    },
259    /// Characters of timed runs, by the run's time against the current time.
260    Timing {
261        /// Which runs it selects: those not yet said, being said, or said.
262        state: RunState,
263        /// How long the state takes to fade in and out; zero switches.
264        #[serde(default)]
265        ramp: MediaTime,
266        /// Splits each run's span over its characters in order, sweeping the run character by
267        /// character.
268        #[serde(default)]
269        sweep: bool,
270    },
271    /// Characters of runs that carry a class.
272    Class {
273        /// The class name.
274        class: String,
275    },
276}
277
278const fn zero() -> Animated<f32> {
279    Animated::Constant { value: 0.0 }
280}
281
282const fn hundred() -> Animated<f32> {
283    Animated::Constant { value: 100.0 }
284}
285
286const fn one() -> Animated<f32> {
287    Animated::Constant { value: 1.0 }
288}
289
290/// The units a Range selector counts.
291#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
292#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
293#[serde(rename_all = "snake_case")]
294pub enum TextUnit {
295    /// Grapheme clusters, spaces included.
296    #[default]
297    Characters,
298    /// Grapheme clusters that are not white space.
299    CharactersExcludingSpaces,
300    /// UAX #29 words that hold a letter or digit; a CJK ideograph is a word.
301    Words,
302    /// Laid-out lines.
303    Lines,
304}
305
306/// What a Range selector's start, end and offset count in.
307#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
308#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
309#[serde(rename_all = "snake_case")]
310pub enum RangeUnits {
311    /// Percents of the units.
312    #[default]
313    Percent,
314    /// Unit indices.
315    Index,
316}
317
318/// How selection rises and falls across a Range selector's range.
319#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
320#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
321#[serde(rename_all = "snake_case")]
322pub enum RangeShape {
323    /// Fully selected inside the range, partly at fractional ends.
324    #[default]
325    Square,
326    /// Rising from the start to the end.
327    RampUp,
328    /// Falling from the start to the end.
329    RampDown,
330    /// Rising to the middle, falling after it.
331    Triangle,
332    /// A half circle over the range.
333    Round,
334    /// The triangle eased by smoothstep.
335    Smooth,
336}
337
338/// Which runs a Timing selector selects.
339#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
340#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
341#[serde(rename_all = "snake_case")]
342pub enum RunState {
343    /// Runs whose time has not started.
344    Upcoming,
345    /// Runs whose time holds the current time.
346    Active,
347    /// Runs whose time has ended.
348    Spoken,
349}
350
351/// What an animator does to each character, in proportion to its selection. A property left
352/// out does nothing.
353#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
354#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
355#[serde(deny_unknown_fields)]
356pub struct TextAnimatorProperties {
357    /// Moves the character, in font sizes, +y down.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub offset: Option<Animated<Vec2>>,
360    /// Scales the character about its centre; 1 is none. Each axis in `[0, 10]`. The scales of
361    /// several animators multiply, and the product is at most 10 on each axis.
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub scale: Option<Animated<Vec2>>,
364    /// Turns the character about its centre, clockwise degrees.
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub rotation_degrees: Option<Animated<f32>>,
367    /// The opacity a fully selected character takes, in `[0, 1]`.
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub opacity: Option<Animated<f32>>,
370    /// The fill color a fully selected character takes; a gradient fill is mixed toward it.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub fill: Option<Animated<Rgba>>,
373    /// The color every stroke of a fully selected character takes.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub stroke: Option<Animated<Rgba>>,
376    /// Space added after the character, in font sizes, in `[-0.5, 1]`, as letter spacing adds
377    /// it. Lines are not re-broken.
378    #[serde(default, skip_serializing_if = "Option::is_none")]
379    pub tracking: Option<Animated<f32>>,
380}
381
382impl TextAnimatorProperties {
383    /// Whether no property is set: the animator does nothing.
384    #[must_use]
385    pub const fn is_empty(&self) -> bool {
386        self.offset.is_none()
387            && self.scale.is_none()
388            && self.rotation_degrees.is_none()
389            && self.opacity.is_none()
390            && self.fill.is_none()
391            && self.stroke.is_none()
392            && self.tracking.is_none()
393    }
394
395    fn is_valid(&self) -> bool {
396        let vec2 = |animation: &Animated<Vec2>, check: &dyn Fn(f32) -> bool| match animation {
397            Animated::Constant { value } => check(value.x) && check(value.y),
398            Animated::Keyframes { keyframes } => {
399                valid_keyframes(keyframes)
400                    && keyframes
401                        .iter()
402                        .all(|keyframe| check(keyframe.value.x) && check(keyframe.value.y))
403            }
404            Animated::Data(_) => true,
405        };
406        let color = |animation: &Animated<Rgba>| match animation {
407            Animated::Constant { value } => value.is_valid(),
408            Animated::Keyframes { keyframes } => {
409                valid_keyframes(keyframes) && keyframes.iter().all(|key| key.value.is_valid())
410            }
411            Animated::Data(_) => false,
412        };
413        self.offset
414            .as_ref()
415            .is_none_or(|offset| vec2(offset, &|value| value.abs() <= MAX_ANIMATOR_OFFSET))
416            && self.scale.as_ref().is_none_or(|scale| {
417                vec2(scale, &|value| {
418                    value.is_finite() && ANIMATOR_SCALE_RANGE.contains(&value)
419                })
420            })
421            && self
422                .rotation_degrees
423                .as_ref()
424                .is_none_or(|rotation| valid_scalar_values(rotation, |_| true))
425            && self.opacity.as_ref().is_none_or(|opacity| {
426                valid_scalar_values(opacity, |value| (0.0..=1.0).contains(&value))
427            })
428            && self.fill.as_ref().is_none_or(color)
429            && self.stroke.as_ref().is_none_or(color)
430            && self.tracking.as_ref().is_none_or(|tracking| {
431                valid_scalar_values(tracking, |value| {
432                    crate::LETTER_SPACING_RANGE.contains(&value)
433                })
434            })
435    }
436}
437
438impl TextSelector {
439    fn is_valid(&self) -> bool {
440        match self {
441            Self::Range {
442                units,
443                start,
444                end,
445                offset,
446                amount,
447                ..
448            } => {
449                let range = match units {
450                    RangeUnits::Percent => RANGE_PERCENT,
451                    RangeUnits::Index => -MAX_RANGE_INDEX..=2.0 * MAX_RANGE_INDEX,
452                };
453                [start, end, offset]
454                    .into_iter()
455                    .all(|value| valid_scalar_values(value, |value| range.contains(&value)))
456                    && valid_scalar_values(amount, |value| (0.0..=1.0).contains(&value))
457            }
458            Self::Timing { ramp, .. } => ramp.ticks() >= 0,
459            Self::Class { class } => valid_class_name(class),
460        }
461    }
462}
463
464/// Whether `animators` are at most [`MAX_TEXT_ANIMATORS`] valid animators, using only Range
465/// selectors when `range_only`.
466pub(crate) fn valid_animators(animators: &[TextAnimator], range_only: bool) -> bool {
467    animators.len() <= MAX_TEXT_ANIMATORS
468        && animators.iter().all(|animator| {
469            animator.selector.is_valid()
470                && animator.properties.is_valid()
471                && (!range_only || matches!(animator.selector, TextSelector::Range { .. }))
472        })
473}
474
475/// Whether any value of `animators` has keyframes or data.
476pub(crate) fn animators_have_keyframes(animators: &[TextAnimator]) -> bool {
477    let mut keyed = false;
478    for_each_keyed_animator(animators, "", &mut |_, _| keyed = true);
479    keyed
480}
481
482/// Calls `visit` with each keyed value of `animators` under `at`, for the lint's keyframe
483/// walk.
484pub(crate) fn for_each_keyed_animator(
485    animators: &[TextAnimator],
486    at: &str,
487    visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
488) {
489    use crate::animation::visit_keyed;
490    for (index, animator) in animators.iter().enumerate() {
491        let at = format!("{at}[{index}]");
492        if let TextSelector::Range {
493            start,
494            end,
495            offset,
496            amount,
497            ..
498        } = &animator.selector
499        {
500            visit_keyed(&format!("{at}.selector.start"), start, visit);
501            visit_keyed(&format!("{at}.selector.end"), end, visit);
502            visit_keyed(&format!("{at}.selector.offset"), offset, visit);
503            visit_keyed(&format!("{at}.selector.amount"), amount, visit);
504        }
505        let properties = &animator.properties;
506        let at = format!("{at}.properties");
507        if let Some(value) = &properties.offset {
508            visit_keyed(&format!("{at}.offset"), value, visit);
509        }
510        if let Some(value) = &properties.scale {
511            visit_keyed(&format!("{at}.scale"), value, visit);
512        }
513        if let Some(value) = &properties.rotation_degrees {
514            visit_keyed(&format!("{at}.rotation_degrees"), value, visit);
515        }
516        if let Some(value) = &properties.opacity {
517            visit_keyed(&format!("{at}.opacity"), value, visit);
518        }
519        if let Some(value) = &properties.fill {
520            visit_keyed(&format!("{at}.fill"), value, visit);
521        }
522        if let Some(value) = &properties.stroke {
523            visit_keyed(&format!("{at}.stroke"), value, visit);
524        }
525        if let Some(value) = &properties.tracking {
526            visit_keyed(&format!("{at}.tracking"), value, visit);
527        }
528    }
529}