raui_core/
view_model.rs

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
use crate::widget::{WidgetId, WidgetIdCommon};
use intuicio_data::{
    lifetime::{ValueReadAccess, ValueWriteAccess},
    managed::DynamicManaged,
    managed::{Managed, ManagedLazy, ManagedRef, ManagedRefMut},
};
use std::{
    collections::{HashMap, HashSet},
    ops::{Deref, DerefMut},
};

pub struct ViewModelBindings {
    widgets: HashSet<WidgetId>,
    common_root: WidgetIdCommon,
    notify: bool,
}

impl Default for ViewModelBindings {
    fn default() -> Self {
        Self {
            widgets: Default::default(),
            common_root: Default::default(),
            notify: true,
        }
    }
}

impl ViewModelBindings {
    pub fn bind(&mut self, id: WidgetId) {
        self.widgets.insert(id);
        self.rebuild_common_root();
    }

    pub fn unbind(&mut self, id: &WidgetId) {
        self.widgets.remove(id);
        self.rebuild_common_root();
    }

    pub fn clear(&mut self) {
        self.widgets.clear();
        self.common_root = Default::default();
    }

    pub fn is_empty(&self) -> bool {
        self.widgets.is_empty()
    }

    pub fn is_bound(&self, id: &WidgetId) -> bool {
        self.widgets.contains(id)
    }

    pub fn widgets(&self) -> impl Iterator<Item = &WidgetId> {
        self.widgets.iter()
    }

    pub fn common_root(&self) -> &WidgetIdCommon {
        &self.common_root
    }

    pub fn notify(&mut self) {
        self.notify = true;
    }

    pub fn is_notified(&self) -> bool {
        self.notify
    }

    pub fn consume_notification(&mut self) -> bool {
        !self.widgets.is_empty() && std::mem::take(&mut self.notify)
    }

    fn rebuild_common_root(&mut self) {
        self.common_root = WidgetIdCommon::from_iter(self.widgets.iter());
    }
}

#[derive(Default)]
pub struct ViewModelProperties {
    inner: HashMap<String, Managed<ViewModelBindings>>,
}

impl ViewModelProperties {
    pub fn unbind_all(&mut self, id: &WidgetId) {
        for bindings in self.inner.values_mut() {
            if let Some(mut bindings) = bindings.write() {
                bindings.unbind(id);
            }
        }
    }

    pub fn remove(&mut self, id: &str) {
        self.inner.remove(id);
    }

    pub fn clear(&mut self) {
        self.inner.clear();
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn has(&self, id: &str) -> bool {
        self.inner.contains_key(id)
    }

    pub fn remove_empty_bindings(&mut self) {
        let to_remove = self
            .inner
            .iter()
            .filter_map(|(key, bindings)| {
                if let Some(bindings) = bindings.read() {
                    if bindings.is_empty() {
                        return Some(key.to_owned());
                    }
                }
                None
            })
            .collect::<Vec<_>>();
        for key in to_remove {
            self.inner.remove(&key);
        }
    }

    pub fn bindings(&mut self, id: impl ToString) -> Option<ValueWriteAccess<ViewModelBindings>> {
        self.inner.entry(id.to_string()).or_default().write()
    }

    pub fn notifier(&mut self, id: impl ToString) -> ViewModelNotifier {
        ViewModelNotifier {
            inner: self.inner.entry(id.to_string()).or_default().lazy(),
        }
    }

    pub fn consume_notification(&mut self) -> bool {
        self.inner.values_mut().any(|bindings| {
            bindings
                .write()
                .map(|mut bindings| bindings.consume_notification())
                .unwrap_or_default()
        })
    }

    pub fn consume_notified_common_root(&mut self) -> WidgetIdCommon {
        let mut result = WidgetIdCommon::default();
        for bindings in self.inner.values_mut() {
            if let Some(mut bindings) = bindings.write() {
                if bindings.consume_notification() {
                    let root = bindings.common_root();
                    result.include_other(root);
                }
            }
        }
        result
    }
}

#[derive(Clone)]
pub struct ViewModelNotifier {
    inner: ManagedLazy<ViewModelBindings>,
}

impl ViewModelNotifier {
    pub fn notify(&mut self) -> bool {
        if let Some(mut bindings) = self.inner.write() {
            bindings.notify();
            true
        } else {
            false
        }
    }
}

pub struct ViewModel {
    object: DynamicManaged,
    pub properties: ViewModelProperties,
}

impl ViewModel {
    pub fn new<T: 'static>(object: T, properties: ViewModelProperties) -> Self {
        Self {
            object: DynamicManaged::new(object).ok().unwrap(),
            properties,
        }
    }

