ferroui-controls 0.2.0

The controls of FerroUI: the application model, top levels, the control set and automation peers
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
//! The untyped collection contract of the items controls.
//!
//! The managed framework types `ItemsSource`, selection sources and the
//! like as "any enumerable" and discovers at run time whether the object is
//! an indexable list and whether it notifies of changes. Here that contract
//! is explicit:
//!
//! - an item is an `Option<BoxedValue>` (an untyped, nullable value);
//! - [`IItemsList`] is the untyped, indexable, optionally notifying list;
//! - [`ItemsSource`] is the shared handle stored in properties. It compares
//!   by the identity of the collection, so assigning the same collection
//!   twice is not a change.
//!
//! [`IItemsList`] is implemented for the collection abstractions of the
//! port, so each of them converts into an [`ItemsSource`] without copying:
//!
//! | Collection | Notifying | Items |
//! |---|---|---|
//! | `Rc<FerroList<T>>` | yes | each `T` boxed on access (no allocation when `T` is `BoxedValue` or `Option<BoxedValue>`) |
//! | `Rc<BindableList<T>>` | yes | as its inner `FerroList<T>` |
//! | `Vec<Option<BoxedValue>>`, `Vec<BoxedValue>` | no | as stored |
//! | any iterator of property values ([`ItemsSource::from_values`]) | no | boxed once, up front |
//!
//! A source that only enumerates is copied into a list when it is assigned,
//! exactly as the managed implementation copies a non-list enumerable.
//!
//! # Change notifications
//!
//! A notifying list reports changes with [`ItemsChangedEventArgs`], the
//! untyped counterpart of the typed `NotifyCollectionChangedEventArgs` of
//! `FerroList<T>`. The managed framework hands the changed list itself to
//! the handlers, which mostly ask it for its count only. Likewise
//! `new_items` and `old_items` here are an [`ItemsView`]: a `Copy` view,
//! two or three words wide, whose `len()` never reads an item and whose
//! `get(i)`/`iter()`/`to_vec()` read exactly the items asked for. A view is
//! one of:
//!
//! - a borrowed slice of untyped items ([`ItemsView::from_slice`]);
//! - a window of a list, read through [`IItemsList::get_at`] on demand
//!   ([`ItemsView::window`], [`ItemsView::of_source`]): replacing the source
//!   of an items control notifies with windows over the old and the new
//!   source, so a data-virtualised source is never enumerated;
//! - the typed items of a `FerroList<T>` change ([`ItemsView::from_typed`]),
//!   boxed one by one when read: adapting a typed notification allocates
//!   nothing, whatever the number of items.
//!
//! Handlers on virtualizing paths use the counts only. A handler that keeps
//! items beyond the notification copies them with `to_vec()`.
//!
//! Controls are items too: a control item is boxed as exactly `Ref<Control>`
//! (see `Control::boxed`).
//!
//! Bindings deliver untyped values of the view model's property type. To
//! bind a view model property holding one of the collection types above to
//! an items source property, register the conversion once with
//! [`ItemsSource::register_binding_conversion`].

use ferroui_base::collections::{FerroList, NotifyCollectionChangedAction, NotifyCollectionChangedEventArgs};
use ferroui_base::data::core::ValueTypes;
use ferroui_base::data::model::BindableList;
use ferroui_base::{AnyValue, BoxedValue, PropertyValue};
use std::any::Any;
use std::rc::Rc;

/// The items carried by a change notification of an untyped items list: a
/// cheap, copyable view that produces an item only when asked for it.
///
/// See the module documentation ("Change notifications").
#[derive(Clone, Copy)]
pub struct ItemsView<'a>(ItemsViewSource<'a>);

