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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! View drivers
//!
//! The [`Driver`] trait is used as a binding between data models and
//! controllers. Implementations define the view (using widgets) and
//! message handling (mapping widget messages to actions).
//!
//! Several implementations are provided to cover simpler cases:
//!
//! -   [`View`] is the default, providing a simple read-only view over content
//! -   [`NavView`] is like [`View`], but using keyboard navigable widgets
//! -   [`EditBox`], [`CheckBox`] etc. provide an interactive view over common
//!     data types using the like-named widgets
//! -   [`EventConfig`] provides an editor over a specific complex data type
//!
//! Intended usage is to import the module name rather than its contents, thus
//! allowing referal to e.g. `driver::View`.

mod config;
pub use config::EventConfig;

use crate::MaybeOwned;
use kas::model::{SharedData, SharedDataMut};
use kas::prelude::*;
use kas::theme::TextClass;
use kas_widgets::edit::{EditGuard, GuardNotify};
use kas_widgets::{CheckBox, Label, NavFrame, RadioGroup, SliderValue, SpinnerValue};
use std::default::Default;
use std::fmt::Debug;
use std::ops::RangeInclusive;

/// View widget driver/binder
///
/// The driver can:
///
/// -   construct (empty) widgets with [`Self::make`]
/// -   assign data to an existing widget with [`Self::set`]
/// -   (optional) handle messages from a widget with [`Self::on_message`]
///
/// NOTE: `Item` is a direct type parameter (in addition to an assoc. type
/// param. of `SharedData`) only to avoid "conflicting implementations" errors.
/// Similar to: rust#20400, rust#92894. Given fixes, we may remove the param.
#[autoimpl(for<T: trait + ?Sized> &T, &mut T, Box<T>, std::rc::Rc<T>, std::sync::Arc<T>)]
pub trait Driver<Item, Data: SharedData<Item = Item>>: Debug {
    /// Type of the widget used to view data
    type Widget: kas::Widget;

    /// Construct a new widget with no data
    ///
    /// Such instances are used for sizing and cached widgets, but not shown.
    /// The controller may later call [`Driver::set`] on the widget then show it.
    fn make(&self) -> Self::Widget;

    /// Set the viewed data
    ///
    /// The widget may expect `configure` to be called at least once before data
    /// is set and to have `set_rect` called after each time data is set.
    ///
    /// This method is a convenience wrapper around [`Self::set_mo`].
    fn set<'b>(
        &self,
        widget: &mut Self::Widget,
        key: &Data::Key,
        item: impl Into<MaybeOwned<'b, Item>>,
    ) -> Action
    where
        Self: Sized,
        Item: 'b,
    {
        self.set_mo(widget, key, item.into())
    }

    /// Set the viewed data ([`MaybeOwned`])
    ///
    /// The widget may expect `configure` to be called at least once before data
    /// is set and to have `set_rect` called after each time data is set.
    fn set_mo(&self, widget: &mut Self::Widget, key: &Data::Key, item: MaybeOwned<Item>) -> Action;

    /// Handle a message from a widget
    ///
    /// This method is called when a view widget returns with a message; it
    /// may retrieve this message with [`EventMgr::try_pop`].
    ///
    /// There are three main ways of implementing this method:
    ///
    /// 1.  Do nothing. This is always safe, though may result in unhandled
    ///     message warnings when the view widget is interactive.
    /// 2.  On user input actions, view widgets send a message including their
    ///     content (potentially wrapped with a user-defined enum or struct
    ///     type). The implementation of this method retrieves this message and
    ///     updates `data` given this content. In this case, the `widget`
    ///     parameter is not used.
    /// 3.  On user input actions, view widgets send a "trigger" message (likely
    ///     a unit struct). The implementation of this method retrieves this
    ///     message and updates `data` using values read from `widget`.
    ///
    /// See, for example, the implementation for [`CheckButton`]: the `make`
    /// method assigns a state-change handler which `on_message` uses to update
    /// the shared data.
    ///
    /// Default implementation: do nothing.
    fn on_message(
        &self,
        mgr: &mut EventMgr,
        widget: &mut Self::Widget,
        data: &Data,
        key: &Data::Key,
    ) {
        let _ = (mgr, widget, data, key);
    }
}

