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