Skip to content

Commit 63629bb

Browse files
committed
widget: slider: Add stepping functionality
A new builder method `with_step(f64)` is added to set the stepping value. Signed-off-by: Christopher N. Hesse <raymanfx@gmail.com>
1 parent a08ea03 commit 63629bb

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,4 @@ Robert Wittams
1616
Jaap Aarts
1717
Maximilian Köstler
1818
Bruno Dupuis
19+
Christopher Noel Hesse

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ You can find its changes [documented below](#070---2021-01-01).
5151
- Linux extension: primary_clipboard ([#1843] by [@Maan2003])
5252
- x11: Implement primary_clipboard ([#1867] by [@psychon])
5353
- x11: Set WM_CLASS property ([#1868] by [@psychon])
54+
- Widget/Slider: Add stepping functionality ([#1875] by [@raymanfx])
5455

5556
### Changed
5657

druid/src/widget/slider.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ const KNOB_STROKE_WIDTH: f64 = 2.0;
3131
pub struct Slider {
3232
min: f64,
3333
max: f64,
34+
step: Option<f64>,
3435
knob_pos: Point,
3536
knob_hovered: bool,
3637
x_offset: f64,
@@ -42,6 +43,7 @@ impl Slider {
4243
Slider {
4344
min: 0.,
4445
max: 1.,
46+
step: None,
4547
knob_pos: Default::default(),
4648
knob_hovered: Default::default(),
4749
x_offset: Default::default(),
@@ -56,6 +58,24 @@ impl Slider {
5658
self.max = max;
5759
self
5860
}
61+
62+
/// Builder-style method to set the stepping.
63+
///
64+
/// The default step size is `0.0` (smooth).
65+
pub fn with_step(mut self, step: f64) -> Self {
66+
if step < 0.0 {
67+
tracing::warn!("bad stepping (must be positive): {}", step);
68+
return self;
69+
}
70+
self.step = if step > 0.0 {
71+
Some(step)
72+
} else {
73+
// A stepping value of 0.0 would yield an infinite amount of steps.
74+
// Enforce no stepping instead.
75+
None
76+
};
77+
self
78+
}
5979
}
6080

6181
impl Slider {
@@ -68,7 +88,14 @@ impl Slider {
6888
let scalar = ((mouse_x + self.x_offset - knob_width / 2.) / (slider_width - knob_width))
6989
.max(0.0)
7090
.min(1.0);
71-
self.min + scalar * (self.max - self.min)
91+
let mut value = self.min + scalar * (self.max - self.min);
92+
if let Some(stepping) = self.step {
93+
// Determine the number of steps and fit the slider position to a discrete step
94+
let steps = (self.max / stepping).round();
95+
let step = (value * steps / self.max).round();
96+
value = step / steps * self.max;
97+
}
98+
value
7299
}
73100

74101
fn normalize(&self, data: f64) -> f64 {

0 commit comments

Comments
 (0)