ferroui-base 0.3.0

The base library of FerroUI: the property system, layout, input, styling, media, text, animation, data binding and the compositor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
use crate::animation::Animatable;
use crate::collections::{FerroList, NotifyCollectionChangedAction, NotifyCollectionChangedEventArgs, ResetBehavior};
use crate::controls::{
    Classes, IPseudoClasses, IResourceHost, IResourceNode, ResourceDictionary, ResourceHostRef, ResourceKey,
    ResourceValue, ResourcesChangedEventArgs,
};
use crate::data::BindingPriority;
use crate::logical_tree::{IChildIndexProvider, LogicalTreeAttachmentEventArgs};
use crate::property_store::FrameType;
use crate::reactive::{Disposable, IDisposable};
use crate::styling::{
    DuplicateSetterError, ContainerQuery, ControlTheme, IStyle, IStyleHost, IThemeVariantHost, Style, StyleBase, StyleHostRef,
    StyleInstance, Styles, ThemeVariant,
};
use crate::utilities::HandlerList;
use crate::InitializationError;
use crate::{
    ferro_class, ferro_property, instantiate, AnyValue, BoxedValue, DirectProperty, FerroObject, FerroObjectImpl,
    FerroObjectImplExt, FerroProperty, FerroPropertyChangedEventArgs, Nullable, Ref, StyledProperty,
    StyledPropertyOptions, TypeInfo, WeakRef,
};
use std::cell::{Cell, OnceCell, RefCell};
use std::rc::Rc;

/// Extends an [`Animatable`] with the following features:
///
/// - An inherited `DataContext`.
/// - Implements the logical tree.
/// - A collection of class strings for custom styling.
/// - Implements styling: tracks the frames applied by styles and themes.
#[repr(C)]
pub struct StyledElement {
    base: Animatable,
    init_count: Cell<u32>,
    name: RefCell<Option<String>>,
    classes: OnceCell<Classes>,
    logical_root: RefCell<Option<WeakRef<StyledElement>>>,
    logical_children: OnceCell<FerroList<Ref<StyledElement>>>,
    parent: RefCell<Option<WeakRef<StyledElement>>>,
    resources: RefCell<Option<Ref<ResourceDictionary>>>,
    styles: OnceCell<Ref<Styles>>,
    styles_applied: Cell<bool>,
    theme_applied: Cell<bool>,
    templated_parent_theme_applied: Cell<bool>,
    templated_parent: RefCell<Option<WeakRef<FerroObject>>>,
    data_context_updating: Cell<bool>,
    implicit_theme: RefCell<ImplicitTheme>,
    last_resources_changed_event_args: Cell<ResourcesChangedEventArgs>,
    is_initialized: Cell<bool>,
    /// True when this element has been removed from a logical children
    /// collection and not added back since. Avoids a costly quadratic
    /// `contains` check when attaching to the logical tree.
    removed_from_logical_parent: Cell<bool>,
    attached_to_logical_tree: HandlerList<dyn Fn(&LogicalTreeAttachmentEventArgs)>,
    detached_from_logical_tree: HandlerList<dyn Fn(&LogicalTreeAttachmentEventArgs)>,
    data_context_changed: HandlerList<dyn Fn()>,
    initialized: HandlerList<dyn Fn()>,
    resources_changed: HandlerList<dyn Fn(&ResourcesChangedEventArgs)>,
    actual_theme_variant_changed: HandlerList<dyn Fn()>,
}

/// The control theme found for an element whose `Theme` property is not set.
enum ImplicitTheme {
    /// The theme has not been looked up yet.
    Unknown,
    /// The lookup found no theme.
    Invalid,
    Theme(Ref<ControlTheme>),
}