    pub fn new_object<T: 'static>(object: T) -> Self {
        Self::new(object, Default::default())
    }

    pub fn produce<T: 'static>(producer: impl FnOnce(&mut ViewModelProperties) -> T) -> Self {
        let mut properties = Default::default();
        let object = DynamicManaged::new(producer(&mut properties)).ok().unwrap();
        Self { object, properties }
    }

    pub fn borrow<T: 'static>(&self) -> Option<ManagedRef<T>> {
        self.object
            .borrow()
            .and_then(|object| object.into_typed::<T>().ok())
    }

    pub fn borrow_mut<T: 'static>(&mut self) -> Option<ManagedRefMut<T>> {
        self.object
            .borrow_mut()
            .and_then(|object| object.into_typed::<T>().ok())
    }

    pub fn lazy<T: 'static>(&self) -> Option<ManagedLazy<T>> {
        self.object.lazy().into_typed::<T>().ok()
    }

    pub fn read<T: 'static>(&self) -> Option<ValueReadAccess<T>> {
        self.object.read::<T>()
    }

    pub fn write<T: 'static>(&mut self) -> Option<ValueWriteAccess<T>> {
        self.object.write::<T>()
    }

    pub fn write_notified<T: 'static>(&mut self) -> Option<ViewModelObject<T>> {
        if let Some(access) = self.object.write::<T>() {
            Some(ViewModelObject {
                access,
                notifier: self.properties.notifier(""),
            })
        } else {
            None
        }
    }
}

#[derive(Default)]
pub struct ViewModelCollection {
    named: HashMap<String, ViewModel>,
    widgets: HashMap<WidgetId, HashMap<String, ViewModel>>,
}

impl ViewModelCollection {
    pub fn unbind_all(&mut self, id: &WidgetId) {
        for view_model in self.named.values_mut() {
            view_model.properties.unbind_all(id);
        }
        for view_model in self.widgets.values_mut() {
            for view_model in view_model.values_mut() {
                view_model.properties.unbind_all(id);
            }
        }
    }

    pub fn remove_empty_bindings(&mut self) {
        for view_model in self.named.values_mut() {
            view_model.properties.remove_empty_bindings();
        }
        for view_model in self.widgets.values_mut() {
            for view_model in view_model.values_mut() {
                view_model.properties.remove_empty_bindings();
            }
        }
    }

    pub fn consume_notification(&mut self) -> bool {
        let mut result = false;
        for view_model in self.named.values_mut() {
            result = result || view_model.properties.consume_notification();
        }
        for view_model in self.widgets.values_mut() {
            for view_model in view_model.values_mut() {
                result = result || view_model.properties.consume_notification();
            }
        }
        result
    }

    pub fn consume_notified_common_root(&mut self) -> WidgetIdCommon {
        let mut result = WidgetIdCommon::default();
        for view_model in self.named.values_mut() {
            result.include_other(&view_model.properties.consume_notified_common_root());
        }
        for view_model in self.widgets.values_mut() {
            for view_model in view_model.values_mut() {
                result.include_other(&view_model.properties.consume_notified_common_root());
            }
        }
        result
    }

    pub fn remove_widget_view_models(&mut self, id: &WidgetId) {
        self.widgets.remove(id);
    }
}

impl Deref for ViewModelCollection {
    type Target = HashMap<String, ViewModel>;

