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
18pub trait PropertyValue: Clone + PartialEq + 'static {}
20
21impl<T: Clone + PartialEq + 'static> PropertyValue for T {}
22
23pub trait AnyValue: Any {
29 #[doc(hidden)]
37 fn any_value_as_any(&self) -> &dyn Any;
38
39 #[doc(hidden)]
42 fn any_value_eq(&self, other: &dyn AnyValue) -> bool;
43
44 #[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#[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 #[inline]
100 pub fn as_any(&self) -> &dyn Any {
101 self.any_value_as_any()
102 }
103
104 #[inline]
106 pub fn value_type_id(&self) -> TypeId {
107 self.any_value_as_any().type_id()
108 }
109
110 #[inline]
112 pub fn type_name(&self) -> &'static str {
113 self.any_value_type_name()
114 }
115
116 #[inline]
118 pub fn is<T: 'static>(&self) -> bool {
119 self.any_value_as_any().is::<T>()
120 }
121
122 #[inline]
124 pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
125 self.any_value_as_any().downcast_ref::<T>()
126 }
127
128 #[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
148pub type BoxedValue = Rc<dyn AnyValue>;
152
153#[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#[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
173pub type NotifyingCallback = Box<dyn Fn(&FerroObject, bool)>;
176
177pub(crate) type InheritedValueChanged = fn(
181 &dyn EffectiveValueDyn,
182 &FerroObject,
183 Option<&dyn EffectiveValueDyn>,
184 Option<&dyn EffectiveValueDyn>,
185);
186
187pub(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
197pub(crate) trait PayloadSlot {
202 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
214pub(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 #[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
244pub(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
254pub(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 drop(converted);
277 copied
278}
279
280pub(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 fn as_any(&'static self) -> &'static dyn Any;
303 fn route_copy_value(&'static self, value: &dyn Any, out: &mut dyn Any) -> bool;
307 fn route_box_value(&'static self, value: &dyn Any) -> Option<BoxedValue>;
310 fn route_enable_data_validation(&'static self, owner: &FerroObject) -> Option<bool>;
314 fn route_unpack_binding_value(&'static self, value: &dyn Any) -> Option<BindingValue<BoxedValue>>;
317 fn route_set_local_value(&'static self, _o: &FerroObject, _value: BoxedValue) {
321 panic!("not supported for direct properties");
322 }
323 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
334pub struct PropertyChangedObservable {
336 handlers: HandlerList<ChangedHandler>,
337}
338
339impl PropertyChangedObservable {
340 fn new() -> Self {
341 Self { handlers: HandlerList::new() }
342 }
343
344 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 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
387pub 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 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 #[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 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 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 #[inline]
513 pub fn host_type(&self) -> Option<&'static TypeInfo> {
514 self.host_type.get()
515 }
516
517 #[inline]
519 pub fn name(&self) -> &str {
520 &self.name
521 }
522
523 #[inline]
525 pub fn property_type(&self) -> TypeId {
526 self.property_type
527 }
528
529 #[inline]
531 pub fn property_type_name(&self) -> &'static str {
532 self.property_type_name
533 }
534
535 #[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 #[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 #[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 #[inline]
560 pub fn owner_type(&self) -> &'static TypeInfo {
561 self.owner_type
562 }
563
564 #[inline]
566 pub fn inherits(&self) -> bool {
567 self.inherits
568 }
569
570 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 #[inline]
585 pub fn is_attached(&self) -> bool {
586 self.is_attached
587 }
588
589 #[inline]
591 pub fn is_direct(&self) -> bool {
592 self.is_direct
593 }
594
595 #[inline]
597 pub fn is_read_only(&self) -> bool {
598 self.is_read_only
599 }
600
601 #[inline]
607 pub fn assign_binding(&self) -> bool {
608 self.assign_binding.get()
609 }
610
611 pub fn set_assign_binding(&self, value: bool) {
616 self.assign_binding.set(value);
617 }
618
619 #[inline]
622 pub fn id(&self) -> u32 {
623 self.id
624 }
625
626 #[inline]
630 pub fn changed(&'static self) -> &'static PropertyChangedObservable {
631 &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 pub fn get_metadata(&self, type_: &'static TypeInfo) -> FerroPropertyMetadata {
647 self.routes().route_get_metadata(type_)
648 }
649
650 pub fn get_metadata_for(&self, owner: &FerroObject) -> FerroPropertyMetadata {
652 self.routes().route_get_metadata(owner.get_type())
653 }
654
655 #[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 pub fn unregister(&self, type_: &'static TypeInfo) {
669 self.routes().route_unregister(type_)
670 }
671
672 pub fn is_valid_value(&self, value: &dyn Any) -> bool {
675 self.routes().route_is_valid_value(value)
676 }
677
678 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 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 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 #[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 #[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 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 #[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 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 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
821pub 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 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 pub fn default_binding_mode(mut self, mode: BindingMode) -> Self {
862 self.default_binding_mode = mode;
863 self
864 }
865
866 pub fn validate(mut self, validate: impl Fn(&T) -> bool + 'static) -> Self {
869 self.validate = Some(Box::new(validate));
870 self
871 }
872
873 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 pub fn enable_data_validation(mut self, enable: bool) -> Self {
881 self.enable_data_validation = enable;
882 self
883 }
884
885 pub fn assign_binding(mut self, assign_binding: bool) -> Self {
888 self.assign_binding = assign_binding;
889 self
890 }
891
892 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 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(®istered, metadata.coerce_value().unwrap()));
923 }
924}
925
926#[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#[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#[macro_export]
982macro_rules! ferro_property {
983 (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 ::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#[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
1099impl<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#[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#[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 (
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 #[doc(hidden)]
1348 pub fn __register_properties() {
1349 $( let _ = <$owner>::$name(); )+
1350 $($( $more(); )*)?
1351 }
1352 }
1353 };
1354
1355 (
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 #[doc(hidden)]
1367 pub fn $part() {
1368 $( let _ = <$owner>::$name(); )+
1369 }
1370 }
1371 };
1372
1373 (
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 #[doc(hidden)]
1385 pub fn $part() {
1386 $( let _ = <$owner>::$name(); )*
1387 }
1388 }
1389 };
1390
1391 (
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 #[doc(hidden)]
1403 pub fn __register_properties() {
1404 $( let _ = <$owner>::$name(); )*
1405 $($( $more(); )*)?
1406 }
1407 }
1408 };
1409}