Skip to main content

egui_pop_core/slider/
range.rs

1//! A range slider: a low and a high value on one bar (an ISO, date or
2//! focal length filter), with the gestures of [`Slider`](super::Slider).
3//!
4//! Each thumb is its own widget: it takes the focus (Tab goes from the
5//! low to the high one), steps with the keys and the wheel, opens the
6//! typed entry, and is an AccessKit slider named after the bar's label
7//! ("ISO, minimum", "ISO, maximum"). A press on the bar takes the
8//! nearer thumb: the half of the bar left of the point between the
9//! thumbs drives the low one, the rest the high one. The thumbs never
10//! cross. A double click resets both to the default.
11
12use std::ops::RangeInclusive;
13
14use egui::{Rect, Response, Sense, Ui, Widget, WidgetInfo, pos2, vec2};
15
16use super::{
17    Cause, Change, Drag, Hook, SliderOutput, Spec, Thumb, Verdict, access, decide, drag, gestures,
18    keep_auto_ids, keys_wheel_access, modifier_scale, open_typed_entry, paint_bar, paint_state,
19    spec_builders, state_of, typed_entry, typing_id, typing_text,
20};
21use crate::strings::{self, SLIDER_MAXIMUM, SLIDER_MINIMUM};
22
23/// Two values on one bar, `low <= high`.
24#[derive(Debug)]
25pub struct RangeSlider<'a> {
26    low: &'a mut f64,
27    high: &'a mut f64,
28    spec: Spec,
29    default: Option<(f64, f64)>,
30    hook: Option<Hook<'a>>,
31}
32
33impl<'a> RangeSlider<'a> {
34    /// A range slider spanning `soft`, which is also its hard range until
35    /// [`RangeSlider::hard`] widens it.
36    pub fn new(
37        low: &'a mut f64,
38        high: &'a mut f64,
39        label: &str,
40        soft: RangeInclusive<f64>,
41    ) -> Self {
42        Self {
43            low,
44            high,
45            spec: Spec::new(label, soft),
46            default: None,
47            hook: None,
48        }
49    }
50
51    spec_builders!();
52
53    /// What a double click goes back to.
54    pub fn default(mut self, low: f64, high: f64) -> Self {
55        self.default = Some((low.min(high), low.max(high)));
56        self
57    }
58
59    /// Sees every change of either thumb before it is written
60    /// ([`Change::thumb`] says which; see the slider module's "Hooks").
61    pub fn on_change(mut self, hook: impl FnMut(&Change) -> Verdict + 'a) -> Self {
62        self.hook = Some(Hook(Box::new(hook)));
63        self
64    }
65
66    /// Draws the range slider; says what changed.
67    pub fn show(self, ui: &mut Ui) -> SliderOutput {
68        if self.spec.state.is_disabled() {
69            return ui
70                .scope(|ui| {
71                    ui.disable();
72                    self.draw(ui)
73                })
74                .inner;
75        }
76        self.draw(ui)
77    }
78
79    fn draw(self, ui: &mut Ui) -> SliderOutput {
80        let RangeSlider {
81            low,
82            high,
83            spec,
84            default,
85            mut hook,
86        } = self;
87        if *low > *high {
88            std::mem::swap(low, high);
89        }
90        let height = ui.spacing().interact_size.y;
91        let width = ui.available_width().max(super::MIN_WIDTH);
92        let (_, bar) = ui.allocate_space(vec2(width, height));
93        let id = super::stable_id(ui, "egui_pop.range_slider", &spec.label);
94        let (low_rect, high_rect) = halves(bar, &spec, *low, *high);
95        let mut lo_r = ui.interact(low_rect, id.with("low"), Sense::click_and_drag());
96        let mut hi_r = ui.interact(high_rect, id.with("high"), Sense::click_and_drag());
97        let (before_lo, before_hi) = (*low, *high);
98        let mut changes = Vec::new();
99        let mut apply = |change: Change, value: &mut f64| -> bool {
100            match decide(&mut hook, change, &spec) {
101                Some(c) => {
102                    *value = c.to;
103                    changes.push(c);
104                    true
105                }
106                None => false,
107            }
108        };
109        let mut typing = false;
110        for thumb in [Thumb::Low, Thumb::High] {
111            let (response, value, bounds) = match thumb {
112                Thumb::Low => (&mut lo_r, &mut *low, (spec.soft.0, *high)),
113                _ => (&mut hi_r, &mut *high, (*low, spec.soft.1)),
114            };
115            let change = |from: f64, to: f64, cause: Cause, done: bool| Change {
116                thumb,
117                from,
118                to,
119                cause,
120                done,
121                delta: to - from,
122            };
123            // A typed value stays on its side of the other thumb.
124            let hard = match thumb {
125                Thumb::Low => (spec.hard.0, bounds.1),
126                _ => (bounds.0, spec.hard.1),
127            };
128            let tid = typing_id(response.id);
129            if let Some(text) = typing_text(ui.ctx(), tid) {
130                typing = true;
131                if let Some(end) = typed_entry(ui, bar, tid, text, &spec, *value) {
132                    if let Some(v) = end.value {
133                        let to = spec.settle(v, hard);
134                        if to != *value {
135                            apply(change(*value, to, Cause::Typed, true), value);
136                        }
137                    }
138                    if end.refocus {
139                        response.request_focus();
140                    }
141                }
142                continue;
143            }
144            keep_auto_ids(ui);
145            let g = gestures(ui.ctx());
146            let scale = modifier_scale(ui, &g);
147            match drag(ui, response, &spec, *value, bounds, scale, bar.width()) {
148                Drag::None => {}
149                Drag::Moved(v) => {
150                    let to = spec.settle(v, hard);
151                    if to != *value {
152                        apply(change(*value, to, Cause::Drag, false), value);
153                    }
154                }
155                Drag::Ended(start) => {
156                    if start != *value && !apply(change(start, *value, Cause::Drag, true), value) {
157                        *value = start;
158                        crate::binding::cancel_gesture(ui.ctx(), response.id);
159                    }
160                }
161                Drag::Cancelled(start) => {
162                    *value = start;
163                    crate::binding::cancel_gesture(ui.ctx(), response.id);
164                }
165            }
166            if response.clicked() {
167                // A click focuses; it never makes the value jump.
168                response.request_focus();
169            }
170            if let Some((v, cause)) =
171                keys_wheel_access(ui, response, &spec, *value, bounds, scale, &g)
172            {
173                let to = spec.settle(v, hard);
174                if to != *value {
175                    apply(change(*value, to, cause, true), value);
176                }
177            }
178            if response.has_focus()
179                && spec.state.is_editable()
180                && ui.input(|i| i.key_pressed(g.typed_entry))
181            {
182                open_typed_entry(ui, tid, spec.number(ui.ctx(), *value));
183            }
184        }
185        let g = gestures(ui.ctx());
186        if !typing
187            && g.reset_on_double_click
188            && (lo_r.double_clicked() || hi_r.double_clicked())
189            && let Some((dl, dh)) = default
190        {
191            for (thumb, value, to) in [(Thumb::Low, &mut *low, dl), (Thumb::High, &mut *high, dh)] {
192                if to != *value {
193                    let c = Change {
194                        thumb,
195                        from: *value,
196                        to,
197                        cause: Cause::Reset,
198                        done: true,
199                        delta: to - *value,
200                    };
201                    apply(c, value);
202                }
203            }
204        }
205        // A hook may redirect a thumb past the other one: keep the order.
206        if *low > *high {
207            std::mem::swap(low, high);
208        }
209        if !typing {
210            let text = spec.with_unit(
211                ui.ctx(),
212                &format!(
213                    "{} – {}",
214                    spec.number(ui.ctx(), *low),
215                    spec.number(ui.ctx(), *high)
216                ),
217            );
218            let past = *low < spec.soft.0 || *high > spec.soft.1;
219            paint_bar(ui, bar, &[&lo_r, &hi_r], &spec, &[*low, *high], &text, past);
220            paint_state(ui, bar, &spec);
221        }
222        let enabled = ui.is_enabled();
223        for (r, v, before, key) in [
224            (&mut lo_r, *low, before_lo, SLIDER_MINIMUM),
225            (&mut hi_r, *high, before_hi, SLIDER_MAXIMUM),
226        ] {
227            if v != before {
228                r.mark_changed();
229            }
230            let name = strings::tr_args(ui.ctx(), &key, &[("label", spec.label.as_str())]);
231            r.widget_info(|| WidgetInfo::slider(enabled, v, &name));
232        }
233        access(ui, lo_r.id, &spec, *low, (spec.soft.0, *high));
234        access(ui, hi_r.id, &spec, *high, (*low, spec.soft.1));
235        state_of(ui, &[&lo_r, &hi_r], &spec, "range");
236        let response = crate::field::hover(ui, &(lo_r | hi_r), &spec.state);
237        SliderOutput {
238            response,
239            changes,
240            quad: None,
241        }
242    }
243}
244
245impl Widget for RangeSlider<'_> {
246    fn ui(self, ui: &mut Ui) -> Response {
247        self.show(ui).response
248    }
249}
250
251/// The two halves of the bar each thumb answers in: split at the point
252/// between the thumbs, kept a thumb's reach from either end.
253fn halves(bar: Rect, spec: &Spec, low: f64, high: f64) -> (Rect, Rect) {
254    let x = |v: f64| bar.left() + bar.width() * spec.frac(v).clamp(0.0, 1.0) as f32;
255    let reach = (bar.width() / 4.0).min(bar.height());
256    let mid = ((x(low) + x(high)) / 2.0).clamp(bar.left() + reach, bar.right() - reach);
257    (
258        Rect::from_min_max(bar.min, pos2(mid, bar.bottom())),
259        Rect::from_min_max(pos2(mid, bar.top()), bar.max),
260    )
261}