1use 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
16pub const MAX_TEXT_RUNS: usize = 512;
18
19pub const MAX_RUN_CLASSES: usize = 8;
21
22pub const MAX_CLASS_NAME_BYTES: usize = 64;
24
25pub const MAX_TEXT_ANIMATORS: usize = 8;
27
28pub const MAX_RANGE_INDEX: f32 = 4_096.0;
31
32pub const RANGE_PERCENT: std::ops::RangeInclusive<f32> = -100.0..=200.0;
34
35pub const MAX_ANIMATOR_OFFSET: f32 = 1_024.0;
37pub const ANIMATOR_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.0..=10.0;
39
40#[derive(Clone, Debug, PartialEq, Serialize)]
44#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
45#[serde(untagged)]
46pub enum TextContent {
47 Plain(String),
49 Runs(#[cfg_attr(feature = "schema", schemars(length(max = MAX_TEXT_RUNS)))] Vec<TextRun>),
51}
52
53impl<'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
107impl 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 #[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 #[must_use]
132 pub fn runs(&self) -> &[TextRun] {
133 match self {
134 Self::Plain(_) => &[],
135 Self::Runs(runs) => runs,
136 }
137 }
138
139 #[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 #[must_use]
150 pub fn is_empty(&self) -> bool {
151 self.len() == 0
152 }
153
154 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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
168#[serde(deny_unknown_fields)]
169pub struct TextRun {
170 pub text: String,
173 #[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 #[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#[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#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
208#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
209#[serde(deny_unknown_fields)]
210pub struct RunTime {
211 pub start: MediaTime,
213 pub end: MediaTime,
215}
216
217#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
220#[serde(deny_unknown_fields)]
221pub struct TextAnimator {
222 pub selector: TextSelector,
224 #[serde(default)]
226 pub properties: TextAnimatorProperties,
227}
228
229#[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 Range {
236 #[serde(default)]
238 based_on: TextUnit,
239 #[serde(default)]
241 units: RangeUnits,
242 #[serde(default = "zero")]
245 start: Animated<f32>,
246 #[serde(default = "hundred")]
248 end: Animated<f32>,
249 #[serde(default = "zero")]
251 offset: Animated<f32>,
252 #[serde(default)]
254 shape: RangeShape,
255 #[serde(default = "one")]
257 amount: Animated<f32>,
258 },
259 Timing {
261 state: RunState,
263 #[serde(default)]
265 ramp: MediaTime,
266 #[serde(default)]
269 sweep: bool,
270 },
271 Class {
273 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#[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 #[default]
297 Characters,
298 CharactersExcludingSpaces,
300 Words,
302 Lines,
304}
305
306#[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 #[default]
313 Percent,
314 Index,
316}
317
318#[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 #[default]
325 Square,
326 RampUp,
328 RampDown,
330 Triangle,
332 Round,
334 Smooth,
336}
337
338#[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 Upcoming,
345 Active,
347 Spoken,
349}
350
351#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
354#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
355#[serde(deny_unknown_fields)]
356pub struct TextAnimatorProperties {
357 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub offset: Option<Animated<Vec2>>,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
363 pub scale: Option<Animated<Vec2>>,
364 #[serde(default, skip_serializing_if = "Option::is_none")]
366 pub rotation_degrees: Option<Animated<f32>>,
367 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub opacity: Option<Animated<f32>>,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub fill: Option<Animated<Rgba>>,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub stroke: Option<Animated<Rgba>>,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub tracking: Option<Animated<f32>>,
380}
381
382impl TextAnimatorProperties {
383 #[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
464pub(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
475pub(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
482pub(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}