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

use {
    CharacterCache,
    Color,
    Colorable,
    Dimension,
    FontSize,
    Frameable,
    Labelable,
    IndexSlot,
    KidArea,
    Mouse,
    Padding,
    Positionable,
    Range,
    Rect,
    Rectangle,
    Scalar,
    Text,
    Theme,
    Ui,
    Widget,
};
use num::{Float, NumCast, ToPrimitive};
use widget;


/// Linear value selection. If the slider's width is greater than it's height, it will
/// automatically become a horizontal slider, otherwise it will be a vertical slider. Its reaction
/// is triggered if the value is updated or if the mouse button is released while the cursor is
/// above the rectangle.
pub struct Slider<'a, T, F> {
    common: widget::CommonBuilder,
    value: T,
    min: T,
    max: T,
    skew: f32,
    maybe_react: Option<F>,
    maybe_label: Option<&'a str>,
    style: Style,
    enabled: bool,
}

/// Styling for the Slider, necessary for constructing its renderable Element.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Style {
    /// The color of the slidable rectangle.
    pub maybe_color: Option<Color>,
    /// The length of the frame around the edges of the slidable rectangle.
    pub maybe_frame: Option<Scalar>,
    /// The color of the Slider's frame.
    pub maybe_frame_color: Option<Color>,
    /// The color of the Slider's label.
    pub maybe_label_color: Option<Color>,
    /// The font-size for the Slider's label.
    pub maybe_label_font_size: Option<u32>,
}

/// Represents the state of the Slider widget.
#[derive(Clone, Debug, PartialEq)]
pub struct State<T> {
    value: T,
    min: T,
    max: T,
    skew: f32,
    interaction: Interaction,
    frame_idx: IndexSlot,
    slider_idx: IndexSlot,
    label_idx: IndexSlot,
}

/// Unique kind for the widget type.
pub const KIND: widget::Kind = "Slider";

/// The ways in which the Slider can be interacted with.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Interaction {
    Normal,
    Highlighted,
    Clicked,
}


impl Interaction {
    /// Return the color associated with the state.
    fn color(&self, color: Color) -> Color {
        match *self {
            Interaction::Normal => color,
            Interaction::Highlighted => color.highlighted(),
            Interaction::Clicked => color.clicked(),
        }
    }
}

/// Check the current state of the slider.
fn get_new_interaction(is_over: bool, prev: Interaction, mouse: Mouse) -> Interaction {
    use mouse::ButtonPosition::{Down, Up};
    use self::Interaction::{Normal, Highlighted, Clicked};
    match (is_over, prev, mouse.left.position) {
        (true,  Normal,  Down) => Normal,
        (true,  _,       Down) => Clicked,
        (true,  _,       Up)   => Highlighted,
        (false, Clicked, Down) => Clicked,
        _ => Normal,
    }
}

impl<'a, T, F> Slider<'a, T, F> {

    /// Construct a new Slider widget.
    pub fn new(value: T, min: T, max: T) -> Self {
        Slider {
            common: widget::CommonBuilder::new(),
            value: value,
            min: min,
            max: max,
            skew: 1.0,
            maybe_react: None,
            maybe_label: None,
            style: Style::new(),
            enabled: true,
        }
    }

    /// Set the amount in which the slider's display should be skewed.
    ///
    /// Higher skew amounts (above 1.0) will weight lower values.
    ///
    /// Lower skew amounts (below 1.0) will weight heigher values.
    ///
    /// All skew amounts should be greater than 0.0.
    pub fn skew(mut self, skew: f32) -> Self {
        self.skew = skew;
        self
    }

    /// Set the reaction for the Slider.
    ///
    /// It will be triggered if the value is updated or if the mouse button is released while the
    /// cursor is above the rectangle.
    pub fn react(mut self, reaction: F) -> Self {
        self.maybe_react = Some(reaction);
        self
    }

    /// If true, will allow adjusting the slider.
    ///
    /// If false, will disallow adjusting the slider.
    pub fn enabled(mut self, flag: bool) -> Self {
        self.enabled = flag;
        self
    }

}