#[derive(Clone, Copy)]
enum ItemsViewSource<'a> {
    /// Items that already exist as untyped values.
    Slice(&'a [Option<BoxedValue>]),
    /// `count` items of `list` starting at `start`, read on demand.
    Window { list: &'a dyn IItemsList, start: usize, count: usize },
    /// The items of a typed collection, boxed on demand.
    Typed(&'a dyn TypedItemsSource),
}

/// The typed items of a change, viewed as untyped items by
/// [`ItemsView::from_typed`]. Each item is boxed when it is read (no
/// allocation when `T` is `BoxedValue` or `Option<BoxedValue>`).
pub struct TypedItems<'a, T>(pub &'a [T]);

trait TypedItemsSource {
    fn len(&self) -> usize;
    fn get(&self, index: usize) -> Option<BoxedValue>;
}

impl<T: PropertyValue> TypedItemsSource for TypedItems<'_, T> {
    #[inline]
    fn len(&self) -> usize {
        self.0.len()
    }

    #[inline]
    fn get(&self, index: usize) -> Option<BoxedValue> {
        box_item(&self.0[index])
    }
}

impl<'a> ItemsView<'a> {
    /// A view of no items.
    pub const EMPTY: ItemsView<'static> = ItemsView(ItemsViewSource::Slice(&[]));

    /// A view of existing untyped items.
    #[inline]
    pub const fn from_slice(items: &'a [Option<BoxedValue>]) -> Self {
        Self(ItemsViewSource::Slice(items))
    }

    /// A view of `count` items of `list` starting at `start`. Nothing is
    /// read from the list until an item is asked for.
    #[inline]
    pub fn window(list: &'a dyn IItemsList, start: usize, count: usize) -> Self {
        Self(ItemsViewSource::Window { list, start, count })
    }

    /// A view of all the items of `source`. Only the count is read.
    #[inline]
    pub fn of_source(source: &'a ItemsSource) -> Self {
        Self::window(&**source.list(), 0, source.count())
    }

    /// A view of `count` items of `source` starting at `start`.
    #[inline]
    pub fn of_source_range(source: &'a ItemsSource, start: usize, count: usize) -> Self {
        Self::window(&**source.list(), start, count)
    }

    /// A view of typed items, each boxed when it is read.
    #[inline]
    pub fn from_typed<T: PropertyValue>(items: &'a TypedItems<'a, T>) -> Self {
        Self(ItemsViewSource::Typed(items))
    }

    /// The number of items. Never reads an item.
    #[inline]
    pub fn len(&self) -> usize {
        match self.0 {
            ItemsViewSource::Slice(items) => items.len(),
            ItemsViewSource::Window { count, .. } => count,
            ItemsViewSource::Typed(items) => items.len(),
        }
    }

    /// Whether the view has no items. Never reads an item.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The item at `index`. Panics if out of range.
    #[inline]
    pub fn get(&self, index: usize) -> Option<BoxedValue> {
        match self.0 {
            ItemsViewSource::Slice(items) => items[index].clone(),
            ItemsViewSource::Window { list, start, count } => {
                assert!(index < count, "index out of range");
                list.get_at(start + index)
            }
            ItemsViewSource::Typed(items) => items.get(index),
        }
    }

    /// The items, each read when the iterator reaches it.
    #[inline]
    pub fn iter(&self) -> ItemsViewIter<'a> {
        ItemsViewIter { view: *self, index: 0, end: self.len() }
    }

    /// A copy of the items. Reads every item.
    pub fn to_vec(&self) -> Vec<Option<BoxedValue>> {
        match self.0 {
            ItemsViewSource::Slice(items) => items.to_vec(),
            _ => self.iter().collect(),
        }
    }
}

impl Default for ItemsView<'_> {
    fn default() -> Self {
        ItemsView::EMPTY
    }
}

impl std::fmt::Debug for ItemsView<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ItemsView(len = {})", self.len())
    }
}

impl<'a> From<&'a [Option<BoxedValue>]> for ItemsView<'a> {
    #[inline]
    fn from(items: &'a [Option<BoxedValue>]) -> Self {
        Self::from_slice(items)
    }
}

