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
//! A widget for selecting a single value along some linear range.
use conrod_core::{
    builder_methods, image,
    position::Range,
    utils,
    widget::{self, Image},
    widget_ids, Color, Colorable, Positionable, Rect, Sizeable, Widget, WidgetCommon,
};
use num::{Float, Integer, Num, NumCast};

pub enum Discrete {}
pub enum Continuous {}

pub trait ValueFromPercent<T> {
    fn value_from_percent(percent: f32, min: T, max: T) -> T;
}

/// Linear value selection.
///
/// If the slider's width is greater than its 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.
#[derive(WidgetCommon)]
pub struct ImageSlider<T, K> {
    #[conrod(common_builder)]
    common: widget::CommonBuilder,
    value: T,
    min: T,
    max: T,
    // If `value > soft_max` we will display the slider at `soft_max` along with a faded ghost
    // slider at `value`. The slider displayed at `soft_max` is purely a visual indicator and has
    // no effect on the values produced by this slider.
    soft_max: T,
    /// The amount in which the slider's display should be skewed.
    ///
    /// Higher skew amounts (above 1.0) will weigh lower values.
    ///
    /// Lower skew amounts (below 1.0) will weigh higher values.
    ///
    /// All skew amounts should be greater than 0.0.
    skew: f32,
    track: Track,
    slider: Slider,
    kind: std::marker::PhantomData<K>,
}

struct Track {
    image_id: image::Id,
    color: Option<Color>,
    // TODO: this is being set by users but we don't use it for anything here, figure out what it
    // is supposed to be used for
    #[allow(dead_code)]
    breadth: Option<f32>,
    // Padding on the ends of the track constraining the slider to a smaller area.
    padding: (f32, f32),
}

struct Slider {
    image_id: image::Id,
    hover_image_id: Option<image::Id>,
    press_image_id: Option<image::Id>,
    color: Option<Color>,
    length: Option<f32>,
}

widget_ids! {
    struct Ids {
        track,
        slider,
        soft_max_slider,
    }
}

/// Represents the state of the ImageSlider widget.
pub struct State {
    ids: Ids,
}

impl<T, K> ImageSlider<T, K> {
    builder_methods! {
        pub skew { skew = f32 }
        pub soft_max { soft_max = T }
        pub pad_track { track.padding = (f32, f32) }
        pub hover_image { slider.hover_image_id = Some(image::Id) }
        pub press_image { slider.press_image_id = Some(image::Id) }
        pub track_breadth { track.breadth = Some(f32) }
        pub slider_length { slider.length = Some(f32) }
        pub track_color { track.color = Some(Color) }
        pub slider_color { slider.color = Some(Color) }
    }

    fn new(value: T, min: T, max: T, slider_image_id: image::Id, track_image_id: image::Id) -> Self
    where
        T: Copy,
    {
        Self {
            common: widget::CommonBuilder::default(),
            value,
            min,
            max,
            soft_max: max,
            skew: 1.0,
            track: Track {
                image_id: track_image_id,
                color: None,
                breadth: None,
                padding: (0.0, 0.0),
            },
            slider: Slider {
                image_id: slider_image_id,
                hover_image_id: None,
                press_image_id: None,
                color: None,
                length: None,
            },
            kind: std::marker::PhantomData,
        }
    }
}

impl<T> ImageSlider<T, Continuous>
where
    T: Float,
{
    pub fn continuous(
        value: T,
        min: T,
        max: T,
        slider_image_id: image::Id,
        track_image_id: image::Id,
    ) -> Self {
        ImageSlider::new(value, min, max, slider_image_id, track_image_id)
    }
}

impl<T> ImageSlider<T, Discrete>
where
    T: Integer + Copy,
{
    pub fn discrete(
        value: T,
        min: T,
        max: T,
        slider_image_id: image::Id,
        track_image_id: image::Id,
    ) -> Self {
        ImageSlider::new(value, min, max, slider_image_id, track_image_id)
    }
}

impl<T: Float> ValueFromPercent<T> for Continuous {
    fn value_from_percent(percent: f32, min: T, max: T) -> T {
        utils::value_from_perc(percent, min, max)
    }
}
impl<T: Integer + NumCast> ValueFromPercent<T> for Discrete {
    fn value_from_percent(percent: f32, min: T, max: T) -> T {
        NumCast::from(
            utils::value_from_perc(percent, min.to_f32().unwrap(), max.to_f32().unwrap()).round(),
        )
        .unwrap()
    }
}

