Skip to main content

iced_widget/
vertical_slider.rs

1//! Sliders let users set a value by moving an indicator.
2//!
3//! # Example
4//! ```no_run
5//! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
6//! # use iced::widget::Widget;
7//! #
8//! use iced::widget::slider;
9//!
10//! struct State {
11//!    value: f32,
12//! }
13//!
14//! #[derive(Debug, Clone)]
15//! enum Message {
16//!     ValueChanged(f32),
17//! }
18//!
19//! fn view(state: &State) -> impl Widget<Message> {
20//!     slider(0.0..=100.0, state.value, Message::ValueChanged)
21//! }
22//!
23//! fn update(state: &mut State, message: Message) {
24//!     match message {
25//!         Message::ValueChanged(value) => {
26//!             state.value = value;
27//!         }
28//!     }
29//! }
30//! ```
31use std::ops::RangeInclusive;
32
33pub use crate::slider::{Catalog, Handle, HandleShape, Status, Style, StyleFn, default};
34
35use crate::core::border::Border;
36use crate::core::keyboard;
37use crate::core::keyboard::key::{self, Key};
38use crate::core::layout::{self, Layout};
39use crate::core::mouse;
40use crate::core::renderer;
41use crate::core::touch;
42use crate::core::widget::Meta;
43use crate::core::widget::tree::{self, Tree};
44use crate::core::window;
45use crate::core::{self, Event, Length, Pixels, Point, Rectangle, Shell, Size, Widget};
46
47/// An vertical bar and a handle that selects a single value from a range of
48/// values.
49///
50/// A [`VerticalSlider`] will try to fill the vertical space of its container.
51///
52/// The [`VerticalSlider`] range of numeric values is generic and its step size defaults
53/// to 1 unit.
54///
55/// Note: Under the hood values are converted to/from f64 so only values representable exactly as an f64
56/// are possible to select via the slider. However it is likely that the precision of the slider at these
57/// scales is already less than the precision lost from the f64 representation.
58///
59/// # Example
60/// ```no_run
61/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
62/// # use iced::widget::Widget;
63/// #
64/// use iced::widget::vertical_slider;
65///
66/// struct State {
67///    value: f32,
68/// }
69///
70/// #[derive(Debug, Clone)]
71/// enum Message {
72///     ValueChanged(f32),
73/// }
74///
75/// fn view(state: &State) -> impl Widget<Message> {
76///     vertical_slider(0.0..=100.0, state.value, Message::ValueChanged)
77/// }
78///
79/// fn update(state: &mut State, message: Message) {
80///     match message {
81///         Message::ValueChanged(value) => {
82///             state.value = value;
83///         }
84///     }
85/// }
86/// ```
87pub struct VerticalSlider<'a, T, Message, Theme = crate::Theme>
88where
89    Theme: Catalog,
90{
91    range: RangeInclusive<T>,
92    step: f64,
93    shift_step: Option<f64>,
94    value: T,
95    default: Option<T>,
96    on_change: Box<dyn Fn(T) -> Message + 'a>,
97    on_release: Option<Message>,
98    width: f32,
99    height: Length,
100    class: Theme::Class<'a>,
101    status: Option<Status>,
102}
103
104impl<'a, T, Message, Theme> VerticalSlider<'a, T, Message, Theme>
105where
106    T: Copy + std::cmp::PartialOrd,
107    Message: Clone,
108    Theme: Catalog,
109{
110    /// The default width of a [`VerticalSlider`].
111    pub const DEFAULT_WIDTH: f32 = 16.0;
112
113    /// Creates a new [`VerticalSlider`].
114    ///
115    /// It expects:
116    ///   * an inclusive range of possible values
117    ///   * the current value of the [`VerticalSlider`]
118    ///   * a function that will be called when the [`VerticalSlider`] is dragged.
119    ///     It receives the new value of the [`VerticalSlider`] and must produce a
120    ///     `Message`.
121    pub fn new<F>(range: RangeInclusive<T>, value: T, on_change: F) -> Self
122    where
123        F: 'a + Fn(T) -> Message,
124    {
125        let value = if value >= *range.start() {
126            value
127        } else {
128            *range.start()
129        };
130
131        let value = if value <= *range.end() {
132            value
133        } else {
134            *range.end()
135        };
136
137        VerticalSlider {
138            value,
139            default: None,
140            range,
141            step: 1.0,
142            shift_step: None,
143            on_change: Box::new(on_change),
144            on_release: None,
145            width: Self::DEFAULT_WIDTH,
146            height: Length::Fill,
147            class: Theme::default(),
148            status: None,
149        }
150    }
151
152    /// Sets the optional default value for the [`VerticalSlider`].
153    ///
154    /// If set, the [`VerticalSlider`] will reset to this value when ctrl-clicked or command-clicked.
155    pub fn default(mut self, default: impl Into<T>) -> Self {
156        self.default = Some(default.into());
157        self
158    }
159
160    /// Sets the release message of the [`VerticalSlider`].
161    /// This is called when the mouse is released from the slider.
162    ///
163    /// Typically, the user's interaction with the slider is finished when this message is produced.
164    /// This is useful if you need to spawn a long-running task from the slider's result, where
165    /// the default on_change message could create too many events.
166    pub fn on_release(mut self, on_release: Message) -> Self {
167        self.on_release = Some(on_release);
168        self
169    }
170
171    /// Sets the width of the [`VerticalSlider`].
172    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
173        self.width = width.into().0;
174        self
175    }
176
177    /// Sets the height of the [`VerticalSlider`].
178    pub fn height(mut self, height: impl Into<Length>) -> Self {
179        self.height = height.into();
180        self
181    }
182
183    /// Sets the step size of the [`VerticalSlider`].
184    pub fn step(mut self, step: impl num_traits::AsPrimitive<f64>) -> Self {
185        self.step = step.as_();
186        self
187    }
188
189    /// Sets the optional "shift" step for the [`VerticalSlider`].
190    ///
191    /// If set, this value is used as the step while the shift key is pressed.
192    pub fn shift_step(mut self, shift_step: impl num_traits::AsPrimitive<f64>) -> Self {
193        self.shift_step = Some(shift_step.as_());
194        self
195    }
196
197    /// Sets the style of the [`VerticalSlider`].
198    #[must_use]
199    pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
200    where
201        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
202    {
203        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
204        self
205    }
206
207    /// Sets the style class of the [`VerticalSlider`].
208    #[cfg(feature = "advanced")]
209    #[must_use]
210    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
211        self.class = class.into();
212        self
213    }
214}
215
216impl<T, Message, Theme> Meta for VerticalSlider<'_, T, Message, Theme> where Theme: Catalog {}
217
218impl<T, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
219    for VerticalSlider<'_, T, Message, Theme>
220where
221    T: Copy + num_traits::AsPrimitive<f64> + num_traits::FromPrimitive,
222    Message: Clone,
223    Theme: Catalog,
224    Renderer: core::Renderer,
225{
226    fn tag(&self) -> tree::Tag {
227        tree::Tag::of::<State>()
228    }
229
230    fn state(&self) -> tree::State {
231        tree::State::new(State::default())
232    }
233
234    fn size(&self) -> Size<Length> {
235        Size {
236            width: Length::Shrink,
237            height: self.height,
238        }
239    }
240
241    fn layout(&mut self, tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) {
242        tree.size = layout::atomic(limits, self.width, self.height);
243    }
244
245    fn update(
246        &mut self,
247        tree: &mut Tree,
248        event: &Event,
249        layout: Layout,
250        cursor: mouse::Cursor,
251        _renderer: &Renderer,
252        shell: &mut Shell<'_, Message>,
253        _viewport: &Rectangle,
254    ) {
255        let state = tree.state.downcast_mut::<State>();
256        let is_dragging = state.is_dragging;
257        let current_value = self.value;
258
259        let locate = |cursor_position: Point| -> Option<T> {
260            let bounds = layout.bounds();
261
262            if cursor_position.y >= bounds.y + bounds.height {
263                Some(*self.range.start())
264            } else if cursor_position.y <= bounds.y {
265                Some(*self.range.end())
266            } else {
267                let step = if state.keyboard_modifiers.shift() {
268                    self.shift_step.unwrap_or(self.step)
269                } else {
270                    self.step
271                };
272
273                let start = (*self.range.start()).as_();
274                let end = (*self.range.end()).as_();
275
276                let percent =
277                    1.0 - f64::from(cursor_position.y - bounds.y) / f64::from(bounds.height);
278
279                let steps = (percent * (end - start) / step).round();
280                let value = steps * step + start;
281
282                T::from_f64(value.min(end))
283            }
284        };
285
286        let increment = |value: T| -> Option<T> {
287            let step = if state.keyboard_modifiers.shift() {
288                self.shift_step.unwrap_or(self.step)
289            } else {
290                self.step
291            };
292
293            let steps = (value.as_() / step).round();
294            let new_value = step * (steps + 1.0);
295
296            if new_value > (*self.range.end()).as_() {
297                return Some(*self.range.end());
298            }
299
300            T::from_f64(new_value)
301        };
302
303        let decrement = |value: T| -> Option<T> {
304            let step = if state.keyboard_modifiers.shift() {
305                self.shift_step.unwrap_or(self.step)
306            } else {
307                self.step
308            };
309
310            let steps = (value.as_() / step).round();
311            let new_value = step * (steps - 1.0);
312
313            if new_value < (*self.range.start()).as_() {
314                return Some(*self.range.start());
315            }
316
317            T::from_f64(new_value)
318        };
319
320        let change = |new_value: T| {
321            if (self.value.as_() - new_value.as_()).abs() > f64::EPSILON {
322                shell.publish((self.on_change)(new_value));
323
324                self.value = new_value;
325            }
326        };
327
328        match event {
329            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
330            | Event::Touch(touch::Event::FingerPressed { .. }) => {
331                if let Some(cursor_position) = cursor.position_over(layout.bounds()) {
332                    if state.keyboard_modifiers.control() || state.keyboard_modifiers.command() {
333                        let _ = self.default.map(change);
334                        state.is_dragging = false;
335                    } else {
336                        let _ = locate(cursor_position).map(change);
337                        state.is_dragging = true;
338                    }
339
340                    shell.capture_event();
341                }
342            }
343            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
344            | Event::Touch(touch::Event::FingerLifted { .. })
345            | Event::Touch(touch::Event::FingerLost { .. })
346                if is_dragging =>
347            {
348                if let Some(on_release) = self.on_release.clone() {
349                    shell.publish(on_release);
350                }
351                state.is_dragging = false;
352            }
353            Event::Mouse(mouse::Event::CursorMoved { .. })
354            | Event::Touch(touch::Event::FingerMoved { .. })
355                if is_dragging =>
356            {
357                let _ = cursor.observe().position().and_then(locate).map(change);
358
359                shell.capture_event();
360            }
361            Event::Mouse(mouse::Event::WheelScrolled { delta })
362                if state.keyboard_modifiers.control() && cursor.is_over(layout.bounds()) =>
363            {
364                let delta = match *delta {
365                    mouse::ScrollDelta::Lines { x: _, y } => y,
366                    mouse::ScrollDelta::Pixels { x: _, y } => y,
367                };
368
369                if delta < 0.0 {
370                    let _ = decrement(current_value).map(change);
371                } else {
372                    let _ = increment(current_value).map(change);
373                }
374
375                shell.capture_event();
376            }
377            Event::Keyboard(keyboard::Event::KeyPressed { key, .. })
378                if cursor.is_over(layout.bounds()) =>
379            {
380                match key {
381                    Key::Named(key::Named::ArrowUp) => {
382                        let _ = increment(current_value).map(change);
383                        shell.capture_event();
384                    }
385                    Key::Named(key::Named::ArrowDown) => {
386                        let _ = decrement(current_value).map(change);
387                        shell.capture_event();
388                    }
389                    _ => (),
390                }
391            }
392            Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
393                state.keyboard_modifiers = *modifiers;
394            }
395            _ => {}
396        }
397
398        let current_status = if state.is_dragging {
399            Status::Dragged
400        } else if cursor.is_over(layout.bounds()) {
401            Status::Hovered
402        } else {
403            Status::Active
404        };
405
406        if let Event::Window(window::Event::RedrawRequested(_now)) = event {
407            self.status = Some(current_status);
408        } else if self.status.is_some_and(|status| status != current_status) {
409            shell.request_redraw();
410        }
411    }
412
413    fn draw(
414        &self,
415        _tree: &Tree,
416        renderer: &mut Renderer,
417        theme: &Theme,
418        _style: &renderer::Style,
419        layout: Layout,
420        _cursor: mouse::Cursor,
421        _viewport: &Rectangle,
422    ) {
423        let bounds = layout.bounds();
424
425        let style = theme.style(&self.class, self.status.unwrap_or(Status::Active));
426
427        let (handle_width, handle_height, handle_border_radius) = match style.handle.shape {
428            HandleShape::Circle { radius } => (radius * 2.0, radius * 2.0, radius.into()),
429            HandleShape::Rectangle {
430                width,
431                border_radius,
432            } => (f32::from(width), bounds.width, border_radius),
433        };
434
435        let value = self.value.as_() as f32;
436        let (range_start, range_end) = {
437            let (start, end) = self.range.clone().into_inner();
438
439            (start.as_() as f32, end.as_() as f32)
440        };
441
442        let offset = if range_start >= range_end {
443            0.0
444        } else {
445            (bounds.height - handle_width) * (value - range_end) / (range_start - range_end)
446        };
447
448        let rail_x = bounds.x + bounds.width / 2.0;
449
450        renderer.fill_quad(
451            renderer::Quad {
452                bounds: Rectangle {
453                    x: rail_x - style.rail.width / 2.0,
454                    y: bounds.y,
455                    width: style.rail.width,
456                    height: offset + handle_width / 2.0,
457                },
458                border: style.rail.border,
459                ..renderer::Quad::default()
460            },
461            style.rail.backgrounds.1,
462        );
463
464        renderer.fill_quad(
465            renderer::Quad {
466                bounds: Rectangle {
467                    x: rail_x - style.rail.width / 2.0,
468                    y: bounds.y + offset + handle_width / 2.0,
469                    width: style.rail.width,
470                    height: bounds.height - offset - handle_width / 2.0,
471                },
472                border: style.rail.border,
473                ..renderer::Quad::default()
474            },
475            style.rail.backgrounds.0,
476        );
477
478        renderer.fill_quad(
479            renderer::Quad {
480                bounds: Rectangle {
481                    x: rail_x - handle_height / 2.0,
482                    y: bounds.y + offset,
483                    width: handle_height,
484                    height: handle_width,
485                },
486                border: Border {
487                    radius: handle_border_radius,
488                    width: style.handle.border_width,
489                    color: style.handle.border_color,
490                },
491                ..renderer::Quad::default()
492            },
493            style.handle.background,
494        );
495    }
496
497    fn mouse_interaction(
498        &self,
499        tree: &Tree,
500        layout: Layout,
501        cursor: mouse::Cursor,
502        _viewport: &Rectangle,
503        _renderer: &Renderer,
504    ) -> mouse::Interaction {
505        let state = tree.state.downcast_ref::<State>();
506
507        if state.is_dragging {
508            // FIXME: Fall back to `Pointer` on Windows
509            // See https://github.com/rust-windowing/winit/issues/1043
510            if cfg!(target_os = "windows") {
511                mouse::Interaction::Pointer
512            } else {
513                mouse::Interaction::Grabbing
514            }
515        } else if cursor.is_over(layout.bounds()) {
516            if cfg!(target_os = "windows") {
517                mouse::Interaction::Pointer
518            } else {
519                mouse::Interaction::Grab
520            }
521        } else {
522            mouse::Interaction::default()
523        }
524    }
525}
526
527#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
528struct State {
529    is_dragging: bool,
530    keyboard_modifiers: keyboard::Modifiers,
531}