impl<'a> From<&'a Vec<Option<BoxedValue>>> for ItemsView<'a> {
    #[inline]
    fn from(items: &'a Vec<Option<BoxedValue>>) -> Self {
        Self::from_slice(items)
    }
}

impl<'a, const N: usize> From<&'a [Option<BoxedValue>; N]> for ItemsView<'a> {
    #[inline]
    fn from(items: &'a [Option<BoxedValue>; N]) -> Self {
        Self::from_slice(items)
    }
}

impl<'a> From<&'a ItemsSource> for ItemsView<'a> {
    #[inline]
    fn from(source: &'a ItemsSource) -> Self {
        Self::of_source(source)
    }
}

/// The iterator of an [`ItemsView`].
#[derive(Clone)]
pub struct ItemsViewIter<'a> {
    view: ItemsView<'a>,
    index: usize,
    end: usize,
}

impl Iterator for ItemsViewIter<'_> {
    type Item = Option<BoxedValue>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.end {
            self.index += 1;
            Some(self.view.get(self.index - 1))
        } else {
            None
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.end - self.index;
        (remaining, Some(remaining))
    }
}

impl DoubleEndedIterator for ItemsViewIter<'_> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.index < self.end {
            self.end -= 1;
            Some(self.view.get(self.end))
        } else {
            None
        }
    }
}

impl ExactSizeIterator for ItemsViewIter<'_> {}

impl<'a> IntoIterator for ItemsView<'a> {
    type Item = Option<BoxedValue>;
    type IntoIter = ItemsViewIter<'a>;

    #[inline]
    fn into_iter(self) -> ItemsViewIter<'a> {
        self.iter()
    }
}

impl<'a> IntoIterator for &ItemsView<'a> {
    type Item = Option<BoxedValue>;
    type IntoIter = ItemsViewIter<'a>;

    #[inline]
    fn into_iter(self) -> ItemsViewIter<'a> {
        self.iter()
    }
}

/// A change to an untyped items list.
#[derive(Clone, Copy, Debug)]
pub struct ItemsChangedEventArgs<'a> {
    /// The action that caused the notification.
    pub action: NotifyCollectionChangedAction,
    /// The items involved in the change (added, or the replacements).
    pub new_items: ItemsView<'a>,
    /// The items affected by a replace, remove or move.
    pub old_items: ItemsView<'a>,
    /// The index at which the change occurred, or `-1`.
    pub new_starting_index: i32,
    /// The index at which a move, remove or replace occurred, or `-1`.
    pub old_starting_index: i32,
}

impl ItemsChangedEventArgs<'static> {
    /// The arguments of a reset notification.
    pub const RESET: ItemsChangedEventArgs<'static> = ItemsChangedEventArgs {
        action: NotifyCollectionChangedAction::Reset,
        new_items: ItemsView::EMPTY,
        old_items: ItemsView::EMPTY,
        new_starting_index: -1,
        old_starting_index: -1,
    };
}

impl<'a> ItemsChangedEventArgs<'a> {
    /// The arguments of an add of `new_items` at `new_starting_index`.
    #[inline]
    pub fn add(new_items: impl Into<ItemsView<'a>>, new_starting_index: i32) -> Self {
        Self {
            action: NotifyCollectionChangedAction::Add,
            new_items: new_items.into(),
            old_items: ItemsView::EMPTY,
            new_starting_index,
            old_starting_index: -1,
        }
    }

    /// The arguments of a remove of `old_items` from `old_starting_index`.
    #[inline]
    pub fn remove(old_items: impl Into<ItemsView<'a>>, old_starting_index: i32) -> Self {
        Self {
            action: NotifyCollectionChangedAction::Remove,
            new_items: ItemsView::EMPTY,
            old_items: old_items.into(),
            new_starting_index: -1,
            old_starting_index,
        }
    }
}

