ferroui-controls 0.4.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
// This source file is adapted from the WinUI project.
// (https://github.com/microsoft/microsoft-ui-xaml)

use crate::items_source::{unbox_item, IItemsList, ItemsChangedEventArgs, ItemsChangedHandler, ItemsSource};
use crate::utils::{CollectionChangedEventManager, ICollectionChangedListener};
use ferroui_base::utilities::HandlerList;
use ferroui_base::{BoxedValue, PropertyValue};
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::{Rc, Weak};

ferroui_base::ferro_thread_local! {
    static EMPTY: Rc<ItemsSourceView> = ItemsSourceView::new(ItemsSource::from_items([]));
    // This is a sentinel value and must be unique.
    static UNINITIALIZED_SOURCE: ItemsSource = ItemsSource::from_items([]);
}

/// Represents a standardized view of the supported interactions between an
/// items collection and an items control.
pub struct ItemsSourceView {
    this: Weak<ItemsSourceView>,
    source: RefCell<ItemsSource>,
    collection_changed: HandlerList<ItemsChangedHandler>,
    pre_collection_changed: HandlerList<ItemsChangedHandler>,
    post_collection_changed: HandlerList<ItemsChangedHandler>,
    listening: Cell<bool>,
}

/// A view is a reference: two views are equal when they are the same view.
impl PartialEq for ItemsSourceView {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self, other)
    }
}

impl ItemsSourceView {
    /// Gets an empty [`ItemsSourceView`].
    pub fn empty() -> Rc<ItemsSourceView> {
        EMPTY.with(Rc::clone)
    }

    /// Gets an instance representing an uninitialized source.
    pub(crate) fn uninitialized_source() -> ItemsSource {
        UNINITIALIZED_SOURCE.with(Clone::clone)
    }

    /// Initializes a new instance of the view for the specified data source.
    // Deviation (DEVIATIONS.md, Items sources): upstream's constructor is `private protected`;
    // WinUI's is public, and markup constructs a view (`ItemsSourceView(Object source)`).
    pub fn new(source: ItemsSource) -> Rc<Self> {
        Rc::new_cyclic(|this| Self {
            this: this.clone(),
            source: RefCell::new(source),
            collection_changed: HandlerList::new(),
            pre_collection_changed: HandlerList::new(),
            post_collection_changed: HandlerList::new(),
            listening: Cell::new(false),
        })
    }

    /// Gets the number of items in the collection.
    #[inline]
    pub fn count(&self) -> usize {
        self.source.borrow().count()
    }

    /// Gets a value that indicates whether the items source can provide a unique key for
    /// each item: whether the source implements [`IKeyIndexMapping`](crate::IKeyIndexMapping)
    /// (WinUI `ItemsSourceView.HasKeyIndexMapping`).
    // Deviation (DEVIATIONS.md, Items sources): upstream keeps the member internal and always
    // `false` ("preserved here for ItemsRepeater's usage"); here it is WinUI's.
    pub fn has_key_index_mapping(&self) -> bool {
        self.source().list().key_index_mapping().is_some()
    }

    /// Retrieves the unique key of the item at `index` from the items source
    /// (WinUI `ItemsSourceView.KeyFromIndex`).
    ///
    /// Panics if the source does not implement [`IKeyIndexMapping`](crate::IKeyIndexMapping)
    /// (WinUI throws `hresult_not_implemented`), or if `index` is not the index of an item.
    // Deviation (DEVIATIONS.md, Items sources): upstream throws `NotImplementedException`
    // whatever the source; here it is WinUI's, with the index checked before it is passed on.
    pub fn key_from_index(&self, index: i32) -> String {
        let source = self.source();
        assert!(index >= 0 && (index as usize) < source.count(), "Argument index is invalid.");
        source
            .list()
            .key_index_mapping()
            .expect("The items source does not implement IKeyIndexMapping.")
            .key_from_index(index)
    }

    /// Retrieves the index of the item that has the unique key `key`, or `-1` when no item
    /// has it (WinUI `ItemsSourceView.IndexFromKey`).
    ///
    /// Panics if the source does not implement [`IKeyIndexMapping`](crate::IKeyIndexMapping)
    /// (WinUI throws `hresult_not_implemented`).
    pub fn index_from_key(&self, key: &str) -> i32 {
        self.source()
            .list()
            .key_index_mapping()
            .expect("The items source does not implement IKeyIndexMapping.")
            .index_from_key(key)
    }

