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> {
178 match self {
179 PropValue::Bounds(b) => Ok(*b),
180 PropValue::Int(_) | PropValue::Float(_) => Ok(Bounds::all(self.to_f32()?)),
181 _ => Err(Error::type_mismatch("bounds", self)),
182 }
183 }
184
185 pub fn to_enum<T: PropEnum>(&self) -> Result<T> {
187 let name = match self {
188 PropValue::Enum(s) | PropValue::String(s) => s,
189 _ => return Err(Error::type_mismatch("enum", self)),
190 };
191 T::from_name(name).ok_or_else(|| {
192 Error::invalid(format!("valor '{name}' inválido; use um de: {}", T::NAMES.join(", ")))
193 })
194 }
195
196 pub fn to_anchors(&self) -> Result<Anchors> {
198 let parsed = match self {
199 PropValue::Set(names) => Anchors::from_names(names),
200 PropValue::String(s) | PropValue::Enum(s) => {
201 Anchors::from_names(s.split(',').map(str::trim).filter(|p| !p.is_empty()))
202 }
203 _ => return Err(Error::type_mismatch("set", self)),
204 };
205 parsed.ok_or_else(|| {
206 Error::invalid(format!("âncoras inválidas; use: {}", Anchors::NAMES.join(", ")))
207 })
208 }
209
210 pub fn to_component(&self) -> Result<Option<ComponentId>> {
211 match self {
212 PropValue::Component(c) => Ok(*c),
213 PropValue::Null => Ok(None),
214 _ => Err(Error::type_mismatch("component", self)),
215 }
216 }
217
218 pub fn to_event(&self) -> Result<Option<String>> {
220 match self {
221 PropValue::Event(e) => Ok(e.clone()),
222 PropValue::String(s) => Ok((!s.is_empty()).then(|| s.clone())),
223 PropValue::Null => Ok(None),
224 _ => Err(Error::type_mismatch("event", self)),
225 }
226 }
227}
228
229impl From<bool> for PropValue {
230 fn from(v: bool) -> Self {
231 PropValue::Bool(v)
232 }
233}
234
235impl From<i32> for PropValue {
236 fn from(v: i32) -> Self {
237 PropValue::Int(v as i64)
238 }
239}
240
241impl From<i64> for PropValue {
242 fn from(v: i64) -> Self {
243 PropValue::Int(v)
244 }
245}
246
247impl From<u32> for PropValue {
248 fn from(v: u32) -> Self {
249 PropValue::Int(v as i64)
250 }
251}
252
253impl From<f32> for PropValue {
254 fn from(v: f32) -> Self {
255 PropValue::Float(v as f64)
256 }
257}
258
259impl From<f64> for PropValue {
260 fn from(v: f64) -> Self {
261 PropValue::Float(v)
262 }
263}
264
265impl From<&str> for PropValue {
266 fn from(v: &str) -> Self {
267 PropValue::String(v.to_string())
268 }
269}
270
271impl From<String> for PropValue {
272 fn from(v: String) -> Self {
273 PropValue::String(v)
274 }
275}
276
277impl From<Color> for PropValue {
278 fn from(v: Color) -> Self {
279 PropValue::Color(v)
280 }
281}
282
283impl From<Bounds> for PropValue {
284 fn from(v: Bounds) -> Self {
285 PropValue::Bounds(v)
286 }
287}
288
289impl From<Anchors> for PropValue {
290 fn from(v: Anchors) -> Self {
291 PropValue::Set(v.names())
292 }
293}
294
295impl From<ComponentId> for PropValue {
296 fn from(v: ComponentId) -> Self {
297 PropValue::Component(Some(v))
298 }
299}
300
301impl From<Option<ComponentId>> for PropValue {
302 fn from(v: Option<ComponentId>) -> Self {
303 PropValue::Component(v)
304 }
305}
306
307impl From<crate::align::Align> for PropValue {
308 fn from(v: crate::align::Align) -> Self {
309 PropValue::enum_value(v)
310 }
311}
312
313impl PropValue {
314 pub fn enum_value<T: PropEnum>(v: T) -> Self {
316 PropValue::Enum(v.name().to_string())
317 }
318}
319
320pub trait PropType: Sized {
322 const KIND: PropKind;
323 fn to_value(&self) -> PropValue;
324 fn from_value(value: PropValue) -> Result<Self>;
325}
326
327impl PropType for bool {
328 const KIND: PropKind = PropKind::Bool;
329 fn to_value(&self) -> PropValue {
330 PropValue::Bool(*self)
331 }
332 fn from_value(value: PropValue) -> Result<Self> {
333 value.to_bool()
334 }
335}
336
337impl PropType for i64 {
338 const KIND: PropKind = PropKind::Int;
339 fn to_value(&self) -> PropValue {
340 PropValue::Int(*self)
341 }
342 fn from_value(value: PropValue) -> Result<Self> {
343 value.to_i64()
344 }
345}
346
347macro_rules! int_prop {
348 ($($t:ty),*) => {$(
349 impl PropType for $t {
350 const KIND: PropKind = PropKind::Int;
351 fn to_value(&self) -> PropValue {
352 PropValue::Int(*self as i64)
353 }
354 fn from_value(value: PropValue) -> Result<Self> {
355 let v = value.to_i64()?;
356 <$t>::try_from(v).map_err(|_| Error::invalid(format!("valor {v} fora do intervalo")))
357 }
358 }
359 )*};
360}
361
362int_prop!(i32, u32, usize);
363
364impl PropType for f32 {
365 const KIND: PropKind = PropKind::Float;
366 fn to_value(&self) -> PropValue {
367 PropValue::Float(*self as f64)
368 }
369 fn from_value(value: PropValue) -> Result<Self> {
370 value.to_f32()
371 }
372}
373
374impl PropType for f64 {
375 const KIND: PropKind = PropKind::Float;
376 fn to_value(&self) -> PropValue {
377 PropValue::Float(*self)
378 }
379 fn from_value(value: PropValue) -> Result<Self> {
380 value.to_f64()
381 }
382}
383
384impl PropType for String {
385 const KIND: PropKind = PropKind::String;
386 fn to_value(&self) -> PropValue {
387 PropValue::String(self.clone())
388 }
389 fn from_value(value: PropValue) -> Result<Self> {
390 value.to_str().map(str::to_string)
391 }
392}
393
394impl PropType for Color {
395 const KIND: PropKind = PropKind::Color;
396 fn to_value(&self) -> PropValue {
397 PropValue::Color(*self)
398 }
399 fn from_value(value: PropValue) -> Result<Self> {
400 value.to_color()
401 }
402}
403
404impl PropType for Bounds {
405 const KIND: PropKind = PropKind::Bounds;
406 fn to_value(&self) -> PropValue {
407 PropValue::Bounds(*self)
408 }
409 fn from_value(value: PropValue) -> Result<Self> {
410 value.to_bounds()
411 }
412}
413
414impl PropType for Anchors {
415 const KIND: PropKind = PropKind::Set(&Anchors::NAMES);
416 fn to_value(&self) -> PropValue {
417 (*self).into()
418 }
419 fn from_value(value: PropValue) -> Result<Self> {
420 value.to_anchors()
421 }
422}
423
424impl PropType for Option<f32> {
426 const KIND: PropKind = PropKind::Float;
427 fn to_value(&self) -> PropValue {
428 self.map_or(PropValue::Null, |v| PropValue::Float(v as f64))
429 }
430 fn from_value(value: PropValue) -> Result<Self> {
431 match value {
432 PropValue::Null => Ok(None),
433 v => v.to_f32().map(Some),
434 }
435 }
436}
437
438impl PropType for Option<Color> {
440 const KIND: PropKind = PropKind::Color;
441 fn to_value(&self) -> PropValue {
442 self.map_or(PropValue::Null, PropValue::Color)
443 }
444 fn from_value(value: PropValue) -> Result<Self> {
445 match value {
446 PropValue::Null => Ok(None),
447 PropValue::String(s) if s.is_empty() => Ok(None),
448 v => v.to_color().map(Some),
449 }
450 }
451}
452
453impl PropType for Option<crate::canvas::Shadow> {
455 const KIND: PropKind = PropKind::Shadow;
456 fn to_value(&self) -> PropValue {
457 self.map_or(PropValue::Null, |s| PropValue::String(s.to_spec()))
458 }
459 fn from_value(value: PropValue) -> Result<Self> {
460 match value {
461 PropValue::Null => Ok(None),
462 v => {
463 let text = v.to_str()?;
464 if text.trim().is_empty() || text.trim().eq_ignore_ascii_case("none") {
465 return Ok(None);
466 }
467 crate::canvas::Shadow::parse(text)
468 .map(Some)
469 .ok_or_else(|| Error::invalid(format!("sombra inválida: '{text}'; use \"dx dy desfoque [espalhamento] #cor\"")))
470 }
471 }
472 }
473}
474
475impl PropType for Option<ComponentId> {
477 const KIND: PropKind = PropKind::Component;
478 fn to_value(&self) -> PropValue {
479 PropValue::Component(*self)
480 }
481 fn from_value(value: PropValue) -> Result<Self> {
482 value.to_component()
483 }
484}
485
486impl<T: PropEnum> PropType for T {
487 const KIND: PropKind = PropKind::Enum(T::NAMES);
488 fn to_value(&self) -> PropValue {
489 PropValue::enum_value(*self)
490 }
491 fn from_value(value: PropValue) -> Result<Self> {
492 value.to_enum()
493 }
494}
495
496#[macro_export]
534macro_rules! properties {
535 (
536 $( $field:ident : $ty:ty $( as $kind:ident )? => $category:literal ),* $(,)?
537 $( ; events: $( $event:ident ),* $(,)? )?
538 $( ; computed: $( $cname:ident : $cty:ty => $cget:ident / $cset:ident ),* $(,)? )?
539 $( ; on_set: $hook:ident )?
540 ) => {
541 fn props(&self) -> &'static [$crate::PropInfo] {
542 const PROPS: &[$crate::PropInfo] = &[
543 $( $crate::PropInfo::new(
544 stringify!($field),
545 $crate::prop::kind_or(<$ty as $crate::prop::PropType>::KIND, &[$( $crate::PropKind::$kind )?]),
546 $category,
547 ), )*
548 $( $( $crate::PropInfo::new(stringify!($event), $crate::PropKind::Event, "Events"), )* )?
549 $( $( $crate::PropInfo::new(stringify!($cname), <$cty as $crate::prop::PropType>::KIND, "Runtime").runtime(), )* )?
550 ];
551 PROPS
552 }
553
554 fn get_prop(&self, name: &str) -> ::core::option::Option<$crate::PropValue> {
555 match name {
556 $( stringify!($field) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$field)), )*
557 $( $( stringify!($cname) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$cget())), )* )?
558 _ => ::core::option::Option::None,
559 }
560 }
561
562 fn set_prop(&mut self, name: &str, value: $crate::PropValue) -> $crate::Result<()> {
563 match name {
564 $( stringify!($field) => {
565 self.$field = <$ty as $crate::prop::PropType>::from_value(value)?;
566 } )*
567 $( $( stringify!($cname) => {
568 let v: $cty = <$cty as $crate::prop::PropType>::from_value(value)?;
569 self.$cset(v);
570 } )* )?
571 _ => return ::core::result::Result::Err($crate::Error::UnknownProperty(name.to_string())),
572 }
573 $( self.$hook(name); )?
574 ::core::result::Result::Ok(())
575 }
576 };
577}