/// The change of a list of untyped items, as it is: the items are viewed in
/// place.
impl<'a> From<&NotifyCollectionChangedEventArgs<'a, Option<BoxedValue>>> for ItemsChangedEventArgs<'a> {
    #[inline]
    fn from(e: &NotifyCollectionChangedEventArgs<'a, Option<BoxedValue>>) -> Self {
        Self {
            action: e.action,
            new_items: ItemsView::from_slice(e.new_items),
            old_items: ItemsView::from_slice(e.old_items),
            new_starting_index: e.new_starting_index,
            old_starting_index: e.old_starting_index,
        }
    }
}

/// The signature of a handler of changes to an untyped items list.
pub type ItemsChangedHandler = dyn for<'a> Fn(&ItemsChangedEventArgs<'a>);

/// Compares two items: both null, or both of the same type and equal.
#[inline]
pub fn items_equal(a: &Option<BoxedValue>, b: &Option<BoxedValue>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => Rc::ptr_eq(a, b) || (**a).any_value_eq(&**b),
        _ => false,
    }
}

/// Whether two untyped values are the same object: C# `ReferenceEquals` (and
/// `==` / `!=` on `object`) for values that travel in boxes.
///
/// The rule:
/// * both null, or the same box: the same reference;
/// * boxes that hold handles of the same object of the class hierarchy (a
///   control boxed twice, or boxed once as `Ref<Control>` and once as
///   `Ref<Border>`): the same reference;
/// * boxes that both hold a string: the same reference if the strings are
///   equal. A string is the immutable value-like type that the lists of the
///   managed original hand out as the same instance on every read, whereas a
///   typed list of strings here boxes each string anew on every read; without
///   this, an unchanged item read twice would look like another object;
/// * anything else in two boxes (two separately boxed equal numbers, two
///   equal structures) is two references, as two boxings are in the managed
///   original.
///
/// Use [`items_equal`] where the original calls `Equals`.
pub fn reference_equals(a: &Option<BoxedValue>, b: &Option<BoxedValue>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => boxed_reference_equals(a, b),
        _ => false,
    }
}

/// [`reference_equals`] for two values that are not null.
pub fn boxed_reference_equals(a: &BoxedValue, b: &BoxedValue) -> bool {
    // The addresses of the boxes; the comparison of the handles themselves
    // would also compare their metadata.
    if std::ptr::addr_eq(Rc::as_ptr(a), Rc::as_ptr(b)) {
        return true;
    }

    fn as_str(value: &dyn AnyValue) -> Option<&str> {
        if let Some(text) = value.downcast_ref::<String>() {
            return Some(text.as_str());
        }
        value.downcast_ref::<&'static str>().copied()
    }

    let (a, b): (&dyn AnyValue, &dyn AnyValue) = (&**a, &**b);
    if let (Some(a), Some(b)) = (as_str(a), as_str(b)) {
        return a == b;
    }

    match (ValueTypes::as_object(a), ValueTypes::as_object(b)) {
        (Some(a), Some(b)) => a.ptr_eq(&b),
        _ => false,
    }
}

/// Boxes a typed value as an item. A value that already is an untyped value
/// is passed through.
#[inline]
pub fn box_item<T: PropertyValue>(value: &T) -> Option<BoxedValue> {
    let any: &dyn Any = value;
    if let Some(boxed) = any.downcast_ref::<BoxedValue>() {
        return Some(boxed.clone());
    }
    if let Some(boxed) = any.downcast_ref::<Option<BoxedValue>>() {
        return boxed.clone();
    }
    Some(Rc::new(value.clone()))
}