    /// Gets the source collection.
    #[inline]
    pub fn source(&self) -> ItemsSource {
        self.source.borrow().clone()
    }

    pub(crate) fn try_get_initialized_source(&self) -> Option<ItemsSource> {
        let source = self.source();
        if source.ptr_eq(&Self::uninitialized_source()) {
            None
        } else {
            Some(source)
        }
    }

    /// Occurs when the collection has changed to indicate the reason for
    /// the change and which items changed. Returns the token for
    /// [`remove_collection_changed`](Self::remove_collection_changed).
    pub fn add_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> u64 {
        self.add_listener_if_necessary();
        self.collection_changed.add(handler)
    }

    pub fn remove_collection_changed(&self, token: u64) {
        self.collection_changed.remove(token);
        self.remove_listener_if_necessary();
    }

    /// Occurs when a collection is about to notify its
    /// [`collection changed`](Self::add_collection_changed) handlers.
    pub(crate) fn add_pre_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> u64 {
        self.add_listener_if_necessary();
        self.pre_collection_changed.add(handler)
    }

    pub(crate) fn remove_pre_collection_changed(&self, token: u64) {
        self.pre_collection_changed.remove(token);
        self.remove_listener_if_necessary();
    }

    /// Occurs when a collection has finished changing and all
    /// [`collection changed`](Self::add_collection_changed) handlers have
    /// been notified.
    pub(crate) fn add_post_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> u64 {
        self.add_listener_if_necessary();
        self.post_collection_changed.add(handler)
    }

    pub(crate) fn remove_post_collection_changed(&self, token: u64) {
        self.post_collection_changed.remove(token);
        self.remove_listener_if_necessary();
    }

    /// Retrieves the item at the specified index. Panics if out of range.
    #[inline]
    pub fn get_at(&self, index: usize) -> Option<BoxedValue> {
        let source = self.source.borrow().clone();
        source.get_at(index)
    }

    /// Whether the collection contains the item.
    pub fn contains(&self, item: &Option<BoxedValue>) -> bool {
        self.index_of(item) >= 0
    }

    /// The index of the item, or `-1`.
    pub fn index_of(&self, item: &Option<BoxedValue>) -> i32 {
        let source = self.source.borrow().clone();
        source.index_of(item)
    }

    /// Gets or creates an [`ItemsSourceView`] for the specified source.
    ///
    /// Returns [`empty`](Self::empty) if `items` is `None`, the view itself if `items`
    /// is a view (`ItemsSourceView isv => isv`), otherwise a new view.
    pub fn get_or_create(items: Option<&ItemsSource>) -> Rc<ItemsSourceView> {
        match items {
            None => Self::empty(),
            Some(items) => items
                .downcast_ref::<Self>()
                .and_then(|view| view.this.upgrade())
                .unwrap_or_else(|| Self::new(items.clone())),
        }
    }

    /// Gets or creates a typed view for the specified source.
    pub fn get_or_create_of<T: PropertyValue>(items: Option<&ItemsSource>) -> ItemsSourceViewOf<T> {
        match items {
            None => ItemsSourceViewOf::empty(),
            Some(items) => ItemsSourceViewOf::new(items.clone()),
        }
    }

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

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

    pub(crate) fn raise_collection_changed(&self, e: &ItemsChangedEventArgs<'_>) {
        Self::invoke(&self.pre_collection_changed, e);
        Self::invoke(&self.collection_changed, e);
        Self::invoke(&self.post_collection_changed, e);
    }

    pub(crate) fn set_source(&self, source: ItemsSource) {
        let listener: Weak<dyn ICollectionChangedListener> = self.this.clone();

        if self.listening.get() {
            let old = self.source();
            if old.is_notifying() {
                CollectionChangedEventManager::remove_listener(&old, &listener);
            }
        }

        *self.source.borrow_mut() = source.clone();

        if self.listening.get() && source.is_notifying() {
            CollectionChangedEventManager::add_listener(&source, listener);
        }
    }

    fn add_listener_if_necessary(&self) {
        if !self.listening.get() {
            let source = self.source();
            if source.is_notifying() {
                CollectionChangedEventManager::add_listener(&source, self.this.clone());
            }
            self.listening.set(true);
        }
    }