ferro_class! {
    StyledElement: Animatable, virtuals StyledElementImpl: FerroObjectImpl {
        /// Signals the beginning of a batch of initialization: styling is
        /// deferred until the matching `end_init`.
        fn begin_init(this);
        /// Signals the end of a batch of initialization: the element is
        /// styled (if it is attached to a rooted logical tree) and
        /// initialized. A style or control theme that cannot be applied (two
        /// setters for the same property) is an error, the counterpart of
        /// the invalid operation `EndInit` raises in the managed original;
        /// what follows the failure is skipped. This is the overridable
        /// member; [`end_init`](StyledElement::end_init) is the form that
        /// panics on the error.
        fn try_end_init(this) -> Result<(), InitializationError>;
        /// Called when the logical children collection changes.
        fn logical_children_collection_changed(this, e: &NotifyCollectionChangedEventArgs<'_, Ref<StyledElement>>);
        /// Called when the styled element is added to a rooted logical tree.
        fn on_attached_to_logical_tree(this, e: &LogicalTreeAttachmentEventArgs);
        /// Called when the styled element is removed from a rooted logical tree.
        fn on_detached_from_logical_tree(this, e: &LogicalTreeAttachmentEventArgs);
        /// Called when the data context changes.
        fn on_data_context_changed(this);
        /// Called when the data context begins updating.
        fn on_data_context_begin_update(this);
        /// Called when the data context finishes updating.
        fn on_data_context_end_update(this);
        /// Called when the control finishes initialization.
        fn on_initialized(this);
        /// The type by which the element is styled. Defaults to the element's
        /// own type; override to be styled as a base class.
        fn style_key_override(this) -> &'static TypeInfo;
        /// Called when the control theme changes.
        fn on_control_theme_changed(this);
        /// Called when the templated parent's control theme changes.
        fn on_templated_parent_control_theme_changed(this);
        /// Detaches all styles from the element (and optionally from its
        /// inheritance children) so that they are re-applied.
        fn invalidate_styles(this, recurse: bool);
        /// Whether the element is the root of a logical tree.
        fn is_logical_root(this) -> bool;
        /// The parent style host of the element: by default the inheritance
        /// parent, when it is a styled element. The root of a tree overrides
        /// this to return the host of the global styles.
        fn styling_parent(this) -> Option<StyleHostRef>;
        /// Notifies the children of the element that the resources visible to
        /// them have changed. The base method notifies the logical children.
        fn notify_child_resources_changed(this, e: ResourcesChangedEventArgs);
        /// The child index provider implemented by the element, if any. Used
        /// to match the children of the element by their position.
        fn child_index_provider(this) -> Option<Rc<dyn IChildIndexProvider>>;
        /// Whether the element is a root of theme variant resolution: at a
        /// root the default theme variant resolves to the variant of the
        /// platform instead of being inherited.
        fn is_theme_variant_root(this) -> bool;
    }
}
crate::ferro_class_info!(StyledElement {
    new: StyledElement::new,
    interfaces: [
        Rc<dyn crate::ISupportInitialize>,
        Rc<dyn crate::INamed>,
        crate::controls::ResourceHostRef,
        crate::styling::StyleHostRef,
    ],
});

crate::ferro_overrides! { impl FerroObjectImpl for StyledElement {
    fn constructed(this: &Self) {
        Self::parent_constructed(this);
        if this.is_logical_root() {
            *this.logical_root.borrow_mut() = Some(this.to_ref().downgrade());
        }
    }

    fn on_property_changed(this: &Self, change: &FerroPropertyChangedEventArgs<'_>) {
        Self::parent_on_property_changed(this, change);

        if change.property() == Self::theme_property().as_property() {
            this.on_control_theme_changed();
        } else if change.property() == ThemeVariant::actual_theme_variant_property().as_property()
            && !this.actual_theme_variant_changed.is_empty()
        {
            for (_, handler) in this.actual_theme_variant_changed.snapshot().iter() {
                handler();
            }
        }
    }
} }

impl StyledElementImpl for StyledElement {
    fn begin_init(this: &Self) {
        this.init_count.set(this.init_count.get() + 1);
    }

    fn try_end_init(this: &Self) -> Result<(), InitializationError> {
        let count = this.init_count.get();
        assert!(count != 0, "BeginInit was not called.");
        this.init_count.set(count - 1);
        if count == 1 && this.logical_root.borrow().is_some() {
            this.try_apply_styling()?;
            this.initialize_if_needed();
        }
        Ok(())
    }

    fn logical_children_collection_changed(this: &Self, e: &NotifyCollectionChangedEventArgs<'_, Ref<StyledElement>>) {
        match e.action {
            NotifyCollectionChangedAction::Add => this.set_logical_parent_of(e.new_items),
            NotifyCollectionChangedAction::Remove => this.clear_logical_parent_of(e.old_items),
            NotifyCollectionChangedAction::Replace => {
                this.clear_logical_parent_of(e.old_items);
                this.set_logical_parent_of(e.new_items);
            }
            NotifyCollectionChangedAction::Reset => {
                panic!("Reset should not be signaled on LogicalChildren collection")
            }
            NotifyCollectionChangedAction::Move => {}
        }
    }

    fn on_attached_to_logical_tree(_this: &Self, _e: &LogicalTreeAttachmentEventArgs) {}

    fn on_detached_from_logical_tree(_this: &Self, _e: &LogicalTreeAttachmentEventArgs) {}

    fn on_data_context_changed(this: &Self) {
        if !this.data_context_changed.is_empty() {
            for (_, handler) in this.data_context_changed.snapshot().iter() {
                handler();
            }
        }
    }

    fn on_data_context_begin_update(_this: &Self) {}

    fn on_data_context_end_update(_this: &Self) {}

    fn on_initialized(_this: &Self) {}

    fn style_key_override(this: &Self) -> &'static TypeInfo {
        this.get_type()
    }

    fn on_control_theme_changed(this: &Self) {
        let values = this.values();
        values.begin_styling();
        values.remove_frames(this, FrameType::Theme);
        values.end_styling(this);
        this.theme_applied.set(false);
    }

    fn on_templated_parent_control_theme_changed(this: &Self) {
        let values = this.values();
        values.begin_styling();
        values.remove_frames(this, FrameType::TemplatedParentTheme);
        values.end_styling(this);
        this.templated_parent_theme_applied.set(false);
    }

    fn invalidate_styles(this: &Self, recurse: bool) {
        let values = this.values();
        values.begin_styling();
        values.remove_frames(this, FrameType::Style);
        values.end_styling(this);
        this.styles_applied.set(false);

        if recurse {
            for child in this.inheritance_children() {
                if let Some(child) = child.downcast_ref::<StyledElement>() {
                    child.invalidate_styles(recurse);
                }
            }
        }
    }

    fn is_logical_root(_this: &Self) -> bool {
        false
    }

    fn styling_parent(this: &Self) -> Option<StyleHostRef> {
        // The handle of the inheritance parent becomes the handle of the
        // host: the walks up the tree (styles, resources, the logical root)
        // ask for it at every step, and a second handle made and dropped
        // there is a count up and down per step.
        this.inheritance_parent().and_then(|p| p.downcast::<StyledElement>().ok()).map(StyleHostRef::Element)
    }

    fn is_theme_variant_root(_this: &Self) -> bool {
        false
    }

    fn notify_child_resources_changed(this: &Self, e: ResourcesChangedEventArgs) {
        if let Some(children) = this.logical_children.get() {
            if !children.is_empty() {
                for child in children.snapshot().iter() {
                    child.notify_resources_changed(e, true);
                }
            }
        }
    }

    fn child_index_provider(_this: &Self) -> Option<Rc<dyn IChildIndexProvider>> {
        None
    }
}

