Skip to main content

ferroui_base/
ferro_property.rs

1use crate::data::{BindingMode, BindingPriority, BindingValue};
2use crate::ferro_property_metadata::Coercion;
3use crate::property_store::{EffectiveValue, EffectiveValueDyn, IValueEntry};
4use crate::reactive::{Disposable, IDisposable, IObservable, Subscription};
5use crate::utilities::HandlerList;
6use crate::{
7    AttachedProperty, DirectProperty, DirectPropertyMetadata, FerroObject, FerroPropertyChangedEventArgs,
8    FerroPropertyMetadata, FerroPropertyRegistry, ObjectType, StaticType, StyledProperty, StyledPropertyMetadata,
9    TypeInfo,
10};
11use std::any::{Any, TypeId};
12use std::cell::{Cell, OnceCell};
13use std::fmt;
14use std::hash::{Hash, Hasher};
15use std::rc::Rc;
16use std::sync::atomic::{AtomicU32, Ordering};
17
18/// The bounds every property value type must satisfy.
19pub trait PropertyValue: Clone + PartialEq + 'static {}
20
21impl<T: Clone + PartialEq + 'static> PropertyValue for T {}
22
23/// A value of any property value type, for untyped access to properties.
24///
25/// Implemented for every type that can be a property value. Unlike
26/// [`Any`], it supports equality, so untyped values can themselves be
27/// property values (for example a data context).
28pub trait AnyValue: Any {
29    /// The value as [`Any`]. Call [`as_any`](trait.AnyValue.html#method.as_any)
30    /// on `dyn AnyValue` instead.
31    ///
32    /// The trait is implemented for every `PartialEq` type, which includes
33    /// `Rc<dyn AnyValue>` itself. The trait methods therefore have names that
34    /// cannot be reached by accident on a boxed value: the inherent methods
35    /// of `dyn AnyValue` are the API, and they dereference through the box.
36    #[doc(hidden)]
37    fn any_value_as_any(&self) -> &dyn Any;
38
39    /// Compares with another untyped value: equal if both hold the same type
40    /// and the values are equal. Use `==` on `dyn AnyValue` instead.
41    #[doc(hidden)]
42    fn any_value_eq(&self, other: &dyn AnyValue) -> bool;
43
44    /// The Rust type name of the contained value. Use `type_name` on
45    /// `dyn AnyValue` instead.
46    #[doc(hidden)]
47    fn any_value_type_name(&self) -> &'static str;
48}
49
50impl<T: PartialEq + 'static> AnyValue for T {
51    #[inline]
52    fn any_value_as_any(&self) -> &dyn Any {
53        self
54    }
55
56    fn any_value_eq(&self, other: &dyn AnyValue) -> bool {
57        other.any_value_as_any().downcast_ref::<T>().is_some_and(|other| value_equals(self, other))
58    }
59
60    fn any_value_type_name(&self) -> &'static str {
61        std::any::type_name::<T>()
62    }
63}
64
65/// Deviation (DEVIATIONS.md, Property system): the comparer of the reference
66/// in place of `PartialEq` alone.
67///
68/// Whether two property values are equal as the reference compares them
69/// (`EqualityComparer<T>.Default.Equals`, and `object.Equals` for boxed
70/// values): `==`, and a floating-point value that is not a number equals
71/// another that is not a number, bare or nullable. With `==` alone a value
72/// store whose value is NaN (a `Width` that is not set) reports a change
73/// every time the value is set again.
74#[inline]
75pub fn value_equals<T: PartialEq + 'static>(a: &T, b: &T) -> bool {
76    a == b || both_not_a_number(a, b)
77}
78
79#[inline]
80fn both_not_a_number<T: 'static>(a: &T, b: &T) -> bool {
81    let (a, b): (&dyn Any, &dyn Any) = (a, b);
82    if let (Some(a), Some(b)) = (a.downcast_ref::<f64>(), b.downcast_ref::<f64>()) {
83        return a.is_nan() && b.is_nan();
84    }
85    if let (Some(a), Some(b)) = (a.downcast_ref::<f32>(), b.downcast_ref::<f32>()) {
86        return a.is_nan() && b.is_nan();
87    }
88    if let (Some(Some(a)), Some(Some(b))) = (a.downcast_ref::<Option<f64>>(), b.downcast_ref::<Option<f64>>()) {
89        return a.is_nan() && b.is_nan();
90    }
91    if let (Some(Some(a)), Some(Some(b))) = (a.downcast_ref::<Option<f32>>(), b.downcast_ref::<Option<f32>>()) {
92        return a.is_nan() && b.is_nan();
93    }
94    false
95}
96
97impl dyn AnyValue {
98    /// The contained value as [`Any`], for downcasting.
99    #[inline]
100    pub fn as_any(&self) -> &dyn Any {
101        self.any_value_as_any()
102    }
103
104    /// The [`TypeId`] of the contained value.
105    #[inline]
106    pub fn value_type_id(&self) -> TypeId {
107        self.any_value_as_any().type_id()
108    }
109
110    /// The Rust type name of the contained value.
111    #[inline]
112    pub fn type_name(&self) -> &'static str {
113        self.any_value_type_name()
114    }
115
116    /// Whether the contained value is of type `T`.
117    #[inline]
118    pub fn is<T: 'static>(&self) -> bool {
119        self.any_value_as_any().is::<T>()
120    }
121
122    /// The contained value, if it is of type `T`.
123    #[inline]
124    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
125        self.any_value_as_any().downcast_ref::<T>()
126    }
127
128    /// Compares with another untyped value: equal if both hold the same type
129    /// and the values are equal.
130    #[inline]
131    pub fn value_eq(&self, other: &dyn AnyValue) -> bool {
132        self.any_value_eq(other)
133    }
134}
135
136impl PartialEq for dyn AnyValue {
137    fn eq(&self, other: &Self) -> bool {
138        self.any_value_eq(other)
139    }
140}
141
142impl fmt::Debug for dyn AnyValue {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        write!(f, "AnyValue<{}>", self.any_value_type_name())
145    }
146}
147
148/// An untyped, shared property value. The contained value is always exactly
149/// of the property's value type (or one of the marker types
150/// [`UnsetValueType`] and [`DoNothingType`]).
151pub type BoxedValue = Rc<dyn AnyValue>;
152
153/// The type of the marker value that represents an unset property value.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub struct UnsetValueType;
156
157impl fmt::Display for UnsetValueType {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str("(unset)")
160    }
161}
162
163/// The type of the marker value that tells a binding target to do nothing.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct DoNothingType;
166
167impl fmt::Display for DoNothingType {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.write_str("(do nothing)")
170    }
171}
172
173/// A callback invoked before and after a property change notification is
174/// raised on an object (`true` before, `false` after).
175pub type NotifyingCallback = Box<dyn Fn(&FerroObject, bool)>;
176
177// Installed only by an explicit inheritance registration. The property owns
178// this capability; its metadata may be overridden without changing whether
179// the property inherits or which Rust value type its entries contain.
180pub(crate) type InheritedValueChanged = fn(
181    &dyn EffectiveValueDyn,
182    &FerroObject,
183    Option<&dyn EffectiveValueDyn>,
184    Option<&dyn EffectiveValueDyn>,
185);
186
187/// Only the payload copy depends on T. Keep implicit conversion lookup and
188/// the converted box's ownership in one cold implementation (the `TryConvert`
189/// of the property, see
190/// [`ValueTypes::try_convert_implicit`](crate::data::core::ValueTypes::try_convert_implicit)).
191pub(crate) fn convert_property_value<T: PropertyValue>(property: &FerroProperty, value: &dyn Any) -> Option<T> {
192    let mut typed = None::<T>;
193    copy_converted_property_value(property, value, &mut typed);
194    typed
195}
196
197/// The typed destination of an untyped value: `Option<T>`, which takes a copy of
198/// the payload when it is a `T`. The one typed operation of the untyped routes
199/// of a property (conversion, binding values, notifications), shared by all of
200/// them: one implementation per value type.
201pub(crate) trait PayloadSlot {
202    /// Stores a copy of `value` if it is of the type of the slot (and nothing
203    /// otherwise); whether it was.
204    fn copy_payload(&mut self, value: &dyn Any) -> bool;
205}
206
207impl<T: Clone + 'static> PayloadSlot for Option<T> {
208    fn copy_payload(&mut self, value: &dyn Any) -> bool {
209        *self = value.downcast_ref::<T>().cloned();
210        self.is_some()
211    }
212}
213
214/// The untyped destination of an untyped value: a box of its own, which takes
215/// a copy of the payload when it is of the property's value type. The slot of
216/// the type-erased binding observers, which keep their values boxed; the copy
217/// is the [`route_box_value`](PropertyRoutes::route_box_value) of the
218/// property.
219pub(crate) struct BoxedPayloadSlot {
220    routes: &'static dyn PropertyRoutes,
221    value: Option<BoxedValue>,
222}
223
224impl BoxedPayloadSlot {
225    #[inline]
226    pub(crate) fn new(property: &FerroProperty) -> Self {
227        Self { routes: property.routes(), value: None }
228    }
229
230    /// The copy of the payload, if there is one.
231    #[inline]
232    pub(crate) fn into_value(self) -> Option<BoxedValue> {
233        self.value
234    }
235}
236
237impl PayloadSlot for BoxedPayloadSlot {
238    fn copy_payload(&mut self, value: &dyn Any) -> bool {
239        self.value = self.routes.route_box_value(value);
240        self.value.is_some()
241    }
242}
243
244/// The value of `value` if it holds exactly a `T`: moved out of the box when
245/// no one else holds it, else a clone. The typed end of the type-erased
246/// binding observers, which hand a box they made themselves (the copy of a
247/// converted or notified value) without a second copy.
248pub(crate) fn take_boxed_value<T: PropertyValue>(value: BoxedValue) -> Option<T> {
249    let value: Rc<dyn Any> = value;
250    let value = value.downcast::<T>().ok()?;
251    Some(Rc::try_unwrap(value).unwrap_or_else(|value| T::clone(&value)))
252}
253
254/// The parts of `value` if it is a `BindingValue<T>`, with its value copied
255/// into a box of its own: the binding value case of an untyped binding, the
256/// one that names `T` (see
257/// [`route_unpack_binding_value`](PropertyRoutes::route_unpack_binding_value)).
258pub(crate) fn unpack_binding_value<T: PropertyValue>(value: &dyn Any) -> Option<BindingValue<BoxedValue>> {
259    let value = value.downcast_ref::<BindingValue<T>>()?;
260    let payload = value.has_value().then(|| Rc::new(value.value().clone()) as BoxedValue);
261    Some(BindingValue::from_notification_parts(value.value_type(), payload, value.error().cloned()))
262}
263
264#[inline(never)]
265pub(crate) fn copy_converted_property_value(
266    property: &FerroProperty,
267    value: &dyn Any,
268    copy_value: &mut dyn PayloadSlot,
269) -> bool {
270    let Some(converted) = crate::data::core::ValueTypes::try_convert_implicit(value, property.property_type()) else {
271        return false;
272    };
273    let copied = copy_value.copy_payload(converted.as_any());
274    // A converter's temporary may have an observable destructor. Release it
275    // before validation, coercion or publication; it also drops if Clone panics.
276    drop(converted);
277    copied
278}
279
280/// Untyped operations that a property routes to its typed implementation.
281pub(crate) trait PropertyRoutes {
282    fn create_effective_value(&'static self, o: &FerroObject) -> Rc<dyn EffectiveValueDyn>;
283    fn route_clear_value(&'static self, o: &FerroObject);
284    fn route_coerce_default_value(&'static self, o: &FerroObject);
285    fn route_get_value(&'static self, o: &FerroObject) -> BoxedValue;
286    fn route_get_base_value(&'static self, o: &FerroObject) -> BoxedValue;
287    fn route_get_default_value(&'static self, type_: &'static TypeInfo) -> BoxedValue;
288    fn route_set_value(&'static self, o: &FerroObject, value: &dyn Any, priority: BindingPriority)
289        -> Option<Rc<dyn IDisposable>>;
290    fn route_set_current_value(&'static self, o: &FerroObject, value: &dyn Any);
291    fn route_set_direct_value_unchecked(&'static self, o: &FerroObject, entry: &dyn IValueEntry);
292    fn route_bind(
293        &'static self,
294        o: &FerroObject,
295        source: Rc<dyn IObservable<BoxedValue>>,
296        priority: BindingPriority,
297    ) -> Rc<dyn IDisposable>;
298    fn route_get_metadata(&'static self, type_: &'static TypeInfo) -> FerroPropertyMetadata;
299    fn route_unregister(&'static self, type_: &'static TypeInfo);
300    fn route_is_valid_value(&'static self, value: &dyn Any) -> bool;
301    /// The typed property behind the routes, for downcasting.
302    fn as_any(&'static self) -> &'static dyn Any;
303    /// Clones `value`, which must hold exactly the property's value type `T`,
304    /// into `out`, which must be an `&mut Option<T>`. Returns false if either
305    /// has a different type.
306    fn route_copy_value(&'static self, value: &dyn Any, out: &mut dyn Any) -> bool;
307    /// Clones `value`, which must hold exactly the property's value type `T`,
308    /// into a box of its own. `None` if it has a different type.
309    fn route_box_value(&'static self, value: &dyn Any) -> Option<BoxedValue>;
310    /// Whether the metadata of the property for the type of `owner` enables
311    /// data validation; read without copying the metadata. The binding
312    /// observers of untyped sources read it once, when they are created.
313    fn route_enable_data_validation(&'static self, owner: &FerroObject) -> Option<bool>;
314    /// The parts of `value` if it is a `BindingValue<T>` of the property's
315    /// value type `T`, with the value in a box of its own; `None` if it is not.
316    fn route_unpack_binding_value(&'static self, value: &dyn Any) -> Option<BindingValue<BoxedValue>>;
317    /// Sets the local value of a styled property from a box that holds exactly
318    /// the property's value type: the typed `set_local_value` of the store,
319    /// for an untyped local binding. Only supported by styled properties.
320    fn route_set_local_value(&'static self, _o: &FerroObject, _value: BoxedValue) {
321        panic!("not supported for direct properties");
322    }
323    /// Sets a direct property from an untyped binding value whose value, if
324    /// any, holds exactly the property's value type: the typed
325    /// `set_direct_value_unchecked` of an untyped direct binding. Only
326    /// supported by direct properties.
327    fn route_set_direct_binding_value(&'static self, _o: &FerroObject, _value: BindingValue<BoxedValue>) {
328        panic!("not supported for styled properties");
329    }
330}
331
332type ChangedHandler = dyn Fn(&FerroPropertyChangedEventArgs<'_>);
333
334/// The stream of change notifications of a property across all objects.
335pub struct PropertyChangedObservable {
336    handlers: HandlerList<ChangedHandler>,
337}
338
339impl PropertyChangedObservable {
340    fn new() -> Self {
341        Self { handlers: HandlerList::new() }
342    }
343
344    /// Subscribes to changes of the property on any object.
345    ///
346    /// Dropping the returned guard removes the handler; call
347    /// [`detach`](Subscription::detach) to keep it for the life of the
348    /// property.
349    pub fn subscribe(&'static self, handler: impl Fn(&FerroPropertyChangedEventArgs<'_>) + 'static) -> Subscription {
350        let token = self.handlers.add(Rc::new(handler));
351        Subscription::new(Disposable::create(move || {
352            self.handlers.remove(token);
353        }))
354    }
355
356    /// Subscribes a handler that is only invoked for objects of class
357    /// `TTarget` (or classes derived from it).
358    ///
359    /// Dropping the returned guard removes the handler; call
360    /// [`detach`](Subscription::detach) to keep it for the life of the
361    /// property, as a class handler registered once for its class does.
362    pub fn add_class_handler<TTarget: ObjectType>(
363        &'static self,
364        handler: impl Fn(&TTarget, &FerroPropertyChangedEventArgs<'_>) + 'static,
365    ) -> Subscription {
366        self.subscribe(move |e| {
367            if let Some(target) = e.sender().downcast_ref::<TTarget>() {
368                handler(target, e);
369            }
370        })
371    }
372
373    #[inline]
374    pub(crate) fn notify(&self, e: &FerroPropertyChangedEventArgs<'_>) {
375        if self.handlers.is_empty() {
376            return;
377        }
378        crate::perf_count!(PropertyChangesWithPropertyHandlers);
379        for (_, handler) in self.handlers.snapshot().iter() {
380            handler(e);
381        }
382    }
383}
384
385static NEXT_ID: AtomicU32 = AtomicU32::new(0);
386
387/// Base class for properties: the untyped identity and description of a
388/// property that can be set on a [`FerroObject`].
389pub struct FerroProperty {
390    name: Box<str>,
391    property_type: TypeId,
392    property_type_name: &'static str,
393    owner_type: &'static TypeInfo,
394    id: u32,
395    inherits: bool,
396    inherited_value_changed: Cell<Option<InheritedValueChanged>>,
397    /// The value stores that hold an effective value of the property, when it inherits: while
398    /// none does, every element inherits its default, and a lookup need not walk the ancestors.
399    /// An addition (FerroUI deviation, desktop-performance.md section 9.21). Shared with the
400    /// properties added to other owners: they are the same property.
401    holders: Rc<Cell<u32>>,
402    is_attached: bool,
403    is_direct: bool,
404    is_read_only: bool,
405    assign_binding: Cell<bool>,
406    host_type: Cell<Option<&'static TypeInfo>>,
407    notifying: Option<Rc<dyn Fn(&FerroObject, bool)>>,
408    changed: Rc<PropertyChangedObservable>,
409    routes: OnceCell<&'static dyn PropertyRoutes>,
410}
411
412pub(crate) struct FerroPropertyInit {
413    pub inherits: bool,
414    pub is_attached: bool,
415    pub is_direct: bool,
416    pub is_read_only: bool,
417}
418
419impl FerroProperty {
420    pub(crate) fn new<T: 'static>(
421        name: &str,
422        owner_type: &'static TypeInfo,
423        init: FerroPropertyInit,
424        notifying: Option<NotifyingCallback>,
425    ) -> Self {
426        Self::new_core(name, owner_type, init, notifying, TypeId::of::<T>(), std::any::type_name::<T>())
427    }
428
429    // Identity, allocation and notification setup are independent of the value
430    // type. Keep one copy while preserving the original typed property facade.
431    #[inline(never)]
432    fn new_core(
433        name: &str,
434        owner_type: &'static TypeInfo,
435        init: FerroPropertyInit,
436        notifying: Option<NotifyingCallback>,
437        property_type: TypeId,
438        property_type_name: &'static str,
439    ) -> Self {
440        assert!(!name.contains('.'), "'name' may not contain periods.");
441        Self {
442            name: name.into(),
443            property_type,
444            property_type_name,
445            owner_type,
446            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
447            inherits: init.inherits,
448            inherited_value_changed: Cell::new(None),
449            holders: Rc::new(Cell::new(0)),
450            is_attached: init.is_attached,
451            is_direct: init.is_direct,
452            is_read_only: init.is_read_only,
453            assign_binding: Cell::new(false),
454            host_type: Cell::new(None),
455            notifying: notifying.map(Rc::from),
456            changed: Rc::new(PropertyChangedObservable::new()),
457            routes: OnceCell::new(),
458        }
459    }
460
461    /// Creates the base of a property that shares its identity with `source`
462    /// but has a different owner.
463    pub(crate) fn for_added_owner(source: &FerroProperty, owner_type: &'static TypeInfo, is_read_only: bool) -> Self {
464        Self {
465            name: source.name.clone(),
466            property_type: source.property_type,
467            property_type_name: source.property_type_name,
468            owner_type,
469            id: source.id,
470            inherits: source.inherits,
471            inherited_value_changed: source.inherited_value_changed.clone(),
472            holders: source.holders.clone(),
473            is_attached: source.is_attached,
474            is_direct: source.is_direct,
475            is_read_only,
476            assign_binding: source.assign_binding.clone(),
477            host_type: source.host_type.clone(),
478            notifying: source.notifying.clone(),
479            changed: source.changed.clone(),
480            routes: OnceCell::new(),
481        }
482    }
483
484    pub(crate) fn set_routes(&self, routes: &'static dyn PropertyRoutes) {
485        if self.routes.set(routes).is_err() {
486            panic!("property routes are already set");
487        }
488    }
489
490    // Registration fills this after construction and before exposing the
491    // property through the registry. Private inheriting constructors must do
492    // the same explicitly; a universal typed constructor must not name the
493    // algorithm and thereby retain it for non-inheriting value types.
494    pub(crate) fn set_inherited_value_changed(&self, callback: Option<InheritedValueChanged>) {
495        debug_assert_eq!(self.inherits, callback.is_some());
496        debug_assert!(self.inherited_value_changed.get().is_none());
497        self.inherited_value_changed.set(callback);
498    }
499
500    pub(crate) fn inherited_value_changed(&self) -> InheritedValueChanged {
501        self.inherited_value_changed.get().expect("inheriting property has no change notifier")
502    }
503
504    #[inline]
505    pub(crate) fn routes(&self) -> &'static dyn PropertyRoutes {
506        *self.routes.get().expect("property is not fully registered")
507    }
508
509    /// The class an attached property is declared for: the `THost` of its
510    /// registration, the type of the objects its accessors (`GetX`/`SetX`)
511    /// take. `None` for properties that are not attached.
512    #[inline]
513    pub fn host_type(&self) -> Option<&'static TypeInfo> {
514        self.host_type.get()
515    }
516
517    /// The name of the property.
518    #[inline]
519    pub fn name(&self) -> &str {
520        &self.name
521    }
522
523    /// The type of the property's value.
524    #[inline]
525    pub fn property_type(&self) -> TypeId {
526        self.property_type
527    }
528
529    /// The Rust type name of the property's value type.
530    #[inline]
531    pub fn property_type_name(&self) -> &'static str {
532        self.property_type_name
533    }
534
535    // The errors of the typed property routes. They only depend on the
536    // property, so they are compiled once instead of once per value type.
537
538    /// The message of a value that is not of the value type of the property.
539    #[cold]
540    pub(crate) fn invalid_value_message(&self) -> String {
541        format!("Invalid value for property '{}': expected {}.", self.name(), self.property_type_name())
542    }
543
544    /// Panics for a value that is not of the value type of the property.
545    #[cold]
546    #[track_caller]
547    pub(crate) fn invalid_value_type(&self) -> ! {
548        panic!("Invalid value for property '{}': expected {}.", self.name(), self.property_type_name())
549    }
550
551    /// Panics for a value that the validation of the property rejects.
552    #[cold]
553    #[track_caller]
554    pub(crate) fn value_not_valid(&self) -> ! {
555        panic!("the value is not valid for property '{}'", self.name())
556    }
557
558    /// The class that registered the property.
559    #[inline]
560    pub fn owner_type(&self) -> &'static TypeInfo {
561        self.owner_type
562    }
563
564    /// Whether the property inherits its value.
565    #[inline]
566    pub fn inherits(&self) -> bool {
567        self.inherits
568    }
569
570    /// The value stores that hold an effective value of the property (inheriting properties).
571    pub(crate) fn holders(&self) -> u32 {
572        self.holders.get()
573    }
574
575    pub(crate) fn add_holder(&self) {
576        self.holders.set(self.holders.get() + 1);
577    }
578
579    pub(crate) fn remove_holder(&self) {
580        self.holders.set(self.holders.get().saturating_sub(1));
581    }
582
583    /// Whether this is an attached property.
584    #[inline]
585    pub fn is_attached(&self) -> bool {
586        self.is_attached
587    }
588
589    /// Whether this is a direct property.
590    #[inline]
591    pub fn is_direct(&self) -> bool {
592        self.is_direct
593    }
594
595    /// Whether this is a readonly property.
596    #[inline]
597    pub fn is_read_only(&self) -> bool {
598        self.is_read_only
599    }
600
601    /// Whether a binding given for this property in markup is assigned to
602    /// the property as its value rather than bound to it (the "assign
603    /// binding" attribute of the managed property). The property's value
604    /// type is then a binding type. A fact about the definition: it is the
605    /// same for every owner and is not part of the metadata.
606    #[inline]
607    pub fn assign_binding(&self) -> bool {
608        self.assign_binding.get()
609    }
610
611    /// Marks the property as one that bindings are assigned to. Part of the
612    /// definition of the property: call it where the property is registered
613    /// (styled and attached properties state it through
614    /// [`StyledPropertyOptions::assign_binding`]).
615    pub fn set_assign_binding(&self, value: bool) {
616        self.assign_binding.set(value);
617    }
618
619    /// An integer ID that uniquely identifies the property; shared by all
620    /// owners added with `add_owner`.
621    #[inline]
622    pub fn id(&self) -> u32 {
623        self.id
624    }
625
626    /// Notifications of changes to this property on any object.
627    ///
628    /// The handlers are invoked after the object's own change handling.
629    #[inline]
630    pub fn changed(&'static self) -> &'static PropertyChangedObservable {
631        // The observable is shared between a property and its added owners.
632        &self.changed
633    }
634
635    #[inline]
636    pub(crate) fn notify_changed(&self, e: &FerroPropertyChangedEventArgs<'_>) {
637        self.changed.notify(e)
638    }
639
640    #[inline]
641    pub(crate) fn notifying(&self) -> Option<&dyn Fn(&FerroObject, bool)> {
642        self.notifying.as_deref()
643    }
644
645    /// Gets the base metadata of the property on the specified type.
646    pub fn get_metadata(&self, type_: &'static TypeInfo) -> FerroPropertyMetadata {
647        self.routes().route_get_metadata(type_)
648    }
649
650    /// Gets the base metadata of the property on the type of `owner`.
651    pub fn get_metadata_for(&self, owner: &FerroObject) -> FerroPropertyMetadata {
652        self.routes().route_get_metadata(owner.get_type())
653    }
654
655    /// The default value of the property for `type_`, untyped: the default of
656    /// the metadata of a styled or attached property (upstream's internal
657    /// `IStyledPropertyAccessor.GetDefaultValue(Type)`), the unset value of a
658    /// direct property. For tests only: the snapshot of the property defaults
659    /// (`property_defaults_tests` of `ferroui-controls`) reads it.
660    #[cfg(feature = "testing")]
661    #[doc(hidden)]
662    pub fn default_value_boxed(&self, type_: &'static TypeInfo) -> BoxedValue {
663        self.routes().route_get_default_value(type_)
664    }
665
666    /// Removes the metadata registered for the property on the specified
667    /// type.
668    pub fn unregister(&self, type_: &'static TypeInfo) {
669        self.routes().route_unregister(type_)
670    }
671
672    /// Checks whether `value` is valid for the property: of the property's
673    /// value type and accepted by its validation callback.
674    pub fn is_valid_value(&self, value: &dyn Any) -> bool {
675        self.routes().route_is_valid_value(value)
676    }
677
678    /// The property as a styled (or attached) property with value type `T`:
679    /// the typed view needed to read, set and bind it without boxing.
680    /// `None` for direct properties and when `T` is not the property's value
681    /// type.
682    pub fn as_styled<T: crate::PropertyValue>(&'static self) -> Option<&'static StyledProperty<T>> {
683        self.routes.get().and_then(|routes| routes.as_any().downcast_ref::<StyledProperty<T>>())
684    }
685
686    /// The marker value that represents an unset property value.
687    pub fn unset_value() -> BoxedValue {
688        crate::ferro_thread_local! {
689            static UNSET: BoxedValue = Rc::new(UnsetValueType);
690        }
691        UNSET.with(Rc::clone)
692    }
693
694    /// Registers a styled property with a default value.
695    pub fn register<TOwner: ObjectType, TValue: PropertyValue>(
696        name: &str,
697        default_value: TValue,
698    ) -> &'static StyledProperty<TValue> {
699        Self::register_with::<TOwner, TValue>(name, StyledPropertyOptions::new(default_value))
700    }
701
702    /// Registers a styled property.
703    #[inline]
704    pub fn register_with<TOwner: ObjectType, TValue: PropertyValue>(
705        name: &str,
706        options: StyledPropertyOptions<TValue>,
707    ) -> &'static StyledProperty<TValue> {
708        Self::register_with_core(TOwner::TYPE, name, options)
709    }
710
711    // Ownership is descriptor data. Only the value's metadata, validation and
712    // coercion specialize this installation path; every owner of that value
713    // type shares it without changing the typed read/write implementation.
714    #[inline(never)]
715    fn register_with_core<TValue: PropertyValue>(
716        owner_type: &'static TypeInfo,
717        name: &str,
718        options: StyledPropertyOptions<TValue>,
719    ) -> &'static StyledProperty<TValue> {
720        let assign_binding = options.assign_binding;
721        let inherited_value_changed = options.inherited_value_changed;
722        let (metadata, inherits, validate, notifying) = options.into_parts();
723        let result = StyledProperty::create(name, owner_type, owner_type, metadata, inherits, validate, notifying, false);
724        result.set_inherited_value_changed(inherited_value_changed);
725        result.set_assign_binding(assign_binding);
726        FerroPropertyRegistry::instance().register(owner_type, result);
727        result
728    }
729
730    /// Registers an attached property with a default value.
731    ///
732    /// `TOwner` is the class that registers the property and `THost` the class
733    /// of objects the property can be set on.
734    pub fn register_attached<TOwner: StaticType, THost: ObjectType, TValue: PropertyValue>(
735        name: &str,
736        default_value: TValue,
737    ) -> &'static AttachedProperty<TValue> {
738        Self::register_attached_with::<TOwner, THost, TValue>(name, StyledPropertyOptions::new(default_value))
739    }
740
741    /// Registers an attached property.
742    #[inline]
743    pub fn register_attached_with<TOwner: StaticType, THost: ObjectType, TValue: PropertyValue>(
744        name: &str,
745        options: StyledPropertyOptions<TValue>,
746    ) -> &'static AttachedProperty<TValue> {
747        Self::register_attached_with_core(TOwner::TYPE, THost::TYPE, name, options)
748    }
749
750    #[inline(never)]
751    fn register_attached_with_core<TValue: PropertyValue>(
752        owner_type: &'static TypeInfo,
753        host_type: &'static TypeInfo,
754        name: &str,
755        options: StyledPropertyOptions<TValue>,
756    ) -> &'static AttachedProperty<TValue> {
757        let assign_binding = options.assign_binding;
758        let inherited_value_changed = options.inherited_value_changed;
759        let (metadata, inherits, validate, notifying) = options.into_parts();
760        let result = AttachedProperty::create(name, owner_type, host_type, metadata, inherits, validate, notifying);
761        result.set_inherited_value_changed(inherited_value_changed);
762        result.set_assign_binding(assign_binding);
763        result.host_type.set(Some(host_type));
764        let registry = FerroPropertyRegistry::instance();
765        registry.register(owner_type, result);
766        registry.register_attached(host_type, result);
767        result
768    }
769
770    /// Registers a direct property: a property whose value is stored in a
771    /// field of the owner and accessed through a getter and setter.
772    pub fn register_direct<TOwner: ObjectType, TValue: PropertyValue>(
773        name: &str,
774        getter: fn(&TOwner) -> TValue,
775        setter: Option<fn(&TOwner, TValue)>,
776        unset_value: TValue,
777    ) -> &'static DirectProperty<TOwner, TValue> {
778        Self::register_direct_with(name, getter, setter, DirectPropertyMetadata::new(Some(unset_value)))
779    }
780
781    /// Registers a direct property with explicit metadata.
782    pub fn register_direct_with<TOwner: ObjectType, TValue: PropertyValue>(
783        name: &str,
784        getter: fn(&TOwner) -> TValue,
785        setter: Option<fn(&TOwner, TValue)>,
786        metadata: DirectPropertyMetadata<TValue>,
787    ) -> &'static DirectProperty<TOwner, TValue> {
788        let result = DirectProperty::create(name, getter, setter, metadata);
789        FerroPropertyRegistry::instance().register(TOwner::TYPE, result);
790        result
791    }
792}
793
794impl PartialEq for FerroProperty {
795    #[inline]
796    fn eq(&self, other: &Self) -> bool {
797        self.id == other.id
798    }
799}
800
801impl Eq for FerroProperty {}
802
803impl Hash for FerroProperty {
804    fn hash<H: Hasher>(&self, state: &mut H) {
805        self.id.hash(state)
806    }
807}
808
809impl fmt::Debug for FerroProperty {
810    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
811        f.write_str(&self.name)
812    }
813}
814
815impl fmt::Display for FerroProperty {
816    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
817        f.write_str(&self.name)
818    }
819}
820
821/// Options for registering a styled or attached property.
822pub struct StyledPropertyOptions<T> {
823    default_value: T,
824    inherits: bool,
825    inherited_value_changed: Option<InheritedValueChanged>,
826    default_binding_mode: BindingMode,
827    validate: Option<Box<dyn Fn(&T) -> bool>>,
828    coerce: Option<Coercion<T>>,
829    enable_data_validation: bool,
830    assign_binding: bool,
831    notifying: Option<NotifyingCallback>,
832}
833
834impl<T: PropertyValue> StyledPropertyOptions<T> {
835    pub fn new(default_value: T) -> Self {
836        Self {
837            default_value,
838            inherits: false,
839            inherited_value_changed: None,
840            default_binding_mode: BindingMode::OneWay,
841            validate: None,
842            coerce: None,
843            enable_data_validation: false,
844            assign_binding: false,
845            notifying: None,
846        }
847    }
848
849    /// Whether the property inherits its value from the parent object.
850    pub fn inherits(mut self, inherits: bool) -> Self {
851        self.inherits = inherits;
852        self.inherited_value_changed = if inherits {
853            Some(EffectiveValue::<T>::notify_inherited_value_changed)
854        } else {
855            None
856        };
857        self
858    }
859
860    /// The default binding mode for the property.
861    pub fn default_binding_mode(mut self, mode: BindingMode) -> Self {
862        self.default_binding_mode = mode;
863        self
864    }
865
866    /// A value validation callback. Setting a value for which it returns
867    /// false is rejected.
868    pub fn validate(mut self, validate: impl Fn(&T) -> bool + 'static) -> Self {
869        self.validate = Some(Box::new(validate));
870        self
871    }
872
873    /// A value coercion callback.
874    pub fn coerce(mut self, coerce: impl Fn(&FerroObject, T) -> T + 'static) -> Self {
875        self.coerce = Some(Coercion::new(Rc::new(coerce)));
876        self
877    }
878
879    /// Whether the property is interested in data validation.
880    pub fn enable_data_validation(mut self, enable: bool) -> Self {
881        self.enable_data_validation = enable;
882        self
883    }
884
885    /// Whether a binding given for the property in markup is assigned to the
886    /// property instead of bound to it; see [`FerroProperty::assign_binding`].
887    pub fn assign_binding(mut self, assign_binding: bool) -> Self {
888        self.assign_binding = assign_binding;
889        self
890    }
891
892    /// A callback invoked before and after change notifications are raised.
893    pub fn notifying(mut self, notifying: impl Fn(&FerroObject, bool) + 'static) -> Self {
894        self.notifying = Some(Box::new(notifying));
895        self
896    }
897
898    #[allow(clippy::type_complexity)]
899    fn into_parts(self) -> (StyledPropertyMetadata<T>, bool, Option<Box<dyn Fn(&T) -> bool>>, Option<NotifyingCallback>) {
900        let mut metadata = StyledPropertyMetadata::new(Some(self.default_value))
901            .with_default_binding_mode(self.default_binding_mode)
902            .with_enable_data_validation(self.enable_data_validation);
903        if let Some(coerce) = self.coerce {
904            // Transfer the already registered callback and algorithm. Naming
905            // the algorithm here would root it for every options value type,
906            // including properties that never supplied a coercer.
907            metadata = metadata.with_registered_coercion(coerce);
908        }
909        (metadata, self.inherits, self.validate, self.notifying)
910    }
911}
912
913#[cfg(test)]
914mod styled_property_options_tests {
915    use super::*;
916
917    #[test]
918    fn registration_transfers_the_original_coercer() {
919        let options = StyledPropertyOptions::new(0_i32).coerce(|_, n| n.max(0));
920        let registered = options.coerce.as_ref().unwrap().callback().clone();
921        let (metadata, _, _, _) = options.into_parts();
922        assert!(Rc::ptr_eq(&registered, metadata.coerce_value().unwrap()));
923    }
924}
925
926/// Records the accessor `$name` of `$owner` returning `$property`
927/// (`metadata::record_property_accessor`) with the `compiler-metadata`
928/// feature of this crate; expands to nothing without it.
929#[cfg(feature = "compiler-metadata")]
930#[doc(hidden)]
931#[macro_export]
932macro_rules! __record_property_accessor {
933    ($owner:ident, $vis:vis, $name:ident, $property:expr) => {
934        $crate::metadata::record_property_accessor(
935            <$owner as $crate::StaticType>::TYPE,
936            ::std::any::TypeId::of::<Self>(),
937            ::std::stringify!($name),
938            ::std::stringify!($vis),
939            $crate::Registrable::as_registered_property($property),
940        )
941    };
942}
943
944/// Records the accessor `$name` of `$owner` returning `$property` with the
945/// `compiler-metadata` feature of this crate; expands to nothing without it.
946#[cfg(not(feature = "compiler-metadata"))]
947#[doc(hidden)]
948#[macro_export]
949macro_rules! __record_property_accessor {
950    ($owner:ident, $vis:vis, $name:ident, $property:expr) => {};
951}
952
953/// Declares the accessor of a single property definition.
954///
955/// ```ignore
956/// impl Border {
957///     ferro_property!(pub fn background_property() -> StyledProperty<Option<Ref<Brush>>> {
958///         FerroProperty::register::<Border, _>("Background", None)
959///     });
960/// }
961/// ```
962///
963/// The property is registered the first time the accessor is called on a
964/// thread. Property definitions, like the objects that use them, belong to
965/// the thread that created them.
966///
967/// On its own the macro registers nothing until the accessor is called, so a
968/// lookup by name can miss the property. Declare the properties of a type in
969/// a [`ferro_properties!`] block instead, which also registers them when the
970/// type is initialised.
971///
972/// Where an accessor cannot be written inside the block (it is generated by
973/// a local macro, or declared between other items), name the type whose
974/// initialisation it belongs to and list it in the block of that type:
975///
976/// ```ignore
977/// ferro_property!(for XYFocus; pub fn left_property() -> AttachedProperty<..> { .. });
978///
979/// ferro_properties! { impl XYFocus, also [XYFocus::left_property] {} }
980/// ```
981#[macro_export]
982macro_rules! ferro_property {
983    // An accessor that belongs to the static initialisation of `$owner`: the
984    // first call on a thread first initialises the owner (as reading a
985    // static field of a class runs its static initialisation), which
986    // registers the properties of the owner in declaration order, this one
987    // included.
988    (for $owner:ident; $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block) => {
989        $(#[$meta])*
990        #[inline]
991        $vis fn $name() -> &'static $ty {
992            $crate::ferro_thread_local! {
993                static CELL: ::std::cell::Cell<::std::option::Option<&'static $ty>> =
994                    const { ::std::cell::Cell::new(::std::option::Option::None) };
995            }
996            match CELL.get() {
997                ::std::option::Option::Some(property) => property,
998                ::std::option::Option::None => {
999                    <$owner as $crate::StaticType>::TYPE.ensure_class_init();
1000                    match CELL.get() {
1001                        ::std::option::Option::Some(property) => property,
1002                        // Reached while the owner is being initialised (this
1003                        // is the registration in declaration order), or for
1004                        // an owner whose runtime type has no initialisation.
1005                        ::std::option::Option::None => {
1006                            let property: &'static $ty = $body;
1007                            CELL.set(::std::option::Option::Some(property));
1008                            $crate::__register_value_markup!(property);
1009                            $crate::__record_property_accessor!($owner, $vis, $name, property);
1010                            property
1011                        }
1012                    }
1013                }
1014            }
1015        }
1016    };
1017
1018    ($(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block) => {
1019        $(#[$meta])*
1020        #[inline]
1021        $vis fn $name() -> &'static $ty {
1022            $crate::ferro_thread_local! {
1023                static CELL: ::std::cell::Cell<::std::option::Option<&'static $ty>> =
1024                    const { ::std::cell::Cell::new(::std::option::Option::None) };
1025            }
1026            match CELL.get() {
1027                ::std::option::Option::Some(property) => property,
1028                ::std::option::Option::None => {
1029                    let property: &'static $ty = $body;
1030                    CELL.set(::std::option::Option::Some(property));
1031                    $crate::__register_value_markup!(property);
1032                    property
1033                }
1034            }
1035        }
1036    };
1037}
1038
1039/// Registers the markup metadata of the value type of a property that is registered
1040/// ([`MarkupType::register_used`](crate::metadata::MarkupType::register_used)), when the value
1041/// type has metadata ([`MarkupTyped`](crate::metadata::MarkupTyped)); nothing otherwise. The
1042/// choice is made where the property is declared, by the method a reference to a reference to
1043/// the probe resolves to: the implementation for a value type with metadata (on `&Probe`) takes
1044/// that receiver as it is and is found first; the one of every type (on `Probe`) is found after
1045/// one dereference.
1046///
1047/// In the same way it makes the value type a used type of the untyped value conversions
1048/// ([`ValueTypes::register_used`](crate::data::core::ValueTypes::register_used)) when the type
1049/// (`T`, `Option<T>`, `Rc<T>`, `Option<Rc<T>>`) has registrations
1050/// ([`ValueTypeRegistration`](crate::data::core::ValueTypeRegistration), #566): its nullable
1051/// form and its casts are registered with its first property.
1052#[doc(hidden)]
1053#[macro_export]
1054macro_rules! __register_value_markup {
1055    ($property:expr) => {{
1056        #[allow(unused_imports)]
1057        use $crate::{__NoPropertyValueType as _, __NoValueMarkup as _, __RegisterPropertyValueType as _, __RegisterValueMarkup as _};
1058        let probe = $crate::__ValueMarkupProbe($property);
1059        (&&probe).__register_value_markup();
1060        (&&probe).__register_property_value_type();
1061    }};
1062}
1063
1064#[doc(hidden)]
1065pub struct __ValueMarkupProbe<'a, P: ?Sized>(pub &'a P);
1066
1067#[doc(hidden)]
1068pub trait __RegisterValueMarkup {
1069    fn __register_value_markup(&self);
1070}
1071
1072impl<T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1073    for &__ValueMarkupProbe<'_, crate::StyledProperty<T>>
1074{
1075    #[inline(always)]
1076    fn __register_value_markup(&self) {
1077        crate::metadata::MarkupType::register_used(T::MARKUP);
1078    }
1079}
1080
1081impl<T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1082    for &__ValueMarkupProbe<'_, crate::AttachedProperty<T>>
1083{
1084    #[inline(always)]
1085    fn __register_value_markup(&self) {
1086        crate::metadata::MarkupType::register_used(T::MARKUP);
1087    }
1088}
1089
1090impl<O: crate::ObjectType, T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1091    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, T>>
1092{
1093    #[inline(always)]
1094    fn __register_value_markup(&self) {
1095        crate::metadata::MarkupType::register_used(T::MARKUP);
1096    }
1097}
1098
1099// A nullable value type (`Option<T>`) is found by its metadata too (the nullable form of the type).
1100impl<T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1101    for &__ValueMarkupProbe<'_, crate::StyledProperty<Option<T>>>
1102{
1103    #[inline(always)]
1104    fn __register_value_markup(&self) {
1105        crate::metadata::MarkupType::register_used(T::MARKUP);
1106    }
1107}
1108
1109impl<T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1110    for &__ValueMarkupProbe<'_, crate::AttachedProperty<Option<T>>>
1111{
1112    #[inline(always)]
1113    fn __register_value_markup(&self) {
1114        crate::metadata::MarkupType::register_used(T::MARKUP);
1115    }
1116}
1117
1118impl<O: crate::ObjectType, T: PropertyValue + crate::metadata::MarkupTyped> __RegisterValueMarkup
1119    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, Option<T>>>
1120{
1121    #[inline(always)]
1122    fn __register_value_markup(&self) {
1123        crate::metadata::MarkupType::register_used(T::MARKUP);
1124    }
1125}
1126
1127#[doc(hidden)]
1128pub trait __NoValueMarkup {
1129    #[inline(always)]
1130    fn __register_value_markup(&self) {}
1131}
1132
1133impl<P: ?Sized> __NoValueMarkup for __ValueMarkupProbe<'_, P> {}
1134
1135/// The registration of the value type of a property with the untyped value conversions
1136/// ([`__register_value_markup!`](crate::__register_value_markup)): for a property of `T`,
1137/// `Option<T>`, `Rc<T>` or `Option<Rc<T>>` of a type `T` with registrations.
1138#[doc(hidden)]
1139pub trait __RegisterPropertyValueType {
1140    fn __register_property_value_type(&self);
1141}
1142
1143impl<T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1144    for &__ValueMarkupProbe<'_, crate::StyledProperty<T>>
1145{
1146    #[inline(always)]
1147    fn __register_property_value_type(&self) {
1148        crate::data::core::ValueTypes::register_used::<T>();
1149    }
1150}
1151
1152impl<T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1153    for &__ValueMarkupProbe<'_, crate::StyledProperty<Option<T>>>
1154{
1155    #[inline(always)]
1156    fn __register_property_value_type(&self) {
1157        crate::data::core::ValueTypes::register_used::<T>();
1158    }
1159}
1160
1161impl<T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1162    for &__ValueMarkupProbe<'_, crate::StyledProperty<Rc<T>>>
1163where
1164    Rc<T>: PropertyValue,
1165{
1166    #[inline(always)]
1167    fn __register_property_value_type(&self) {
1168        crate::data::core::ValueTypes::register_used::<T>();
1169    }
1170}
1171
1172impl<T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1173    for &__ValueMarkupProbe<'_, crate::StyledProperty<Option<Rc<T>>>>
1174where
1175    Rc<T>: PropertyValue,
1176{
1177    #[inline(always)]
1178    fn __register_property_value_type(&self) {
1179        crate::data::core::ValueTypes::register_used::<T>();
1180    }
1181}
1182
1183impl<T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1184    for &__ValueMarkupProbe<'_, crate::AttachedProperty<T>>
1185{
1186    #[inline(always)]
1187    fn __register_property_value_type(&self) {
1188        crate::data::core::ValueTypes::register_used::<T>();
1189    }
1190}
1191
1192impl<T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1193    for &__ValueMarkupProbe<'_, crate::AttachedProperty<Option<T>>>
1194{
1195    #[inline(always)]
1196    fn __register_property_value_type(&self) {
1197        crate::data::core::ValueTypes::register_used::<T>();
1198    }
1199}
1200
1201impl<T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1202    for &__ValueMarkupProbe<'_, crate::AttachedProperty<Rc<T>>>
1203where
1204    Rc<T>: PropertyValue,
1205{
1206    #[inline(always)]
1207    fn __register_property_value_type(&self) {
1208        crate::data::core::ValueTypes::register_used::<T>();
1209    }
1210}
1211
1212impl<T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1213    for &__ValueMarkupProbe<'_, crate::AttachedProperty<Option<Rc<T>>>>
1214where
1215    Rc<T>: PropertyValue,
1216{
1217    #[inline(always)]
1218    fn __register_property_value_type(&self) {
1219        crate::data::core::ValueTypes::register_used::<T>();
1220    }
1221}
1222
1223impl<O: crate::ObjectType, T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1224    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, T>>
1225{
1226    #[inline(always)]
1227    fn __register_property_value_type(&self) {
1228        crate::data::core::ValueTypes::register_used::<T>();
1229    }
1230}
1231
1232impl<O: crate::ObjectType, T: PropertyValue + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1233    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, Option<T>>>
1234{
1235    #[inline(always)]
1236    fn __register_property_value_type(&self) {
1237        crate::data::core::ValueTypes::register_used::<T>();
1238    }
1239}
1240
1241impl<O: crate::ObjectType, T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1242    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, Rc<T>>>
1243where
1244    Rc<T>: PropertyValue,
1245{
1246    #[inline(always)]
1247    fn __register_property_value_type(&self) {
1248        crate::data::core::ValueTypes::register_used::<T>();
1249    }
1250}
1251
1252impl<O: crate::ObjectType, T: ?Sized + crate::data::core::ValueTypeRegistration> __RegisterPropertyValueType
1253    for &__ValueMarkupProbe<'_, crate::DirectProperty<O, Option<Rc<T>>>>
1254where
1255    Rc<T>: PropertyValue,
1256{
1257    #[inline(always)]
1258    fn __register_property_value_type(&self) {
1259        crate::data::core::ValueTypes::register_used::<T>();
1260    }
1261}
1262
1263#[doc(hidden)]
1264pub trait __NoPropertyValueType {
1265    #[inline(always)]
1266    fn __register_property_value_type(&self) {}
1267}
1268
1269impl<P: ?Sized> __NoPropertyValueType for __ValueMarkupProbe<'_, P> {}
1270
1271/// Declares the property definitions of a type: the accessors, as
1272/// [`ferro_property!`] declares them one by one, and their registration as
1273/// part of the static initialisation of the type.
1274///
1275/// ```ignore
1276/// ferro_properties! {
1277///     impl Border {
1278///         /// Defines the `Background` property.
1279///         pub fn background_property() -> StyledProperty<Option<Ref<Brush>>> {
1280///             FerroProperty::register::<Border, _>("Background", None)
1281///         }
1282///
1283///         /// Defines the `Child` property (declared by another class).
1284///         pub fn child_property() -> StyledProperty<Option<Ref<Control>>> {
1285///             Decorator::child_property().add_owner::<Border>()
1286///         }
1287///     }
1288/// }
1289/// ```
1290///
1291/// All the properties are registered, in declaration order (the order of the
1292/// static field initialisers of the managed class), when the type is
1293/// initialised on a thread: when the first instance of the class or of a
1294/// class deriving from it is created, when one of the accessors is first
1295/// called, or when the property registry is asked about the type, whichever
1296/// comes first. A lookup by name therefore finds every property, whether or
1297/// not its accessor was called and whether or not an instance exists. After
1298/// that an accessor is a thread-local read, exactly as with
1299/// [`ferro_property!`].
1300///
1301/// The owner is a class ([`ferro_class!`](crate::ferro_class)) or a type
1302/// declared with [`ferro_static_type!`](crate::ferro_static_type).
1303///
1304/// Existing `ferro_property!(..);` invocations can be wrapped in the block
1305/// unchanged:
1306///
1307/// ```ignore
1308/// ferro_properties! { impl Border {
1309///     ferro_property!(pub fn background_property() -> StyledProperty<Option<Ref<Brush>>> {
1310///         FerroProperty::register::<Border, _>("Background", None)
1311///     });
1312/// } }
1313/// ```
1314///
1315/// A type has one such block. Properties of the type that are declared
1316/// elsewhere are named by it: `impl Owner, also [path, ..] { .. }` registers
1317/// the properties of the block first and then calls the listed functions in
1318/// order. A listed function is either
1319///
1320/// * the registration function of another block of accessors, declared with
1321///   `ferro_properties! { impl Owner, fn name { .. } }` (an upstream partial
1322///   class in a second file): `also [InputElement::register_gesture_properties]`;
1323/// * or a single accessor declared with `ferro_property!(for Owner; ..)`
1324///   (accessors generated by a local macro or interleaved with other items):
1325///   `also [XYFocus::left_property, XYFocus::right_property]`.
1326#[macro_export]
1327macro_rules! ferro_properties {
1328    (@accessors $owner:ident { $( $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block )* }) => {
1329        $(
1330            $crate::ferro_property!(for $owner; $(#[$meta])* $vis fn $name() -> $ty $body);
1331        )*
1332    };
1333
1334    // The main block, wrapping `ferro_property!(..);` invocations. The
1335    // accessors are declared through the macro name written at the call
1336    // site, so the block works with the import the file already has.
1337    (
1338        impl $owner:ident $(, also [$($more:path),* $(,)?])? {
1339            $( $macro_:ident ! ( $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block ) ; )+
1340        }
1341    ) => {
1342        impl $owner {
1343            $( $macro_!(for $owner; $(#[$meta])* $vis fn $name() -> $ty $body); )+
1344
1345            /// Registers the properties of the type in declaration order.
1346            /// Called by the static initialisation of the type.
1347            #[doc(hidden)]
1348            pub fn __register_properties() {
1349                $( let _ = <$owner>::$name(); )+
1350                $($( $more(); )*)?
1351            }
1352        }
1353    };
1354
1355    // A part of the properties of a type, wrapping `ferro_property!(..);`.
1356    (
1357        impl $owner:ident, fn $part:ident {
1358            $( $macro_:ident ! ( $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block ) ; )+
1359        }
1360    ) => {
1361        impl $owner {
1362            $( $macro_!(for $owner; $(#[$meta])* $vis fn $name() -> $ty $body); )+
1363
1364            /// Registers a part of the properties of the type; named by its
1365            /// main `ferro_properties!` block.
1366            #[doc(hidden)]
1367            pub fn $part() {
1368                $( let _ = <$owner>::$name(); )+
1369            }
1370        }
1371    };
1372
1373    // A part of the properties of a type.
1374    (
1375        impl $owner:ident, fn $part:ident {
1376            $( $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block )*
1377        }
1378    ) => {
1379        impl $owner {
1380            $crate::ferro_properties!(@accessors $owner { $( $(#[$meta])* $vis fn $name() -> $ty $body )* });
1381
1382            /// Registers a part of the properties of the type; named by its
1383            /// main `ferro_properties!` block.
1384            #[doc(hidden)]
1385            pub fn $part() {
1386                $( let _ = <$owner>::$name(); )*
1387            }
1388        }
1389    };
1390
1391    // The main block.
1392    (
1393        impl $owner:ident $(, also [$($more:path),* $(,)?])? {
1394            $( $(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty $body:block )*
1395        }
1396    ) => {
1397        impl $owner {
1398            $crate::ferro_properties!(@accessors $owner { $( $(#[$meta])* $vis fn $name() -> $ty $body )* });
1399
1400            /// Registers the properties of the type in declaration order.
1401            /// Called by the static initialisation of the type.
1402            #[doc(hidden)]
1403            pub fn __register_properties() {
1404                $( let _ = <$owner>::$name(); )*
1405                $($( $more(); )*)?
1406            }
1407        }
1408    };
1409}