/// Default view widget constructor
///
/// This struct implements [`Driver`], using a default widget for the data type:
///
/// -   [`kas_widgets::Label`] for `String`, `&str`, integer and float types
/// -   [`kas_widgets::CheckBox`] (read-only) for the bool type
#[derive(Clone, Copy, Debug, Default)]
pub struct View;

/// Default view widget constructor supporting keyboard navigation
///
/// This struct implements [`Driver`], using a default widget for the data type
/// which also supports keyboard navigation:
///
/// -   [`kas_widgets::NavFrame`] around a [`kas_widgets::Label`] for `String`, `&str`,
///     integer and float types
/// -   [`kas_widgets::CheckBox`] (read-only) for the bool type
#[derive(Clone, Copy, Debug, Default)]
pub struct NavView;

macro_rules! impl_via_to_string {
    ($t:ty) => {
        impl<Data: SharedData<Item = $t>> Driver<$t, Data> for View {
            type Widget = Label<String>;
            fn make(&self) -> Self::Widget {
                Label::new("".to_string())
            }
            fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<$t>) -> Action {
                widget.set_string(item.to_string())
            }
        }
        impl<Data: SharedData<Item = $t>> Driver<$t, Data> for NavView {
            type Widget = NavFrame<Label<String>>;
            fn make(&self) -> Self::Widget {
                NavFrame::new(Label::new("".to_string()))
            }
            fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<$t>) -> Action {
                widget.set_string(item.to_string())
            }
        }
    };
    ($t:ty, $($tt:ty),+) => {
        impl_via_to_string!($t);
        impl_via_to_string!($($tt),+);
    };
}
impl_via_to_string!(String, &'static str);
impl_via_to_string!(i8, i16, i32, i64, i128, isize);
impl_via_to_string!(u8, u16, u32, u64, u128, usize);
impl_via_to_string!(f32, f64);

impl<Data: SharedData<Item = bool>> Driver<bool, Data> for View {
    type Widget = CheckBox;
    fn make(&self) -> Self::Widget {
        CheckBox::new_on(|mgr, state| mgr.push(state)).with_editable(false)
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<bool>) -> Action {
        widget.set_bool(item.into_owned())
    }
}

impl<Data: SharedData<Item = bool>> Driver<bool, Data> for NavView {
    type Widget = CheckBox;
    fn make(&self) -> Self::Widget {
        CheckBox::new_on(|mgr, state| mgr.push(state)).with_editable(false)
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<bool>) -> Action {
        widget.set_bool(item.into_owned())
    }
}

impl_scope! {
    /// [`kas_widgets::EditField`] view widget constructor
    ///
    /// This is parameterized `G`: [`EditGuard`], which defaults to [`GuardNotify`].
    /// The guard should send a [`String`] message to enable updates on edit.
    #[impl_default(where G: Default)]
    #[derive(Clone, Copy, Debug)]
    pub struct EditField<G: EditGuard + Clone = GuardNotify> {
        guard: G,
        class: TextClass = TextClass::Edit(false),
    }
    impl Self where G: Default {
        /// Construct
        #[inline]
        pub fn new() -> Self {
            Self::default()
        }
    }
    impl Self {
        /// Construct with given `guard`
        #[inline]
        #[must_use]
        pub fn with_guard(mut self, guard: G) -> Self {
            self.guard = guard;
            self
        }

        /// Set whether the editor uses multi-line mode
        ///
        /// This replaces any class set by [`Self::with_class`].
        ///
        /// See: [`kas_widgets::EditField::with_multi_line`].
        #[inline]
        #[must_use]
        pub fn with_multi_line(self, multi_line: bool) -> Self {
            self.with_class(TextClass::Edit(multi_line))
        }

        /// Set the text class used
        ///
        /// See: [`kas_widgets::EditField::with_class`].
        #[inline]
        #[must_use]
        pub fn with_class(mut self, class: TextClass) -> Self {
            self.class = class;
            self
        }
    }
}
impl<G: EditGuard + Clone, Data: SharedDataMut<Item = String>> Driver<String, Data>
    for EditField<G>
{
    type Widget = kas_widgets::EditField<G>;
    fn make(&self) -> Self::Widget {
        kas_widgets::EditField::new("".to_string())
            .with_guard(self.guard.clone())
            .with_class(self.class)
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<String>) -> Action {
        widget.set_string(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(item) = mgr.try_pop() {
            data.set(mgr, key, item);
        }
    }
}

impl_scope! {
    /// [`kas_widgets::EditBox`] view widget constructor
    ///
    /// This is parameterized `G`: [`EditGuard`], which defaults to [`GuardNotify`].
    /// The guard should send a [`String`] message to enable updates on edit.
    #[impl_default(where G: Default)]
    #[derive(Clone, Copy, Debug)]
    pub struct EditBox<G: EditGuard + Clone = GuardNotify> {
        guard: G,
        class: TextClass = TextClass::Edit(false),
    }
    impl Self where G: Default {
        /// Construct
        #[inline]
        pub fn new() -> Self {
            Self::default()
        }
    }
    impl Self {
        /// Construct with given `guard`
        #[inline]
        #[must_use]
        pub fn with_guard(mut self, guard: G) -> Self {
            self.guard = guard;
            self
        }

        /// Set whether the editor uses multi-line mode
        ///
        /// This replaces any class set by [`Self::with_class`].
        ///
        /// See: [`kas_widgets::EditBox::with_multi_line`].
        #[inline]
        #[must_use]
        pub fn with_multi_line(self, multi_line: bool) -> Self {
            self.with_class(TextClass::Edit(multi_line))
        }

        /// Set the text class used
        ///
        /// See: [`kas_widgets::EditBox::with_class`].
        #[inline]
        #[must_use]
        pub fn with_class(mut self, class: TextClass) -> Self {
            self.class = class;
            self
        }
    }
}
impl<G: EditGuard + Clone, Data: SharedDataMut<Item = String>> Driver<String, Data> for EditBox<G> {
    type Widget = kas_widgets::EditBox<G>;
    fn make(&self) -> Self::Widget {
        kas_widgets::EditBox::new("".to_string()).with_guard(self.guard.clone())
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<String>) -> Action {
        widget.set_string(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(item) = mgr.try_pop() {
            data.set(mgr, key, item);
        }
    }
}

/// [`kas_widgets::ProgressBar`] view widget constructor
#[derive(Clone, Copy, Debug, Default)]
pub struct ProgressBar<D: Directional> {
    direction: D,
}
impl<D: Directional + Default> ProgressBar<D> {
    /// Construct
    pub fn new() -> Self {
        ProgressBar::new_with_direction(Default::default())
    }
}
impl<D: Directional> ProgressBar<D> {
    /// Construct with given `direction`
    pub fn new_with_direction(direction: D) -> Self {
        ProgressBar { direction }
    }
}
impl<D: Directional, Data: SharedData<Item = f32>> Driver<f32, Data> for ProgressBar<D> {
    type Widget = kas_widgets::ProgressBar<D>;
    fn make(&self) -> Self::Widget {
        kas_widgets::ProgressBar::new_with_direction(self.direction)
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<f32>) -> Action {
        widget.set_value(item.into_owned())
    }
}

/// [`kas_widgets::CheckButton`] view widget constructor
#[derive(Clone, Debug, Default)]
pub struct CheckButton {
    label: AccelString,
}
impl CheckButton {
    /// Construct, with given `label`
    pub fn new<T: Into<AccelString>>(label: T) -> Self {
        let label = label.into();
        CheckButton { label }
    }
}
impl<Data: SharedDataMut<Item = bool>> Driver<bool, Data> for CheckButton {
    type Widget = kas_widgets::CheckButton;
    fn make(&self) -> Self::Widget {
        kas_widgets::CheckButton::new_on(self.label.clone(), |mgr, state| mgr.push(state))
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<bool>) -> Action {
        widget.set_bool(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(state) = mgr.try_pop() {
            data.set(mgr, key, state);
        }
    }
}

/// [`kas_widgets::RadioBox`] view widget constructor
#[derive(Clone, Debug)]
pub struct RadioBox {
    group: RadioGroup,
}
impl RadioBox {
    /// Construct, with given `group`
    pub fn new(group: RadioGroup) -> Self {
        RadioBox { group }
    }
}
impl<Data: SharedDataMut<Item = bool>> Driver<bool, Data> for RadioBox {
    type Widget = kas_widgets::RadioBox;
    fn make(&self) -> Self::Widget {
        kas_widgets::RadioBox::new_on(self.group.clone(), |mgr| mgr.push(true))
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<bool>) -> Action {
        widget.set_bool(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(state) = mgr.try_pop() {
            data.set(mgr, key, state);
        }
    }
}

/// [`kas_widgets::RadioButton`] view widget constructor
#[derive(Clone, Debug)]
pub struct RadioButton {
    label: AccelString,
    group: RadioGroup,
}
impl RadioButton {
    /// Construct, with given `label` and `group`
    pub fn new<T: Into<AccelString>>(label: T, group: RadioGroup) -> Self {
        let label = label.into();
        RadioButton { label, group }
    }
}
impl<Data: SharedDataMut<Item = bool>> Driver<bool, Data> for RadioButton {
    type Widget = kas_widgets::RadioButton;
    fn make(&self) -> Self::Widget {
        kas_widgets::RadioButton::new(self.label.clone(), self.group.clone())
            .on_select(|mgr| mgr.push(true))
    }
    fn set_mo(&self, widget: &mut Self::Widget, _: &Data::Key, item: MaybeOwned<bool>) -> Action {
        widget.set_bool(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(state) = mgr.try_pop() {
            data.set(mgr, key, state);
        }
    }
}

/// [`kas_widgets::Slider`] view widget constructor
#[derive(Clone, Copy, Debug)]
pub struct Slider<T: SliderValue, D: Directional> {
    range: (T, T),
    step: T,
    direction: D,
}
impl<T: SliderValue, D: Directional + Default> Slider<T, D> {
    /// Construct, with given `range` and `step` (see [`kas_widgets::Slider::new`])
    pub fn new(range: RangeInclusive<T>, step: T) -> Self {
        Slider {
            range: range.into_inner(),
            step,
            direction: D::default(),
        }
    }
}
impl<T: SliderValue, D: Directional> Slider<T, D> {
    /// Construct, with given `range`, `step` and `direction` (see [`Slider::new_with_direction`])
    pub fn new_with_direction(range: RangeInclusive<T>, step: T, direction: D) -> Self {
        Slider {
            range: range.into_inner(),
            step,
            direction,
        }
    }
}
impl<D: Directional, Data: SharedDataMut> Driver<Data::Item, Data> for Slider<Data::Item, D>
where
    Data::Item: SliderValue,
{
    type Widget = kas_widgets::Slider<Data::Item, D>;
    fn make(&self) -> Self::Widget {
        let range = self.range.0..=self.range.1;
        kas_widgets::Slider::new_with_direction(range, self.step, self.direction)
            .on_move(|mgr, value| mgr.push(value))
    }
    fn set_mo(
        &self,
        widget: &mut Self::Widget,
        _: &Data::Key,
        item: MaybeOwned<Data::Item>,
    ) -> Action {
        widget.set_value(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(state) = mgr.try_pop() {
            data.set(mgr, key, state);
        }
    }
}

/// [`kas_widgets::Spinner`] view widget constructor
#[derive(Clone, Copy, Debug)]
pub struct Spinner<T: SpinnerValue> {
    range: (T, T),
    step: T,
}
impl<T: SpinnerValue + Default> Spinner<T> {
    /// Construct, with given `range` and `step` (see [`kas_widgets::Spinner::new`])
    pub fn new(range: RangeInclusive<T>, step: T) -> Self {
        Spinner {
            range: range.into_inner(),
            step,
        }
    }
}
impl<Data: SharedDataMut> Driver<Data::Item, Data> for Spinner<Data::Item>
where
    Data::Item: SpinnerValue,
{
    type Widget = kas_widgets::Spinner<Data::Item>;
    fn make(&self) -> Self::Widget {
        let range = self.range.0..=self.range.1;
        kas_widgets::Spinner::new(range, self.step).on_change(|mgr, val| mgr.push(val))
    }
    fn set_mo(
        &self,
        widget: &mut Self::Widget,
        _: &Data::Key,
        item: MaybeOwned<Data::Item>,
    ) -> Action {
        widget.set_value(item.into_owned())
    }
    fn on_message(&self, mgr: &mut EventMgr, _: &mut Self::Widget, data: &Data, key: &Data::Key) {
        if let Some(state) = mgr.try_pop() {
            data.set(mgr, key, state);
        }
    }
}