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, FontStyle, Paint, Rgba, TextStroke, 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;
39pub const MAX_REVEAL_FEATHER: f32 = 1.0;
41
42#[derive(Clone, Debug, PartialEq, Serialize)]
46#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
47#[serde(untagged)]
48pub enum TextContent {
49 Plain(String),
51 Runs(#[cfg_attr(feature = "schema", schemars(length(max = MAX_TEXT_RUNS)))] Vec<TextRun>),
53}
54
55impl<'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
109impl 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 #[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 #[must_use]
134 pub fn runs(&self) -> &[TextRun] {
135 match self {
136 Self::Plain(_) => &[],
137 Self::Runs(runs) => runs,
138 }
139 }
140
141 #[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 #[must_use]
152 pub fn is_empty(&self) -> bool {
153 self.len() == 0
154 }
155
156 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 #[must_use]
168 pub fn has_run_styles(&self) -> bool {
169 self.runs().iter().any(|run| run.style.is_some())
170 }
171
172 #[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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
207#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
208#[serde(deny_unknown_fields)]
209pub struct TextRunStyle {
210 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub font_weight: Option<u16>,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub font_style: Option<FontStyle>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub font_scale: Option<Animated<f32>>,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub letter_spacing: Option<f32>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub fill: Option<Paint>,
236 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
244 pub background_color: Option<Rgba>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub underline: Option<bool>,
248 #[serde(default, skip_serializing_if = "Option::is_none")]
250 pub line_through: Option<bool>,
251}
252
253impl TextRunStyle {
254 #[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 #[must_use]
312 pub const fn is_static(&self) -> bool {
313 !matches!(
314 self.font_scale,
315 Some(Animated::Keyframes { .. } | 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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
358#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
359#[serde(deny_unknown_fields)]
360pub struct TextRun {
361 pub text: String,
364 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub time: Option<RunTime>,
374 #[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#[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#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
402#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
403#[serde(deny_unknown_fields)]
404pub struct RunTime {
405 pub start: MediaTime,
407 pub end: MediaTime,
409}
410
411#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
413#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
414#[serde(deny_unknown_fields)]
415pub struct TextAnimator {
416 pub selector: TextSelector,
418 #[serde(default)]
420 pub properties: TextAnimatorProperties,
421}
422
423#[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 Range {
430 #[serde(default)]
432 based_on: TextUnit,
433 #[serde(default)]
435 units: RangeUnits,
436 #[serde(default = "zero")]
439 start: Animated<f32>,
440 #[serde(default = "hundred")]
442 end: Animated<f32>,
443 #[serde(default = "zero")]
445 offset: Animated<f32>,
446 #[serde(default)]
448 shape: RangeShape,
449 #[serde(default = "one")]
451 amount: Animated<f32>,
452 },
453 Timing {
455 state: RunState,
457 #[serde(default)]
459 ramp: MediaTime,
460 #[serde(default)]
463 sweep: bool,
464 },
465 Class {
467 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#[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 #[default]
491 Characters,
492 CharactersExcludingSpaces,
494 Words,
496 Lines,
498}
499
500#[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 #[default]
507 Percent,
508 Index,
510}
511
512#[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 #[default]
519 Square,
520 RampUp,
522 RampDown,
524 Triangle,
526 Round,
528 Smooth,
530}
531
532#[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 Upcoming,
539 Active,
541 Spoken,
543}
544
545#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
548#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
549#[serde(deny_unknown_fields)]
550pub struct TextAnimatorProperties {
551 #[serde(default, skip_serializing_if = "Option::is_none")]
553 pub offset: Option<Animated<Vec2>>,
554 #[serde(default, skip_serializing_if = "Option::is_none")]
557 pub scale: Option<Animated<Vec2>>,
558 #[serde(default, skip_serializing_if = "Option::is_none")]
560 pub rotation_degrees: Option<Animated<f32>>,
561 #[serde(default, skip_serializing_if = "Option::is_none")]
563 pub opacity: Option<Animated<f32>>,
564 #[serde(default, skip_serializing_if = "Option::is_none")]
566 pub fill: Option<Animated<Rgba>>,
567 #[serde(default, skip_serializing_if = "Option::is_none")]
569 pub stroke: Option<Animated<Rgba>>,
570 #[serde(default, skip_serializing_if = "Option::is_none")]
573 pub tracking: Option<Animated<f32>>,
574 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
578 pub advance_follows_scale: bool,
579 #[serde(default, skip_serializing_if = "Option::is_none")]
583 pub reveal: Option<TextReveal>,
584}
585
586#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
589#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
590#[serde(deny_unknown_fields)]
591pub struct TextReveal {
592 #[serde(default = "zero")]
595 pub progress: Animated<f32>,
596 #[serde(default = "zero")]
599 pub angle_degrees: Animated<f32>,
600 #[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#[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 #[default]
624 Character,
625 Word,
627 Line,
629 All,
631}
632
633impl TextAnimatorProperties {
634 #[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 { keyframes } => {
651 valid_keyframes(keyframes)
652 && keyframes
653 .iter()
654 .all(|keyframe| check(keyframe.value.x) && check(keyframe.value.y))
655 }
656 Animated::Data(_) => true,
657 };
658 let color = |animation: &Animated<Rgba>| match animation {
659 Animated::Constant { value } => value.is_valid(),
660 Animated::Keyframes { keyframes } => {
661 valid_keyframes(keyframes) && keyframes.iter().all(|key| key.value.is_valid())
662 }
663 Animated::Data(_) => false,
664 };
665 self.offset
666 .as_ref()
667 .is_none_or(|offset| vec2(offset, &|value| value.abs() <= MAX_ANIMATOR_OFFSET))
668 && self.scale.as_ref().is_none_or(|scale| {
669 vec2(scale, &|value| {
670 value.is_finite() && ANIMATOR_SCALE_RANGE.contains(&value)
671 })
672 })
673 && self
674 .rotation_degrees
675 .as_ref()
676 .is_none_or(|rotation| valid_scalar_values(rotation, |_| true))
677 && self.opacity.as_ref().is_none_or(|opacity| {
678 valid_scalar_values(opacity, |value| (0.0..=1.0).contains(&value))
679 })
680 && self.fill.as_ref().is_none_or(color)
681 && self.stroke.as_ref().is_none_or(color)
682 && self.tracking.as_ref().is_none_or(|tracking| {
683 valid_scalar_values(tracking, |value| {
684 crate::LETTER_SPACING_RANGE.contains(&value)
685 })
686 })
687 && (!self.advance_follows_scale || self.scale.is_some())
688 && self.reveal.as_ref().is_none_or(TextReveal::is_valid)
689 }
690}
691
692impl TextSelector {
693 fn is_valid(&self) -> bool {
694 match self {
695 Self::Range {
696 units,
697 start,
698 end,
699 offset,
700 amount,
701 ..
702 } => {
703 let range = match units {
704 RangeUnits::Percent => RANGE_PERCENT,
705 RangeUnits::Index => -MAX_RANGE_INDEX..=2.0 * MAX_RANGE_INDEX,
706 };
707 [start, end, offset]
708 .into_iter()
709 .all(|value| valid_scalar_values(value, |value| range.contains(&value)))
710 && valid_scalar_values(amount, |value| (0.0..=1.0).contains(&value))
711 }
712 Self::Timing { ramp, .. } => ramp.ticks() >= 0,
713 Self::Class { class } => valid_class_name(class),
714 }
715 }
716}
717
718pub(crate) fn valid_animators(animators: &[TextAnimator], range_only: bool) -> bool {
721 animators.len() <= MAX_TEXT_ANIMATORS
722 && animators.iter().all(|animator| {
723 animator.selector.is_valid()
724 && animator.properties.is_valid()
725 && (!range_only || matches!(animator.selector, TextSelector::Range { .. }))
726 })
727}
728
729pub(crate) fn animators_have_keyframes(animators: &[TextAnimator]) -> bool {
731 let mut keyed = false;
732 for_each_keyed_animator(animators, "", &mut |_, _| keyed = true);
733 keyed
734}
735
736pub(crate) fn for_each_keyed_animator(
739 animators: &[TextAnimator],
740 at: &str,
741 visit: &mut impl FnMut(&str, crate::animation::Keyed<'_>),
742) {
743 use crate::animation::visit_keyed;
744 for (index, animator) in animators.iter().enumerate() {
745 let at = format!("{at}[{index}]");
746 if let TextSelector::Range {
747 start,
748 end,
749 offset,
750 amount,
751 ..
752 } = &animator.selector
753 {
754 visit_keyed(&format!("{at}.selector.start"), start, visit);
755 visit_keyed(&format!("{at}.selector.end"), end, visit);
756 visit_keyed(&format!("{at}.selector.offset"), offset, visit);
757 visit_keyed(&format!("{at}.selector.amount"), amount, visit);
758 }
759 let properties = &animator.properties;
760 let at = format!("{at}.properties");
761 if let Some(value) = &properties.offset {
762 visit_keyed(&format!("{at}.offset"), value, visit);
763 }
764 if let Some(value) = &properties.scale {
765 visit_keyed(&format!("{at}.scale"), value, visit);
766 }
767 if let Some(value) = &properties.rotation_degrees {
768 visit_keyed(&format!("{at}.rotation_degrees"), value, visit);
769 }
770 if let Some(value) = &properties.opacity {
771 visit_keyed(&format!("{at}.opacity"), value, visit);
772 }
773 if let Some(value) = &properties.fill {
774 visit_keyed(&format!("{at}.fill"), value, visit);
775 }
776 if let Some(value) = &properties.stroke {
777 visit_keyed(&format!("{at}.stroke"), value, visit);
778 }
779 if let Some(value) = &properties.tracking {
780 visit_keyed(&format!("{at}.tracking"), value, visit);
781 }
782 if let Some(reveal) = &properties.reveal {
783 visit_keyed(&format!("{at}.reveal.progress"), &reveal.progress, visit);
784 visit_keyed(
785 &format!("{at}.reveal.angle_degrees"),
786 &reveal.angle_degrees,
787 visit,
788 );
789 visit_keyed(&format!("{at}.reveal.feather"), &reveal.feather, visit);
790 }
791 }
792}