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
use crate::common::*;

#[derive(Debug, Clone, PartialEq)]
pub enum SliderEvent {
    // TODO - Remove this
    ValueChanged(f32),
    SetValue(f32),
    SetMin(f32),
    SetMax(f32),
}

pub struct Slider {
    // The track that the thumb slides along
    track: Entity,
    // An overlay on the track to indicate the value
    active: Entity,
    // A marker used to indicate the value by its position along the track
    thumb: Entity,

    // Event sent when the slider value has changed
    on_change: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // event sent when the slider value is changing
    on_changing: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the slider reaches the minimum value
    on_min: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the slider reaches the maximum value
    on_max: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the slider is pressed
    on_press: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the slider is released
    on_release: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the mouse cursor enters the slider
    on_over: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,
    // Event sent when the mouse cusor leaves the slider
    on_out: Option<Box<dyn Fn(&mut Self, &mut State, Entity)>>,

    pub value: f32,
    prev: f32,
    min: f32,
    max: f32,

    is_min: bool,
    is_max: bool,
}

impl Default for Slider {
    fn default() -> Self {
        Self {
            track: Entity::default(),
            active: Entity::default(),
            thumb: Entity::default(),

            on_change: None,
            on_changing: None,
            on_min: None,
            on_max: None,
            on_press: None,
            on_release: None,
            on_over: None,
            on_out: None,

            value: 0.0,
            prev: 0.0,
            min: 0.0,
            max: 1.0,

            is_min: true,
            is_max: false,
        }
    }
}

impl Slider {
    /// Create a new slider widget with default values (min: 0.0, max: 1.0, val: 0.0).
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new().build(state, parent, |builder| builder);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the initial value of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///    .with_init(0.5)
    ///    .build(state, parent, |builder| builder)
    /// ```
    pub fn with_init(mut self, val: f32) -> Self {
        self.value = val;

        self
    }

    /// Set the range of the slider. Min and Max values are extracted from the range.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .with_range(0.0..5.0)
    ///     .build(state, parent, |builder| builder)
    /// ```
    pub fn with_range(mut self, range: std::ops::Range<f32>) -> Self {
        self.min = range.start;
        self.max = range.end;

        self
    }

    /// Set the minimum value of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .with_min(0.2)
    ///     .build(state, parent, |builder| builder)
    /// ```
    pub fn with_min(mut self, val: f32) -> Self {
        self.min = val;
        self
    }

    /// Set the maximum value of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .with_max()
    ///     .build(state, parent, |builder| builder)
    /// ```
    pub fn with_max(mut self, val: f32) -> Self {
        self.max = val;
        self
    }