// The theme variant properties are declared with the theme variant type and
// owned by this class.
crate::ferro_properties! { impl StyledElement, also [
    crate::styling::ThemeVariant::actual_theme_variant_property,
    crate::styling::ThemeVariant::requested_theme_variant_property,
] {
    ferro_property!(
        /// Defines the `DataContext` property.
        pub fn data_context_property() -> StyledProperty<Option<BoxedValue>> {
            let property = FerroProperty::register_with::<StyledElement, _>(
                "DataContext",
                StyledPropertyOptions::new(None).inherits(true).notifying(Self::data_context_notifying),
            );
            property.changed().add_class_handler::<StyledElement>(|x, _| x.on_data_context_changed());
            property
        }
    );

    ferro_property!(
        /// Defines the `Name` property.
        pub fn name_property() -> DirectProperty<StyledElement, Option<String>> {
            FerroProperty::register_direct::<StyledElement, _>("Name", |o| o.name(), Some(|o, v| o.set_name(v)), None)
        }
    );

    ferro_property!(
        /// Defines the `Parent` property.
        pub fn parent_property() -> DirectProperty<StyledElement, Option<Ref<StyledElement>>> {
            FerroProperty::register_direct::<StyledElement, _>("Parent", |o| o.parent(), None, None)
        }
    );

    ferro_property!(
        /// Defines the `TemplatedParent` property.
        pub fn templated_parent_property() -> DirectProperty<StyledElement, Option<Ref<FerroObject>>> {
            FerroProperty::register_direct::<StyledElement, _>(
                "TemplatedParent",
                |o| o.templated_parent(),
                None,
                None,
            )
        }
    );

    ferro_property!(
        /// Defines the `Theme` property.
        pub fn theme_property() -> StyledProperty<Option<Ref<ControlTheme>>> {
            FerroProperty::register::<StyledElement, _>("Theme", None)
        }
    );
} }

impl StyledElement {
    /// Creates the class data; see [`FerroObject::construct`].
    pub fn construct() -> Self {
        Self {
            base: Animatable::construct(),
            init_count: Cell::new(0),
            name: RefCell::new(None),
            classes: OnceCell::new(),
            logical_root: RefCell::new(None),
            logical_children: OnceCell::new(),
            parent: RefCell::new(None),
            resources: RefCell::new(None),
            styles: OnceCell::new(),
            styles_applied: Cell::new(false),
            theme_applied: Cell::new(false),
            templated_parent_theme_applied: Cell::new(false),
            templated_parent: RefCell::new(None),
            data_context_updating: Cell::new(false),
            implicit_theme: RefCell::new(ImplicitTheme::Unknown),
            last_resources_changed_event_args: Cell::new(ResourcesChangedEventArgs::default()),
            is_initialized: Cell::new(false),
            removed_from_logical_parent: Cell::new(false),
            attached_to_logical_tree: HandlerList::new(),
            detached_from_logical_tree: HandlerList::new(),
            data_context_changed: HandlerList::new(),
            initialized: HandlerList::new(),
            resources_changed: HandlerList::new(),
            actual_theme_variant_changed: HandlerList::new(),
        }
    }

    pub fn new() -> Ref<Self> {
        instantiate(Self::construct())
    }

    // --- events -----------------------------------------------------------

