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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! An interface for Widgets to respond to interaction.
//!
//! Widgets like Button require their content implement the trait `Selectable`
//! so that they can update their graphics in response to a change in the
//! button's state.
//!
//! The type `SelectableData` provides a simple way to select between values.
//!
//! The type `SelectableIgnored` provides a no-op implementation of
//! `Selectable`, in case a particular Widget has no need to respond to a
//! change in selection state.
//!
//! Selectable implementations are provided with an opaque struct
//! `SelectionState`.  This can be converted into a number of "versioned"
//! enums.  This pattern allows additional states to be added in the future
//! with reasonable fallbacks for backwards-compatibility.

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum SelectionStateAll {
    Normal,
    Hover,
    Focus,
    Pressed,
    Active,
}

impl Default for SelectionStateAll {
    fn default() -> Self {
        Self::Normal
    }
}

/// A selection state is an opaque type which indicates the current state
/// a selectable widget should transition to.
///
/// In order to account for potential future selection states, this type
/// primarily provides "versioned" conversions, in increasing order of
/// complexity.  Matching on a versioned type means that if a future state is
/// added, it can "fall back" to a similar state of the version the match
/// already handles.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct SelectionState(SelectionStateAll);

impl SelectionState {
    /// Normal selection state
    pub const fn normal() -> Self {
        Self(SelectionStateAll::Normal)
    }

    /// Hover selection state
    pub const fn hover() -> Self {
        Self(SelectionStateAll::Hover)
    }

    /// Focus selection state
    pub const fn focus() -> Self {
        Self(SelectionStateAll::Focus)
    }

    /// Pressed selection state
    pub const fn pressed() -> Self {
        Self(SelectionStateAll::Pressed)
    }

    /// Active selection state
    pub const fn active() -> Self {
        Self(SelectionStateAll::Active)
    }

    /// Get version 0 selection states.
    pub fn v0(self) -> SelectionStateV0 {
        match self.0 {
            SelectionStateAll::Normal => SelectionStateV0::Normal,
            SelectionStateAll::Hover => SelectionStateV0::Normal,
            SelectionStateAll::Focus => SelectionStateV0::Focus,
            SelectionStateAll::Pressed => SelectionStateV0::Focus,
            SelectionStateAll::Active => SelectionStateV0::Active,
        }
    }

    /// Get version 1 selection states.
    pub fn v1(self) -> SelectionStateV1 {
        match self.0 {
            SelectionStateAll::Normal => SelectionStateV1::Normal,
            SelectionStateAll::Hover => SelectionStateV1::Hover,
            SelectionStateAll::Focus => SelectionStateV1::Focus,
            SelectionStateAll::Pressed => SelectionStateV1::Focus,
            SelectionStateAll::Active => SelectionStateV1::Active,
        }
    }

    /// Get version 2 selection states.
    pub fn v2(self) -> SelectionStateV2 {
        match self.0 {
            SelectionStateAll::Normal => SelectionStateV2::Normal,
            SelectionStateAll::Hover => SelectionStateV2::Hover,
            SelectionStateAll::Focus => SelectionStateV2::Focus,
            SelectionStateAll::Pressed => SelectionStateV2::Pressed,
            SelectionStateAll::Active => SelectionStateV2::Active,
        }
    }

    /// Reduce the selection state to a resonable fallback assumed to be more
    /// widely implemented.
    pub fn reduce(self) -> Self {
        Self(match self.0 {
            SelectionStateAll::Normal => SelectionStateAll::Normal,
            SelectionStateAll::Hover => SelectionStateAll::Normal,
            SelectionStateAll::Focus => SelectionStateAll::Normal,
            SelectionStateAll::Pressed => SelectionStateAll::Focus,
            SelectionStateAll::Active => SelectionStateAll::Normal,
        })
    }
}

/// Version 0 selection states.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectionStateV0 {
    /// Normal selection state.
    Normal,

    /// Focused selection state.
    Focus,

    /// Active selection state.
    Active,
}

impl Default for SelectionStateV0 {
    fn default() -> Self {
        SelectionState::default().into()
    }
}

impl From<SelectionState> for SelectionStateV0 {
    fn from(all: SelectionState) -> Self {
        all.v0()
    }
}

/// Version 1 selection states.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectionStateV1 {
    /// Normal selection state.
    Normal,

    /// Hovered selection state.
    Hover,

    /// Focused selection state.
    Focus,

    /// Active selection state.
    Active,
}

impl From<SelectionState> for SelectionStateV1 {
    fn from(all: SelectionState) -> Self {
        all.v1()
    }
}

impl Default for SelectionStateV1 {
    fn default() -> Self {
        SelectionState::default().into()
    }
}

/// Version 2 selection states.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectionStateV2 {
    /// Normal selection state.
    Normal,

    /// Hovered selection state.
    Hover,

    /// Focused selection state.
    Focus,

    /// Pressed selection state.
    Pressed,

    /// Active selection state.
    Active,
}

impl From<SelectionState> for SelectionStateV2 {
    fn from(all: SelectionState) -> Self {
        all.v2()
    }
}

impl Default for SelectionStateV2 {
    fn default() -> Self {
        SelectionState::default().into()
    }
}

/// A trait which enables a widget to respond to changes in selection state.
pub trait Selectable {
    /// Notify the selectable element of a change in state.
    fn selection_changed(&mut self, state: SelectionState);
}

/// A type which provides a simple implementation of `Selectable` which
/// selects between a set of values.
///
/// This type dereferences to the the best instance of the value
/// corosponding to the current selection state.
#[derive(Clone, Debug, Default)]
pub struct SelectableData<T> {
    state: drying_paint::Watched<SelectionState>,
    normal: T,
    hover: Option<T>,
    focus: Option<T>,
    pressed: Option<T>,
    active: Option<T>,
}