    /// Set the callback triggered when the slider value has changed.
    ///
    /// Takes a closure which provides the current value and returns an event to be sent when the slider
    /// value has changed after releasing the slider. If the slider thumb is pressed but not moved, and thus
    /// the value is not changed, then the event will not be sent.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_change(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_change: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_change = Some(Box::new(callback));
        self
    }

    /// Set the callback triggered when the slider value is changing (dragging).
    ///
    /// Takes a closure which triggers when the slider value is changing, 
    /// either by pressing the track or dragging the thumb along the track.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_changing(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_changing: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_changing<F>(mut self, callback: F) -> Self
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_changing = Some(Box::new(callback));
        self
    }

    /// Set the callback triggered when the slider value reaches the minimum.
    ///
    /// Takes a closure which triggers when the slider reaches the minimum value, 
    /// either by pressing the track at the start or dragging the thumb to the start
    /// of the track. The event is sent once for each time the value reaches the minimum.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_min(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_min<F>(mut self, callback: F) -> Self
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_min = Some(Box::new(callback));
        self
    }

    /// Set the callback triggered when the slider value reaches the maximum.
    ///
    /// Takes a closure which triggers when the slider reaches the maximum value, 
    /// either by pressing the track at the end or dragging the thumb to the end
    /// of the track. The event is sent once for each time the value reaches the maximum.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_max(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_max<F>(mut self, callback: F) -> Self
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_max = Some(Box::new(callback));
        self
    }

    /// Set the event sent when the slider is pressed.
    ///
    /// The event is sent when the left mouse button is pressed on any part of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_max(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    // pub fn on_press<F>(mut self, callback: F) -> Self 
    // where
    //     F: 'static + Fn(&mut Self, &mut State, Entity),
    // {
    //     self.on_press = Some(Box::new(callback));
    //     self
    // }

    /// Set the event sent when the slider is released.
    ///
    /// The event is sent when the left mouse button is released after being pressed on any part of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_max(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_release<F>(mut self, callback: F) -> Self 
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_release = Some(Box::new(callback));
        self
    }

    /// Set the event sent when the mouse cursor enters the slider.
    ///
    /// The event is sent when the mouse cursor enters the bounding box of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_max(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_over<F>(mut self, callback: F) -> Self 
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_over = Some(Box::new(callback));
        self
    }

    /// Set the event sent when the mouse cursor leaves the slider
    ///
    /// The event is sent when the mouse cursor leaves the bounding box of the slider.
    ///
    /// # Example
    /// 
    /// ```
    /// Slider::new()
    ///     .on_max(|slider, state, entity| {
    ///         entity.emit(WindowEvent::Debug(format!("Slider on_min: {}", slider.value)));
    ///     })
    ///     .build(state, parent, |builder| builder);
    /// ```
    pub fn on_out<F>(mut self, callback: F) -> Self 
    where
        F: 'static + Fn(&mut Self, &mut State, Entity),
    {
        self.on_out = Some(Box::new(callback));
        self
    }

    // Private helper functions

    // Update the active size and thumb position
    fn update_value(&mut self, state: &mut State, entity: Entity, mut dx: f32) {
        let width = state.data.get_width(entity);
        let thumb_width = state.data.get_width(self.thumb);

        if dx <= thumb_width / 2.0 {
            dx = thumb_width / 2.0;
        }
        if dx >= width - thumb_width / 2.0 {
            dx = width - thumb_width / 2.0;
        }

        let nx = (dx - thumb_width / 2.0) / (width - thumb_width);

        self.thumb
            .set_left(state, Units::Percentage(100.0 * (dx - thumb_width / 2.0) / width));

        self.active.set_width(state, Units::Percentage(nx * 100.0));

        self.value = self.min + nx * (self.max - self.min);

        if self.value == self.min {
            if !self.is_min {
                self.is_min = true;
                //self.send_value_event(state, entity, &self.on_min);
                if let Some(callback) = self.on_min.take() {
                    (callback)(self, state, entity);
                    self.on_min = Some(callback);
                }
            }
        } else {
            self.is_min = false;
        }

        if self.value == self.max {
            if !self.is_max {
                self.is_max = true;
                if let Some(callback) = self.on_max.take() {
                    (callback)(self, state, entity);
                    self.on_max = Some(callback);
                }
            }
        } else {
            self.is_max = false;
        }
    }

    fn update_visuals(&mut self, state: &mut State, entity: Entity) {
        let normalised_value = (self.value - self.min) / (self.max - self.min);

        let width = state.data.get_width(entity);
        let thumb_width = state.data.get_width(self.thumb);

        let dx = normalised_value * (width - thumb_width) + thumb_width / 2.0;

        self.update_value(state, entity, dx);
    }

    fn clamp_value(&mut self) {
        self.value = self.value.clamp(self.min, self.max);
    }
}

impl Widget for Slider {
    type Ret = Entity;
    type Data = f32;
    fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
        if self.min > self.max {
            panic!("minimum value must be less than maximum value")
        }

        self.clamp_value();

        self.is_min = self.value == self.min;
        self.is_max = self.value == self.max;

        entity
            .set_layout_type(state, LayoutType::Row)
            .set_child_top(state, Stretch(1.0))
            .set_child_bottom(state, Stretch(1.0));

