Skip to content

Commit

Permalink
widget: slider: Add stepping functionality
Browse files Browse the repository at this point in the history
A new builder method `with_step(f64)` is added to set the stepping value.

Signed-off-by: Christopher N. Hesse <[email protected]>
  • Loading branch information
raymanfx committed Jul 16, 2021
1 parent a08ea03 commit a6bbf2b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ Robert Wittams
Jaap Aarts
Maximilian Köstler
Bruno Dupuis
Christopher Noel Hesse
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ You can find its changes [documented below](#070---2021-01-01).
- Linux extension: primary_clipboard ([#1843] by [@Maan2003])
- x11: Implement primary_clipboard ([#1867] by [@psychon])
- x11: Set WM_CLASS property ([#1868] by [@psychon])
- Widget/Slider: Add stepping functionality ([#1875] by [@raymanfx])

### Changed

Expand Down
28 changes: 27 additions & 1 deletion druid/src/widget/slider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const KNOB_STROKE_WIDTH: f64 = 2.0;
pub struct Slider {
min: f64,
max: f64,
step: Option<f64>,
knob_pos: Point,
knob_hovered: bool,
x_offset: f64,
Expand All @@ -42,6 +43,7 @@ impl Slider {
Slider {
min: 0.,
max: 1.,
step: None,
knob_pos: Default::default(),
knob_hovered: Default::default(),
x_offset: Default::default(),
Expand All @@ -56,6 +58,24 @@ impl Slider {
self.max = max;
self
}

/// Builder-style method to set the stepping.
///
/// The default step size is `0.0` (smooth).
pub fn with_step(mut self, step: f64) -> Self {
if step < 0.0 {
tracing::warn!("Bad slider step: {}", step);
return self;
}
self.step = if step == 0.0 {
// A stepping value of 0.0 would yield an infinite amount of steps.
// Enforce a single step instead.
Some(self.max)
} else {
Some(step)
};
self
}
}

impl Slider {
Expand All @@ -68,7 +88,13 @@ impl Slider {
let scalar = ((mouse_x + self.x_offset - knob_width / 2.) / (slider_width - knob_width))
.max(0.0)
.min(1.0);
self.min + scalar * (self.max - self.min)
let mut value = self.min + scalar * (self.max - self.min);
if let Some(stepping) = self.step {
let steps = (self.max / stepping).round();
let step = (value * steps).round();
value = step / steps;
}
value
}

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

0 comments on commit a6bbf2b

Please sign in to comment.