impl<T> SelectableData<T> {
    /// Create a builder to populate the SelectableData.
    ///
    /// The value provided is the only one requred: the value for the normal
    /// state.
    pub fn builder(normal: T) -> SelectableDataBuilder<T> {
        SelectableDataBuilder {
            content: Self {
                state: Default::default(),
                normal,
                hover: None,
                focus: None,
                pressed: None,
                active: None,
            },
        }
    }
}

impl<T> std::ops::Deref for SelectableData<T> {
    type Target = T;
    fn deref(&self) -> &T {
        match self.state.0 {
            SelectionStateAll::Normal => &self.normal,
            SelectionStateAll::Hover => {
                self.hover.as_ref().unwrap_or(&self.normal)
            }
            SelectionStateAll::Focus => {
                self.focus.as_ref().unwrap_or(&self.normal)
            }
            SelectionStateAll::Pressed =>
            {
                #[allow(clippy::or_fun_call)]
                self.pressed
                    .as_ref()
                    .or(self.focus.as_ref())
                    .unwrap_or(&self.normal)
            }
            SelectionStateAll::Active => {
                self.active.as_ref().unwrap_or(&self.normal)
            }
        }
    }
}

impl<T> std::ops::DerefMut for SelectableData<T> {
    fn deref_mut(&mut self) -> &mut T {
        match self.state.0 {
            SelectionStateAll::Normal => &mut self.normal,
            SelectionStateAll::Hover => {
                self.hover.as_mut().unwrap_or(&mut self.normal)
            }
            SelectionStateAll::Focus => {
                self.focus.as_mut().unwrap_or(&mut self.normal)
            }
            SelectionStateAll::Pressed =>
            {
                #[allow(clippy::or_fun_call)]
                self.pressed
                    .as_mut()
                    .or(self.focus.as_mut())
                    .unwrap_or(&mut self.normal)
            }
            SelectionStateAll::Active => {
                self.active.as_mut().unwrap_or(&mut self.normal)
            }
        }
    }
}

/// A builder enables populating the selectable data.
#[derive(Clone, Debug, Default)]
pub struct SelectableDataBuilder<T> {
    content: SelectableData<T>,
}

impl<T> SelectableDataBuilder<T> {
    /// Provide a value for the hover state.
    pub fn hover(mut self, item: T) -> Self {
        self.content.hover = Some(item);
        self
    }

    /// Provide a value for the focus state.
    pub fn focus(mut self, item: T) -> Self {
        self.content.focus = Some(item);
        self
    }

    /// Provide a value for the pressed state.
    pub fn pressed(mut self, item: T) -> Self {
        self.content.pressed = Some(item);
        self
    }

    /// Provide a value for the active state.
    pub fn active(mut self, item: T) -> Self {
        self.content.active = Some(item);
        self
    }

    /// Finish providing values and create the `SelectableData`.
    pub fn build(self) -> SelectableData<T> {
        self.content
    }
}

impl<T> Selectable for SelectableData<T> {
    fn selection_changed(&mut self, state: SelectionState) {
        *self.state = state;
    }
}

/// A type which ignores changes to selection state.
///
/// This type implements `Selectable`, but does nothing in response.  It can be
/// useful if a interface (such as button) requires that a type parameter be
/// Selectable, but you do not actually care about changes to the selection
/// state.
#[derive(Clone, Copy, Debug, Default)]
pub struct SelectableIgnored<T> {
    data: T,
}

impl<T> std::ops::Deref for SelectableIgnored<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.data
    }
}

impl<T> std::ops::DerefMut for SelectableIgnored<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.data
    }
}

impl<T> Selectable for SelectableIgnored<T> {
    fn selection_changed(&mut self, _state: SelectionState) {}
}

mod extra_impls {
    use super::*;
    use crate::graphics::{DrawContext, Graphic};
    use crate::platform::RenderPlatform;
    use crate::pointer::PointerEvent;
    use crate::widget::{
        WidgetChildReceiver, WidgetContent, WidgetExtra,
        WidgetGraphicReceiver, WidgetInit,
    };

    impl<T, P> WidgetContent<P> for SelectableIgnored<T>
    where
        P: RenderPlatform,
        T: WidgetContent<P>,
    {
        fn init(mut init: impl WidgetInit<Self, P>) {
            init.init_child_inline(|x| &mut x.data);
        }

        fn children(&mut self, receiver: impl WidgetChildReceiver<P>) {
            self.data.children(receiver);
        }

        fn graphics(&mut self, receiver: impl WidgetGraphicReceiver<P>) {
            self.data.graphics(receiver);
        }

        fn hittest(
            &self,
            extra: &mut WidgetExtra<'_>,
            point: (f32, f32),
        ) -> bool {
            self.data.hittest(extra, point)
        }

        fn pointer_event(
            &mut self,
            extra: &mut WidgetExtra<'_>,
            event: &mut PointerEvent,
        ) -> bool {
            self.data.pointer_event(extra, event)
        }
    }

    impl<T, P> Graphic<P> for SelectableIgnored<T>
    where
        P: RenderPlatform,
        T: Graphic<P>,
    {
        fn draw(&mut self, ctx: &mut DrawContext<P>) {
            self.data.draw(ctx)
        }
    }

    impl<T, P> Graphic<P> for SelectableData<T>
    where
        P: RenderPlatform,
        T: Graphic<P>,
    {
        fn draw(&mut self, ctx: &mut DrawContext<P>) {
            T::draw(self, ctx)
        }
    }
}