impl<'a, T, F> Widget for Slider<'a, T, F> where
    F: FnOnce(T),
    T: ::std::any::Any + ::std::fmt::Debug + Float + NumCast + ToPrimitive,
{
    type State = State<T>;
    type Style = Style;

    fn common(&self) -> &widget::CommonBuilder {
        &self.common
    }

    fn common_mut(&mut self) -> &mut widget::CommonBuilder {
        &mut self.common
    }

    fn unique_kind(&self) -> &'static str {
        KIND
    }

    fn init_state(&self) -> State<T> {
        State {
            value: self.value,
            min: self.min,
            max: self.max,
            skew: self.skew,
            interaction: Interaction::Normal,
            frame_idx: IndexSlot::new(),
            slider_idx: IndexSlot::new(),
            label_idx: IndexSlot::new(),
        }
    }

    fn style(&self) -> Style {
        self.style.clone()
    }

    fn default_x_dimension<C: CharacterCache>(&self, ui: &Ui<C>) -> Dimension {
        widget::default_x_dimension(self, ui).unwrap_or(Dimension::Absolute(192.0))
    }

    fn default_y_dimension<C: CharacterCache>(&self, ui: &Ui<C>) -> Dimension {
        widget::default_y_dimension(self, ui).unwrap_or(Dimension::Absolute(48.0))
    }

    fn kid_area<C: CharacterCache>(&self, args: widget::KidAreaArgs<Self, C>) -> KidArea {
        const LABEL_PADDING: Scalar = 10.0;
        KidArea {
            rect: args.rect,
            pad: Padding {
                x: Range::new(LABEL_PADDING, LABEL_PADDING),
                y: Range::new(LABEL_PADDING, LABEL_PADDING),
            },
        }
    }

    /// Update the state of the Slider.
    fn update<C: CharacterCache>(self, args: widget::UpdateArgs<Self, C>) {
        use self::Interaction::{Clicked, Highlighted, Normal};
        use utils::{clamp, map_range, percentage, value_from_perc};

        let widget::UpdateArgs { idx, state, rect, style, mut ui, .. } = args;
        let Slider { value, min, max, skew, enabled, maybe_label, maybe_react, .. } = self;

        let maybe_mouse = ui.input().maybe_mouse;
        let interaction = state.view().interaction;
        let new_interaction = match (enabled, maybe_mouse) {
            (false, _) | (true, None) => Normal,
            (true, Some(mouse)) => {
                let is_over = rect.is_over(mouse.xy);
                get_new_interaction(is_over, interaction, mouse)
            },
        };

        match (interaction, new_interaction) {
            (Highlighted, Clicked) => { ui.capture_mouse(); },
            (Clicked, Highlighted) |
            (Clicked, Normal)      => { ui.uncapture_mouse(); },
            _ => (),
        }

        let is_horizontal = rect.w() > rect.h();
        let frame = style.frame(ui.theme());
        let inner_rect = rect.pad(frame);
        let new_value = if let Some(mouse) = maybe_mouse {
            if is_horizontal {
                // Horizontal.
                let inner_w = inner_rect.w();
                let w_perc = match (interaction, new_interaction) {
                    (Highlighted, Clicked) | (Clicked, Clicked) => {
                        let slider_w = mouse.xy[0] - inner_rect.x.start;
                        let perc = clamp(slider_w, 0.0, inner_w) / inner_w;
                        let skewed_perc = (perc).powf(skew as f64);
                        skewed_perc
                    },
                    _ => {
                        let value_percentage = percentage(value, min, max);
                        let slider_w = clamp(value_percentage as f64 * inner_w, 0.0, inner_w);
                        let perc = slider_w / inner_w;
                        perc
                    },
                };
                value_from_perc(w_perc as f32, min, max)
            } else {
                // Vertical.
                let inner_h = inner_rect.h();
                let h_perc = match (interaction, new_interaction) {
                    (Highlighted, Clicked) | (Clicked, Clicked) => {
                        let slider_h = mouse.xy[1] - inner_rect.y.start;
                        let perc = clamp(slider_h, 0.0, inner_h) / inner_h;
                        let skewed_perc = (perc).powf(skew as f64);
                        skewed_perc
                    },
                    _ => {
                        let value_percentage = percentage(value, min, max);
                        let slider_h = clamp(value_percentage as f64 * inner_h, 0.0, inner_h);
                        let perc = slider_h / inner_h;
                        perc
                    },
                };
                value_from_perc(h_perc as f32, min, max)
            }
        } else {
            value
        };

        // If the value has just changed, or if the slider has been clicked/released, call the
        // reaction function.
        if let Some(react) = maybe_react {
            let should_react = value != new_value
                || (interaction == Highlighted && new_interaction == Clicked)
                || (interaction == Clicked && new_interaction == Highlighted);
            if should_react {
                react(new_value)
            }
        }

        if state.view().interaction != new_interaction {
            state.update(|state| state.interaction = new_interaction);
        }

        if state.view().value != new_value {
            state.update(|state| state.value = value);
        }

        if state.view().min != min {
            state.update(|state| state.min = min);
        }

        if state.view().max != max {
            state.update(|state| state.max = max);
        }

        if state.view().skew != skew {
            state.update(|state| state.skew = skew);
        }

        // The **Rectangle** for the frame.
        let frame_idx = state.view().frame_idx.get(&mut ui);
        let frame_color = new_interaction.color(style.frame_color(ui.theme()));
        Rectangle::fill(rect.dim())
            .middle_of(idx)
            .graphics_for(idx)
            .color(frame_color)
            .set(frame_idx, &mut ui);

        // The **Rectangle** for the adjustable slider.
        let slider_rect = if is_horizontal {
            let left = inner_rect.x.start;
            let right = map_range(new_value, min, max, left, inner_rect.x.end);
            let x = Range::new(left, right);
            let y = inner_rect.y;
            Rect { x: x, y: y }
        } else {
            let bottom = inner_rect.y.start;
            let top = map_range(new_value, min, max, bottom, inner_rect.y.end);
            let x = inner_rect.x;
            let y = Range::new(bottom, top);
            Rect { x: x, y: y }
        };
        let color = new_interaction.color(style.color(ui.theme()));
        let slider_idx = state.view().slider_idx.get(&mut ui);
        let slider_xy_offset = [slider_rect.x() - rect.x(), slider_rect.y() - rect.y()];
        Rectangle::fill(slider_rect.dim())
            .xy_relative_to(idx, slider_xy_offset)
            .graphics_for(idx)
            .parent(idx)
            .color(color)
            .set(slider_idx, &mut ui);

        // The **Text** for the slider's label (if it has one).
        if let Some(label) = maybe_label {
            let label_color = style.label_color(ui.theme());
            let font_size = style.label_font_size(ui.theme());
            //const TEXT_PADDING: f64 = 10.0;
            let label_idx = state.view().label_idx.get(&mut ui);
            if is_horizontal { Text::new(label).mid_left_of(idx) }
            else             { Text::new(label).mid_bottom_of(idx) }
                .graphics_for(idx)
                .color(label_color)
                .font_size(font_size)
                .set(label_idx, &mut ui);
        }
    }

}