/// The typed value held by an item: the item itself when `T` is the untyped
/// value type, otherwise the contained `T`. `None` for a null item or an
/// item of another type.
#[inline]
pub fn unbox_item<T: PropertyValue>(item: &Option<BoxedValue>) -> Option<T> {
    let boxed = item.as_ref()?;
    let any: &dyn Any = boxed;
    if let Some(value) = any.downcast_ref::<T>() {
        // `T` is `BoxedValue`.
        return Some(value.clone());
    }
    let value: &dyn AnyValue = &**boxed;
    value.downcast_ref::<T>().cloned()
}

/// Whether an item holds a value equal to `value`, without boxing `value`.
#[inline]
fn item_equals_typed<T: PropertyValue>(item: &Option<BoxedValue>, value: &T) -> bool {
    let any: &dyn Any = value;
    if let Some(boxed) = any.downcast_ref::<BoxedValue>() {
        return item.as_ref().is_some_and(|item| Rc::ptr_eq(item, boxed) || (**item).any_value_eq(&**boxed));
    }
    if let Some(boxed) = any.downcast_ref::<Option<BoxedValue>>() {
        return items_equal(item, boxed);
    }
    match item {
        Some(item) => {
            let item: &dyn AnyValue = &**item;
            item.downcast_ref::<T>().is_some_and(|item| item == value)
        }
        None => false,
    }
}

/// An untyped, indexable list of items that may notify of changes.
pub trait IItemsList {
    /// The number of items.
    fn count(&self) -> usize;

    /// The item at `index`. Panics if out of range.
    fn get_at(&self, index: usize) -> Option<BoxedValue>;

    /// The index of the first item equal to `item`, or `-1`.
    fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        for i in 0..self.count() {
            if items_equal(&self.get_at(i), item) {
                return i as i32;
            }
        }
        -1
    }

    /// Whether the list notifies of changes.
    fn is_notifying(&self) -> bool {
        false
    }

    /// Subscribes to changes. Returns the token for
    /// [`remove_collection_changed`](Self::remove_collection_changed), or
    /// `None` if the list does not notify.
    fn add_collection_changed(&self, _handler: Rc<ItemsChangedHandler>) -> Option<u64> {
        None
    }

    /// Unsubscribes a handler.
    fn remove_collection_changed(&self, _token: u64) {}

    /// The identity of the collection, for a list that is a handle to a collection
    /// (a [`FerroList`]): two handles to one collection are the same collection. `None`
    /// for a list that is the collection itself, whose identity is its address.
    fn identity(&self) -> Option<usize> {
        None
    }

    /// The collection as [`Any`], to get back to the typed collection.
    fn as_any(&self) -> &dyn Any;
}

impl IItemsList for Vec<Option<BoxedValue>> {
    fn count(&self) -> usize {
        self.len()
    }

    fn get_at(&self, index: usize) -> Option<BoxedValue> {
        self[index].clone()
    }

    fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        self.iter().position(|i| items_equal(i, item)).map_or(-1, |i| i as i32)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<T: PropertyValue> IItemsList for FerroList<T> {
    fn count(&self) -> usize {
        FerroList::count(self)
    }

    fn get_at(&self, index: usize) -> Option<BoxedValue> {
        let snapshot = self.snapshot();
        box_item(&snapshot[index])
    }

    fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        let snapshot = self.snapshot();
        if let Some(index) = snapshot.iter().position(|i| item_equals_typed(item, i)) {
            return index as i32;
        }
        // The item in another form than the list holds it in: a shared object of a list of
        // handles (`Rc<T>`) is delivered by a binding as the object itself. Upstream's
        // `IList.IndexOf(object)` finds the reference whatever the static type of the list.
        let is_typed = item.as_ref().is_some_and(|boxed| (**boxed).downcast_ref::<T>().is_some());
        if !is_typed {
            if let Some(typed) = ferroui_base::metadata::from_markup_value::<T>(item) {
                return snapshot.iter().position(|i| *i == typed).map_or(-1, |i| i as i32);
            }
        }
        -1
    }

    fn is_notifying(&self) -> bool {
        true
    }