    fn deref(&self) -> &Self::Target {
        &self.named
    }
}

impl DerefMut for ViewModelCollection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.named
    }
}

pub struct ViewModelCollectionView<'a> {
    id: &'a WidgetId,
    collection: &'a mut ViewModelCollection,
}

impl<'a> ViewModelCollectionView<'a> {
    pub fn new(id: &'a WidgetId, collection: &'a mut ViewModelCollection) -> Self {
        Self { id, collection }
    }

    pub fn id(&self) -> &WidgetId {
        self.id
    }

    pub fn collection(&'a self) -> &'a ViewModelCollection {
        self.collection
    }

    pub fn collection_mut(&'a mut self) -> &'a mut ViewModelCollection {
        self.collection
    }

    pub fn bindings(
        &mut self,
        view_model: &str,
        property: impl ToString,
    ) -> Option<ValueWriteAccess<ViewModelBindings>> {
        self.collection
            .get_mut(view_model)?
            .properties
            .bindings(property)
    }

    pub fn view_model(&self, name: &str) -> Option<&ViewModel> {
        self.collection.get(name)
    }

    pub fn view_model_mut(&mut self, name: &str) -> Option<&mut ViewModel> {
        self.collection.get_mut(name)
    }

    pub fn widget_register(&mut self, name: impl ToString, view_model: ViewModel) {
        self.collection
            .widgets
            .entry(self.id.to_owned())
            .or_default()
            .insert(name.to_string(), view_model);
    }

    pub fn widget_unregister(&mut self, name: &str) -> Option<ViewModel> {
        let view_models = self.collection.widgets.get_mut(self.id)?;
        let result = view_models.remove(name)?;
        if view_models.is_empty() {
            self.collection.widgets.remove(self.id);
        }
        Some(result)
    }

    pub fn widget_bindings(
        &mut self,
        view_model: &str,
        property: impl ToString,
    ) -> Option<ValueWriteAccess<ViewModelBindings>> {
        self.collection
            .widgets
            .get_mut(self.id)?
            .get_mut(view_model)?
            .properties
            .bindings(property)
    }

    pub fn widget_view_model(&self, name: &str) -> Option<&ViewModel> {
        self.collection.widgets.get(self.id)?.get(name)
    }

    pub fn widget_view_model_mut(&mut self, name: &str) -> Option<&mut ViewModel> {
        self.collection.widgets.get_mut(self.id)?.get_mut(name)
    }

    pub fn hierarchy_view_model(&self, name: &str) -> Option<&ViewModel> {
        self.collection
            .widgets
            .iter()
            .filter_map(|(id, view_models)| {
                id.distance_to(self.id).ok().and_then(|distance| {
                    if distance <= 0 {
                        Some((distance, view_models.get(name)?))
                    } else {
                        None
                    }
                })
            })
            .min_by(|(a, _), (b, _)| a.cmp(b))
            .map(|(_, view_model)| view_model)
    }

    pub fn hierarchy_view_model_mut(&mut self, name: &str) -> Option<&mut ViewModel> {
        self.collection
            .widgets
            .iter_mut()
            .filter_map(|(id, view_models)| {
                id.distance_to(self.id).ok().and_then(|distance| {
                    if distance <= 0 {
                        Some((distance, view_models.get_mut(name)?))
                    } else {
                        None
                    }
                })
            })
            .min_by(|(a, _), (b, _)| a.cmp(b))
            .map(|(_, view_model)| view_model)
    }
}

pub struct ViewModelObject<'a, T> {
    access: ValueWriteAccess<'a, T>,
    notifier: ViewModelNotifier,
}

impl<'a, T> ViewModelObject<'a, T> {
    pub fn set_unique_notify(&mut self, value: T)
    where
        T: PartialEq,
    {
        if *self.access != value {
            *self.access = value;
            self.notifier.notify();
        }
    }
}

impl<'a, T> Deref for ViewModelObject<'a, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.access
    }
}