    /// Raised when the styled element is attached to a rooted logical tree.
    pub fn attached_to_logical_tree(
        &self,
        handler: impl Fn(&LogicalTreeAttachmentEventArgs) + 'static,
    ) -> Rc<dyn IDisposable> {
        let token = self.attached_to_logical_tree.add(Rc::new(handler));
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.attached_to_logical_tree.remove(token);
            }
        })
    }

    /// Raised when the styled element is detached from a rooted logical tree.
    pub fn detached_from_logical_tree(
        &self,
        handler: impl Fn(&LogicalTreeAttachmentEventArgs) + 'static,
    ) -> Rc<dyn IDisposable> {
        let token = self.detached_from_logical_tree.add(Rc::new(handler));
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.detached_from_logical_tree.remove(token);
            }
        })
    }

    /// Occurs when the data context property changes.
    pub fn data_context_changed(&self, handler: impl Fn() + 'static) -> Rc<dyn IDisposable> {
        let token = self.data_context_changed.add(Rc::new(handler));
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.data_context_changed.remove(token);
            }
        })
    }

    /// Occurs when the styled element has finished initialization.
    pub fn initialized(&self, handler: impl Fn() + 'static) -> Rc<dyn IDisposable> {
        let token = self.initialized.add(Rc::new(handler));
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.initialized.remove(token);
            }
        })
    }

    /// Raised when the resources change on the element or an ancestor of the
    /// element.
    pub fn resources_changed(
        &self,
        handler: impl Fn(&ResourcesChangedEventArgs) + 'static,
    ) -> Rc<dyn IDisposable> {
        self.subscribe_resources_changed(Rc::new(handler))
    }

    fn subscribe_resources_changed(&self, handler: Rc<dyn Fn(&ResourcesChangedEventArgs)>) -> Rc<dyn IDisposable> {
        let token = self.resources_changed.add(handler);
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.resources_changed.remove(token);
            }
        })
    }

    /// Raised when the theme variant in effect for the element changes.
    pub fn actual_theme_variant_changed(&self, handler: impl Fn() + 'static) -> Rc<dyn IDisposable> {
        self.subscribe_actual_theme_variant_changed(Rc::new(handler))
    }

    fn subscribe_actual_theme_variant_changed(&self, handler: Rc<dyn Fn()>) -> Rc<dyn IDisposable> {
        let token = self.actual_theme_variant_changed.add(handler);
        let weak = self.to_ref().downgrade();
        Disposable::create(move || {
            if let Some(this) = weak.upgrade() {
                this.actual_theme_variant_changed.remove(token);
            }
        })
    }

    // --- properties -------------------------------------------------------

    /// The name of the styled element.
    ///
    /// An element's name is used to uniquely identify it within its name
    /// scope. Once the element has been styled its name may not be changed.
    pub fn name(&self) -> Option<String> {
        self.name.borrow().clone()
    }

    pub fn set_name(&self, value: Option<String>) {
        assert!(!self.styles_applied.get(), "Cannot set Name : styled element already styled.");
        *self.name.borrow_mut() = value;
    }

    /// The styled element's classes.
    ///
    /// The collection is returned by handle: clones refer to the same
    /// collection.
    pub fn classes(&self) -> Classes {
        self.classes_ref().clone()
    }

    #[inline]
    fn classes_ref(&self) -> &Classes {
        self.classes.get_or_init(Classes::new)
    }

    /// The pseudoclasses of the element, settable by the control itself.
    pub fn pseudo_classes(&self) -> &dyn IPseudoClasses {
        self.classes_ref()
    }

    /// The control's data context.
    ///
    /// The data context is an inherited property that specifies the default
    /// object that will be used for data binding.
    pub fn data_context(&self) -> Option<BoxedValue> {
        self.get_value(Self::data_context_property())
    }

    pub fn set_data_context(&self, value: Option<BoxedValue>) {
        self.set_value(Self::data_context_property(), value)
    }

    /// Whether the element has finished initialization.
    ///
    /// For more information about when this happens, see the `initialized`
    /// event.
    pub fn is_initialized(&self) -> bool {
        self.is_initialized.get()
    }

    /// The styles for the styled element.
    ///
    /// Styles for the entire application are added to the application's
    /// styles collection.
    pub fn styles(&self) -> Ref<Styles> {
        self.styles.get_or_init(|| Styles::with_owner(self.to_ref())).clone()
    }

    /// Whether the styles collection of the element has been created.
    pub fn is_styles_initialized(&self) -> bool {
        self.styles.get().is_some()
    }

    /// The type by which the element is styled.
    pub fn style_key(&self) -> &'static TypeInfo {
        self.style_key_override()
    }

    /// The styled element's resource dictionary.
    pub fn resources(&self) -> Ref<ResourceDictionary> {
        if let Some(resources) = &*self.resources.borrow() {
            return resources.clone();
        }
        let resources = ResourceDictionary::with_owner(self.to_ref());
        *self.resources.borrow_mut() = Some(resources.clone());
        resources
    }

    pub fn set_resources(&self, value: Ref<ResourceDictionary>) {
        let this = ResourceHostRef::Element(self.to_ref());
        let old = self.resources.borrow_mut().take();
        if let Some(old) = old {
            old.remove_owner(&this);
        }
        *self.resources.borrow_mut() = Some(value.clone());
        value.add_owner(&this);
    }

    /// The theme to be applied to the element.
    ///
    /// By default the theme is looked up as a resource keyed by the element's
    /// style key; setting this property takes precedence over that lookup.
    pub fn theme(&self) -> Option<Ref<ControlTheme>> {
        self.get_value(Self::theme_property())
    }

    pub fn set_theme(&self, value: impl Into<Nullable<ControlTheme>>) {
        self.set_value(Self::theme_property(), value.into().0)
    }

    /// The UI theme variant that is currently used by the element, which
    /// might be different than the requested theme variant. `None` until a
    /// theme variant has been established for the element or an ancestor.
    pub fn actual_theme_variant(&self) -> Option<ThemeVariant> {
        self.get_value(ThemeVariant::actual_theme_variant_property())
    }

    /// Whether the element or its styles have resources.
    pub fn has_resources(&self) -> bool {
        self.resources.borrow().as_ref().is_some_and(|r| r.has_resources())
            || self.styles.get().is_some_and(|s| s.has_resources())
    }

    /// Tries to find a resource within the element: in its resource
    /// dictionary, then in its styles.
    pub fn try_get_resource(&self, key: &ResourceKey, theme: Option<&ThemeVariant>) -> Option<ResourceValue> {
        let resources = self.resources.borrow().clone();
        if let Some(resources) = resources {
            if let Some(value) = resources.try_get_resource(key, theme) {
                return Some(value);
            }
        }
        match self.styles.get() {
            Some(styles) => styles.try_get_resource(key, theme),
            None => None,
        }
    }

    /// Tries to find a resource by searching up the logical tree and then
    /// the global styles.
    pub fn try_find_resource(&self, key: &ResourceKey, theme: Option<&ThemeVariant>) -> Option<ResourceValue> {
        let host: &dyn IResourceHost = self;
        host.try_find_resource(key, theme)
    }

    /// Finds a resource by searching up the logical tree and then the global
    /// styles. Returns the unset value marker if it is not found.
    pub fn find_resource(&self, key: &ResourceKey) -> ResourceValue {
        let host: &dyn IResourceHost = self;
        host.find_resource(key)
    }

    /// The styled element whose lookless template this element is part of.
    pub fn templated_parent(&self) -> Option<Ref<FerroObject>> {
        self.templated_parent.borrow().as_ref().and_then(WeakRef::upgrade)
    }

    /// Sets the templated parent. Called by the template that creates the
    /// element.
    pub fn set_templated_parent(&self, value: impl Into<Nullable<FerroObject>>) {
        let value = value.into().0;
        let old = self.templated_parent();
        if old != value {
            *self.templated_parent.borrow_mut() = value.as_ref().map(Ref::downgrade);
            self.raise_direct_property_changed(Self::templated_parent_property(), &old, &value);
        }
    }

    /// The styled element's logical children.
    pub fn logical_children(&self) -> &FerroList<Ref<StyledElement>> {
        self.logical_children.get_or_init(|| {
            let list = FerroList::new();
            list.set_reset_behavior(ResetBehavior::Remove);
            let weak = self.to_ref().downgrade();
            list.add_collection_changed(Rc::new(move |e: &NotifyCollectionChangedEventArgs<'_, Ref<StyledElement>>| {
                if let Some(this) = weak.upgrade() {
                    this.logical_children_collection_changed(e);
                }
            }));
            list
        })
    }

    /// Whether the element is attached to a rooted logical tree.
    pub fn is_attached_to_logical_tree(&self) -> bool {
        self.logical_root.borrow().is_some()
    }

    /// The styled element's logical parent.
    pub fn parent(&self) -> Option<Ref<StyledElement>> {
        self.parent.borrow().as_ref().and_then(WeakRef::upgrade)
    }

    // --- initialization and styling ---------------------------------------

    /// Applies styling to the control if the control is initialized and
    /// styling is not already applied.
    ///
    /// The styling system will automatically apply styling when required, so
    /// this method need only be called by tests or in rare special cases.
    ///
    /// Returns true if styling is applied to the control, false if the
    /// control is still initializing.
    pub fn apply_styling(&self) -> bool {
        match self.try_apply_styling() {
            Ok(applied) => applied,
            Err(error) => panic!("{error}"),
        }
    }

    /// As [`apply_styling`](Self::apply_styling), reporting a style or
    /// control theme that cannot be applied (two setters for the same
    /// property: the invalid operation of the managed original) instead of
    /// panicking. After an error the styling pass is ended and the element
    /// is not marked as styled, as when the managed original throws.
    pub fn try_apply_styling(&self) -> Result<bool, DuplicateSetterError> {
        if self.init_count.get() == 0
            && (!self.styles_applied.get()
                || !self.theme_applied.get()
                || !self.templated_parent_theme_applied.get())
        {
            let values = self.values();
            values.begin_styling();
            let _end_styling = EndStyling(self);
            if !self.theme_applied.get() {
                self.apply_control_theme()?;
                self.theme_applied.set(true);
            }
            if !self.templated_parent_theme_applied.get() {
                self.apply_templated_parent_control_theme()?;
                self.templated_parent_theme_applied.set(true);
            }
            if !self.styles_applied.get() {
                self.apply_styles(&StyleHostRef::Element(self.to_ref()))?;
                self.styles_applied.set(true);
            }
        }
        Ok(self.styles_applied.get())
    }

    /// Signals the end of a batch of initialization
    /// ([`try_end_init`](Self::try_end_init)). A style or control theme that
    /// cannot be applied panics with the message of the error.
    pub fn end_init(&self) {
        if let Err(error) = self.try_end_init() {
            panic!("{error}");
        }
    }

    /// Marks the element as initialized and raises the initialization
    /// notifications, if initialization is complete.
    pub fn initialize_if_needed(&self) {
        if self.init_count.get() == 0 && !self.is_initialized.get() {
            self.is_initialized.set(true);
            self.on_initialized();
            if !self.initialized.is_empty() {
                for (_, handler) in self.initialized.snapshot().iter() {
                    handler();
                }
            }
        }
    }

    // --- logical tree -----------------------------------------------------

    /// Sets the element's logical parent.
    ///
    /// You should not usually need to call this method: it is called when an
    /// element is added to or removed from a logical children collection.
    pub fn set_parent(&self, parent: impl Into<Nullable<StyledElement>>) {
        let parent = parent.into().0;
        let old = self.parent();
        if parent == old {
            return;
        }
        assert!(old.is_none() || parent.is_none(), "The Control already has a parent.");

        if self.inheritance_parent().is_none() || parent.is_none() {
            self.set_inheritance_parent(parent.clone().map(Ref::upcast::<FerroObject>));
        }

        *self.parent.borrow_mut() = parent.as_ref().map(Ref::downgrade);

        let this = self.to_ref();
        let old_root = self.logical_root();
        if let Some(root) = old_root {
            let e = LogicalTreeAttachmentEventArgs::new(root, this.clone(), old.clone());
            self.on_detached_from_logical_tree_core(&e);
        }

        if let Some(new_root) = self.find_logical_root() {
            let e = LogicalTreeAttachmentEventArgs::new(new_root, this, parent.clone());
            self.on_attached_to_logical_tree_core(&e);
        } else if parent.is_none() {
            // If we were attached to the logical tree, we piggyback on the
            // tree traversal there to raise resources changed notifications.
            // If we're being removed from the logical tree, then traverse the
            // tree raising notifications now.
            //
            // We don't raise resources changed notifications if we're being
            // attached to a non-rooted control because it's unlikely that
            // dynamic resources need to be correct until the control is added
            // to the tree, and it causes a *lot* of notifications.
            self.notify_resources_changed(ResourcesChangedEventArgs::create(), true);
        }

        self.raise_direct_property_changed(Self::parent_property(), &old, &parent);
    }

    /// Notifies the element that it has been attached to a rooted logical
    /// tree. Called by a parent for children that are part of its logical
    /// tree without being in its logical children collection (the template
    /// child of a templated control).
    pub fn notify_attached_to_logical_tree(&self, e: &LogicalTreeAttachmentEventArgs) {
        self.on_attached_to_logical_tree_core(e);
    }

    /// Notifies the element that it has been detached from a rooted logical
    /// tree. See [`notify_attached_to_logical_tree`](Self::notify_attached_to_logical_tree).
    pub fn notify_detached_from_logical_tree(&self, e: &LogicalTreeAttachmentEventArgs) {
        self.on_detached_from_logical_tree_core(e);
    }

    fn logical_root(&self) -> Option<Ref<StyledElement>> {
        self.logical_root.borrow().as_ref().and_then(WeakRef::upgrade)
    }

    fn find_logical_root(&self) -> Option<Ref<StyledElement>> {
        if self.is_logical_root() {
            return Some(self.to_ref());
        }
        let mut current = self.styling_parent();
        while let Some(host) = current {
            if let StyleHostRef::Element(e) = &host {
                if e.is_logical_root() {
                    return Some(e.clone());
                }
            }
            current = host.styling_parent();
        }
        None
    }

    fn on_attached_to_logical_tree_core(&self, e: &LogicalTreeAttachmentEventArgs) {
        if self.parent().is_none() && !self.is_logical_root() {
            panic!(
                "AttachedToLogicalTreeCore called for '{}' but control has no logical parent.",
                self.get_type().name()
            );
        }

        // This method can be called when a control is already attached to the
        // logical tree in the following scenario:
        // - ListBox gets assigned Items containing ListBoxItem
        // - ListBox makes ListBoxItem a logical child
        // - ListBox template gets applied; making its Panel get attached to
        //   the logical tree
        // - That AttachedToLogicalTree signal travels down to the ListBoxItem
        if self.logical_root.borrow().is_none() {
            crate::perf_count!(LogicalTreeAttachments);
            *self.logical_root.borrow_mut() = Some(e.root().downgrade());
            self.reevaluate_implicit_theme();
            self.apply_styling();
            self.notify_resources_changed(ResourcesChangedEventArgs::create(), false);
            self.on_attached_to_logical_tree(e);
            if !self.attached_to_logical_tree.is_empty() {
                for (_, handler) in self.attached_to_logical_tree.snapshot().iter() {
                    handler(e);
                }
            }
        }

        if let Some(children) = self.logical_children.get() {
            // An event handler may have modified the children while we're
            // enumerating a snapshot of the collection.
            for child in children.snapshot().iter() {
                let attached_to_root = child.logical_root().is_some_and(|r| r == *e.root());
                if !attached_to_root && (child.parent().is_some() || !child.removed_from_logical_parent.get()) {
                    child.on_attached_to_logical_tree_core(e);
                }
            }
        }
    }

    fn on_detached_from_logical_tree_core(&self, e: &LogicalTreeAttachmentEventArgs) {
        if self.logical_root.borrow().is_some() {
            crate::perf_count!(LogicalTreeDetachments);
            *self.logical_root.borrow_mut() = None;
            self.invalidate_styles(false);
            self.on_detached_from_logical_tree(e);
            if !self.detached_from_logical_tree.is_empty() {
                for (_, handler) in self.detached_from_logical_tree.snapshot().iter() {
                    handler(e);
                }
            }

            if let Some(children) = self.logical_children.get() {
                for child in children.snapshot().iter() {
                    child.on_detached_from_logical_tree_core(e);
                }
            }
        }
    }

    fn set_logical_parent_of(&self, children: &[Ref<StyledElement>]) {
        for child in children {
            child.removed_from_logical_parent.set(false);
            if child.parent().is_none() {
                child.set_parent(self.to_ref());
            }
        }
    }

    fn clear_logical_parent_of(&self, children: &[Ref<StyledElement>]) {
        let this = self.to_ref();
        for child in children {
            child.removed_from_logical_parent.set(true);
            if child.parent().is_some_and(|p| p == this) {
                child.set_parent(None);
            }
        }
    }

    // --- styling ----------------------------------------------------------

    /// The theme in effect for the element: the `Theme` property if set,
    /// otherwise the control theme resource keyed by the element's style key
    /// that is visible to the element (a resource holding a
    /// `Ref<ControlTheme>`).
    pub fn get_effective_theme(&self) -> Option<Ref<ControlTheme>> {
        // Explicitly set Theme property takes precedence.
        if let Some(theme) = self.theme() {
            return Some(theme);
        }

        // If the Theme property is not set, try to find a ControlTheme
        // resource with our StyleKey.
        if matches!(*self.implicit_theme.borrow(), ImplicitTheme::Unknown) {
            crate::perf_count!(ImplicitThemeLookups);
            let key = ResourceKey::Type(self.style_key());
            let found = self.try_find_resource(&key, None).flatten().and_then(|value| {
                let value: &dyn AnyValue = &*value;
                value.downcast_ref::<Ref<ControlTheme>>().cloned()
            });
            *self.implicit_theme.borrow_mut() = match found {
                Some(theme) => ImplicitTheme::Theme(theme),
                None => ImplicitTheme::Invalid,
            };
        }

        match &*self.implicit_theme.borrow() {
            ImplicitTheme::Theme(theme) => Some(theme.clone()),
            _ => None,
        }
    }

    fn apply_control_theme(&self) -> Result<(), DuplicateSetterError> {
        if let Some(theme) = self.get_effective_theme() {
            self.apply_control_theme_core(&theme, FrameType::Theme)?;
        }
        Ok(())
    }

    fn apply_templated_parent_control_theme(&self) -> Result<(), DuplicateSetterError> {
        // Most elements have no templated parent: avoid upgrading the weak
        // reference for them.
        if self.templated_parent.borrow().is_none() {
            return Ok(());
        }
        let parent_theme = self
            .templated_parent()
            .and_then(|p| p.downcast_ref::<StyledElement>().and_then(StyledElement::get_effective_theme));
        if let Some(parent_theme) = parent_theme {
            self.apply_control_theme_core(&parent_theme, FrameType::TemplatedParentTheme)?;
        }
        Ok(())
    }

    fn apply_control_theme_core(&self, theme: &ControlTheme, type_: FrameType) -> Result<(), DuplicateSetterError> {
        debug_assert!(matches!(type_, FrameType::Theme | FrameType::TemplatedParentTheme));

        if let Some(based_on) = theme.based_on() {
            self.apply_control_theme_core(&based_on, type_)?;
        }

        theme.try_attach_checked(self, type_)?;

        if theme.has_children() {
            let children = theme.children().snapshot();
            for child in children.iter() {
                self.apply_style(&**child, None, type_)?;
            }
        }
        Ok(())
    }

    fn apply_styles(&self, host: &StyleHostRef) -> Result<(), DuplicateSetterError> {
        if let Some(parent) = host.styling_parent() {
            self.apply_styles(&parent)?;
        }
        crate::perf_count!(StyleHostsWalked);

        if host.is_styles_initialized() {
            let styles = host.styles().snapshot();
            for style in styles.iter() {
                self.apply_style(&**style, Some(host), FrameType::Style)?;
            }
        }
        Ok(())
    }

    fn apply_style(
        &self,
        style: &dyn IStyle,
        host: Option<&StyleHostRef>,
        type_: FrameType,
    ) -> Result<(), DuplicateSetterError> {
        if let Some(base) = style.as_object().and_then(|o| o.downcast_ref::<StyleBase>()) {
            if let Some(s) = base.downcast_ref::<Style>() {
                s.try_attach_checked(self, host, type_)?;
            } else if let Some(m) = base.downcast_ref::<ContainerQuery>() {
                m.try_attach_checked(self, host, type_)?;
            }

            // The common case of a style without nested styles.
            if !base.has_children() {
                return Ok(());
            }
        }

        let children = style.children();
        for child in children.iter() {
            self.apply_style(&**child, host, type_)?;
        }
        Ok(())
    }

    fn reevaluate_implicit_theme(&self) {
        // We only need to check if the theme has changed when Theme isn't set
        // (i.e. when we have an implicit theme).
        if self.theme().is_some() {
            return;
        }

        // Refetch the implicit theme.
        let old_implicit_theme = match self.implicit_theme.replace(ImplicitTheme::Unknown) {
            ImplicitTheme::Theme(theme) => Some(theme),
            _ => None,
        };
        let new_implicit_theme = self.get_effective_theme();

        // If the implicit theme has changed, detach the existing theme.
        if new_implicit_theme != old_implicit_theme {
            self.on_control_theme_changed();
            self.theme_applied.set(false);
        }
    }

    /// Called when styles are added to the styles collection of the element
    /// or a nested styles collection.
    pub fn styles_added(&self, styles: &[Rc<dyn IStyle>]) {
        if Self::has_setters_or_animations(styles) {
            self.invalidate_styles(true);
        }
    }

    /// Called when styles are removed from the styles collection of the
    /// element or a nested styles collection.
    pub fn styles_removed(&self, styles: &[Rc<dyn IStyle>]) {
        let mut all_styles = Vec::new();
        Self::flatten_styles(styles, &mut all_styles);
        if !all_styles.is_empty() {
            self.detach_styles(&all_styles);
        }
    }

    fn detach_styles(&self, styles: &[Ref<StyleBase>]) {
        let values = self.values();
        values.begin_styling();
        values.remove_frames_where(self, |frame| {
            frame
                .as_any()
                .downcast_ref::<StyleInstance>()
                .is_some_and(|instance| styles.iter().any(|style| instance.is_source(style)))
        });
        values.end_styling(self);

        if let Some(children) = self.logical_children.get() {
            if !children.is_empty() {
                for child in children.snapshot().iter() {
                    child.detach_styles(styles);
                }
            }
        }
    }

    /// Notifies the element, and with `propagate` its children, that the
    /// resources visible to it have changed.
    pub fn notify_resources_changed(&self, e: ResourcesChangedEventArgs, propagate: bool) {
        // We already got a notification for this element, ignore.
        if e == self.last_resources_changed_event_args.get() {
            return;
        }

        self.last_resources_changed_event_args.set(e);

        if !self.resources_changed.is_empty() {
            for (_, handler) in self.resources_changed.snapshot().iter() {
                handler(&e);
            }
        }

        if propagate {
            self.notify_child_resources_changed(e);
        }
    }

    fn flatten_styles(styles: &[Rc<dyn IStyle>], result: &mut Vec<Ref<StyleBase>>) {
        for style in styles {
            if let Some(s) = style.as_object().and_then(|o| o.downcast_ref::<Style>()) {
                result.push(s.to_ref().upcast());
            }
            let children = style.children();
            if !children.is_empty() {
                Self::flatten_styles(&children, result);
            }
        }
    }

    fn has_setters_or_animations(styles: &[Rc<dyn IStyle>]) -> bool {
        styles.iter().any(|style| {
            if style
                .as_object()
                .and_then(|o| o.downcast_ref::<StyleBase>())
                .is_some_and(StyleBase::has_setters_or_animations)
            {
                return true;
            }
            let children = style.children();
            !children.is_empty() && Self::has_setters_or_animations(&children)
        })
    }

    // --- data context -----------------------------------------------------

    fn data_context_notifying(o: &FerroObject, update_started: bool) {
        if let Some(element) = o.downcast_ref::<StyledElement>() {
            element.data_context_notifying_core(update_started);
        }
    }

    fn data_context_notifying_core(&self, update_started: bool) {
        if update_started {
            if !self.data_context_updating.get() {
                self.data_context_updating.set(true);
                self.on_data_context_begin_update();

                if let Some(children) = self.logical_children.get() {
                    let this: &FerroObject = self;
                    for child in children.snapshot().iter() {
                        if child.is_inheritance_parent(this) && !child.is_set(Self::data_context_property())
                        {
                            child.data_context_notifying_core(update_started);
                        }
                    }
                }
            }
        } else if self.data_context_updating.get() {
            self.on_data_context_end_update();
            self.data_context_updating.set(false);
        }
    }

    /// The priority-aware setter used by templates.
    pub fn set_data_context_with_priority(
        &self,
        value: Option<BoxedValue>,
        priority: BindingPriority,
    ) -> Option<Rc<dyn IDisposable>> {
        self.set_value_with_priority(Self::data_context_property(), value, priority)
    }
}

