1use crate::{
4 ClipEffect, GeneratorIssue, LayoutNode, MAX_TEXT_CONTENT_BYTES, MAX_TEXT_GENERATOR_FONT_SIZE,
5 ShapeItem, TextStyle, Vec2,
6};
7use serde::{Deserialize, Serialize};
8
9pub const MAX_GRADIENT_STOPS: usize = 16;
11
12#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
17#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
18#[cfg_attr(
19 feature = "schema",
20 schemars(rename = "Rgba", transform = crate::schema::with_hex_form)
21)]
22#[serde(remote = "Self", deny_unknown_fields)]
23pub struct Rgba {
24 pub red: f32,
26 pub green: f32,
28 pub blue: f32,
30 pub alpha: f32,
32}
33
34impl Rgba {
35 #[must_use]
37 pub const fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
38 Self {
39 red,
40 green,
41 blue,
42 alpha,
43 }
44 }
45
46 pub(crate) fn is_valid(self) -> bool {
47 [self.red, self.green, self.blue, self.alpha]
48 .iter()
49 .all(|value| (0.0..=1.0).contains(value))
50 }
51
52 #[must_use]
54 pub fn from_hex(text: &str) -> Option<Self> {
55 let digits = text.strip_prefix('#')?.as_bytes();
56 let nibble = |index: usize| char::from(digits[index]).to_digit(16);
57 let component = |value: u32| u8::try_from(value).ok().map(|byte| f32::from(byte) / 255.0);
58 let channels = match digits.len() {
59 3 | 4 => (0..digits.len())
60 .map(|index| component(nibble(index)? * 17))
61 .collect::<Option<Vec<_>>>()?,
62 6 | 8 => (0..digits.len() / 2)
63 .map(|index| component(nibble(index * 2)? * 16 + nibble(index * 2 + 1)?))
64 .collect::<Option<Vec<_>>>()?,
65 _ => return None,
66 };
67 Some(Self::new(
68 channels[0],
69 channels[1],
70 channels[2],
71 channels.get(3).copied().unwrap_or(1.0),
72 ))
73 }
74}
75
76struct RgbaVisitor;
78
79impl<'de> serde::de::Visitor<'de> for RgbaVisitor {
80 type Value = Rgba;
81
82 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 formatter.write_str("a color: the {red, green, blue, alpha} object or a CSS hex string")
84 }
85
86 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Rgba, E> {
87 Rgba::from_hex(value).ok_or_else(|| {
88 E::custom(format!(
89 "invalid color \"{value}\": write #rgb, #rgba, #rrggbb, or #rrggbbaa"
90 ))
91 })
92 }
93
94 fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Rgba, A::Error> {
95 Rgba::deserialize(serde::de::value::MapAccessDeserializer::new(map))
96 }
97}
98
99impl<'de> Deserialize<'de> for Rgba {
100 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
101 deserializer.deserialize_any(RgbaVisitor)
102 }
103}
104
105impl Serialize for Rgba {
106 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
107 Self::serialize(self, serializer)
108 }
109}
110
111#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
118#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
119#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
120pub enum Generator {
121 Fill {
123 paint: Paint,
125 },
126 Shapes {
129 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_SHAPE_ITEMS }>")]
131 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_SHAPE_ITEMS)))]
132 items: Vec<ShapeItem>,
133 },
134 Text {
137 text: crate::TextContent,
140 #[serde(default)]
143 style: Box<TextStyle>,
144 },
145 Layout {
148 root: Box<LayoutNode>,
150 },
151 Effect {
154 effect: ClipEffect,
157 },
158}
159
160#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
166#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
167#[cfg_attr(
168 feature = "schema",
169 schemars(rename = "Paint", transform = crate::schema::with_color_form)
170)]
171#[serde(
172 remote = "Self",
173 tag = "type",
174 rename_all = "snake_case",
175 deny_unknown_fields
176)]
177pub enum Paint {
178 Solid {
180 color: Rgba,
182 },
183 LinearGradient {
185 start: Vec2,
187 end: Vec2,
189 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
191 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
192 stops: Vec<GradientStop>,
193 #[serde(default)]
195 spread: Spread,
196 },
197 RadialGradient {
199 center: Vec2,
201 radius: f32,
204 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
206 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
207 stops: Vec<GradientStop>,
208 #[serde(default)]
210 spread: Spread,
211 },
212 ConicGradient {
214 center: Vec2,
216 #[serde(default)]
218 angle_degrees: f32,
219 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
221 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
222 stops: Vec<GradientStop>,
223 },
224}
225
226impl<'de> Deserialize<'de> for Paint {
227 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
228 use serde::de::Error as _;
229 let value = serde_json::Value::deserialize(deserializer)?;
231 if value.get("type").is_some() {
232 Self::deserialize(value).map_err(D::Error::custom)
233 } else {
234 <Rgba as Deserialize>::deserialize(value)
235 .map(|color| Self::Solid { color })
236 .map_err(D::Error::custom)
237 }
238 }
239}
240
241impl Serialize for Paint {
242 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
243 Self::serialize(self, serializer)
244 }
245}
246
247#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
249#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
250#[serde(deny_unknown_fields)]
251pub struct GradientStop {
252 pub offset: f32,
254 pub color: Rgba,
256}
257
258#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
260#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
261#[serde(rename_all = "snake_case")]
262pub enum Spread {
263 #[default]
265 Pad,
266 Repeat,
268 Reflect,
270}
271
272impl Generator {
273 #[must_use]
275 pub fn is_valid(&self) -> bool {
276 self.validate().is_ok()
277 }
278
279 pub fn validate(&self) -> Result<(), GeneratorIssue> {
287 self.validate_canvas(None)
288 }
289
290 pub fn validate_on(&self, width: u32, height: u32) -> Result<(), GeneratorIssue> {
296 self.validate_canvas(Some((width, height)))
297 }
298
299 fn validate_canvas(&self, canvas: Option<(u32, u32)>) -> Result<(), GeneratorIssue> {
300 let valid = match self {
301 Self::Fill { paint } => paint.is_valid(),
302 Self::Shapes { items } => {
303 return crate::shapes::validate_shape_items(items).map_err(GeneratorIssue::Shape);
304 }
305 Self::Layout { root } => return crate::layout::validate_layout(root, canvas),
306 Self::Effect { effect } => {
307 if !effect.is_valid() {
308 return Err(GeneratorIssue::Invalid);
309 }
310 return crate::effect_spec::check_builtin(
311 effect,
312 crate::EffectKind::Generator,
313 None,
314 )
315 .map_err(|problem| GeneratorIssue::Effect {
316 id: effect.id.clone(),
317 problem,
318 });
319 }
320 Self::Text { text, style } => {
321 if !(text.is_valid(MAX_TEXT_CONTENT_BYTES)
322 && style.is_valid(MAX_TEXT_GENERATOR_FONT_SIZE))
323 {
324 return Err(GeneratorIssue::Invalid);
325 }
326 return match text.invalid_run_style(crate::text_animation::FontSelection::of(style))
327 {
328 Some(run) => Err(GeneratorIssue::TextRun { run }),
329 None => Ok(()),
330 };
331 }
332 };
333 valid.then_some(()).ok_or(GeneratorIssue::Invalid)
334 }
335}
336
337impl Paint {
338 pub(crate) fn is_valid(&self) -> bool {
339 match self {
340 Self::Solid { color } => color.is_valid(),
341 Self::LinearGradient {
342 start, end, stops, ..
343 } => finite(*start) && finite(*end) && start != end && valid_stops(stops),
344 Self::RadialGradient {
345 center,
346 radius,
347 stops,
348 ..
349 } => finite(*center) && radius.is_finite() && *radius > 0.0 && valid_stops(stops),
350 Self::ConicGradient {
351 center,
352 angle_degrees,
353 stops,
354 } => finite(*center) && angle_degrees.is_finite() && valid_stops(stops),
355 }
356 }
357}
358
359fn finite(value: Vec2) -> bool {
360 value.x.is_finite() && value.y.is_finite()
361}
362
363fn valid_stops(stops: &[GradientStop]) -> bool {
364 (2..=MAX_GRADIENT_STOPS).contains(&stops.len())
365 && stops
366 .iter()
367 .all(|stop| (0.0..=1.0).contains(&stop.offset) && stop.color.is_valid())
368 && stops
369 .windows(2)
370 .all(|pair| pair[0].offset <= pair[1].offset)
371}