impl<'a, T> DerefMut for ViewModelObject<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.notifier.notify();
        &mut self.access
    }
}

pub struct ViewModelValue<T> {
    value: T,
    notifier: ViewModelNotifier,
}

impl<T> ViewModelValue<T> {
    pub fn new(value: T, notifier: ViewModelNotifier) -> Self {
        Self { value, notifier }
    }

    pub fn consume(self) -> T {
        self.value
    }

    pub fn set_unique_notify(&mut self, value: T)
    where
        T: PartialEq,
    {
        if self.value != value {
            self.value = value;
            self.notifier.notify();
        }
    }
}

impl<T> Deref for ViewModelValue<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for ViewModelValue<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.notifier.notify();
        &mut self.value
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    const FOO_VIEW_MODEL: &str = "foo";
    const COUNTER_PROPERTY: &str = "counter";
    const FLAG_PROPERTY: &str = "flag";

    // view-model data type
    struct Foo {
        // can hold view-model value wrapper that implicitly notifies on mutation.
        counter: ViewModelValue<usize>,
        // or can hold raw notifiers to explicitly notify.
        flag: bool,
        flag_notifier: ViewModelNotifier,
    }

    impl Foo {
        fn toggle(&mut self) {
            self.flag = !self.flag;
            self.flag_notifier.notify();
        }
    }

    #[test]
    fn test_view_model() {
        let a = WidgetId::from_str("a:root/a").unwrap();
        let b = WidgetId::from_str("b:root/b").unwrap();
        let mut collection = ViewModelCollection::default();

        // create new view-model and add it to collection.
        // `produce` method allows to setup notifiers as we construct view-model.
        let view_model = ViewModel::produce(|properties| Foo {
            counter: ViewModelValue::new(0, properties.notifier(COUNTER_PROPERTY)),
            flag: false,
            flag_notifier: properties.notifier(FLAG_PROPERTY),
        });
        // handle to view-model data we can use to share around.
        // it stays alive as long as its view-model object.
        let handle = view_model.lazy::<Foo>().unwrap();
        collection.insert(FOO_VIEW_MODEL.to_owned(), view_model);

        // unbound properties won't trigger notification until we bind widgets to them.
        assert_eq!(collection.consume_notified_common_root().is_valid(), false);
        handle.write().unwrap().toggle();
        assert_eq!(collection.consume_notified_common_root().is_valid(), false);
        assert!(collection
            .get_mut(FOO_VIEW_MODEL)
            .unwrap()
            .properties
            .bindings(COUNTER_PROPERTY)
            .unwrap()
            .is_notified());
        assert!(collection
            .get_mut(FOO_VIEW_MODEL)
            .unwrap()
            .properties
            .bindings(FLAG_PROPERTY)
            .unwrap()
            .is_notified());

        // bind widget to properties.
        // whenever property gets notified, its widgets will rebuild.
        collection
            .get_mut(FOO_VIEW_MODEL)
            .unwrap()
            .properties
            .bindings(COUNTER_PROPERTY)
            .unwrap()
            .bind(a);
        collection
            .get_mut(FOO_VIEW_MODEL)
            .unwrap()
            .properties
            .bindings(FLAG_PROPERTY)
            .unwrap()
            .bind(b);

        // once we bind properties, notification will be triggered.
        assert_eq!(
            collection.consume_notified_common_root().path(),
            Some("root")
        );

        // automatically notify on view-model value mutation.
        *handle.write().unwrap().counter += 1;
        assert_eq!(
            collection.consume_notified_common_root().path(),
            Some("root/a"),
        );

        // proxy notify via view-model method call.
        handle.write().unwrap().toggle();
        assert_eq!(
            collection.consume_notified_common_root().path(),
            Some("root/b"),
        );

        // rebuilding widgets tree will occur always from common root of notified widgets.
        *handle.write().unwrap().counter += 1;
        handle.write().unwrap().toggle();
        assert_eq!(
            collection.consume_notified_common_root().path(),
            Some("root"),
        );
    }
}