impl<T, K> Widget for ImageSlider<T, K>
where
    T: NumCast + Num + Copy + PartialOrd,
    K: ValueFromPercent<T>,
{
    type Event = Option<T>;
    type State = State;
    type Style = ();

    fn init_state(&self, id_gen: widget::id::Generator) -> Self::State {
        State {
            ids: Ids::new(id_gen),
        }
    }

    fn style(&self) -> Self::Style {}

    /// Update the state of the Slider.
    fn update(self, args: widget::UpdateArgs<Self>) -> Self::Event {
        let widget::UpdateArgs {
            id,
            state,
            rect,
            ui,
            ..
        } = args;
        let ImageSlider {
            value,
            min,
            max,
            skew,
            track,
            slider,
            ..
        } = self;
        let (start_pad, end_pad) = (track.padding.0 as f64, track.padding.1 as f64);

        let is_horizontal = rect.w() > rect.h();

        let new_value = if let Some(mouse) = ui.widget_input(id).mouse() {
            if mouse.buttons.left().is_down() {
                let mouse_abs_xy = mouse.abs_xy();
                let (mouse_offset, track_length) = if is_horizontal {
                    // Horizontal
                    (
                        mouse_abs_xy[0] - rect.x.start - start_pad,
                        rect.w() - start_pad - end_pad,
                    )
                } else {
                    // Vertical
                    (
                        mouse_abs_xy[1] - rect.y.start - start_pad,
                        rect.h() - start_pad - end_pad,
                    )
                };
                let perc = utils::clamp(mouse_offset, 0.0, track_length) / track_length;
                let skewed_perc = (perc).powf(skew as f64);
                K::value_from_percent(skewed_perc as f32, min, max)
            } else {
                value
            }
        } else {
            value
        };

        // Track
        let track_rect = if is_horizontal {
            let h = slider.length.map_or(rect.h() / 3.0, |h| h as f64);
            Rect {
                y: Range::from_pos_and_len(rect.y(), h),
                ..rect
            }
        } else {
            let w = slider.length.map_or(rect.w() / 3.0, |w| w as f64);
            Rect {
                x: Range::from_pos_and_len(rect.x(), w),
                ..rect
            }
        };

        let (x, y, w, h) = track_rect.x_y_w_h();
        Image::new(track.image_id)
            .x_y(x, y)
            .w_h(w, h)
            .parent(id)
            .graphics_for(id)
            .color(track.color)
            .set(state.ids.track, ui);

        // Slider
        let slider_image = ui
            .widget_input(id)
            .mouse()
            .map(|mouse| {
                if mouse.buttons.left().is_down() {
                    slider
                        .press_image_id
                        .or(slider.hover_image_id)
                        .unwrap_or(slider.image_id)
                } else {
                    slider.hover_image_id.unwrap_or(slider.image_id)
                }
            })
            .unwrap_or(slider.image_id);

        // A rectangle for positioning and sizing the slider.
        let slider_rect = |slider_value| {
            let value_perc = utils::map_range(slider_value, min, max, 0.0, 1.0);
            let unskewed_perc = value_perc.powf(1.0 / skew as f64);
            if is_horizontal {
                let pos = utils::map_range(
                    unskewed_perc,
                    0.0,
                    1.0,
                    rect.x.start + start_pad,
                    rect.x.end - end_pad,
                );
                let w = slider.length.map_or(rect.w() / 10.0, |w| w as f64);
                Rect {
                    x: Range::from_pos_and_len(pos, w),
                    ..rect
                }
            } else {
                let pos = utils::map_range(
                    unskewed_perc,
                    0.0,
                    1.0,
                    rect.y.start + start_pad,
                    rect.y.end - end_pad,
                );
                let h = slider.length.map_or(rect.h() / 10.0, |h| h as f64);
                Rect {
                    y: Range::from_pos_and_len(pos, h),
                    ..rect
                }
            }
        };

        // Whether soft max slider needs to be displayed and main slider faded to look
        // like a ghost.
        let over_soft_max = new_value > self.soft_max;

        let (x, y, w, h) = slider_rect(new_value).x_y_w_h();
        let fade = if over_soft_max { 0.5 } else { 1.0 };
        Image::new(slider_image)
            .x_y(x, y)
            .w_h(w, h)
            .parent(id)
            .graphics_for(id)
            .color(Some(
                slider
                    .color
                    .map_or(Color::Rgba(1.0, 1.0, 1.0, fade), |c: Color| c.alpha(fade)),
            ))
            .set(state.ids.slider, ui);

        if over_soft_max {
            let (x, y, w, h) = slider_rect(self.soft_max).x_y_w_h();
            Image::new(slider_image)
                .x_y(x, y)
                .w_h(w, h)
                .parent(id)
                .graphics_for(id)
                .color(slider.color)
                .set(state.ids.soft_max_slider, ui);
        }

        // If the value has just changed, return the new value.
        if value != new_value {
            Some(new_value)
        } else {
            None
        }
    }
}

impl<T, K> Colorable for ImageSlider<T, K> {
    fn color(mut self, color: Color) -> Self {
        self.slider.color = Some(color);
        self.track.color = Some(color);
        self
    }
}