impl Style {

    /// Construct the default Style.
    pub fn new() -> Style {
        Style {
            maybe_color: None,
            maybe_frame: None,
            maybe_frame_color: None,
            maybe_label_color: None,
            maybe_label_font_size: None,
        }
    }

    /// Get the Color for an Element.
    pub fn color(&self, theme: &Theme) -> Color {
        self.maybe_color.or(theme.widget_style::<Self>(KIND).map(|default| {
            default.style.maybe_color.unwrap_or(theme.shape_color)
        })).unwrap_or(theme.shape_color)
    }

    /// Get the frame for an Element.
    pub fn frame(&self, theme: &Theme) -> f64 {
        self.maybe_frame.or(theme.widget_style::<Self>(KIND).map(|default| {
            default.style.maybe_frame.unwrap_or(theme.frame_width)
        })).unwrap_or(theme.frame_width)
    }

    /// Get the frame Color for an Element.
    pub fn frame_color(&self, theme: &Theme) -> Color {
        self.maybe_frame_color.or(theme.widget_style::<Self>(KIND).map(|default| {
            default.style.maybe_frame_color.unwrap_or(theme.frame_color)
        })).unwrap_or(theme.frame_color)
    }

    /// Get the label Color for an Element.
    pub fn label_color(&self, theme: &Theme) -> Color {
        self.maybe_label_color.or(theme.widget_style::<Self>(KIND).map(|default| {
            default.style.maybe_label_color.unwrap_or(theme.label_color)
        })).unwrap_or(theme.label_color)
    }

    /// Get the label font size for an Element.
    pub fn label_font_size(&self, theme: &Theme) -> FontSize {
        self.maybe_label_font_size.or(theme.widget_style::<Self>(KIND).map(|default| {
            default.style.maybe_label_font_size.unwrap_or(theme.font_size_medium)
        })).unwrap_or(theme.font_size_medium)
    }

}


impl<'a, T, F> Colorable for Slider<'a, T, F> {
    fn color(mut self, color: Color) -> Self {
        self.style.maybe_color = Some(color);
        self
    }
}

impl<'a, T, F> Frameable for Slider<'a, T, F> {
    fn frame(mut self, width: f64) -> Self {
        self.style.maybe_frame = Some(width);
        self
    }
    fn frame_color(mut self, color: Color) -> Self {
        self.style.maybe_frame_color = Some(color);
        self
    }
}

impl<'a, T, F> Labelable<'a> for Slider<'a, T, F> {
    fn label(mut self, text: &'a str) -> Self {
        self.maybe_label = Some(text);
        self
    }

    fn label_color(mut self, color: Color) -> Self {
        self.style.maybe_label_color = Some(color);
        self
    }

    fn label_font_size(mut self, size: FontSize) -> Self {
        self.style.maybe_label_font_size = Some(size);
        self
    }
}