1use crate::{Paint, Rgba, TextAnimator, Vec2};
4use alpha2_time::MediaTime;
5use serde::{Deserialize, Serialize};
6
7pub const MAX_TEXT_CONTENT_BYTES: usize = 4_096;
9
10pub const MAX_FONT_FAMILY_BYTES: usize = 256;
12
13pub const MAX_TEXT_GENERATOR_FONT_SIZE: f32 = 1.0;
15
16pub const LINE_HEIGHT_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;
18
19pub const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;
21
22pub const FONT_WEIGHT_RANGE: std::ops::RangeInclusive<u16> = 1..=1000;
24
25pub const MAX_TEXT_STROKES: usize = 8;
27
28pub const MAX_TEXT_STROKE_EXTENT: f32 = 0.5;
31
32pub const MAX_TEXT_FONT_SELECTIONS: usize = 16;
35
36pub const FONT_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.1..=10.0;
38
39pub const MAX_TEXT_SHADOWS: usize = 4;
41
42pub const MAX_TEXT_SHADOW_OFFSET: f32 = 1.0;
44
45pub const MAX_TEXT_SHADOW_BLUR: f32 = 1.0;
47
48pub const MAX_TEXT_PADDING: f32 = 2.0;
50
51pub const MAX_TEXT_BORDER_WIDTH: f32 = 0.5;
53
54pub const MAX_TEXT_DASH_ENTRY: f32 = 4.0;
56
57pub const MAX_TEXT_DASH_OFFSET: f32 = 16.0;
59pub const MAX_TEXT_POSITION: f32 = 1_024.0;
61
62pub const MAX_BLOCK_ELLIPSIS_BYTES: usize = 64;
64
65pub const FONT_SIZE_FIT_STEPS: f32 = 8_192.0;
68
69#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
79#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
80#[serde(deny_unknown_fields)]
81pub struct TextStyle {
82 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub font_family: Option<String>,
88 #[serde(default = "default_font_size")]
92 pub font_size: f32,
93 #[serde(default = "white_paint")]
97 pub fill: Paint,
98 #[serde(default = "default_line_height")]
101 pub line_height: f32,
102 #[serde(default)]
106 pub letter_spacing: f32,
107 #[serde(default = "default_font_weight")]
111 pub font_weight: u16,
112 #[serde(default, skip_serializing_if = "FontStyle::is_normal")]
116 pub font_style: FontStyle,
117 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119 pub underline: bool,
120 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
123 pub line_through: bool,
124 #[serde(default)]
126 pub align: TextAlign,
127 #[serde(default = "default_max_width")]
129 pub max_width: f32,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub max_height: Option<f32>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub font_size_fit: Option<FontSizeFit>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub line_clamp: Option<LineClamp>,
142 #[serde(default = "default_position")]
145 pub position: Vec2,
146 #[serde(default = "default_anchor")]
149 pub anchor: Vec2,
150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
153 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
154 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
155 pub strokes: Vec<TextStroke>,
156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
159 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
160 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
161 pub shadows: Vec<TextShadow>,
162 #[serde(default)]
164 pub background: Option<TextBackground>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub highlight: Option<TextHighlight>,
168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
173 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
174 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
175 pub animators: Vec<TextAnimator>,
176 #[serde(default, skip_serializing_if = "is_default")]
178 pub animator_grouping: crate::AnimatorGrouping,
179 #[serde(
184 default = "default_animator_pivot",
185 skip_serializing_if = "is_default_animator_pivot"
186 )]
187 pub animator_pivot: Vec2,
188}
189
190fn is_default<T: Default + PartialEq>(value: &T) -> bool {
191 *value == T::default()
192}
193
194pub(crate) const fn default_animator_pivot() -> Vec2 {
196 Vec2::new(0.5, 0.5)
197}
198
199#[allow(
200 clippy::trivially_copy_pass_by_ref,
201 reason = "serde passes a reference; the lint fires only where a pointer is as wide as a Vec2"
202)]
203pub(crate) fn is_default_animator_pivot(pivot: &Vec2) -> bool {
204 *pivot == default_animator_pivot()
205}
206
207pub(crate) fn valid_animator_pivot(pivot: Vec2) -> bool {
209 (0.0..=1.0).contains(&pivot.x) && (0.0..=1.0).contains(&pivot.y)
210}
211
212impl Default for TextStyle {
213 fn default() -> Self {
214 Self {
215 font_family: None,
216 font_size: default_font_size(),
217 fill: white_paint(),
218 line_height: default_line_height(),
219 letter_spacing: 0.0,
220 font_weight: default_font_weight(),
221 font_style: FontStyle::Normal,
222 underline: false,
223 line_through: false,
224 align: TextAlign::default(),
225 max_width: default_max_width(),
226 max_height: None,
227 font_size_fit: None,
228 line_clamp: None,
229 position: default_position(),
230 anchor: default_anchor(),
231 strokes: Vec::new(),
232 shadows: Vec::new(),
233 background: None,
234 highlight: None,
235 animators: Vec::new(),
236 animator_grouping: crate::AnimatorGrouping::Character,
237 animator_pivot: default_animator_pivot(),
238 }
239 }
240}
241
242const fn default_font_size() -> f32 {
243 0.05
244}
245
246const fn white_paint() -> Paint {
247 Paint::Solid {
248 color: Rgba::new(1.0, 1.0, 1.0, 1.0),
249 }
250}
251
252const fn default_line_height() -> f32 {
253 1.2
254}
255
256const fn default_font_weight() -> u16 {
257 400
258}
259
260const fn default_max_width() -> f32 {
261 0.9
262}
263
264const fn default_position() -> Vec2 {
265 Vec2::new(0.5, 0.92)
266}
267
268const fn default_anchor() -> Vec2 {
269 Vec2::new(0.5, 1.0)
270}
271
272#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
279#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
280#[serde(deny_unknown_fields)]
281pub struct FontSizeFit {
282 pub min: f32,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub max: Option<f32>,
288}
289
290impl FontSizeFit {
291 pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
293 let size = |value: f32| value.is_finite() && value > 0.0 && value <= max_font_size;
294 size(self.min) && self.max.is_none_or(|max| size(max) && self.min <= max)
295 }
296}
297
298#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
306#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
307#[serde(deny_unknown_fields)]
308pub struct LineClamp {
309 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub max_lines: Option<u32>,
312 #[serde(default)]
314 pub block_ellipsis: BlockEllipsis,
315}
316
317impl LineClamp {
318 pub(crate) fn is_valid(&self) -> bool {
319 self.max_lines != Some(0) && self.block_ellipsis.is_valid()
320 }
321}
322
323#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
325#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
326#[serde(rename_all = "snake_case")]
327pub enum BlockEllipsis {
328 NoEllipsis,
330 #[default]
332 Ellipsis,
333 String(String),
336}
337
338impl BlockEllipsis {
339 #[must_use]
341 pub fn text(&self) -> Option<&str> {
342 match self {
343 Self::NoEllipsis => None,
344 Self::Ellipsis => Some("\u{2026}"),
345 Self::String(text) => Some(text),
346 }
347 }
348
349 fn is_valid(&self) -> bool {
350 match self {
351 Self::String(text) => {
352 !text.is_empty()
353 && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
354 && !text.chars().any(|character| {
355 character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
356 })
357 }
358 Self::NoEllipsis | Self::Ellipsis => true,
359 }
360 }
361}
362
363#[derive(
365 Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
366)]
367#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
368#[serde(rename_all = "snake_case")]
369pub enum FontStyle {
370 #[default]
372 Normal,
373 Italic,
375 Oblique,
377}
378
379impl FontStyle {
380 #[must_use]
382 pub const fn is_normal(&self) -> bool {
383 matches!(self, Self::Normal)
384 }
385}
386
387#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
389#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
390#[serde(rename_all = "snake_case")]
391pub enum TextAlign {
392 Start,
394 #[default]
396 Center,
397 End,
399}
400
401#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
403#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
404#[serde(deny_unknown_fields)]
405pub struct TextStroke {
406 pub color: Rgba,
408 pub width: f32,
411}
412
413#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
415#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
416#[serde(deny_unknown_fields)]
417pub struct TextShadow {
418 pub color: Rgba,
420 #[serde(default)]
423 pub offset: Vec2,
424 #[serde(default)]
427 pub blur: f32,
428}
429
430#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
433#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
434#[serde(deny_unknown_fields)]
435pub struct TextBackground {
436 pub color: Rgba,
438 #[serde(default)]
441 pub padding: TextInsets,
442 #[serde(default, skip_serializing_if = "is_zero")]
445 pub radius: f32,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub border: Option<TextBoxBorder>,
449 #[serde(default, skip_serializing_if = "is_default")]
451 pub extent: TextBoxExtent,
452}
453
454#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
457#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
458#[serde(rename_all = "snake_case")]
459pub enum TextBoxExtent {
460 #[default]
462 Line,
463 Revealed,
467 Block,
469}
470
471#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
475#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
476#[serde(deny_unknown_fields)]
477pub struct TextHighlight {
478 pub color: Rgba,
480 #[serde(default)]
482 pub padding: TextInsets,
483 #[serde(default, skip_serializing_if = "is_zero")]
485 pub radius: f32,
486 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub border: Option<TextBoxBorder>,
489 #[serde(default, skip_serializing_if = "is_default")]
492 pub transition: MediaTime,
493 #[serde(default = "linear", skip_serializing_if = "is_linear")]
495 pub easing: crate::Easing,
496 #[serde(default, skip_serializing_if = "is_default")]
498 pub gap: HighlightGap,
499}
500
501#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
503#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
504#[serde(rename_all = "snake_case")]
505pub enum HighlightGap {
506 #[default]
508 Hold,
509 Hide,
512}
513
514pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
516 MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);
517
518const fn linear() -> crate::Easing {
519 crate::Easing::Linear
520}
521
522fn is_linear(easing: &crate::Easing) -> bool {
523 matches!(easing, crate::Easing::Linear)
524}
525
526impl TextHighlight {
527 pub(crate) fn is_valid(&self) -> bool {
528 self.color.is_valid()
529 && self.padding.is_valid()
530 && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
531 && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
532 && self.transition >= MediaTime::ZERO
533 && self.transition <= MAX_HIGHLIGHT_TRANSITION
534 && self.easing.is_valid()
535 }
536}
537
538impl TextBackground {
539 #[must_use]
541 pub const fn padded(color: Rgba, padding: f32) -> Self {
542 Self {
543 color,
544 padding: TextInsets::all(padding),
545 radius: 0.0,
546 border: None,
547 extent: TextBoxExtent::Line,
548 }
549 }
550
551 pub(crate) fn is_valid(&self) -> bool {
552 self.color.is_valid()
553 && self.padding.is_valid()
554 && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
555 && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
556 }
557}
558
559#[expect(
560 clippy::trivially_copy_pass_by_ref,
561 reason = "serde's skip_serializing_if passes a reference"
562)]
563fn is_zero(value: &f32) -> bool {
564 *value == 0.0
565}
566
567#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
569#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
570#[serde(deny_unknown_fields)]
571pub struct TextBoxBorder {
572 pub width: f32,
574 pub color: Rgba,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
578 pub dash: Option<TextDash>,
579}
580
581impl TextBoxBorder {
582 fn is_valid(&self) -> bool {
583 self.width.is_finite()
584 && self.width > 0.0
585 && self.width <= MAX_TEXT_BORDER_WIDTH
586 && self.color.is_valid()
587 && self.dash.as_ref().is_none_or(TextDash::is_valid)
588 }
589}
590
591#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
594#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
595#[serde(deny_unknown_fields)]
596pub struct TextDash {
597 #[serde(deserialize_with = "dash_pattern")]
601 #[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
602 pub pattern: Vec<f32>,
603 #[serde(default, skip_serializing_if = "is_zero")]
605 pub offset: f32,
606}
607
608fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
609 let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
610 if pattern.is_empty() {
611 return Err(serde::de::Error::invalid_length(
612 0,
613 &"one to sixteen entries",
614 ));
615 }
616 Ok(pattern)
617}
618
619impl TextDash {
620 fn is_valid(&self) -> bool {
621 !self.pattern.is_empty()
622 && self.pattern.len() <= crate::MAX_DASH_ENTRIES
623 && self
624 .pattern
625 .iter()
626 .all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
627 && self.pattern.iter().any(|entry| *entry > 0.0)
628 && (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
629 }
630}
631
632#[derive(Copy, Clone, Debug, Default, PartialEq)]
637pub struct TextInsets {
638 pub top: f32,
640 pub right: f32,
642 pub bottom: f32,
644 pub left: f32,
646}
647
648impl TextInsets {
649 #[must_use]
651 pub const fn all(value: f32) -> Self {
652 Self {
653 top: value,
654 right: value,
655 bottom: value,
656 left: value,
657 }
658 }
659
660 #[must_use]
662 pub const fn sides(self) -> [f32; 4] {
663 [self.top, self.right, self.bottom, self.left]
664 }
665
666 fn is_valid(self) -> bool {
667 self.sides()
668 .iter()
669 .all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
670 }
671
672 fn from_shorthand(values: &[f32]) -> Option<Self> {
673 let [top, right, bottom, left] = match *values {
674 [all] => [all; 4],
675 [vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
676 [top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
677 [top, right, bottom, left] => [top, right, bottom, left],
678 _ => return None,
679 };
680 Some(Self {
681 top,
682 right,
683 bottom,
684 left,
685 })
686 }
687}
688
689impl<'de> Deserialize<'de> for TextInsets {
690 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
691 #[derive(Deserialize)]
692 #[serde(untagged)]
693 enum Written {
694 Number(f32),
695 Shorthand(String),
696 Sides(std::collections::BTreeMap<String, f32>),
697 }
698 match Written::deserialize(deserializer)? {
699 Written::Number(value) => Ok(Self::all(value)),
700 Written::Shorthand(text) => text
701 .split(' ')
702 .filter(|token| !token.is_empty())
703 .map(str::parse::<f32>)
704 .collect::<Result<Vec<_>, _>>()
705 .ok()
706 .and_then(|values| Self::from_shorthand(&values))
707 .ok_or_else(|| {
708 serde::de::Error::custom(format!(
709 "text insets: expected one to four numbers, got {text:?}"
710 ))
711 }),
712 Written::Sides(sides) => {
713 let mut insets = Self::default();
714 for (side, value) in sides {
715 *match side.as_str() {
716 "top" => &mut insets.top,
717 "right" => &mut insets.right,
718 "bottom" => &mut insets.bottom,
719 "left" => &mut insets.left,
720 _ => {
721 return Err(serde::de::Error::unknown_field(
722 &side,
723 &["top", "right", "bottom", "left"],
724 ));
725 }
726 } = value;
727 }
728 Ok(insets)
729 }
730 }
731 }
732}
733
734impl Serialize for TextInsets {
736 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
737 use serde::ser::SerializeStruct;
738 let [top, right, bottom, left] = self.sides().map(f32::to_bits);
739 if top == right && top == bottom && top == left {
740 return serializer.serialize_f32(self.top);
741 }
742 let mut sides = serializer.serialize_struct("TextInsets", 4)?;
743 sides.serialize_field("top", &self.top)?;
744 sides.serialize_field("right", &self.right)?;
745 sides.serialize_field("bottom", &self.bottom)?;
746 sides.serialize_field("left", &self.left)?;
747 sides.end()
748 }
749}
750
751#[cfg(feature = "schema")]
752impl schemars::JsonSchema for TextInsets {
753 fn schema_name() -> std::borrow::Cow<'static, str> {
754 "TextInsets".into()
755 }
756
757 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
758 let number = r"-?(\d+\.?\d*|\.\d+)";
759 let side = schemars::json_schema!({ "type": "number", "format": "float" });
760 schemars::json_schema!({
761 "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.",
762 "anyOf": [
763 { "type": "number", "format": "float" },
764 { "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
765 {
766 "type": "object",
767 "properties": { "top": side, "right": side, "bottom": side, "left": side },
768 "additionalProperties": false,
769 },
770 ],
771 })
772 }
773}
774
775impl TextStyle {
776 pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
778 let finite =
779 |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
780 self.font_family
781 .as_ref()
782 .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
783 && self.font_size > 0.0
784 && self.font_size <= max_font_size
785 && self.fill.is_valid()
786 && LINE_HEIGHT_RANGE.contains(&self.line_height)
787 && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
788 && FONT_WEIGHT_RANGE.contains(&self.font_weight)
789 && self.max_width > 0.0
790 && self.max_width <= 1.0
791 && self
792 .max_height
793 .is_none_or(|height| height > 0.0 && height <= 1.0)
794 && self
795 .font_size_fit
796 .is_none_or(|fit| fit.is_valid(max_font_size))
797 && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
798 && finite(self.position)
799 && finite(self.anchor)
800 && valid_strokes(&self.strokes)
801 && valid_shadows(&self.shadows)
802 && crate::text_animation::valid_animators(&self.animators, false)
803 && valid_animator_pivot(self.animator_pivot)
804 && self
805 .background
806 .as_ref()
807 .is_none_or(TextBackground::is_valid)
808 && self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
809 }
810}
811
812pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
815 strokes.len() <= MAX_TEXT_STROKES
816 && strokes
817 .iter()
818 .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
819 && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
820}
821
822pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
824 let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
825 shadows.len() <= MAX_TEXT_SHADOWS
826 && shadows.iter().all(|shadow| {
827 shadow.color.is_valid()
828 && offset(shadow.offset.x)
829 && offset(shadow.offset.y)
830 && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
831 })
832}