1use crate::align::Anchors;
8use crate::color::Color;
9use crate::component::ComponentId;
10use crate::error::{Error, Result};
11use crate::geometry::Bounds;
12
13pub trait PropEnum: Sized + Copy + 'static {
15 const NAMES: &'static [&'static str];
17
18 fn from_index(index: usize) -> Option<Self>;
19 fn index(self) -> usize;
20
21 fn name(self) -> &'static str {
22 Self::NAMES[self.index()]
23 }
24
25 fn from_name(name: &str) -> Option<Self> {
27 Self::NAMES
28 .iter()
29 .position(|n| n.eq_ignore_ascii_case(name))
30 .and_then(Self::from_index)
31 }
32}
33
34#[derive(Clone, Copy, Debug, PartialEq)]
36pub enum PropKind {
37 Bool,
38 Int,
39 Float,
40 String,
41 Color,
42 Enum(&'static [&'static str]),
44 Set(&'static [&'static str]),
46 Bounds,
47 Component,
49 Event,
51 Angle,
53 Duration,
55 Shadow,
58 Easing,
61}
62
63#[doc(hidden)]
65pub const fn kind_or(default: PropKind, over: &[PropKind]) -> PropKind {
66 if let [k] = over { *k } else { default }
67}
68
69#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct PropInfo {
72 pub name: &'static str,
73 pub kind: PropKind,
74 pub category: &'static str,
76 pub read_only: bool,
77 pub runtime: bool,
81}
82
83impl PropInfo {
84 pub const fn new(name: &'static str, kind: PropKind, category: &'static str) -> Self {
85 Self { name, kind, category, read_only: false, runtime: false }
86 }
87
88 pub const fn read_only(mut self) -> Self {
89 self.read_only = true;
90 self
91 }
92
93 pub const fn runtime(mut self) -> Self {
94 self.runtime = true;
95 self
96 }
97}
98
99#[derive(Clone, Debug, Default, PartialEq)]
101pub enum PropValue {
102 #[default]
103 Null,
104 Bool(bool),
105 Int(i64),
106 Float(f64),
107 String(String),
108 Color(Color),
109 Enum(String),
110 Set(Vec<String>),
111 Bounds(Bounds),
112 Component(Option<ComponentId>),
113 Event(Option<String>),
114}
115
116impl PropValue {
117 pub fn kind_name(&self) -> &'static str {
118 match self {
119 PropValue::Null => "null",
120 PropValue::Bool(_) => "bool",
121 PropValue::Int(_) => "int",
122 PropValue::Float(_) => "float",
123 PropValue::String(_) => "string",
124 PropValue::Color(_) => "color",
125 PropValue::Enum(_) => "enum",
126 PropValue::Set(_) => "set",
127 PropValue::Bounds(_) => "bounds",
128 PropValue::Component(_) => "component",
129 PropValue::Event(_) => "event",
130 }
131 }
132
133 pub fn to_bool(&self) -> Result<bool> {
134 match self {
135 PropValue::Bool(b) => Ok(*b),
136 _ => Err(Error::type_mismatch("bool", self)),
137 }
138 }
139
140 pub fn to_i64(&self) -> Result<i64> {
141 match self {
142 PropValue::Int(v) => Ok(*v),
143 PropValue::Float(v) if v.fract() == 0.0 => Ok(*v as i64),
144 _ => Err(Error::type_mismatch("int", self)),
145 }
146 }
147
148 pub fn to_f64(&self) -> Result<f64> {
149 match self {
150 PropValue::Float(v) => Ok(*v),
151 PropValue::Int(v) => Ok(*v as f64),
152 _ => Err(Error::type_mismatch("float", self)),
153 }
154 }
155
156 pub fn to_f32(&self) -> Result<f32> {
157 self.to_f64().map(|v| v as f32)
158 }
159
160 pub fn to_str(&self) -> Result<&str> {
161 match self {
162 PropValue::String(s) | PropValue::Enum(s) => Ok(s),
163 _ => Err(Error::type_mismatch("string", self)),
164 }
165 }
166
167 pub fn to_color(&self) -> Result<Color> {
169 match self {
170 PropValue::Color(c) => Ok(*c),
171 PropValue::String(s) => s.parse(),
172 _ => Err(Error::type_mismatch("color", self)),
173 }
174 }
175
176 pub fn to_bounds(&self) -> Result<Bounds> {
181 match self {
182 PropValue::Bounds(b) => Ok(*b),
183 PropValue::Int(_) | PropValue::Float(_) => Ok(Bounds::all(self.to_f32()?)),
184 PropValue::String(s) => {
185 let numbers: Option<Vec<f32>> = s.split([',', ' ', ';']).filter(|p| !p.trim().is_empty()).map(|p| p.trim().parse::<f32>().ok()).collect();
186 match numbers.as_deref() {
187 Some([all]) => Ok(Bounds::all(*all)),
188 Some([h, v]) => Ok(Bounds::symmetric(*h, *v)),
189 Some([l, t, r, b]) => Ok(Bounds::new(*l, *t, *r, *b)),
190 _ => Err(Error::invalid(format!("margens inválidas '{s}'; use 1, 2 (h, v) ou 4 (esquerda, cima, direita, baixo) números"))),
191 }
192 }
193 _ => Err(Error::type_mismatch("bounds", self)),
194 }
195 }
196
197 pub fn to_enum<T: PropEnum>(&self) -> Result<T> {
199 let name = match self {
200 PropValue::Enum(s) | PropValue::String(s) => s,
201 _ => return Err(Error::type_mismatch("enum", self)),
202 };
203 T::from_name(name).ok_or_else(|| {
204 Error::invalid(format!("valor '{name}' inválido; use um de: {}", T::NAMES.join(", ")))
205 })
206 }
207
208 pub fn to_anchors(&self) -> Result<Anchors> {
210 let parsed = match self {
211 PropValue::Set(names) => Anchors::from_names(names),
212 PropValue::String(s) | PropValue::Enum(s) => {
213 Anchors::from_names(s.split(',').map(str::trim).filter(|p| !p.is_empty()))
214 }
215 _ => return Err(Error::type_mismatch("set", self)),
216 };
217 parsed.ok_or_else(|| {
218 Error::invalid(format!("âncoras inválidas; use: {}", Anchors::NAMES.join(", ")))
219 })
220 }
221
222 pub fn to_component(&self) -> Result<Option<ComponentId>> {
223 match self {
224 PropValue::Component(c) => Ok(*c),
225 PropValue::Null => Ok(None),
226 _ => Err(Error::type_mismatch("component", self)),
227 }
228 }
229
230 pub fn to_event(&self) -> Result<Option<String>> {
232 match self {
233 PropValue::Event(e) => Ok(e.clone()),
234 PropValue::String(s) => Ok((!s.is_empty()).then(|| s.clone())),
235 PropValue::Null => Ok(None),
236 _ => Err(Error::type_mismatch("event", self)),
237 }
238 }
239}
240
241impl From<bool> for PropValue {
242 fn from(v: bool) -> Self {
243 PropValue::Bool(v)
244 }
245}
246
247impl From<i32> for PropValue {
248 fn from(v: i32) -> Self {
249 PropValue::Int(v as i64)
250 }
251}
252
253impl From<i64> for PropValue {
254 fn from(v: i64) -> Self {
255 PropValue::Int(v)
256 }
257}
258
259impl From<u32> for PropValue {
260 fn from(v: u32) -> Self {
261 PropValue::Int(v as i64)
262 }
263}
264
265impl From<f32> for PropValue {
266 fn from(v: f32) -> Self {
267 PropValue::Float(v as f64)
268 }
269}
270
271impl From<f64> for PropValue {
272 fn from(v: f64) -> Self {
273 PropValue::Float(v)
274 }
275}
276
277impl From<&str> for PropValue {
278 fn from(v: &str) -> Self {
279 PropValue::String(v.to_string())
280 }
281}
282
283impl From<String> for PropValue {
284 fn from(v: String) -> Self {
285 PropValue::String(v)
286 }
287}
288
289impl From<Color> for PropValue {
290 fn from(v: Color) -> Self {
291 PropValue::Color(v)
292 }
293}
294
295impl From<Bounds> for PropValue {
296 fn from(v: Bounds) -> Self {
297 PropValue::Bounds(v)
298 }
299}
300
301impl From<Anchors> for PropValue {
302 fn from(v: Anchors) -> Self {
303 PropValue::Set(v.names())
304 }
305}
306
307impl From<ComponentId> for PropValue {
308 fn from(v: ComponentId) -> Self {
309 PropValue::Component(Some(v))
310 }
311}
312
313impl From<Option<ComponentId>> for PropValue {
314 fn from(v: Option<ComponentId>) -> Self {
315 PropValue::Component(v)
316 }
317}
318
319impl From<crate::align::Align> for PropValue {
320 fn from(v: crate::align::Align) -> Self {
321 PropValue::enum_value(v)
322 }
323}
324
325impl PropValue {
326 pub fn enum_value<T: PropEnum>(v: T) -> Self {
328 PropValue::Enum(v.name().to_string())
329 }
330}
331
332pub trait PropType: Sized {
334 const KIND: PropKind;
335 fn to_value(&self) -> PropValue;
336 fn from_value(value: PropValue) -> Result<Self>;
337}
338
339impl PropType for bool {
340 const KIND: PropKind = PropKind::Bool;
341 fn to_value(&self) -> PropValue {
342 PropValue::Bool(*self)
343 }
344 fn from_value(value: PropValue) -> Result<Self> {
345 value.to_bool()
346 }
347}
348
349impl PropType for i64 {
350 const KIND: PropKind = PropKind::Int;
351 fn to_value(&self) -> PropValue {
352 PropValue::Int(*self)
353 }
354 fn from_value(value: PropValue) -> Result<Self> {
355 value.to_i64()
356 }
357}
358
359macro_rules! int_prop {
360 ($($t:ty),*) => {$(
361 impl PropType for $t {
362 const KIND: PropKind = PropKind::Int;
363 fn to_value(&self) -> PropValue {
364 PropValue::Int(*self as i64)
365 }
366 fn from_value(value: PropValue) -> Result<Self> {
367 let v = value.to_i64()?;
368 <$t>::try_from(v).map_err(|_| Error::invalid(format!("valor {v} fora do intervalo")))
369 }
370 }
371 )*};
372}
373
374int_prop!(i32, u32, usize);
375
376impl PropType for f32 {
377 const KIND: PropKind = PropKind::Float;
378 fn to_value(&self) -> PropValue {
379 PropValue::Float(*self as f64)
380 }
381 fn from_value(value: PropValue) -> Result<Self> {
382 value.to_f32()
383 }
384}
385
386impl PropType for f64 {
387 const KIND: PropKind = PropKind::Float;
388 fn to_value(&self) -> PropValue {
389 PropValue::Float(*self)
390 }
391 fn from_value(value: PropValue) -> Result<Self> {
392 value.to_f64()
393 }
394}
395
396impl PropType for String {
397 const KIND: PropKind = PropKind::String;
398 fn to_value(&self) -> PropValue {
399 PropValue::String(self.clone())
400 }
401 fn from_value(value: PropValue) -> Result<Self> {
402 value.to_str().map(str::to_string)
403 }
404}
405
406impl PropType for Color {
407 const KIND: PropKind = PropKind::Color;
408 fn to_value(&self) -> PropValue {
409 PropValue::Color(*self)
410 }
411 fn from_value(value: PropValue) -> Result<Self> {
412 value.to_color()
413 }
414}
415
416impl PropType for Bounds {
417 const KIND: PropKind = PropKind::Bounds;
418 fn to_value(&self) -> PropValue {
419 PropValue::Bounds(*self)
420 }
421 fn from_value(value: PropValue) -> Result<Self> {
422 value.to_bounds()
423 }
424}
425
426impl PropType for Anchors {
427 const KIND: PropKind = PropKind::Set(&Anchors::NAMES);
428 fn to_value(&self) -> PropValue {
429 (*self).into()
430 }
431 fn from_value(value: PropValue) -> Result<Self> {
432 value.to_anchors()
433 }
434}
435
436impl PropType for Option<f32> {
438 const KIND: PropKind = PropKind::Float;
439 fn to_value(&self) -> PropValue {
440 self.map_or(PropValue::Null, |v| PropValue::Float(v as f64))
441 }
442 fn from_value(value: PropValue) -> Result<Self> {
443 match value {
444 PropValue::Null => Ok(None),
445 v => v.to_f32().map(Some),
446 }
447 }
448}
449
450impl PropType for Option<Bounds> {
452 const KIND: PropKind = PropKind::Bounds;
453 fn to_value(&self) -> PropValue {
454 self.map_or(PropValue::Null, PropValue::Bounds)
455 }
456 fn from_value(value: PropValue) -> Result<Self> {
457 match value {
458 PropValue::Null => Ok(None),
459 v => v.to_bounds().map(Some),
460 }
461 }
462}
463
464impl PropType for Option<Color> {
466 const KIND: PropKind = PropKind::Color;
467 fn to_value(&self) -> PropValue {
468 self.map_or(PropValue::Null, PropValue::Color)
469 }
470 fn from_value(value: PropValue) -> Result<Self> {
471 match value {
472 PropValue::Null => Ok(None),
473 PropValue::String(s) if s.is_empty() => Ok(None),
474 v => v.to_color().map(Some),
475 }
476 }
477}
478
479impl PropType for Option<crate::canvas::Shadow> {
481 const KIND: PropKind = PropKind::Shadow;
482 fn to_value(&self) -> PropValue {
483 self.map_or(PropValue::Null, |s| PropValue::String(s.to_spec()))
484 }
485 fn from_value(value: PropValue) -> Result<Self> {
486 match value {
487 PropValue::Null => Ok(None),
488 v => {
489 let text = v.to_str()?;
490 if text.trim().is_empty() || text.trim().eq_ignore_ascii_case("none") {
491 return Ok(None);
492 }
493 crate::canvas::Shadow::parse(text)
494 .map(Some)
495 .ok_or_else(|| Error::invalid(format!("sombra inválida: '{text}'; use \"dx dy desfoque [espalhamento] #cor\"")))
496 }
497 }
498 }
499}
500
501impl PropType for Option<ComponentId> {
503 const KIND: PropKind = PropKind::Component;
504 fn to_value(&self) -> PropValue {
505 PropValue::Component(*self)
506 }
507 fn from_value(value: PropValue) -> Result<Self> {
508 value.to_component()
509 }
510}
511
512impl<T: PropEnum> PropType for T {
513 const KIND: PropKind = PropKind::Enum(T::NAMES);
514 fn to_value(&self) -> PropValue {
515 PropValue::enum_value(*self)
516 }
517 fn from_value(value: PropValue) -> Result<Self> {
518 value.to_enum()
519 }
520}
521
522#[macro_export]
560macro_rules! properties {
561 (
562 $( $field:ident : $ty:ty $( as $kind:ident )? => $category:literal ),* $(,)?
563 $( ; events: $( $event:ident ),* $(,)? )?
564 $( ; computed: $( $cname:ident : $cty:ty => $cget:ident / $cset:ident ),* $(,)? )?
565 $( ; on_set: $hook:ident )?
566 ) => {
567 fn props(&self) -> &'static [$crate::PropInfo] {
568 const PROPS: &[$crate::PropInfo] = &[
569 $( $crate::PropInfo::new(
570 stringify!($field),
571 $crate::prop::kind_or(<$ty as $crate::prop::PropType>::KIND, &[$( $crate::PropKind::$kind )?]),
572 $category,
573 ), )*
574 $( $( $crate::PropInfo::new(stringify!($event), $crate::PropKind::Event, "Events"), )* )?
575 $( $( $crate::PropInfo::new(stringify!($cname), <$cty as $crate::prop::PropType>::KIND, "Runtime").runtime(), )* )?
576 ];
577 PROPS
578 }
579
580 fn get_prop(&self, name: &str) -> ::core::option::Option<$crate::PropValue> {
581 match name {
582 $( stringify!($field) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$field)), )*
583 $( $( stringify!($cname) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$cget())), )* )?
584 _ => ::core::option::Option::None,
585 }
586 }
587
588 fn set_prop(&mut self, name: &str, value: $crate::PropValue) -> $crate::Result<()> {
589 match name {
590 $( stringify!($field) => {
591 self.$field = <$ty as $crate::prop::PropType>::from_value(value)?;
592 } )*
593 $( $( stringify!($cname) => {
594 let v: $cty = <$cty as $crate::prop::PropType>::from_value(value)?;
595 self.$cset(v);
596 } )* )?
597 _ => return ::core::result::Result::Err($crate::Error::UnknownProperty(name.to_string())),
598 }
599 $( self.$hook(name); )?
600 ::core::result::Result::Ok(())
601 }
602 };
603}