1use crate::{
4 GeneratorIssue, LayoutNode, MAX_TEXT_CONTENT_BYTES, MAX_TEXT_GENERATOR_FONT_SIZE, ShapeItem,
5 TextStyle, Vec2,
6};
7use serde::{Deserialize, Serialize};
8
9pub const MAX_GRADIENT_STOPS: usize = 8;
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}
152
153#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
159#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
160#[cfg_attr(
161 feature = "schema",
162 schemars(rename = "Paint", transform = crate::schema::with_color_form)
163)]
164#[serde(
165 remote = "Self",
166 tag = "type",
167 rename_all = "snake_case",
168 deny_unknown_fields
169)]
170pub enum Paint {
171 Solid {
173 color: Rgba,
175 },
176 LinearGradient {
178 start: Vec2,
180 end: Vec2,
182 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
184 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
185 stops: Vec<GradientStop>,
186 #[serde(default)]
188 spread: Spread,
189 },
190 RadialGradient {
192 center: Vec2,
194 radius: f32,
197 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
199 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
200 stops: Vec<GradientStop>,
201 #[serde(default)]
203 spread: Spread,
204 },
205 ConicGradient {
207 center: Vec2,
209 #[serde(default)]
211 angle_degrees: f32,
212 #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_GRADIENT_STOPS }>")]
214 #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_GRADIENT_STOPS)))]
215 stops: Vec<GradientStop>,
216 },
217}
218
219impl<'de> Deserialize<'de> for Paint {
220 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
221 use serde::de::Error as _;
222 let value = serde_json::Value::deserialize(deserializer)?;
224 if value.get("type").is_some() {
225 Self::deserialize(value).map_err(D::Error::custom)
226 } else {
227 <Rgba as Deserialize>::deserialize(value)
228 .map(|color| Self::Solid { color })
229 .map_err(D::Error::custom)
230 }
231 }
232}
233
234impl Serialize for Paint {
235 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
236 Self::serialize(self, serializer)
237 }
238}
239
240#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
242#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
243#[serde(deny_unknown_fields)]
244pub struct GradientStop {
245 pub offset: f32,
247 pub color: Rgba,
249}
250
251#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
253#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
254#[serde(rename_all = "snake_case")]
255pub enum Spread {
256 #[default]
258 Pad,
259 Repeat,
261 Reflect,
263}
264
265impl Generator {
266 #[must_use]
268 pub fn is_valid(&self) -> bool {
269 self.validate().is_ok()
270 }
271
272 pub fn validate(&self) -> Result<(), GeneratorIssue> {
279 self.validate_canvas(None)
280 }
281
282 pub fn validate_on(&self, width: u32, height: u32) -> Result<(), GeneratorIssue> {
288 self.validate_canvas(Some((width, height)))
289 }
290
291 fn validate_canvas(&self, canvas: Option<(u32, u32)>) -> Result<(), GeneratorIssue> {
292 let valid = match self {
293 Self::Fill { paint } => paint.is_valid(),
294 Self::Shapes { items } => {
295 return crate::shapes::validate_shape_items(items).map_err(GeneratorIssue::Shape);
296 }
297 Self::Layout { root } => return crate::layout::validate_layout(root, canvas),
298 Self::Text { text, style } => {
299 text.is_valid(MAX_TEXT_CONTENT_BYTES)
300 && style.is_valid(MAX_TEXT_GENERATOR_FONT_SIZE)
301 }
302 };
303 valid.then_some(()).ok_or(GeneratorIssue::Invalid)
304 }
305}
306
307impl Paint {
308 pub(crate) fn is_valid(&self) -> bool {
309 match self {
310 Self::Solid { color } => color.is_valid(),
311 Self::LinearGradient {
312 start, end, stops, ..
313 } => finite(*start) && finite(*end) && start != end && valid_stops(stops),
314 Self::RadialGradient {
315 center,
316 radius,
317 stops,
318 ..
319 } => finite(*center) && radius.is_finite() && *radius > 0.0 && valid_stops(stops),
320 Self::ConicGradient {
321 center,
322 angle_degrees,
323 stops,
324 } => finite(*center) && angle_degrees.is_finite() && valid_stops(stops),
325 }
326 }
327}
328
329fn finite(value: Vec2) -> bool {
330 value.x.is_finite() && value.y.is_finite()
331}
332
333fn valid_stops(stops: &[GradientStop]) -> bool {
334 (2..=MAX_GRADIENT_STOPS).contains(&stops.len())
335 && stops
336 .iter()
337 .all(|stop| (0.0..=1.0).contains(&stop.offset) && stop.color.is_valid())
338 && stops
339 .windows(2)
340 .all(|pair| pair[0].offset <= pair[1].offset)
341}