/// Ends a styling pass when dropped, so that the pass also ends when applying
/// a style panics.
struct EndStyling<'a>(&'a StyledElement);

impl Drop for EndStyling<'_> {
    fn drop(&mut self) {
        self.0.values().end_styling(self.0);
    }
}

impl IResourceNode for StyledElement {
    fn has_resources(&self) -> bool {
        StyledElement::has_resources(self)
    }

    fn try_get_resource(&self, key: &ResourceKey, theme: Option<&ThemeVariant>) -> Option<ResourceValue> {
        StyledElement::try_get_resource(self, key, theme)
    }
}

impl IResourceHost for StyledElement {
    fn resources_changed(&self, handler: Rc<dyn Fn(&ResourcesChangedEventArgs)>) -> Rc<dyn IDisposable> {
        self.subscribe_resources_changed(handler)
    }

    fn notify_hosted_resources_changed(&self, e: ResourcesChangedEventArgs) {
        self.notify_resources_changed(e, true)
    }

    fn as_style_host(&self) -> Option<&dyn IStyleHost> {
        Some(self)
    }

    fn as_theme_variant_host(&self) -> Option<&dyn IThemeVariantHost> {
        Some(self)
    }
}

impl IStyleHost for StyledElement {
    fn is_styles_initialized(&self) -> bool {
        StyledElement::is_styles_initialized(self)
    }

    fn styles(&self) -> Ref<Styles> {
        StyledElement::styles(self)
    }

    fn styling_parent(&self) -> Option<StyleHostRef> {
        StyledElement::styling_parent(self)
    }

    fn styles_added(&self, styles: &[Rc<dyn IStyle>]) {
        StyledElement::styles_added(self, styles)
    }

    fn styles_removed(&self, styles: &[Rc<dyn IStyle>]) {
        StyledElement::styles_removed(self, styles)
    }
}

impl IThemeVariantHost for StyledElement {
    fn actual_theme_variant(&self) -> Option<ThemeVariant> {
        StyledElement::actual_theme_variant(self)
    }

    fn actual_theme_variant_changed(&self, handler: Rc<dyn Fn()>) -> Rc<dyn IDisposable> {
        self.subscribe_actual_theme_variant_changed(handler)
    }
}