    fn add_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> Option<u64> {
        Some(FerroList::add_collection_changed(
            self,
            Rc::new(move |e: &NotifyCollectionChangedEventArgs<'_, T>| {
                // Nothing is boxed or copied here: the handler boxes the
                // items it reads.
                let new_items = TypedItems(e.new_items);
                let old_items = TypedItems(e.old_items);
                handler(&ItemsChangedEventArgs {
                    action: e.action,
                    new_items: ItemsView::from_typed(&new_items),
                    old_items: ItemsView::from_typed(&old_items),
                    new_starting_index: e.new_starting_index,
                    old_starting_index: e.old_starting_index,
                });
            }),
        ))
    }

    fn remove_collection_changed(&self, token: u64) {
        FerroList::remove_collection_changed(self, token);
    }

    fn identity(&self) -> Option<usize> {
        Some(ferroui_base::utilities::WeakEventSender::sender_address(self))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<T: PropertyValue> IItemsList for BindableList<T> {
    fn count(&self) -> usize {
        self.items().count()
    }

    fn get_at(&self, index: usize) -> Option<BoxedValue> {
        IItemsList::get_at(self.items(), index)
    }

    fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        IItemsList::index_of(self.items(), item)
    }

    fn is_notifying(&self) -> bool {
        true
    }

    fn add_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> Option<u64> {
        IItemsList::add_collection_changed(self.items(), handler)
    }

    fn remove_collection_changed(&self, token: u64) {
        IItemsList::remove_collection_changed(self.items(), token);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A shared handle to an untyped items list: the value of an items source
/// property.
///
/// Equality is the identity of the underlying collection.
#[derive(Clone)]
pub struct ItemsSource(Rc<dyn IItemsList>);

impl ItemsSource {
    /// Wraps a list.
    pub fn new(list: Rc<dyn IItemsList>) -> Self {
        Self(list)
    }

    /// Creates a non-notifying source holding the given items.
    pub fn from_items(items: impl IntoIterator<Item = Option<BoxedValue>>) -> Self {
        Self(Rc::new(items.into_iter().collect::<Vec<_>>()))
    }

    /// Creates a non-notifying source by boxing each of the given values.
    pub fn from_values<T: PropertyValue>(values: impl IntoIterator<Item = T>) -> Self {
        Self(Rc::new(values.into_iter().map(|v| box_item(&v)).collect::<Vec<_>>()))
    }

    /// Creates a non-notifying source of strings.
    pub fn from_strs<'a>(values: impl IntoIterator<Item = &'a str>) -> Self {
        Self::from_values(values.into_iter().map(str::to_string))
    }

    /// The list.
    #[inline]
    pub fn list(&self) -> &Rc<dyn IItemsList> {
        &self.0
    }

    /// The number of items.
    #[inline]
    pub fn count(&self) -> usize {
        self.0.count()
    }

    /// The item at `index`. Panics if out of range.
    #[inline]
    pub fn get_at(&self, index: usize) -> Option<BoxedValue> {
        self.0.get_at(index)
    }

    /// The index of the first item equal to `item`, or `-1`.
    #[inline]
    pub fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        self.0.index_of(item)
    }

    /// Whether the list contains an item equal to `item`.
    #[inline]
    pub fn contains(&self, item: &Option<BoxedValue>) -> bool {
        self.0.index_of(item) >= 0
    }

    /// Whether the list notifies of changes.
    #[inline]
    pub fn is_notifying(&self) -> bool {
        self.0.is_notifying()
    }

    /// The typed collection behind the source, if it is a `T`.
    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
        self.0.as_any().downcast_ref::<T>()
    }

    /// The identity of the underlying collection.
    #[inline]
    pub fn identity(&self) -> usize {
        self.0.identity().unwrap_or(Rc::as_ptr(&self.0) as *const () as usize)
    }

    /// Whether two handles refer to the same collection.
    #[inline]
    pub fn ptr_eq(&self, other: &ItemsSource) -> bool {
        self.identity() == other.identity()
    }

    /// The items, enumerated by index over the live list.
    pub fn iter(&self) -> impl Iterator<Item = Option<BoxedValue>> + '_ {
        let mut index = 0;
        std::iter::from_fn(move || {
            if index < self.0.count() {
                index += 1;
                Some(self.0.get_at(index - 1))
            } else {
                None
            }
        })
    }

    /// A copy of the items.
    pub fn to_vec(&self) -> Vec<Option<BoxedValue>> {
        self.iter().collect()
    }

    /// Lets bindings deliver a value of the collection type `S` to a
    /// property of type `Option<ItemsSource>` (or `ItemsSource`) on the
    /// current thread.
    /// [`register_binding_conversion`](Self::register_binding_conversion) for a
    /// collection type that converts with `convert` (a list handle that is delivered as
    /// the shared list).
    pub fn register_binding_conversion_with<S: 'static>(convert: fn(&S) -> ItemsSource) {
        ValueTypes::register_conversion::<S, ItemsSource>(move |s| Some(convert(s)));
        ValueTypes::register_conversion::<S, Option<ItemsSource>>(move |s| Some(Some(convert(s))));
    }

    pub fn register_binding_conversion<S: Clone + Into<ItemsSource> + 'static>() {
        ValueTypes::register_conversion::<S, ItemsSource>(|s| Some(s.clone().into()));
        ValueTypes::register_conversion::<S, Option<ItemsSource>>(|s| Some(Some(s.clone().into())));
    }
}

