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 Date,
64 Time,
66 DateTime,
68 List,
70 NumberList,
72 ColorList,
74 PointList,
76 Record(&'static RecordInfo),
80 RecordList(&'static RecordInfo),
83 StyleName,
87 ThemeName,
90 FormName,
93}
94
95pub struct RecordInfo {
101 pub name: &'static str,
102 pub fields: &'static [(&'static str, PropKind)],
103}
104
105impl std::fmt::Debug for RecordInfo {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 write!(f, "RecordInfo({})", self.name)
109 }
110}
111
112impl PartialEq for RecordInfo {
114 fn eq(&self, other: &Self) -> bool {
115 self.name == other.name
116 }
117}
118
119#[doc(hidden)]
121pub const fn kind_or(default: PropKind, over: &[PropKind]) -> PropKind {
122 if let [k] = over { *k } else { default }
123}
124
125#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct PropInfo {
128 pub name: &'static str,
129 pub kind: PropKind,
130 pub category: &'static str,
132 pub read_only: bool,
133 pub runtime: bool,
137 pub rust_type: &'static str,
140 pub event_arg: crate::EventArg,
142}
143
144impl PropInfo {
145 pub const fn new(name: &'static str, kind: PropKind, category: &'static str) -> Self {
146 Self { name, kind, category, read_only: false, runtime: false, rust_type: "", event_arg: crate::EventArg::Unknown }
147 }
148
149 pub const fn rust_type(mut self, name: &'static str) -> Self {
152 self.rust_type = name;
153 self
154 }
155
156 pub const fn event_arg(mut self, arg: crate::EventArg) -> Self {
158 self.event_arg = arg;
159 self
160 }
161
162 pub const fn read_only(mut self) -> Self {
163 self.read_only = true;
164 self
165 }
166
167 pub const fn runtime(mut self) -> Self {
168 self.runtime = true;
169 self
170 }
171}
172
173#[derive(Clone, Debug, Default, PartialEq)]
175pub enum PropValue {
176 #[default]
177 Null,
178 Bool(bool),
179 Int(i64),
180 Float(f64),
181 String(String),
182 Color(Color),
183 Enum(String),
184 Set(Vec<String>),
185 Bounds(Bounds),
186 Component(Option<ComponentId>),
187 Event(Option<String>),
188}
189
190impl PropValue {
191 pub fn kind_name(&self) -> &'static str {
192 match self {
193 PropValue::Null => "null",
194 PropValue::Bool(_) => "bool",
195 PropValue::Int(_) => "int",
196 PropValue::Float(_) => "float",
197 PropValue::String(_) => "string",
198 PropValue::Color(_) => "color",
199 PropValue::Enum(_) => "enum",
200 PropValue::Set(_) => "set",
201 PropValue::Bounds(_) => "bounds",
202 PropValue::Component(_) => "component",
203 PropValue::Event(_) => "event",
204 }
205 }
206
207 pub fn to_bool(&self) -> Result<bool> {
208 match self {
209 PropValue::Bool(b) => Ok(*b),
210 _ => Err(Error::type_mismatch("bool", self)),
211 }
212 }
213
214 pub fn to_i64(&self) -> Result<i64> {
215 match self {
216 PropValue::Int(v) => Ok(*v),
217 PropValue::Float(v) if v.fract() == 0.0 => Ok(*v as i64),
218 _ => Err(Error::type_mismatch("int", self)),
219 }
220 }
221
222 pub fn to_f64(&self) -> Result<f64> {
223 match self {
224 PropValue::Float(v) => Ok(*v),
225 PropValue::Int(v) => Ok(*v as f64),
226 _ => Err(Error::type_mismatch("float", self)),
227 }
228 }
229
230 pub fn to_f32(&self) -> Result<f32> {
231 self.to_f64().map(|v| v as f32)
232 }
233
234 pub fn to_str(&self) -> Result<&str> {
235 match self {
236 PropValue::String(s) | PropValue::Enum(s) => Ok(s),
237 _ => Err(Error::type_mismatch("string", self)),
238 }
239 }
240
241 pub fn to_color(&self) -> Result<Color> {
243 match self {
244 PropValue::Color(c) => Ok(*c),
245 PropValue::String(s) => s.parse(),
246 _ => Err(Error::type_mismatch("color", self)),
247 }
248 }
249
250 pub fn to_bounds(&self) -> Result<Bounds> {
255 match self {
256 PropValue::Bounds(b) => Ok(*b),
257 PropValue::Int(_) | PropValue::Float(_) => Ok(Bounds::all(self.to_f32()?)),
258 PropValue::String(s) => {
259 let numbers: Option<Vec<f32>> = s.split([',', ' ', ';']).filter(|p| !p.trim().is_empty()).map(|p| p.trim().parse::<f32>().ok()).collect();
260 match numbers.as_deref() {
261 Some([all]) => Ok(Bounds::all(*all)),
262 Some([h, v]) => Ok(Bounds::symmetric(*h, *v)),
263 Some([l, t, r, b]) => Ok(Bounds::new(*l, *t, *r, *b)),
264 _ => Err(Error::invalid(format!("margens inválidas '{s}'; use 1, 2 (h, v) ou 4 (esquerda, cima, direita, baixo) números"))),
265 }
266 }
267 _ => Err(Error::type_mismatch("bounds", self)),
268 }
269 }
270
271 pub fn to_enum<T: PropEnum>(&self) -> Result<T> {
273 let name = match self {
274 PropValue::Enum(s) | PropValue::String(s) => s,
275 _ => return Err(Error::type_mismatch("enum", self)),
276 };
277 T::from_name(name).ok_or_else(|| {
278 Error::invalid(format!("valor '{name}' inválido; use um de: {}", T::NAMES.join(", ")))
279 })
280 }
281
282 pub fn to_anchors(&self) -> Result<Anchors> {
284 let parsed = match self {
285 PropValue::Set(names) => Anchors::from_names(names),
286 PropValue::String(s) | PropValue::Enum(s) => {
287 Anchors::from_names(s.split(',').map(str::trim).filter(|p| !p.is_empty()))
288 }
289 _ => return Err(Error::type_mismatch("set", self)),
290 };
291 parsed.ok_or_else(|| {
292 Error::invalid(format!("âncoras inválidas; use: {}", Anchors::NAMES.join(", ")))
293 })
294 }
295
296 pub fn to_component(&self) -> Result<Option<ComponentId>> {
297 match self {
298 PropValue::Component(c) => Ok(*c),
299 PropValue::Null => Ok(None),
300 _ => Err(Error::type_mismatch("component", self)),
301 }
302 }
303
304 pub fn to_event(&self) -> Result<Option<String>> {
306 match self {
307 PropValue::Event(e) => Ok(e.clone()),
308 PropValue::String(s) => Ok((!s.is_empty()).then(|| s.clone())),
309 PropValue::Null => Ok(None),
310 _ => Err(Error::type_mismatch("event", self)),
311 }
312 }
313}
314
315impl From<bool> for PropValue {
316 fn from(v: bool) -> Self {
317 PropValue::Bool(v)
318 }
319}
320
321impl From<i32> for PropValue {
322 fn from(v: i32) -> Self {
323 PropValue::Int(v as i64)
324 }
325}
326
327impl From<i64> for PropValue {
328 fn from(v: i64) -> Self {
329 PropValue::Int(v)
330 }
331}
332
333impl From<u32> for PropValue {
334 fn from(v: u32) -> Self {
335 PropValue::Int(v as i64)
336 }
337}
338
339impl From<f32> for PropValue {
340 fn from(v: f32) -> Self {
341 PropValue::Float(v as f64)
342 }
343}
344
345impl From<f64> for PropValue {
346 fn from(v: f64) -> Self {
347 PropValue::Float(v)
348 }
349}
350
351impl From<&str> for PropValue {
352 fn from(v: &str) -> Self {
353 PropValue::String(v.to_string())
354 }
355}
356
357impl From<String> for PropValue {
358 fn from(v: String) -> Self {
359 PropValue::String(v)
360 }
361}
362
363impl From<Color> for PropValue {
364 fn from(v: Color) -> Self {
365 PropValue::Color(v)
366 }
367}
368
369impl From<Bounds> for PropValue {
370 fn from(v: Bounds) -> Self {
371 PropValue::Bounds(v)
372 }
373}
374
375impl From<Anchors> for PropValue {
376 fn from(v: Anchors) -> Self {
377 PropValue::Set(v.names())
378 }
379}
380
381impl From<ComponentId> for PropValue {
382 fn from(v: ComponentId) -> Self {
383 PropValue::Component(Some(v))
384 }
385}
386
387impl From<Option<ComponentId>> for PropValue {
388 fn from(v: Option<ComponentId>) -> Self {
389 PropValue::Component(v)
390 }
391}
392
393impl From<crate::align::Align> for PropValue {
394 fn from(v: crate::align::Align) -> Self {
395 PropValue::enum_value(v)
396 }
397}
398
399impl PropValue {
400 pub fn enum_value<T: PropEnum>(v: T) -> Self {
402 PropValue::Enum(v.name().to_string())
403 }
404}
405
406pub trait PropType: Sized {
408 const KIND: PropKind;
409 fn to_value(&self) -> PropValue;
410 fn from_value(value: PropValue) -> Result<Self>;
411}
412
413impl PropType for bool {
414 const KIND: PropKind = PropKind::Bool;
415 fn to_value(&self) -> PropValue {
416 PropValue::Bool(*self)
417 }
418 fn from_value(value: PropValue) -> Result<Self> {
419 value.to_bool()
420 }
421}
422
423impl PropType for i64 {
424 const KIND: PropKind = PropKind::Int;
425 fn to_value(&self) -> PropValue {
426 PropValue::Int(*self)
427 }
428 fn from_value(value: PropValue) -> Result<Self> {
429 value.to_i64()
430 }
431}
432
433macro_rules! int_prop {
434 ($($t:ty),*) => {$(
435 impl PropType for $t {
436 const KIND: PropKind = PropKind::Int;
437 fn to_value(&self) -> PropValue {
438 PropValue::Int(*self as i64)
439 }
440 fn from_value(value: PropValue) -> Result<Self> {
441 let v = value.to_i64()?;
442 <$t>::try_from(v).map_err(|_| Error::invalid(format!("valor {v} fora do intervalo")))
443 }
444 }
445 )*};
446}
447
448int_prop!(i32, u32, usize);
449
450impl PropType for f32 {
451 const KIND: PropKind = PropKind::Float;
452 fn to_value(&self) -> PropValue {
453 PropValue::Float(*self as f64)
454 }
455 fn from_value(value: PropValue) -> Result<Self> {
456 value.to_f32()
457 }
458}
459
460impl PropType for f64 {
461 const KIND: PropKind = PropKind::Float;
462 fn to_value(&self) -> PropValue {
463 PropValue::Float(*self)
464 }
465 fn from_value(value: PropValue) -> Result<Self> {
466 value.to_f64()
467 }
468}
469
470impl PropType for String {
471 const KIND: PropKind = PropKind::String;
472 fn to_value(&self) -> PropValue {
473 PropValue::String(self.clone())
474 }
475 fn from_value(value: PropValue) -> Result<Self> {
476 value.to_str().map(str::to_string)
477 }
478}
479
480impl PropType for Color {
481 const KIND: PropKind = PropKind::Color;
482 fn to_value(&self) -> PropValue {
483 PropValue::Color(*self)
484 }
485 fn from_value(value: PropValue) -> Result<Self> {
486 value.to_color()
487 }
488}
489
490impl PropType for Bounds {
491 const KIND: PropKind = PropKind::Bounds;
492 fn to_value(&self) -> PropValue {
493 PropValue::Bounds(*self)
494 }
495 fn from_value(value: PropValue) -> Result<Self> {
496 value.to_bounds()
497 }
498}
499
500impl PropType for Anchors {
501 const KIND: PropKind = PropKind::Set(&Anchors::NAMES);
502 fn to_value(&self) -> PropValue {
503 (*self).into()
504 }
505 fn from_value(value: PropValue) -> Result<Self> {
506 value.to_anchors()
507 }
508}
509
510impl PropType for Option<f32> {
512 const KIND: PropKind = PropKind::Float;
513 fn to_value(&self) -> PropValue {
514 self.map_or(PropValue::Null, |v| PropValue::Float(v as f64))
515 }
516 fn from_value(value: PropValue) -> Result<Self> {
517 match value {
518 PropValue::Null => Ok(None),
519 v => v.to_f32().map(Some),
520 }
521 }
522}
523
524impl PropType for Option<Bounds> {
526 const KIND: PropKind = PropKind::Bounds;
527 fn to_value(&self) -> PropValue {
528 self.map_or(PropValue::Null, PropValue::Bounds)
529 }
530 fn from_value(value: PropValue) -> Result<Self> {
531 match value {
532 PropValue::Null => Ok(None),
533 v => v.to_bounds().map(Some),
534 }
535 }
536}
537
538impl PropType for Option<Color> {
540 const KIND: PropKind = PropKind::Color;
541 fn to_value(&self) -> PropValue {
542 self.map_or(PropValue::Null, PropValue::Color)
543 }
544 fn from_value(value: PropValue) -> Result<Self> {
545 match value {
546 PropValue::Null => Ok(None),
547 PropValue::String(s) if s.is_empty() => Ok(None),
548 v => v.to_color().map(Some),
549 }
550 }
551}
552
553impl PropType for Option<crate::canvas::Shadow> {
555 const KIND: PropKind = PropKind::Shadow;
556 fn to_value(&self) -> PropValue {
557 self.map_or(PropValue::Null, |s| PropValue::String(s.to_spec()))
558 }
559 fn from_value(value: PropValue) -> Result<Self> {
560 match value {
561 PropValue::Null => Ok(None),
562 v => {
563 let text = v.to_str()?;
564 if text.trim().is_empty() || text.trim().eq_ignore_ascii_case("none") {
565 return Ok(None);
566 }
567 crate::canvas::Shadow::parse(text)
568 .map(Some)
569 .ok_or_else(|| Error::invalid(format!("sombra inválida: '{text}'; use \"dx dy desfoque [espalhamento] #cor\"")))
570 }
571 }
572 }
573}
574
575impl PropType for Option<ComponentId> {
577 const KIND: PropKind = PropKind::Component;
578 fn to_value(&self) -> PropValue {
579 PropValue::Component(*self)
580 }
581 fn from_value(value: PropValue) -> Result<Self> {
582 value.to_component()
583 }
584}
585
586impl<T: PropEnum> PropType for T {
587 const KIND: PropKind = PropKind::Enum(T::NAMES);
588 fn to_value(&self) -> PropValue {
589 PropValue::enum_value(*self)
590 }
591 fn from_value(value: PropValue) -> Result<Self> {
592 value.to_enum()
593 }
594}
595
596#[macro_export]
634macro_rules! properties {
635 (
636 $( $field:ident : $ty:ty $( as $kind:ident $( ( $karg:expr ) )? )? => $category:literal ),* $(,)?
637 $( ; events: $( $event:ident $( : $ety:ty )? ),* $(,)? )?
638 $( ; computed: $( $cname:ident : $cty:ty $( as $ckind:ident $( ( $ckarg:expr ) )? )? => $cget:ident / $cset:ident ),* $(,)? )?
639 $( ; on_set: $hook:ident )?
640 ) => {
641 fn props(&self) -> &'static [$crate::PropInfo] {
642 const PROPS: &[$crate::PropInfo] = &[
643 $( $crate::PropInfo::new(
644 stringify!($field),
645 $crate::prop::kind_or(<$ty as $crate::prop::PropType>::KIND, &[$( $crate::PropKind::$kind $( ($karg) )? )?]),
646 $category,
647 ).rust_type(stringify!($ty)), )*
648 $( $( $crate::PropInfo::new(stringify!($event), $crate::PropKind::Event, "Events")
649 $( .event_arg(<$ety as $crate::EventValue>::ARG).rust_type(stringify!($ety)) )?, )* )?
650 $( $( $crate::PropInfo::new(
651 stringify!($cname),
652 $crate::prop::kind_or(<$cty as $crate::prop::PropType>::KIND, &[$( $crate::PropKind::$ckind $( ($ckarg) )? )?]),
653 "Runtime",
654 ).runtime().rust_type(stringify!($cty)), )* )?
655 ];
656 PROPS
657 }
658
659 fn get_prop(&self, name: &str) -> ::core::option::Option<$crate::PropValue> {
660 match name {
661 $( stringify!($field) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$field)), )*
662 $( $( stringify!($cname) => ::core::option::Option::Some($crate::prop::PropType::to_value(&self.$cget())), )* )?
663 _ => ::core::option::Option::None,
664 }
665 }
666
667 fn set_prop(&mut self, name: &str, value: $crate::PropValue) -> $crate::Result<()> {
668 match name {
669 $( stringify!($field) => {
670 self.$field = <$ty as $crate::prop::PropType>::from_value(value)?;
671 } )*
672 $( $( stringify!($cname) => {
673 let v: $cty = <$cty as $crate::prop::PropType>::from_value(value)?;
674 self.$cset(v);
675 } )* )?
676 _ => return ::core::result::Result::Err($crate::Error::UnknownProperty(name.to_string())),
677 }
678 $( self.$hook(name); )?
679 ::core::result::Result::Ok(())
680 }
681 };
682}