Skip to main content

aylis_core/
prop.rs

1//! Sistema de propriedades publicadas (o "RTTI" do aylis).
2//!
3//! Cada componente declara suas propriedades com [`PropInfo`] e as lê/grava por nome
4//! com [`PropValue`]. É isso que permite carregar e salvar layouts, o Object Inspector
5//! da IDE, animações por nome e o controle remoto da tela por outras linguagens.
6
7use crate::align::Anchors;
8use crate::color::Color;
9use crate::component::ComponentId;
10use crate::error::{Error, Result};
11use crate::geometry::Bounds;
12
13/// Enum que pode ser usado como propriedade (lido e gravado pelo nome).
14pub trait PropEnum: Sized + Copy + 'static {
15    /// Nomes de todos os valores, na ordem de [`PropEnum::index`].
16    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    /// Procura pelo nome, sem diferenciar maiúsculas.
26    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/// Tipo de uma propriedade; define o editor no Object Inspector.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub enum PropKind {
37    Bool,
38    Int,
39    Float,
40    String,
41    Color,
42    /// Um valor entre os nomes dados.
43    Enum(&'static [&'static str]),
44    /// Zero ou mais valores entre os nomes dados.
45    Set(&'static [&'static str]),
46    Bounds,
47    /// Referência a outro componente (gravada pelo nome).
48    Component,
49    /// Evento (gravado pelo nome do handler).
50    Event,
51    /// Ângulo em graus (valor `Float`). Na IDE: o relógio de ângulo.
52    Angle,
53    /// Duração em milissegundos (valor `Float`). Na IDE: a linha do tempo da animação.
54    Duration,
55    /// Sombra `"dx dy desfoque [espalhamento] #cor"` (valor `String`; vazio = sem sombra).
56    /// Na IDE: o editor de sombra.
57    Shadow,
58    /// Curva de suavização: um nome (`out_quad`, `ease-in`...) ou
59    /// `cubic-bezier(x1, y1, x2, y2)` (valor `String`). Na IDE: o editor da curva.
60    Easing,
61    /// Data do calendário em ISO (`2026-10-24`; valor `String`, vazio = nenhuma): o acesso
62    /// tipado usa a data de cada linguagem ([`crate::Date`] no Rust).
63    Date,
64    /// Hora `HH:MM` ou `HH:MM:SS` (valor `String`, vazio = nenhuma).
65    Time,
66    /// Dia e hora em ISO sem fuso (`2026-11-12T14:30`; valor `String`, vazio = nenhum).
67    DateTime,
68    /// Lista de textos separados por `;` (valor `String`): no acesso tipado, uma lista.
69    List,
70    /// Lista de números separados por `;` (`0.4;0.9`; valor `String`).
71    NumberList,
72    /// Lista de cores separadas por `;` (`#FF0000;#00AA00`; valor `String`).
73    ColorList,
74    /// Pontos `x,y` separados por espaço (`0.5,0 1,1 0,1`; valor `String`).
75    PointList,
76    /// Um registro (valor `String` com o JSON dele; no form, o objeto): o resultado de um método
77    /// com campos, como o `Screen.monitor`. Cada linguagem ganha um tipo com os campos
78    /// ([`RecordInfo`]).
79    Record(&'static RecordInfo),
80    /// Uma lista de registros (valor `String` com o JSON da lista; no form, a lista de objetos):
81    /// os itens do `ListView`, as colunas do `DataGrid`, os nós do `TreeView`...
82    RecordList(&'static RecordInfo),
83    /// O nome de uma variante do tema para a classe (o `style`: `primary`, `outline`...; valor
84    /// `String`, vazio = o estilo da classe). No acesso tipado, um enum por classe com as
85    /// variantes do Aylis e as dos temas do projeto.
86    StyleName,
87    /// O nome de um tema (os de plataforma do Aylis e os do projeto; valor `String`, vazio = o
88    /// do pai). No acesso tipado, um enum com eles.
89    ThemeName,
90    /// O nome de um form do projeto (valor `String`, vazio = nenhum). No acesso tipado, um enum
91    /// com os forms do projeto.
92    FormName,
93}
94
95/// Um registro do acesso tipado: o nome do tipo e os campos (no fio, um objeto JSON com os
96/// mesmos nomes). Os campos: `String`, `Int`, `Float`, `Bool`, `Color` (`"#RRGGBB"` ou um
97/// nome), `Date`/`DateTime` (ISO), `List` (lista de textos), `NumberList` (lista de números),
98/// `Record` e `RecordList` (outro registro, ou o mesmo: os filhos de um nó). Um registro que
99/// se contém é um `static` (`&TREE_NODE` dentro dele mesmo).
100pub struct RecordInfo {
101    pub name: &'static str,
102    pub fields: &'static [(&'static str, PropKind)],
103}
104
105/// Pelo nome: mostrar os campos entraria sem fim num registro que se contém.
106impl 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
112/// Pelo nome: comparar os campos entraria sem fim num registro que se contém.
113impl PartialEq for RecordInfo {
114    fn eq(&self, other: &Self) -> bool {
115        self.name == other.name
116    }
117}
118
119/// O tipo da propriedade: o do campo, ou o dado com `as` no [`properties!`].
120#[doc(hidden)]
121pub const fn kind_or(default: PropKind, over: &[PropKind]) -> PropKind {
122    if let [k] = over { *k } else { default }
123}
124
125/// Metadados de uma propriedade publicada.
126#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct PropInfo {
128    pub name: &'static str,
129    pub kind: PropKind,
130    /// Agrupamento no Object Inspector ("Layout", "Appearance", "Events"...).
131    pub category: &'static str,
132    pub read_only: bool,
133    /// Só em execução: lida e gravada pelo código e pelo
134    /// protocolo, mas não vai para o JSON do form, não é copiada ao duplicar e não aparece
135    /// no Object Inspector.
136    pub runtime: bool,
137    /// O tipo Rust do valor (`WindowState`, `Align`), quando é um enum: o acesso tipado gerado
138    /// usa o nome no Rust e nas outras linguagens. Vazio nos outros.
139    pub rust_type: &'static str,
140    /// O que o evento leva (só nos eventos; veja [`crate::EventValue`]).
141    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    /// O tipo Rust do enum (veja [`PropInfo::rust_type`]): o último nome do caminho
150    /// (`crate::Align` → `Align`).
151    pub const fn rust_type(mut self, name: &'static str) -> Self {
152        self.rust_type = name;
153        self
154    }
155
156    /// O que o evento leva (`EventArg::None`: nada; veja [`crate::EventValue`]).
157    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/// Valor de uma propriedade.
174#[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    /// Aceita uma cor ou um texto `#RRGGBB[AA]`.
242    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    /// Aceita `Bounds` ou um número (o mesmo valor nos quatro lados).
251    /// Aceita também o texto, como no JSON: `"8"` (todos), `"16, 12"` (horizontal, vertical)
252    /// ou `"12, 4, 12, 0"` (esquerda, cima, direita, baixo); vírgula ou espaço separam. É como
253    /// o acesso tipado das linguagens manda `margins` e `padding`.
254    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    /// Aceita o nome do valor (como `Enum` ou `String`).
272    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    /// Aceita uma lista de nomes ou um texto separado por vírgulas (`"left,right"`).
283    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    /// Nome do handler de um evento (`None` desliga o evento).
305    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    /// Valor de enum a partir de qualquer [`PropEnum`].
401    pub fn enum_value<T: PropEnum>(v: T) -> Self {
402        PropValue::Enum(v.name().to_string())
403    }
404}
405
406/// Tipo que pode ser campo de uma propriedade publicada (usado pelo [`properties!`]).
407pub 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
510/// `None` = usar o valor do tema. `Null` (ou texto vazio) volta para `None`.
511impl 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
524/// `None` = o do tema (o raio do estilo). Número, `[h, v]` ou `[a, b, c, d]`.
525impl 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
538/// `None` = usar a cor do tema. `Null` (ou texto vazio) volta para `None`.
539impl 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
553/// `None` = sem sombra (a do tema, se houver). Texto: `"0 4 12 #00000040"`.
554impl 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
575/// Referência a outro componente.
576impl 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/// Publica campos como propriedades, gerando `props`, `get_prop` e `set_prop` de um
597/// [`Component`](crate::Component). Use dentro do `impl Component for ...`.
598///
599/// O nome da propriedade é o nome do campo. O tipo dela vem do tipo do campo; para trocar
600/// o editor na IDE, use `as`: `giro: f32 as Angle`, `tempo: f32 as Duration`.
601///
602/// Seções opcionais, separadas por `;`:
603/// - `events:` eventos próprios da classe (os comuns, como `on_click`, já existem em
604///   todo controle);
605/// - `on_set:` método `fn(&mut self, name: &str)` chamado depois que uma propriedade é
606///   gravada (para manter outros dados em sincronia).
607///
608/// ```
609/// use aylis_core::*;
610///
611/// #[derive(Default)]
612/// struct Gauge { base: ControlBase, value: f32, caption: String, color: Option<Color> }
613///
614/// impl Component for Gauge {
615///     fn class_name(&self) -> &'static str { "Gauge" }
616///     fn control(&self) -> Option<&ControlBase> { Some(&self.base) }
617///     fn control_mut(&mut self) -> Option<&mut ControlBase> { Some(&mut self.base) }
618///
619///     properties! {
620///         value: f32 => "Data",
621///         caption: String => "Appearance",
622///         color: Option<Color> => "Appearance";
623///         events: on_change
624///     }
625/// }
626///
627/// let mut ui = Ui::new();
628/// let g = ui.add_root(Gauge::default());
629/// ui.set_prop(g, "value", 42).unwrap();
630/// assert_eq!(ui.get::<Gauge>(g).unwrap().value, 42.0);
631/// assert!(ui.prop_info(g, "on_change").is_some());
632/// ```
633#[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}