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(
336 String,
338 ),
339}
340
341impl BlockEllipsis {
342 #[must_use]
344 pub fn text(&self) -> Option<&str> {
345 match self {
346 Self::NoEllipsis => None,
347 Self::Ellipsis => Some("\u{2026}"),
348 Self::String(text) => Some(text),
349 }
350 }
351
352 fn is_valid(&self) -> bool {
353 match self {
354 Self::String(text) => {
355 !text.is_empty()
356 && text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
357 && !text.chars().any(|character| {
358 character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
359 })
360 }
361 Self::NoEllipsis | Self::Ellipsis => true,
362 }
363 }
364}
365
366#[derive(
368 Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
369)]
370#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
371#[serde(rename_all = "snake_case")]
372pub enum FontStyle {
373 #[default]
375 Normal,
376 Italic,
378 Oblique,
380}
381
382impl FontStyle {
383 #[must_use]
385 pub const fn is_normal(&self) -> bool {
386 matches!(self, Self::Normal)
387 }
388}
389
390#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
392#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
393#[serde(rename_all = "snake_case")]
394pub enum TextAlign {
395 Start,
397 #[default]
399 Center,
400 End,
402}
403
404#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
406#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
407#[serde(deny_unknown_fields)]
408pub struct TextStroke {
409 pub color: Rgba,
411 pub width: f32,
414}
415
416#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
418#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
419#[serde(deny_unknown_fields)]
420pub struct TextShadow {
421 pub color: Rgba,
423 #[serde(default)]
426 pub offset: Vec2,
427 #[serde(default)]
430 pub blur: f32,
431}
432
433#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
436#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
437#[serde(deny_unknown_fields)]
438pub struct TextBackground {
439 pub color: Rgba,
441 #[serde(default)]
444 pub padding: TextInsets,
445 #[serde(default, skip_serializing_if = "is_zero")]
448 pub radius: f32,
449 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub border: Option<TextBoxBorder>,
452 #[serde(default, skip_serializing_if = "is_default")]
454 pub extent: TextBoxExtent,
455}
456
457#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
460#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
461#[serde(rename_all = "snake_case")]
462pub enum TextBoxExtent {
463 #[default]
465 Line,
466 Revealed,
470 Block,
472}
473
474#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
478#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
479#[serde(deny_unknown_fields)]
480pub struct TextHighlight {
481 pub color: Rgba,
483 #[serde(default)]
485 pub padding: TextInsets,
486 #[serde(default, skip_serializing_if = "is_zero")]
488 pub radius: f32,
489 #[serde(default, skip_serializing_if = "Option::is_none")]
491 pub border: Option<TextBoxBorder>,
492 #[serde(default, skip_serializing_if = "is_default")]
495 pub transition: MediaTime,
496 #[serde(default = "linear", skip_serializing_if = "is_linear")]
498 pub easing: crate::Easing,
499 #[serde(default, skip_serializing_if = "is_default")]
501 pub gap: HighlightGap,
502}
503
504#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
506#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
507#[serde(rename_all = "snake_case")]
508pub enum HighlightGap {
509 #[default]
511 Hold,
512 Hide,
515}
516
517pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
519 MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);
520
521const fn linear() -> crate::Easing {
522 crate::Easing::Linear
523}
524
525fn is_linear(easing: &crate::Easing) -> bool {
526 matches!(easing, crate::Easing::Linear)
527}
528
529impl TextHighlight {
530 pub(crate) fn is_valid(&self) -> bool {
531 self.color.is_valid()
532 && self.padding.is_valid()
533 && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
534 && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
535 && self.transition >= MediaTime::ZERO
536 && self.transition <= MAX_HIGHLIGHT_TRANSITION
537 && self.easing.is_valid()
538 }
539}
540
541impl TextBackground {
542 #[must_use]
544 pub const fn padded(color: Rgba, padding: f32) -> Self {
545 Self {
546 color,
547 padding: TextInsets::all(padding),
548 radius: 0.0,
549 border: None,
550 extent: TextBoxExtent::Line,
551 }
552 }
553
554 pub(crate) fn is_valid(&self) -> bool {
555 self.color.is_valid()
556 && self.padding.is_valid()
557 && (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
558 && self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
559 }
560}
561
562#[expect(
563 clippy::trivially_copy_pass_by_ref,
564 reason = "serde's skip_serializing_if passes a reference"
565)]
566fn is_zero(value: &f32) -> bool {
567 *value == 0.0
568}
569
570#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
572#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
573#[serde(deny_unknown_fields)]
574pub struct TextBoxBorder {
575 pub width: f32,
577 pub color: Rgba,
579 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub dash: Option<TextDash>,
582}
583
584impl TextBoxBorder {
585 fn is_valid(&self) -> bool {
586 self.width.is_finite()
587 && self.width > 0.0
588 && self.width <= MAX_TEXT_BORDER_WIDTH
589 && self.color.is_valid()
590 && self.dash.as_ref().is_none_or(TextDash::is_valid)
591 }
592}
593
594#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
597#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
598#[serde(deny_unknown_fields)]
599pub struct TextDash {
600 #[serde(deserialize_with = "dash_pattern")]
604 #[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
605 pub pattern: Vec<f32>,
606 #[serde(default, skip_serializing_if = "is_zero")]
608 pub offset: f32,
609}
610
611fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
612 let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
613 if pattern.is_empty() {
614 return Err(serde::de::Error::invalid_length(
615 0,
616 &"one to sixteen entries",
617 ));
618 }
619 Ok(pattern)
620}
621
622impl TextDash {
623 fn is_valid(&self) -> bool {
624 !self.pattern.is_empty()
625 && self.pattern.len() <= crate::MAX_DASH_ENTRIES
626 && self
627 .pattern
628 .iter()
629 .all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
630 && self.pattern.iter().any(|entry| *entry > 0.0)
631 && (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
632 }
633}
634
635#[derive(Copy, Clone, Debug, Default, PartialEq)]
640pub struct TextInsets {
641 pub top: f32,
643 pub right: f32,
645 pub bottom: f32,
647 pub left: f32,
649}
650
651impl TextInsets {
652 #[must_use]
654 pub const fn all(value: f32) -> Self {
655 Self {
656 top: value,
657 right: value,
658 bottom: value,
659 left: value,
660 }
661 }
662
663 #[must_use]
665 pub const fn sides(self) -> [f32; 4] {
666 [self.top, self.right, self.bottom, self.left]
667 }
668
669 fn is_valid(self) -> bool {
670 self.sides()
671 .iter()
672 .all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
673 }
674
675 fn from_shorthand(values: &[f32]) -> Option<Self> {
676 let [top, right, bottom, left] = match *values {
677 [all] => [all; 4],
678 [vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
679 [top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
680 [top, right, bottom, left] => [top, right, bottom, left],
681 _ => return None,
682 };
683 Some(Self {
684 top,
685 right,
686 bottom,
687 left,
688 })
689 }
690}
691
692impl<'de> Deserialize<'de> for TextInsets {
693 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
694 #[derive(Deserialize)]
695 #[serde(untagged)]
696 enum Written {
697 Number(f32),
698 Shorthand(String),
699 Sides(std::collections::BTreeMap<String, f32>),
700 }
701 match Written::deserialize(deserializer)? {
702 Written::Number(value) => Ok(Self::all(value)),
703 Written::Shorthand(text) => text
704 .split(' ')
705 .filter(|token| !token.is_empty())
706 .map(str::parse::<f32>)
707 .collect::<Result<Vec<_>, _>>()
708 .ok()
709 .and_then(|values| Self::from_shorthand(&values))
710 .ok_or_else(|| {
711 serde::de::Error::custom(format!(
712 "text insets: expected one to four numbers, got {text:?}"
713 ))
714 }),
715 Written::Sides(sides) => {
716 let mut insets = Self::default();
717 for (side, value) in sides {
718 *match side.as_str() {
719 "top" => &mut insets.top,
720 "right" => &mut insets.right,
721 "bottom" => &mut insets.bottom,
722 "left" => &mut insets.left,
723 _ => {
724 return Err(serde::de::Error::unknown_field(
725 &side,
726 &["top", "right", "bottom", "left"],
727 ));
728 }
729 } = value;
730 }
731 Ok(insets)
732 }
733 }
734 }
735}
736
737impl Serialize for TextInsets {
739 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
740 use serde::ser::SerializeStruct;
741 let [top, right, bottom, left] = self.sides().map(f32::to_bits);
742 if top == right && top == bottom && top == left {
743 return serializer.serialize_f32(self.top);
744 }
745 let mut sides = serializer.serialize_struct("TextInsets", 4)?;
746 sides.serialize_field("top", &self.top)?;
747 sides.serialize_field("right", &self.right)?;
748 sides.serialize_field("bottom", &self.bottom)?;
749 sides.serialize_field("left", &self.left)?;
750 sides.end()
751 }
752}
753
754#[cfg(feature = "schema")]
755impl schemars::JsonSchema for TextInsets {
756 fn schema_name() -> std::borrow::Cow<'static, str> {
757 "TextInsets".into()
758 }
759
760 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
761 let number = r"-?(\d+\.?\d*|\.\d+)";
762 let side = |name: &str| {
763 schemars::json_schema!({
764 "description": format!("The {name} side, as a fraction of the font size."),
765 "type": "number",
766 "format": "float",
767 })
768 };
769 schemars::json_schema!({
770 "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.",
771 "anyOf": [
772 { "type": "number", "format": "float" },
773 { "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
774 {
775 "type": "object",
776 "properties": {
777 "top": side("top"),
778 "right": side("right"),
779 "bottom": side("bottom"),
780 "left": side("left"),
781 },
782 "additionalProperties": false,
783 },
784 ],
785 })
786 }
787}
788
789impl TextStyle {
790 pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
792 let finite =
793 |value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
794 self.font_family
795 .as_ref()
796 .is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
797 && self.font_size > 0.0
798 && self.font_size <= max_font_size
799 && self.fill.is_valid()
800 && LINE_HEIGHT_RANGE.contains(&self.line_height)
801 && LETTER_SPACING_RANGE.contains(&self.letter_spacing)
802 && FONT_WEIGHT_RANGE.contains(&self.font_weight)
803 && self.max_width > 0.0
804 && self.max_width <= 1.0
805 && self
806 .max_height
807 .is_none_or(|height| height > 0.0 && height <= 1.0)
808 && self
809 .font_size_fit
810 .is_none_or(|fit| fit.is_valid(max_font_size))
811 && self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
812 && finite(self.position)
813 && finite(self.anchor)
814 && valid_strokes(&self.strokes)
815 && valid_shadows(&self.shadows)
816 && crate::text_animation::valid_animators(&self.animators, false)
817 && valid_animator_pivot(self.animator_pivot)
818 && self
819 .background
820 .as_ref()
821 .is_none_or(TextBackground::is_valid)
822 && self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
823 }
824}
825
826pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
829 strokes.len() <= MAX_TEXT_STROKES
830 && strokes
831 .iter()
832 .all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
833 && strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
834}
835
836pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
838 let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
839 shadows.len() <= MAX_TEXT_SHADOWS
840 && shadows.iter().all(|shadow| {
841 shadow.color.is_valid()
842 && offset(shadow.offset.x)
843 && offset(shadow.offset.y)
844 && (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
845 })
846}