    fn remove_listener_if_necessary(&self) {
        if self.listening.get() && self.collection_changed.is_empty() && self.post_collection_changed.is_empty() {
            let source = self.source();
            if source.is_notifying() {
                let listener: Weak<dyn ICollectionChangedListener> = self.this.clone();
                CollectionChangedEventManager::remove_listener(&source, &listener);
            }
            self.listening.set(false);
        }
    }

    #[inline]
    fn invoke(handlers: &HandlerList<ItemsChangedHandler>, e: &ItemsChangedEventArgs<'_>) {
        if !handlers.is_empty() {
            for (_, handler) in handlers.snapshot().iter() {
                handler(e);
            }
        }
    }
}

/// A view is a list of items itself (upstream `ItemsSourceView : IReadOnlyList<object?>, IList,
/// INotifyCollectionChanged`): it can be the items source of a control, which then reads the
/// items and the changes through the view, and [`ItemsSourceView::get_or_create`] returns it as
/// it is. Its unique keys are those of its source.
impl IItemsList for ItemsSourceView {
    fn key_index_mapping(&self) -> Option<&dyn crate::IKeyIndexMapping> {
        self.has_key_index_mapping().then_some(self as &dyn crate::IKeyIndexMapping)
    }

    fn count(&self) -> usize {
        ItemsSourceView::count(self)
    }

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

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

    fn is_notifying(&self) -> bool {
        self.source().is_notifying()
    }

    fn add_collection_changed(&self, handler: Rc<ItemsChangedHandler>) -> Option<u64> {
        self.is_notifying().then(|| ItemsSourceView::add_collection_changed(self, handler))
    }

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

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

impl crate::IKeyIndexMapping for ItemsSourceView {
    fn key_from_index(&self, index: i32) -> String {
        ItemsSourceView::key_from_index(self, index)
    }

    fn index_from_key(&self, key: &str) -> i32 {
        ItemsSourceView::index_from_key(self, key)
    }
}

impl ICollectionChangedListener for ItemsSourceView {
    fn pre_changed(&self, e: &ItemsChangedEventArgs<'_>) {
        Self::invoke(&self.pre_collection_changed, e);
    }

    fn changed(&self, e: &ItemsChangedEventArgs<'_>) {
        Self::invoke(&self.collection_changed, e);
    }

    fn post_changed(&self, e: &ItemsChangedEventArgs<'_>) {
        Self::invoke(&self.post_collection_changed, e);
    }
}

/// A typed [`ItemsSourceView`]: the items are read as `T`.
///
/// With `T` = `BoxedValue` the items are read untyped.
pub struct ItemsSourceViewOf<T: PropertyValue> {
    view: Rc<ItemsSourceView>,
    marker: PhantomData<fn() -> T>,
}

impl<T: PropertyValue> Clone for ItemsSourceViewOf<T> {
    fn clone(&self) -> Self {
        Self { view: self.view.clone(), marker: PhantomData }
    }
}

impl<T: PropertyValue> Deref for ItemsSourceViewOf<T> {
    type Target = ItemsSourceView;

    fn deref(&self) -> &ItemsSourceView {
        &self.view
    }
}

impl<T: PropertyValue> ItemsSourceViewOf<T> {
    /// Gets an empty view.
    pub fn empty() -> Self {
        Self { view: ItemsSourceView::empty(), marker: PhantomData }
    }

    /// Initializes a new instance of the view for the specified data source.
    pub fn new(source: ItemsSource) -> Self {
        Self { view: ItemsSourceView::new(source), marker: PhantomData }
    }

    /// Reads an existing view as a typed view over the same source.
    pub fn from_view(view: &ItemsSourceView) -> Self {
        Self::new(view.source())
    }

    /// The untyped view.
    pub fn view(&self) -> &Rc<ItemsSourceView> {
        &self.view
    }

    /// Retrieves the item at the specified index: `None` for a null item.
    /// Panics if the index is out of range or the item is not a `T`.
    pub fn get_at(&self, index: usize) -> Option<T> {
        let item = self.view.get_at(index);
        if item.is_none() {
            return None;
        }
        match unbox_item::<T>(&item) {
            Some(value) => Some(value),
            None => panic!("Unable to cast the item to type '{}'.", std::any::type_name::<T>()),
        }
    }

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