impl PartialEq for ItemsSource {
    fn eq(&self, other: &Self) -> bool {
        self.ptr_eq(other)
    }
}

impl std::fmt::Debug for ItemsSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ItemsSource(count = {})", self.count())
    }
}

impl From<Rc<dyn IItemsList>> for ItemsSource {
    fn from(value: Rc<dyn IItemsList>) -> Self {
        Self(value)
    }
}

impl<T: PropertyValue> From<Rc<FerroList<T>>> for ItemsSource {
    fn from(value: Rc<FerroList<T>>) -> Self {
        Self(value)
    }
}

impl<T: PropertyValue> From<Rc<BindableList<T>>> for ItemsSource {
    fn from(value: Rc<BindableList<T>>) -> Self {
        Self(value)
    }
}

impl From<Vec<Option<BoxedValue>>> for ItemsSource {
    fn from(value: Vec<Option<BoxedValue>>) -> Self {
        Self(Rc::new(value))
    }
}

impl From<Vec<BoxedValue>> for ItemsSource {
    fn from(value: Vec<BoxedValue>) -> Self {
        Self::from_items(value.into_iter().map(Some))
    }
}

impl From<Rc<Vec<Option<BoxedValue>>>> for ItemsSource {
    fn from(value: Rc<Vec<Option<BoxedValue>>>) -> Self {
        Self(value)
    }
}

#[cfg(test)]
mod reference_equals_tests {
    use super::{boxed_reference_equals, items_equal, reference_equals};
    use crate::{Border, Control};
    use ferroui_base::{BoxedValue, Ref, StyledElement};
    use std::rc::Rc;