        // Track
        self.track = Element::new().build(state, entity, |builder| {
            builder
                .set_width(Stretch(1.0))
                // .set_height(Pixels(4.0))
                .set_bottom(Auto)
                .set_hoverable(false)
                .class("track")
        });

        // Active
        self.active = Element::new().build(state, self.track, |builder| {
            builder
                .set_width(Percentage(0.0))
                .set_height(Stretch(1.0))
                .set_hoverable(false)
                .class("active")
        });

        // Thumb
        self.thumb = Element::new().build(state, entity, |builder| {
            builder
                .set_position_type(PositionType::SelfDirected)
                .set_hoverable(false)
                .class("thumb")
        });

        entity.set_element(state, "slider")
    }

    fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) {
        // Handle window events
        if let Some(window_event) = event.message.downcast() {
            match window_event {
                
                //TODO
                // WindowEvent::GeometryChanged(_) if event.target == entity => {
                //     self.update_visuals(state, entity);
                // }

                WindowEvent::MouseOver if event.target == entity => {
                    if let Some(callback) = self.on_over.take() {
                        (callback)(self, state, entity);
                        self.on_over = Some(callback);
                    }
                }

                WindowEvent::MouseOut if event.target == entity => {
                    if let Some(callback) = self.on_out.take() {
                        (callback)(self, state, entity);
                        self.on_out = Some(callback);
                    }
                }

                WindowEvent::MouseDown(button) if event.target == entity => {
                    if *button == MouseButton::Left {
                        state.capture(entity);

                        self.prev = self.value;

                        entity.set_active(state, true);

                        if let Some(callback) = self.on_press.take() {
                            (callback)(self, state, entity);
                            self.on_press = Some(callback);
                        }

                        let dx = state.mouse.left.pos_down.0 - state.data.get_posx(entity);

                        self.update_value(state, entity, dx);

                        if let Some(callback) = self.on_changing.take() {
                            (callback)(self, state, entity);
                            self.on_changing = Some(callback);
                        }

                        state.insert_event(
                            Event::new(SliderEvent::ValueChanged(self.value)).target(entity),
                        );
                    }
                }

                WindowEvent::MouseUp(button) if event.target == entity => {
                    if *button == MouseButton::Left {
                        state.release(entity);

                        entity.set_active(state, false);

                        if self.prev != self.value {
                            //self.send_value_event(state, entity, &self.on_change);
                            if let Some(callback) = self.on_change.take() {
                                (callback)(self, state, entity);
                                self.on_change = Some(callback);
                            }

                        }

                        if let Some(callback) = self.on_release.take() {
                            (callback)(self, state, entity);
                            self.on_release = Some(callback);
                        }
                    }
                }

                WindowEvent::MouseMove(x, _) if event.target == entity => {
                    if entity.is_active(state) {
                        let dx = *x - state.data.get_posx(entity);

                        self.update_value(state, entity, dx);
                        
                        if let Some(callback) = self.on_changing.take() {
                            (callback)(self, state, entity);
                            self.on_changing = Some(callback);
                        }
                    }
                }

                // TODO - Add keyboard control
                _ => {}
            }
        }

        // Handle slider events
        if let Some(slider_event) = event.message.downcast() {
            match slider_event {
                SliderEvent::SetMin(val) => {
                    self.min = *val;
                    self.min = self.min.min(self.max);
                    self.clamp_value();

                    self.update_visuals(state, entity);
                }

                SliderEvent::SetMax(val) => {
                    self.max = *val;
                    self.max = self.max.max(self.min);
                    self.clamp_value();

                    self.update_visuals(state, entity);
                }

                SliderEvent::SetValue(val) => {
                    self.value = *val;
                    self.clamp_value();

                    self.update_visuals(state, entity);
                }

                _ => {}
            }
        }
    }

    fn on_update(&mut self, state: &mut State, entity: Entity, data: &Self::Data) {
        self.value = *data;
        self.update_visuals(state, entity);
    }
}