use crate::{Paint, Rgba, TextAnimator, Vec2};
use alpha2_time::MediaTime;
use serde::{Deserialize, Serialize};
pub const MAX_TEXT_CONTENT_BYTES: usize = 4_096;
pub const MAX_FONT_FAMILY_BYTES: usize = 256;
pub const MAX_TEXT_GENERATOR_FONT_SIZE: f32 = 1.0;
pub const LINE_HEIGHT_RANGE: std::ops::RangeInclusive<f32> = 0.5..=3.0;
pub const LETTER_SPACING_RANGE: std::ops::RangeInclusive<f32> = -0.5..=1.0;
pub const FONT_WEIGHT_RANGE: std::ops::RangeInclusive<u16> = 1..=1000;
pub const MAX_TEXT_STROKES: usize = 8;
pub const MAX_TEXT_STROKE_EXTENT: f32 = 0.5;
pub const MAX_TEXT_FONT_SELECTIONS: usize = 16;
pub const FONT_SCALE_RANGE: std::ops::RangeInclusive<f32> = 0.1..=10.0;
pub const MAX_TEXT_SHADOWS: usize = 4;
pub const MAX_TEXT_SHADOW_OFFSET: f32 = 1.0;
pub const MAX_TEXT_SHADOW_BLUR: f32 = 1.0;
pub const MAX_TEXT_PADDING: f32 = 2.0;
pub const MAX_TEXT_BORDER_WIDTH: f32 = 0.5;
pub const MAX_TEXT_DASH_ENTRY: f32 = 4.0;
pub const MAX_TEXT_DASH_OFFSET: f32 = 16.0;
pub const MAX_TEXT_POSITION: f32 = 1_024.0;
pub const MAX_BLOCK_ELLIPSIS_BYTES: usize = 64;
pub const FONT_SIZE_FIT_STEPS: f32 = 8_192.0;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextStyle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font_family: Option<String>,
#[serde(default = "default_font_size")]
pub font_size: f32,
#[serde(default = "white_paint")]
pub fill: Paint,
#[serde(default = "default_line_height")]
pub line_height: f32,
#[serde(default)]
pub letter_spacing: f32,
#[serde(default = "default_font_weight")]
pub font_weight: u16,
#[serde(default, skip_serializing_if = "FontStyle::is_normal")]
pub font_style: FontStyle,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub underline: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub line_through: bool,
#[serde(default)]
pub align: TextAlign,
#[serde(default = "default_max_width")]
pub max_width: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_height: Option<f32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font_size_fit: Option<FontSizeFit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub line_clamp: Option<LineClamp>,
#[serde(default = "default_position")]
pub position: Vec2,
#[serde(default = "default_anchor")]
pub anchor: Vec2,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
pub strokes: Vec<TextStroke>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
pub shadows: Vec<TextShadow>,
#[serde(default)]
pub background: Option<TextBackground>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub highlight: Option<TextHighlight>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
pub animators: Vec<TextAnimator>,
#[serde(default, skip_serializing_if = "is_default")]
pub animator_grouping: crate::AnimatorGrouping,
#[serde(
default = "default_animator_pivot",
skip_serializing_if = "is_default_animator_pivot"
)]
pub animator_pivot: Vec2,
}
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}
pub(crate) const fn default_animator_pivot() -> Vec2 {
Vec2::new(0.5, 0.5)
}
#[allow(
clippy::trivially_copy_pass_by_ref,
reason = "serde passes a reference; the lint fires only where a pointer is as wide as a Vec2"
)]
pub(crate) fn is_default_animator_pivot(pivot: &Vec2) -> bool {
*pivot == default_animator_pivot()
}
pub(crate) fn valid_animator_pivot(pivot: Vec2) -> bool {
(0.0..=1.0).contains(&pivot.x) && (0.0..=1.0).contains(&pivot.y)
}
impl Default for TextStyle {
fn default() -> Self {
Self {
font_family: None,
font_size: default_font_size(),
fill: white_paint(),
line_height: default_line_height(),
letter_spacing: 0.0,
font_weight: default_font_weight(),
font_style: FontStyle::Normal,
underline: false,
line_through: false,
align: TextAlign::default(),
max_width: default_max_width(),
max_height: None,
font_size_fit: None,
line_clamp: None,
position: default_position(),
anchor: default_anchor(),
strokes: Vec::new(),
shadows: Vec::new(),
background: None,
highlight: None,
animators: Vec::new(),
animator_grouping: crate::AnimatorGrouping::Character,
animator_pivot: default_animator_pivot(),
}
}
}
const fn default_font_size() -> f32 {
0.05
}
const fn white_paint() -> Paint {
Paint::Solid {
color: Rgba::new(1.0, 1.0, 1.0, 1.0),
}
}
const fn default_line_height() -> f32 {
1.2
}
const fn default_font_weight() -> u16 {
400
}
const fn default_max_width() -> f32 {
0.9
}
const fn default_position() -> Vec2 {
Vec2::new(0.5, 0.92)
}
const fn default_anchor() -> Vec2 {
Vec2::new(0.5, 1.0)
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct FontSizeFit {
pub min: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<f32>,
}
impl FontSizeFit {
pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
let size = |value: f32| value.is_finite() && value > 0.0 && value <= max_font_size;
size(self.min) && self.max.is_none_or(|max| size(max) && self.min <= max)
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LineClamp {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_lines: Option<u32>,
#[serde(default)]
pub block_ellipsis: BlockEllipsis,
}
impl LineClamp {
pub(crate) fn is_valid(&self) -> bool {
self.max_lines != Some(0) && self.block_ellipsis.is_valid()
}
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum BlockEllipsis {
NoEllipsis,
#[default]
Ellipsis,
String(
String,
),
}
impl BlockEllipsis {
#[must_use]
pub fn text(&self) -> Option<&str> {
match self {
Self::NoEllipsis => None,
Self::Ellipsis => Some("\u{2026}"),
Self::String(text) => Some(text),
}
}
fn is_valid(&self) -> bool {
match self {
Self::String(text) => {
!text.is_empty()
&& text.len() <= MAX_BLOCK_ELLIPSIS_BYTES
&& !text.chars().any(|character| {
character.is_control() || matches!(character, '\u{2028}' | '\u{2029}')
})
}
Self::NoEllipsis | Self::Ellipsis => true,
}
}
}
#[derive(
Copy, Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FontStyle {
#[default]
Normal,
Italic,
Oblique,
}
impl FontStyle {
#[must_use]
pub const fn is_normal(&self) -> bool {
matches!(self, Self::Normal)
}
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TextAlign {
Start,
#[default]
Center,
End,
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextStroke {
pub color: Rgba,
pub width: f32,
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextShadow {
pub color: Rgba,
#[serde(default)]
pub offset: Vec2,
#[serde(default)]
pub blur: f32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextBackground {
pub color: Rgba,
#[serde(default)]
pub padding: TextInsets,
#[serde(default, skip_serializing_if = "is_zero")]
pub radius: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub border: Option<TextBoxBorder>,
#[serde(default, skip_serializing_if = "is_default")]
pub extent: TextBoxExtent,
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TextBoxExtent {
#[default]
Line,
Revealed,
Block,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextHighlight {
pub color: Rgba,
#[serde(default)]
pub padding: TextInsets,
#[serde(default, skip_serializing_if = "is_zero")]
pub radius: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub border: Option<TextBoxBorder>,
#[serde(default, skip_serializing_if = "is_default")]
pub transition: MediaTime,
#[serde(default = "linear", skip_serializing_if = "is_linear")]
pub easing: crate::Easing,
#[serde(default, skip_serializing_if = "is_default")]
pub gap: HighlightGap,
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum HighlightGap {
#[default]
Hold,
Hide,
}
pub const MAX_HIGHLIGHT_TRANSITION: MediaTime =
MediaTime::from_ticks(10 * alpha2_time::TICKS_PER_SECOND);
const fn linear() -> crate::Easing {
crate::Easing::Linear
}
fn is_linear(easing: &crate::Easing) -> bool {
matches!(easing, crate::Easing::Linear)
}
impl TextHighlight {
pub(crate) fn is_valid(&self) -> bool {
self.color.is_valid()
&& self.padding.is_valid()
&& (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
&& self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
&& self.transition >= MediaTime::ZERO
&& self.transition <= MAX_HIGHLIGHT_TRANSITION
&& self.easing.is_valid()
}
}
impl TextBackground {
#[must_use]
pub const fn padded(color: Rgba, padding: f32) -> Self {
Self {
color,
padding: TextInsets::all(padding),
radius: 0.0,
border: None,
extent: TextBoxExtent::Line,
}
}
pub(crate) fn is_valid(&self) -> bool {
self.color.is_valid()
&& self.padding.is_valid()
&& (0.0..=MAX_TEXT_PADDING).contains(&self.radius)
&& self.border.as_ref().is_none_or(TextBoxBorder::is_valid)
}
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
fn is_zero(value: &f32) -> bool {
*value == 0.0
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextBoxBorder {
pub width: f32,
pub color: Rgba,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dash: Option<TextDash>,
}
impl TextBoxBorder {
fn is_valid(&self) -> bool {
self.width.is_finite()
&& self.width > 0.0
&& self.width <= MAX_TEXT_BORDER_WIDTH
&& self.color.is_valid()
&& self.dash.as_ref().is_none_or(TextDash::is_valid)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TextDash {
#[serde(deserialize_with = "dash_pattern")]
#[cfg_attr(feature = "schema", schemars(length(min = 1, max = crate::MAX_DASH_ENTRIES)))]
pub pattern: Vec<f32>,
#[serde(default, skip_serializing_if = "is_zero")]
pub offset: f32,
}
fn dash_pattern<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f32>, D::Error> {
let pattern = crate::bounded::seq::<_, _, { crate::MAX_DASH_ENTRIES }>(deserializer)?;
if pattern.is_empty() {
return Err(serde::de::Error::invalid_length(
0,
&"one to sixteen entries",
));
}
Ok(pattern)
}
impl TextDash {
fn is_valid(&self) -> bool {
!self.pattern.is_empty()
&& self.pattern.len() <= crate::MAX_DASH_ENTRIES
&& self
.pattern
.iter()
.all(|entry| (0.0..=MAX_TEXT_DASH_ENTRY).contains(entry))
&& self.pattern.iter().any(|entry| *entry > 0.0)
&& (-MAX_TEXT_DASH_OFFSET..=MAX_TEXT_DASH_OFFSET).contains(&self.offset)
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct TextInsets {
pub top: f32,
pub right: f32,
pub bottom: f32,
pub left: f32,
}
impl TextInsets {
#[must_use]
pub const fn all(value: f32) -> Self {
Self {
top: value,
right: value,
bottom: value,
left: value,
}
}
#[must_use]
pub const fn sides(self) -> [f32; 4] {
[self.top, self.right, self.bottom, self.left]
}
fn is_valid(self) -> bool {
self.sides()
.iter()
.all(|side| (0.0..=MAX_TEXT_PADDING).contains(side))
}
fn from_shorthand(values: &[f32]) -> Option<Self> {
let [top, right, bottom, left] = match *values {
[all] => [all; 4],
[vertical, horizontal] => [vertical, horizontal, vertical, horizontal],
[top, horizontal, bottom] => [top, horizontal, bottom, horizontal],
[top, right, bottom, left] => [top, right, bottom, left],
_ => return None,
};
Some(Self {
top,
right,
bottom,
left,
})
}
}
impl<'de> Deserialize<'de> for TextInsets {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(untagged)]
enum Written {
Number(f32),
Shorthand(String),
Sides(std::collections::BTreeMap<String, f32>),
}
match Written::deserialize(deserializer)? {
Written::Number(value) => Ok(Self::all(value)),
Written::Shorthand(text) => text
.split(' ')
.filter(|token| !token.is_empty())
.map(str::parse::<f32>)
.collect::<Result<Vec<_>, _>>()
.ok()
.and_then(|values| Self::from_shorthand(&values))
.ok_or_else(|| {
serde::de::Error::custom(format!(
"text insets: expected one to four numbers, got {text:?}"
))
}),
Written::Sides(sides) => {
let mut insets = Self::default();
for (side, value) in sides {
*match side.as_str() {
"top" => &mut insets.top,
"right" => &mut insets.right,
"bottom" => &mut insets.bottom,
"left" => &mut insets.left,
_ => {
return Err(serde::de::Error::unknown_field(
&side,
&["top", "right", "bottom", "left"],
));
}
} = value;
}
Ok(insets)
}
}
}
}
impl Serialize for TextInsets {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let [top, right, bottom, left] = self.sides().map(f32::to_bits);
if top == right && top == bottom && top == left {
return serializer.serialize_f32(self.top);
}
let mut sides = serializer.serialize_struct("TextInsets", 4)?;
sides.serialize_field("top", &self.top)?;
sides.serialize_field("right", &self.right)?;
sides.serialize_field("bottom", &self.bottom)?;
sides.serialize_field("left", &self.left)?;
sides.end()
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for TextInsets {
fn schema_name() -> std::borrow::Cow<'static, str> {
"TextInsets".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
let number = r"-?(\d+\.?\d*|\.\d+)";
let side = |name: &str| {
schemars::json_schema!({
"description": format!("The {name} side, as a fraction of the font size."),
"type": "number",
"format": "float",
})
};
schemars::json_schema!({
"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.",
"anyOf": [
{ "type": "number", "format": "float" },
{ "type": "string", "pattern": format!("^ *{number}( +{number}){{0,3}} *$") },
{
"type": "object",
"properties": {
"top": side("top"),
"right": side("right"),
"bottom": side("bottom"),
"left": side("left"),
},
"additionalProperties": false,
},
],
})
}
}
impl TextStyle {
pub(crate) fn is_valid(&self, max_font_size: f32) -> bool {
let finite =
|value: Vec2| value.x.abs() <= MAX_TEXT_POSITION && value.y.abs() <= MAX_TEXT_POSITION;
self.font_family
.as_ref()
.is_none_or(|family| !family.is_empty() && family.len() <= MAX_FONT_FAMILY_BYTES)
&& self.font_size > 0.0
&& self.font_size <= max_font_size
&& self.fill.is_valid()
&& LINE_HEIGHT_RANGE.contains(&self.line_height)
&& LETTER_SPACING_RANGE.contains(&self.letter_spacing)
&& FONT_WEIGHT_RANGE.contains(&self.font_weight)
&& self.max_width > 0.0
&& self.max_width <= 1.0
&& self
.max_height
.is_none_or(|height| height > 0.0 && height <= 1.0)
&& self
.font_size_fit
.is_none_or(|fit| fit.is_valid(max_font_size))
&& self.line_clamp.as_ref().is_none_or(LineClamp::is_valid)
&& finite(self.position)
&& finite(self.anchor)
&& valid_strokes(&self.strokes)
&& valid_shadows(&self.shadows)
&& crate::text_animation::valid_animators(&self.animators, false)
&& valid_animator_pivot(self.animator_pivot)
&& self
.background
.as_ref()
.is_none_or(TextBackground::is_valid)
&& self.highlight.as_ref().is_none_or(TextHighlight::is_valid)
}
}
pub(crate) fn valid_strokes(strokes: &[TextStroke]) -> bool {
strokes.len() <= MAX_TEXT_STROKES
&& strokes
.iter()
.all(|stroke| stroke.color.is_valid() && stroke.width.is_finite() && stroke.width > 0.0)
&& strokes.iter().map(|stroke| stroke.width).sum::<f32>() <= MAX_TEXT_STROKE_EXTENT
}
pub(crate) fn valid_shadows(shadows: &[TextShadow]) -> bool {
let offset = |value: f32| value.is_finite() && value.abs() <= MAX_TEXT_SHADOW_OFFSET;
shadows.len() <= MAX_TEXT_SHADOWS
&& shadows.iter().all(|shadow| {
shadow.color.is_valid()
&& offset(shadow.offset.x)
&& offset(shadow.offset.y)
&& (0.0..=MAX_TEXT_SHADOW_BLUR).contains(&shadow.blur)
})
}