    fn boxed<T: PartialEq + 'static>(value: T) -> Option<BoxedValue> {
        Some(Rc::new(value))
    }

    #[test]
    fn nulls_and_the_same_box_are_the_same_reference() {
        let value = boxed(42_i32);

        assert!(reference_equals(&None, &None));
        assert!(reference_equals(&value, &value.clone()));
        assert!(!reference_equals(&value, &None));
        assert!(!reference_equals(&None, &value));
    }

    #[test]
    fn equal_strings_in_different_boxes_are_the_same_reference() {
        assert!(reference_equals(&boxed("able".to_string()), &boxed("able".to_string())));
        assert!(reference_equals(&boxed("able".to_string()), &boxed("able")));
        assert!(reference_equals(&boxed(String::new()), &boxed(String::new())));
        assert!(!reference_equals(&boxed("able".to_string()), &boxed("abide".to_string())));
        assert!(!reference_equals(&boxed("able".to_string()), &boxed("Able".to_string())));
        assert!(!reference_equals(&boxed("1".to_string()), &boxed(1_i32)));
    }

    #[test]
    fn equal_values_in_different_boxes_are_different_references() {
        assert!(!reference_equals(&boxed(42_i32), &boxed(42_i32)));
        assert!(!reference_equals(&boxed(1.5_f64), &boxed(1.5_f64)));
        assert!(!reference_equals(&boxed(true), &boxed(true)));
        // They are equal values all the same.
        assert!(items_equal(&boxed(42_i32), &boxed(42_i32)));
    }

    #[test]
    fn the_same_control_in_different_boxes_is_the_same_reference() {
        let border = Border::new();
        let as_control: Ref<Control> = border.clone().upcast();
        let as_element: Ref<StyledElement> = border.clone().upcast();

        assert!(reference_equals(&Some(Control::boxed(border.clone())), &Some(Control::boxed(border.clone()))));
        // Whatever the type of the handle in the box is.
        assert!(reference_equals(&boxed(border.clone()), &boxed(as_control)));
        assert!(reference_equals(&boxed(as_element), &boxed(border.clone())));
        assert!(boxed_reference_equals(&Control::boxed(border.clone()), &Control::boxed(border)));
    }

    #[test]
    fn different_controls_are_different_references() {
        let (first, second) = (Border::new(), Border::new());

        assert!(!reference_equals(&Some(Control::boxed(first.clone())), &Some(Control::boxed(second))));
        assert!(!reference_equals(&Some(Control::boxed(first)), &boxed("able".to_string())));
    }
}

#[cfg(test)]
mod reference_item_tests {
    // Not from upstream: an item of a list of handles is found in the form a binding
    // delivers it in (found by the IntegrationTestApp sample, I008).
    use super::*;

    #[derive(PartialEq)]
    struct Model(i32);

    #[test]
    fn a_shared_object_is_found_in_a_list_of_its_handles() {
        ValueTypes::register_reference::<Model>();
        let (first, second) = (Rc::new(Model(1)), Rc::new(Model(2)));
        let list: FerroList<Rc<Model>> = FerroList::new();
        list.add(first.clone());
        list.add(second.clone());
        // The form the list boxes its items in.
        assert_eq!(1, IItemsList::index_of(&list, &IItemsList::get_at(&list, 1)));
        // The object itself, as a binding of a property of the handle type delivers it.
        assert_eq!(1, IItemsList::index_of(&list, &Some(second as BoxedValue)));
        assert_eq!(-1, IItemsList::index_of(&list, &Some(Rc::new(7i32) as BoxedValue)));
    }
}

#[cfg(test)]
mod identity_tests {
    // Not from upstream: the identity of an items source over a handle to a collection.
    use super::ItemsSource;
    use ferroui_base::collections::FerroList;
    use std::rc::Rc;

    #[test]
    fn two_handles_to_one_list_are_the_same_collection() {
        let list = FerroList::from_items([1, 2, 3]);
        let first = ItemsSource::from(Rc::new(list.clone()));
        let second = ItemsSource::from(Rc::new(list.clone()));
        assert!(first.ptr_eq(&second));
        assert_eq!(first, second);

        let other = ItemsSource::from(Rc::new(FerroList::from_items([1, 2, 3])));
        assert!(!first.ptr_eq(&other));

        // A list that is the collection itself is identified by its address.
        let vector = ItemsSource::from(vec![None, None]);
        assert!(vector.ptr_eq(&vector.clone()));
        assert!(!vector.ptr_eq(&ItemsSource::from(vec![None, None])));
    }
}