Skip to main content

egui_pop_core/
slider.rs

1//! The slider family, in the manner of darktable's bauhaus sliders: the
2//! label and the value inside the bar, a soft range the bar spans and a
3//! hard range a typed value may reach, fine and coarse adjustment, reset
4//! on a double click, and a value typed with its unit or as an
5//! expression.
6//!
7//! - [`Slider`]: one value, linear or logarithmic ([`Curve`]), on a plain
8//!   or a gradient track ([`Gradient`]: hue, temperature), with an
9//!   optional quad button at its end (a colour picker, a toggle).
10//! - A **colour ramp** ([`Ramp`], [`Slider::ramp`], `Knob::ramp`): a
11//!   colour for the minimum and one for the maximum (and stops between),
12//!   the value drawn in the colour between them, blended in Oklab; the
13//!   colour at the value ([`RampMode::Value`]) or the whole ramp on the
14//!   track ([`RampMode::Track`]). The number and the thumb still say the
15//!   value; a high-contrast theme keeps the theme's own fill.
16//! - [`RangeSlider`]: two values on one bar, a low and a high thumb.
17//!
18//! Gestures:
19//!
20//! - **Drag** anywhere on the bar: the value follows the pointer's
21//!   motion over the soft range; a click never makes it jump. A drag is
22//!   one gesture (one undo step when bound to a store); Escape during it
23//!   puts the value back with no trace.
24//! - **Fine and coarse**: ten times finer and ten times coarser with
25//!   the pointer profile's modifiers (`gesture.value.fine` and
26//!   `gesture.value.coarse`; Ctrl (Cmd) finer and Shift coarser by
27//!   default), for drags, arrows and the wheel alike, unless the
28//!   profile gives the arrows their own (`value_keys`: Lightroom's Shift
29//!   drag is finer, its Shift with the arrows coarser).
30//! - **Keys** when focused: the arrows step, Page Up and Page Down take
31//!   coarse steps, Home and End go to the soft ends, Enter opens the
32//!   typed entry.
33//! - **Wheel**, as the pointer profile says
34//!   ([`crate::pointer`]): guarded (the default), it scrolls the panel
35//!   and steps a slider only when the slider has the focus or the step
36//!   modifiers are held over it (Alt by default), so scrolling past
37//!   sliders never changes a value; on values (darktable), it steps the
38//!   slider under the pointer, and the panel scrolls with the panel
39//!   modifiers (Ctrl+Alt).
40//! - **Typed entry**: a number or an expression ([`expr`]: `x * 2`,
41//!   `1,5 EV`); units after it are ignored; a value past the soft range
42//!   is kept up to the hard one. Enter or leaving the entry (a click
43//!   elsewhere, Tab, the focus taken by another widget) commits it;
44//!   Escape closes it with nothing. It takes the keyboard when it opens,
45//!   and after only when nobody holds the focus for a frame (a panel
46//!   redrawn), which does not commit it. While open it owns Escape and
47//!   Enter ([`crate::focus::text_input_owns_keyboard`]): key dispatchers
48//!   leave them to it.
49//! - **Double click**: back to the default; so does a click with the
50//!   profile's `gesture.value.reset` modifiers (`Ctrl+PrimaryClick` for
51//!   one), which no shipped profile binds.
52//! - **Right click** (or the context menu key): a menu, "Type a value"
53//!   (the typed entry) and "Reset" when there is a default
54//!   ([`Slider::menu`] turns it off; [`request_typed_entry`] opens the
55//!   entry from a host's own menu).
56//!
57//! The keys are [`Gestures`], data a profile may remap. The value text
58//! is written in the interface's language ([`crate::strings::number`]),
59//! and so is the space before its unit ([`crate::strings::quantity`]).
60//!
61//! **Hooks.** [`Slider::on_change`] sees every change before it is
62//! written, as a [`Change`] (which thumb, from, to, the [`Cause`], and
63//! whether the gesture is done), and answers a [`Verdict`]: go, veto or
64//! redirect to another value. A drag's frames come with `done: false`;
65//! its end comes once more, from the value before the drag to the last
66//! one, with `done: true`, and a veto then puts the value back. The
67//! application API turns the done changes into the `slider.change` step
68//! (`egui_pop_api::sliders`). [`Slider::show`] says what changed.
69//!
70//! **Accessibility.** The bar is an AccessKit slider named by its label,
71//! with its value, its value text (unit included), its range and step,
72//! and the increment, decrement and set-value actions.
73//!
74//! Owned: egui's `Slider` has no soft and hard range, no fine adjustment,
75//! no reset, no gradient and no range (see `docs/widgets.md`).
76//!
77//! ```
78//! use egui_pop_core::slider::{Gradient, RangeSlider, Slider};
79//!
80//! fn sliders(ui: &mut egui::Ui, ev: &mut f64, hue: &mut f64, iso: &mut (f64, f64)) {
81//!     ui.add(Slider::new(ev, "Exposure", -3.0..=4.0).hard(-18.0..=18.0).step(0.01).unit("EV").signed().default(0.0));
82//!     ui.add(Slider::new(hue, "Hue", 0.0..=360.0).unit("°").gradient(Gradient::hue()));
83//!     ui.add(RangeSlider::new(&mut iso.0, &mut iso.1, "ISO", 50.0..=25600.0).logarithmic().integer());
84//! }
85//! ```
86
87pub mod expr;
88mod gradient;
89pub(crate) mod ramp;
90mod range;
91
92pub use gradient::Gradient;
93pub use ramp::{Ramp, RampColor, RampMode, oklab_mix};
94pub use range::RangeSlider;
95
96use std::fmt;
97use std::ops::RangeInclusive;
98
99use egui::{
100    Color32, Id, Key, Modifiers, Rect, Response, Role, Sense, TextEdit, Ui, Vec2, Widget,
101    WidgetInfo, pos2, vec2,
102};
103use egui_pop_model::pointer::KnobDrag;
104use egui_pop_model::values::{Descriptor, Type};
105
106use crate::field::FieldState;
107use crate::icon::Icon;
108use crate::kit::{BoxStyle, Kit, KitCx, Part, State, Tone};
109use crate::state::Slot;
110use crate::theme::Tokens;
111
112/// The slider's gestures, as data so a profile can remap them: by
113/// default they follow the pointer profile ([`Gestures::from_map`]);
114/// [`set_gestures`] sets them outright. The invariants hold whatever
115/// the keys: a click never makes the value jump, a drag is relative and
116/// one gesture, a modifier scales the step and never changes what is
117/// adjusted.
118///
119/// <div class="warning">Experimental: may change in any release
120/// (docs/stability.md).</div>
121#[derive(Clone, Copy, Debug, PartialEq)]
122pub struct Gestures {
123    /// Held: ten times finer (drag, arrows, wheel); none: never.
124    pub fine: Modifiers,
125    /// Held: ten times coarser; none: never.
126    pub coarse: Modifiers,
127    /// Held with the arrow keys: ten times finer; none: never.
128    pub key_fine: Modifiers,
129    /// Held with the arrow keys: ten times coarser; none: never.
130    pub key_coarse: Modifiers,
131    /// Held over a slider without the focus: the wheel steps it (else
132    /// the wheel scrolls the panel); none: only with
133    /// [`Gestures::wheel_steps`] or the focus.
134    pub wheel: Modifiers,
135    /// The wheel steps the slider under the pointer, focused or not
136    /// (darktable); the panel scrolls with [`Gestures::panel`] held.
137    pub wheel_steps: bool,
138    /// Held: the wheel scrolls the panel, even over a slider; none:
139    /// never.
140    pub panel: Modifiers,
141    /// Opens the typed entry on a focused slider.
142    pub typed_entry: Key,
143    /// During a drag: puts the value back, no trace.
144    pub cancel: Key,
145    /// A double click resets to the default.
146    pub reset_on_double_click: bool,
147    /// Held with a primary click: back to the default
148    /// (`gesture.value.reset`, `Ctrl+PrimaryClick` for one); none: a
149    /// click never resets, as in every shipped profile.
150    pub reset_click: Modifiers,
151    /// How a drag turns a knob that does not say
152    /// ([`Knob::drag`](crate::knob::Knob::drag)).
153    pub knob_drag: KnobDrag,
154    /// A knob's drag hides the pointer and puts it back where the drag
155    /// started, for a knob that does not say
156    /// ([`Knob::hide_pointer`](crate::knob::Knob::hide_pointer)); off
157    /// in every shipped profile.
158    pub knob_hide_pointer: bool,
159}
160
161impl Default for Gestures {
162    /// The default pointer profile's.
163    fn default() -> Self {
164        Self::from_map(&crate::pointer::default_map())
165    }
166}
167
168impl Gestures {
169    /// What a pointer map says: the modifiers of `gesture.value.step`
170    /// on the wheel (a plain `Wheel` binding steps unfocused sliders),
171    /// of `gesture.value.panel` on the wheel, of `gesture.value.fine`
172    /// and `gesture.value.coarse` on a primary drag; the profile's
173    /// `value_keys` for the arrows (the drag's where it gives none); the
174    /// profile's option for the wheel over sliders.
175    pub fn from_map(map: &egui_pop_model::pointer::PointerMap) -> Self {
176        use egui_pop_model::keymap::{Button, Pointer};
177        use egui_pop_model::pointer::{SCOPE_VALUE, SliderWheel, gesture};
178        fn on(
179            map: &egui_pop_model::pointer::PointerMap,
180            command: &egui_pop_model::ids::CommandId,
181            pointer: Pointer,
182        ) -> Vec<Modifiers> {
183            map.chords(SCOPE_VALUE, command)
184                .filter(|c| c.pointer() == Some(pointer))
185                .map(crate::pointer::modifiers_of)
186                .collect()
187        }
188        let first = |mods: Vec<Modifiers>| mods.into_iter().find(|m| m.any());
189        let step = on(map, &gesture::VALUE_STEP, Pointer::Wheel);
190        let drag = Pointer::Drag(Button::Primary);
191        let fine = first(on(map, &gesture::VALUE_FINE, drag)).unwrap_or(Modifiers::NONE);
192        let coarse = first(on(map, &gesture::VALUE_COARSE, drag)).unwrap_or(Modifiers::NONE);
193        let keys = |text: &str, drag: Modifiers| {
194            if text.trim().is_empty() {
195                drag
196            } else {
197                crate::pointer::modifiers_from_text(text)
198            }
199        };
200        Self {
201            fine,
202            coarse,
203            key_fine: keys(&map.value_keys.fine, fine),
204            key_coarse: keys(&map.value_keys.coarse, coarse),
205            wheel: first(step.clone()).unwrap_or(Modifiers::NONE),
206            wheel_steps: map.options.slider_wheel == SliderWheel::Value
207                || step.iter().any(|m| !m.any()),
208            panel: first(on(map, &gesture::VALUE_PANEL, Pointer::Wheel)).unwrap_or(Modifiers::NONE),
209            typed_entry: Key::Enter,
210            cancel: Key::Escape,
211            reset_on_double_click: true,
212            reset_click: first(on(
213                map,
214                &gesture::VALUE_RESET,
215                Pointer::Click(Button::Primary),
216            ))
217            .unwrap_or(Modifiers::NONE),
218            knob_drag: map.options.knob_drag,
219            knob_hide_pointer: false,
220        }
221    }
222}
223
224const GESTURES: Slot<Gestures> = Slot::new("core.slider.gestures");
225/// A drag's position as a fraction of the bar, per slider.
226const DRAG_ACC: Slot<f64> = Slot::new("core.slider.drag_acc");
227/// The value a drag started from, per slider.
228const DRAG_START: Slot<f64> = Slot::new("core.slider.drag_start");
229/// The text of an open typed entry, per entry.
230const TYPING: Slot<String> = Slot::new("core.slider.typing");
231/// The typed entry takes the keyboard on its first frame, per entry.
232const TYPING_FOCUS: Slot<bool> = Slot::new("core.slider.typing_focus");
233/// The pass a typed entry without the focus was last held open.
234const TYPING_HELD: Slot<u64> = Slot::new("core.slider.typing_held");
235
236/// The sliders' gestures in a context: those set, else the pointer
237/// profile's ([`crate::pointer::map`]).
238pub fn gestures(ctx: &egui::Context) -> Gestures {
239    GESTURES
240        .get(ctx)
241        .unwrap_or_else(|| Gestures::from_map(&crate::pointer::map(ctx)))
242}
243
244/// Sets the sliders' gestures in a context, over the pointer profile's.
245pub fn set_gestures(ctx: &egui::Context, gestures: Gestures) {
246    GESTURES.set(ctx, gestures);
247}
248
249/// How the bar maps values to positions.
250#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
251pub enum Curve {
252    #[default]
253    Linear,
254    /// Equal ratios take equal lengths (ISO, a radius, a frequency).
255    /// Needs a soft range above zero; else the bar is linear.
256    Logarithmic,
257}
258
259/// What changed a value.
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub enum Cause {
262    Drag,
263    Key,
264    Wheel,
265    Typed,
266    /// A double click, back to the default.
267    Reset,
268    /// An assistive technology's action (increment, decrement, set).
269    Access,
270}
271
272impl Cause {
273    /// Its name in step arguments (`drag`).
274    pub fn name(self) -> &'static str {
275        match self {
276            Cause::Drag => "drag",
277            Cause::Key => "key",
278            Cause::Wheel => "wheel",
279            Cause::Typed => "typed",
280            Cause::Reset => "reset",
281            Cause::Access => "access",
282        }
283    }
284}
285
286/// Which value of a slider.
287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub enum Thumb {
289    /// A [`Slider`]'s only value.
290    Value,
291    /// A [`RangeSlider`]'s low end.
292    Low,
293    /// A [`RangeSlider`]'s high end.
294    High,
295}
296
297impl Thumb {
298    /// Its name in step arguments (`value`, `low`, `high`).
299    pub fn name(self) -> &'static str {
300        match self {
301            Thumb::Value => "value",
302            Thumb::Low => "low",
303            Thumb::High => "high",
304        }
305    }
306}
307
308/// A change a slider proposes, or made.
309#[derive(Clone, Copy, Debug, PartialEq)]
310pub struct Change {
311    pub thumb: Thumb,
312    pub from: f64,
313    pub to: f64,
314    pub cause: Cause,
315    /// The gesture is over: every change but a drag's frames. A drag's
316    /// end comes as one done change from the value before it.
317    pub done: bool,
318    /// How far the value moved: `to - from`, except on an endless knob
319    /// that wraps ([`Knob::endless`](crate::knob::Knob::endless)), where a
320    /// drag, a step or the wheel give the motion unwrapped (a turn past
321    /// the end counts in full, `to` being wrapped), for a host that maps
322    /// changes to nudges. A drag's end gives the whole drag's.
323    pub delta: f64,
324}
325
326/// What an [`on_change`](Slider::on_change) hook decides.
327#[derive(Clone, Copy, Debug, PartialEq)]
328pub enum Verdict {
329    /// Write the value proposed.
330    Go,
331    /// Write nothing (at a drag's end: back to the value before it).
332    Veto,
333    /// Write this value instead (kept to the hard range).
334    Redirect(f64),
335}
336
337/// A hook seeing each change before it is written.
338pub(crate) struct Hook<'a>(pub(crate) Box<dyn FnMut(&Change) -> Verdict + 'a>);
339
340impl fmt::Debug for Hook<'_> {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        f.write_str("Hook")
343    }
344}
345
346/// The change as the hook leaves it; `None` when vetoed, or when the
347/// field's state refuses changes (read-only, disabled).
348pub(crate) fn decide(hook: &mut Option<Hook<'_>>, change: Change, spec: &Spec) -> Option<Change> {
349    if !spec.state.is_editable() {
350        return None;
351    }
352    match hook.as_mut().map_or(Verdict::Go, |h| (h.0)(&change)) {
353        Verdict::Go => Some(change),
354        Verdict::Veto => None,
355        Verdict::Redirect(v) => {
356            let to = spec.settle(v, spec.hard);
357            Some(Change {
358                to,
359                delta: to - change.from,
360                ..change
361            })
362        }
363    }
364}
365
366/// What a slider did in a frame.
367#[derive(Debug)]
368pub struct SliderOutput {
369    /// The bar (for a range slider, both thumbs' responses merged);
370    /// `changed()` when a value changed.
371    pub response: Response,
372    /// The changes written this frame, after the hook.
373    pub changes: Vec<Change>,
374    /// The quad button, when there is one.
375    pub quad: Option<Response>,
376}
377
378impl SliderOutput {
379    /// Whether the quad button was clicked.
380    pub fn quad_clicked(&self) -> bool {
381        self.quad.as_ref().is_some_and(Response::clicked)
382    }
383}
384
385/// The square button at a slider's end.
386#[derive(Debug)]
387struct Quad<'a> {
388    icon: Icon,
389    label: String,
390    /// A toggle's state, flipped by a click.
391    on: Option<&'a mut bool>,
392}
393
394/// What both sliders share: the ranges, steps and how values are shown.
395#[derive(Clone, Debug)]
396pub(crate) struct Spec {
397    pub label: String,
398    pub soft: (f64, f64),
399    pub hard: (f64, f64),
400    pub step: f64,
401    pub coarse: f64,
402    pub unit: String,
403    pub precision: usize,
404    pub scale: f64,
405    pub integer: bool,
406    pub signed: bool,
407    pub curve: Curve,
408    pub gradient: Option<Gradient>,
409    /// The colour ramp ([`Ramp`]), over the gradient.
410    pub ramp: Option<Ramp>,
411    pub ramp_mode: RampMode,
412    /// The field's state ([`crate::field`]).
413    pub state: FieldState,
414}
415
416impl Spec {
417    pub(crate) fn new(label: &str, soft: RangeInclusive<f64>) -> Self {
418        let (lo, hi) = (*soft.start(), *soft.end());
419        let step = if hi > lo { (hi - lo) / 100.0 } else { 0.01 };
420        Self {
421            label: label.into(),
422            soft: (lo, hi),
423            hard: (lo, hi),
424            step,
425            coarse: step * 10.0,
426            unit: String::new(),
427            precision: precision_of(step),
428            scale: 1.0,
429            integer: false,
430            signed: false,
431            curve: Curve::Linear,
432            gradient: None,
433            ramp: None,
434            ramp_mode: RampMode::Value,
435            state: FieldState::default(),
436        }
437    }
438
439    fn from_descriptor(d: &Descriptor) -> Self {
440        let hard = d.hard.unwrap_or((0.0, 1.0));
441        let soft = d.soft.unwrap_or(hard);
442        let mut s = Self::new(&d.label, soft.0..=soft.1);
443        s.set_hard(hard.0..=hard.1);
444        s.set_step(d.step);
445        if d.coarse > 0.0 {
446            s.coarse = d.coarse;
447        }
448        s.precision = d.precision as usize;
449        s.scale = d.display_scale;
450        if let Some(u) = &d.unit {
451            s.unit = u.clone();
452        }
453        s.integer = d.ty == Type::Int;
454        s
455    }
456
457    pub(crate) fn set_hard(&mut self, hard: RangeInclusive<f64>) {
458        self.hard = (hard.start().min(self.soft.0), hard.end().max(self.soft.1));
459    }
460
461    pub(crate) fn set_step(&mut self, step: f64) {
462        if step > 0.0 {
463            self.step = step;
464            self.coarse = step * 10.0;
465            self.precision = precision_of(step);
466        }
467    }
468
469    fn log(&self) -> bool {
470        self.curve == Curve::Logarithmic && self.soft.0 > 0.0 && self.soft.1 > self.soft.0
471    }
472
473    /// Where a value sits on the bar: 0 at the soft start, 1 at its end
474    /// (outside for a value past the soft range).
475    pub(crate) fn frac(&self, v: f64) -> f64 {
476        let (lo, hi) = self.soft;
477        if self.log() {
478            (v.max(f64::MIN_POSITIVE).ln() - lo.ln()) / (hi.ln() - lo.ln())
479        } else if hi > lo {
480            (v - lo) / (hi - lo)
481        } else {
482            0.0
483        }
484    }
485
486    /// The value at a place on the bar.
487    pub(crate) fn value_at(&self, frac: f64) -> f64 {
488        let (lo, hi) = self.soft;
489        if self.log() {
490            (lo.ln() + frac * (hi.ln() - lo.ln())).exp()
491        } else {
492            lo + frac * (hi - lo)
493        }
494    }
495
496    /// `v` moved by `steps` steps, `scale` being the modifiers' factor
497    /// (0.1 fine, 10 coarse). A logarithmic bar steps by a hundredth of
498    /// its length.
499    pub(crate) fn stepped(&self, v: f64, steps: f64, scale: f64) -> f64 {
500        if steps == 0.0 {
501            return v;
502        }
503        if self.log() {
504            return self.value_at(self.frac(v) + steps * 0.01 * scale);
505        }
506        let step = self.step * scale.min(self.coarse / self.step);
507        v + steps * step
508    }
509
510    pub(crate) fn settle(&self, v: f64, (lo, hi): (f64, f64)) -> f64 {
511        let v = if self.integer { v.round() } else { v };
512        v.clamp(lo, hi)
513    }
514
515    /// The number shown, in the interface's language, without the unit.
516    pub(crate) fn number(&self, ctx: &egui::Context, v: f64) -> String {
517        let shown = v * self.scale;
518        let n = crate::strings::number(ctx, shown, self.precision);
519        let nonzero = n.chars().any(|c| c.is_ascii_digit() && c != '0');
520        match n.strip_prefix('-') {
521            // Never "-0.00".
522            Some(rest) if !nonzero => rest.to_string(),
523            _ if self.signed && nonzero && shown > 0.0 => format!("+{n}"),
524            _ => n,
525        }
526    }
527
528    /// The number with its unit.
529    pub(crate) fn text(&self, ctx: &egui::Context, v: f64) -> String {
530        self.with_unit(ctx, &self.number(ctx, v))
531    }
532
533    /// A number written with the unit after it, spaced as the
534    /// interface's language does ([`crate::strings::quantity`]).
535    pub(crate) fn with_unit(&self, ctx: &egui::Context, n: &str) -> String {
536        crate::strings::quantity(ctx, n, &self.unit)
537    }
538
539    /// A typed text's value (in the slider's units), `x` being `current`.
540    pub(crate) fn parse(&self, text: &str, current: f64) -> Option<f64> {
541        expr::eval(text, current * self.scale).map(|v| v / self.scale)
542    }
543}
544
545fn precision_of(step: f64) -> usize {
546    if step >= 1.0 || step <= 0.0 {
547        0
548    } else {
549        (-step.log10()).ceil() as usize
550    }
551}
552
553/// The builder methods both sliders share, over their `spec`.
554macro_rules! spec_builders {
555    () => {
556        /// The range a typed value may reach (it always holds the soft
557        /// range).
558        pub fn hard(mut self, hard: std::ops::RangeInclusive<f64>) -> Self {
559            self.spec.set_hard(hard);
560            self
561        }
562
563        /// The step of arrows and the wheel; also sets the precision.
564        pub fn step(mut self, step: f64) -> Self {
565            self.spec.set_step(step);
566            self
567        }
568
569        /// The coarse step (Shift, Page Up and Page Down).
570        pub fn coarse(mut self, coarse: f64) -> Self {
571            if coarse > 0.0 {
572                self.spec.coarse = coarse;
573            }
574            self
575        }
576
577        /// Shown after the value (`EV`, `%`).
578        pub fn unit(mut self, unit: &str) -> Self {
579            self.spec.unit = unit.into();
580            self
581        }
582
583        /// Digits after the decimal separator.
584        pub fn precision(mut self, decimals: usize) -> Self {
585            self.spec.precision = decimals;
586            self
587        }
588
589        /// Shown and typed as `value * scale` (a fraction as a
590        /// percentage: 100).
591        pub fn display_scale(mut self, scale: f64) -> Self {
592            if scale != 0.0 {
593                self.spec.scale = scale;
594            }
595            self
596        }
597
598        /// Whole numbers only.
599        pub fn integer(mut self) -> Self {
600            self.spec.integer = true;
601            self.spec.precision = 0;
602            self
603        }
604
605        /// A plus sign before positive values (`+1.50 EV`).
606        pub fn signed(mut self) -> Self {
607            self.spec.signed = true;
608            self
609        }
610
611        /// A logarithmic bar ([`Curve::Logarithmic`](crate::slider::Curve)).
612        pub fn logarithmic(mut self) -> Self {
613            self.spec.curve = $crate::slider::Curve::Logarithmic;
614            self
615        }
616
617        /// The track painted with a gradient (hue, temperature) along
618        /// the bar.
619        pub fn gradient(mut self, gradient: $crate::slider::Gradient) -> Self {
620            self.spec.gradient = Some(gradient);
621            self
622        }
623
624        /// The field's state, drawn and announced as every field's
625        /// ([`crate::field`]): a read-only slider takes the focus and
626        /// refuses changes, a disabled one is greyed and skipped by Tab,
627        /// with its reason as the tooltip.
628        pub fn state(mut self, state: $crate::field::FieldState) -> Self {
629            self.spec.state = state;
630            self
631        }
632    };
633}
634pub(crate) use spec_builders;
635
636/// The colour ramp's builders, shared by [`Slider`] and
637/// [`Knob`](crate::knob::Knob).
638macro_rules! ramp_builders {
639    () => {
640        /// A colour for the minimum and one for the maximum, the value
641        /// drawn in the colour between them, blended in Oklab over the
642        /// soft range ([`Ramp`](crate::slider::Ramp)): a token path
643        /// (`"danger"`) or a [`Color32`](egui::Color32) each.
644        /// Drawn in [`RampMode::Value`](crate::slider::RampMode) unless
645        /// [`ramp_track`](Self::ramp_track) says otherwise; a
646        /// high-contrast theme draws the theme's own fill instead.
647        pub fn ramp(
648            self,
649            min: impl Into<$crate::slider::RampColor>,
650            max: impl Into<$crate::slider::RampColor>,
651        ) -> Self {
652            self.ramp_with($crate::slider::Ramp::new(min, max))
653        }
654
655        /// A colour ramp through stops `(place, colour)`, places from 0
656        /// (the soft start) to 1 (its end): for hue-like scales.
657        pub fn ramp_stops(self, stops: &[(f32, $crate::slider::RampColor)]) -> Self {
658            self.ramp_with($crate::slider::Ramp::stops(stops))
659        }
660
661        /// A colour ramp built beforehand.
662        pub fn ramp_with(mut self, ramp: $crate::slider::Ramp) -> Self {
663            self.spec.ramp = Some(ramp);
664            self
665        }
666
667        /// The ramp across the whole track, the value marked on it by
668        /// the thumb or the pointer ([`RampMode::Track`](crate::slider::RampMode)),
669        /// so the scale reads before a touch; nothing without a ramp.
670        pub fn ramp_track(mut self) -> Self {
671            self.spec.ramp_mode = $crate::slider::RampMode::Track;
672            self
673        }
674    };
675}
676pub(crate) use ramp_builders;
677
678/// A slider over an `f64`.
679///
680/// Need (input): a slider over a number.
681#[derive(Debug)]
682pub struct Slider<'a> {
683    value: &'a mut f64,
684    spec: Spec,
685    default: Option<f64>,
686    hook: Option<Hook<'a>>,
687    quad: Option<Quad<'a>>,
688    vertical: bool,
689    size: Option<Vec2>,
690    compact: bool,
691    scrub: bool,
692    menu: bool,
693    travel: Option<f32>,
694}
695
696/// The least width a horizontal slider takes, whatever its room: below
697/// it the bar is clipped. In a narrow room the label goes first (into
698/// the tooltip), then the unit ([`Slider::compact`]).
699pub const MIN_WIDTH: f32 = 24.0;
700
701/// A vertical slider's length when no size is given.
702pub const VERTICAL_LENGTH: f32 = 160.0;
703
704/// Parses a typed number or expression ([`expr::eval`], with no current
705/// value): units after it are ignored, a comma is a point.
706pub fn parse_typed(text: &str) -> Option<f64> {
707    expr::eval(text, f64::NAN)
708}
709
710impl<'a> Slider<'a> {
711    /// A slider spanning `soft`, which is also its hard range until
712    /// [`Slider::hard`] widens it.
713    pub fn new(value: &'a mut f64, label: &str, soft: RangeInclusive<f64>) -> Self {
714        Self {
715            value,
716            spec: Spec::new(label, soft),
717            default: None,
718            hook: None,
719            quad: None,
720            vertical: false,
721            size: None,
722            compact: false,
723            scrub: false,
724            menu: true,
725            travel: None,
726        }
727    }
728
729    /// From a value descriptor: its label, ranges, steps, unit,
730    /// precision, display scale and default.
731    pub fn from_descriptor(value: &'a mut f64, d: &Descriptor) -> Self {
732        Self {
733            value,
734            spec: Spec::from_descriptor(d),
735            default: d.default.as_f64(),
736            hook: None,
737            quad: None,
738            vertical: false,
739            size: None,
740            compact: false,
741            scrub: false,
742            menu: true,
743            travel: None,
744        }
745    }
746
747    spec_builders!();
748    ramp_builders!();
749
750    /// What a double click goes back to.
751    pub fn default(mut self, default: f64) -> Self {
752        self.default = Some(default);
753        self
754    }
755
756    /// A vertical slider, as a mixer's fader: up is more. The same
757    /// gestures along the other axis (a drag up does what a drag right
758    /// does on a horizontal bar; Up and Right step up), the value at the
759    /// top, the label at the bottom, under the track. It has no quad
760    /// button.
761    pub fn vertical(mut self) -> Self {
762        self.vertical = true;
763        self
764    }
765
766    /// Its size, in points: the room it fills (a slot). By default a
767    /// horizontal slider takes the width available (at least
768    /// [`MIN_WIDTH`]) and a row's height; a vertical one is
769    /// [`VERTICAL_LENGTH`] high and a row and a half wide.
770    pub fn size(mut self, size: Vec2) -> Self {
771        self.size = Some(size);
772        self
773    }
774
775    /// The compact representation: the value alone, the label in the
776    /// tooltip (and still the bar's name for assistive technologies). A
777    /// slider too narrow for its label and value turns compact by
778    /// itself, and drops the unit when even the value does not fit.
779    pub fn compact(mut self) -> Self {
780        self.compact = true;
781        self
782    }
783
784    /// The scrub field: the label and the value in a plain field, with
785    /// no fill and no thumb, for a dense row (a HUD, a property sheet)
786    /// where the value matters more than where it sits in its range. The
787    /// slider's gestures, keys, typed entry, menu, history and
788    /// accessibility stay: a drag along the field scrubs the value over
789    /// the soft range, whatever the field's width, or at a set speed with
790    /// [`Slider::travel`]. Too narrow for its
791    /// label, it shows the value alone, as [`Slider::compact`] does.
792    /// Horizontal only: a vertical slider keeps its track.
793    ///
794    /// <div class="warning">Experimental: may change in any release
795    /// (docs/stability.md).</div>
796    pub fn scrub(mut self) -> Self {
797        self.scrub = true;
798        self
799    }
800
801    /// Points of drag over the soft range, whatever the bar's length: a
802    /// scrub field that moves at a set speed (a value's sensitivity, its
803    /// soft range over so many points) rather than across its width. By
804    /// default the bar's length; the fine and coarse modifiers still
805    /// scale it. As [`Knob::travel`](crate::knob::Knob::travel).
806    ///
807    /// <div class="warning">Experimental: may change in any release
808    /// (docs/stability.md).</div>
809    pub fn travel(mut self, points: f32) -> Self {
810        if points > 0.0 && points.is_finite() {
811            self.travel = Some(points);
812        }
813        self
814    }
815
816    /// Whether a right click (or the context menu key) opens the value's
817    /// menu: "Type a value", and "Reset" with a default. On by default;
818    /// off for a host that gives the slider a menu of its own (its
819    /// "Type a value" item calls [`request_typed_entry`]).
820    pub fn menu(mut self, on: bool) -> Self {
821        self.menu = on;
822        self
823    }
824
825    /// Sees every change before it is written (module docs, "Hooks").
826    pub fn on_change(mut self, hook: impl FnMut(&Change) -> Verdict + 'a) -> Self {
827        self.hook = Some(Hook(Box::new(hook)));
828        self
829    }
830
831    /// A quad button at the end of the bar (a colour picker): its click
832    /// is in [`SliderOutput::quad_clicked`]. `label` names it.
833    pub fn quad(mut self, icon: Icon, label: &str) -> Self {
834        self.quad = Some(Quad {
835            icon,
836            label: label.into(),
837            on: None,
838        });
839        self
840    }
841
842    /// A quad button toggling `on` (an effect on or off), lit when on.
843    pub fn quad_toggle(mut self, icon: Icon, label: &str, on: &'a mut bool) -> Self {
844        self.quad = Some(Quad {
845            icon,
846            label: label.into(),
847            on: Some(on),
848        });
849        self
850    }
851
852    /// Draws the slider; says what changed.
853    pub fn show(self, ui: &mut Ui) -> SliderOutput {
854        if self.spec.state.is_disabled() {
855            return ui
856                .scope(|ui| {
857                    ui.disable();
858                    self.draw(ui)
859                })
860                .inner;
861        }
862        self.draw(ui)
863    }
864
865    fn draw(self, ui: &mut Ui) -> SliderOutput {
866        let Slider {
867            value,
868            spec,
869            default,
870            mut hook,
871            quad,
872            vertical,
873            size,
874            compact,
875            scrub,
876            menu,
877            travel,
878        } = self;
879        let row_height = ui.spacing().interact_size.y;
880        let wanted = match (size, vertical) {
881            (Some(s), false) => vec2(s.x.max(MIN_WIDTH), s.y.max(1.0)),
882            (Some(s), true) => vec2(s.x.max(1.0), s.y.max(MIN_WIDTH)),
883            (None, false) => vec2(room(ui).max(MIN_WIDTH), row_height),
884            (None, true) => vec2(row_height * 1.5, VERTICAL_LENGTH),
885        };
886        let (_, row) = ui.allocate_space(wanted);
887        let id = stable_id(ui, "egui_pop.slider", &spec.label);
888        let quad = if vertical { None } else { quad };
889        let (bar, quad_rect) = split_quad(row, quad.is_some(), ui);
890        let mut response = ui.interact(bar, id, Sense::click_and_drag());
891        let quad = quad.map(|q| show_quad(ui, quad_rect, id, q));
892        let before = *value;
893        let mut changes = Vec::new();
894        let mut apply = |change: Change, value: &mut f64| -> bool {
895            match decide(&mut hook, change, &spec) {
896                Some(c) => {
897                    *value = c.to;
898                    changes.push(c);
899                    true
900                }
901                None => false,
902            }
903        };
904        let change = |from: f64, to: f64, cause: Cause, done: bool| Change {
905            thumb: Thumb::Value,
906            from,
907            to,
908            cause,
909            done,
910            delta: to - from,
911        };
912        let typing_id = typing_id(id);
913        if take_typed_request(ui.ctx(), id) && spec.state.is_editable() {
914            open_typed_entry(ui, typing_id, spec.number(ui.ctx(), *value));
915        }
916        let mut label_shown = true;
917        if let Some(text) = typing_text(ui.ctx(), typing_id) {
918            if let Some(end) = typed_entry(ui, bar, typing_id, text, &spec, *value) {
919                if let Some(v) = end.value {
920                    let to = spec.settle(v, spec.hard);
921                    if to != *value {
922                        apply(change(*value, to, Cause::Typed, true), value);
923                    }
924                }
925                if end.refocus {
926                    response.request_focus();
927                }
928            }
929        } else {
930            keep_auto_ids(ui);
931            let g = gestures(ui.ctx());
932            let scale = modifier_scale(ui, &g);
933            let along = if vertical {
934                Axis::Vertical(travel.unwrap_or(bar.height()))
935            } else {
936                Axis::Horizontal(travel.unwrap_or(bar.width()))
937            };
938            match drag_along(ui, &response, &spec, *value, spec.soft, scale, along) {
939                Drag::None => {}
940                Drag::Moved(v) => {
941                    let to = spec.settle(v, spec.hard);
942                    if to != *value {
943                        apply(change(*value, to, Cause::Drag, false), value);
944                    }
945                }
946                Drag::Ended(start) => {
947                    if start != *value && !apply(change(start, *value, Cause::Drag, true), value) {
948                        *value = start;
949                        crate::binding::cancel_gesture(ui.ctx(), response.id);
950                    }
951                }
952                Drag::Cancelled(start) => {
953                    *value = start;
954                    crate::binding::cancel_gesture(ui.ctx(), response.id);
955                }
956            }
957            if g.reset_on_double_click
958                && response.double_clicked()
959                && let Some(d) = default
960                && d != *value
961            {
962                apply(change(*value, d, Cause::Reset, true), value);
963            }
964            if reset_clicked(ui, &response, &g)
965                && let Some(d) = default
966                && d != *value
967            {
968                apply(change(*value, d, Cause::Reset, true), value);
969            }
970            if response.clicked() {
971                // A click focuses; it never makes the value jump.
972                response.request_focus();
973            }
974            if menu
975                && value_menu(&response, &spec, default.filter(|d| *d != *value).is_some())
976                && let Some(d) = default
977            {
978                apply(change(*value, d, Cause::Reset, true), value);
979            }
980            if let Some((v, cause)) =
981                keys_wheel_access(ui, &response, &spec, *value, spec.soft, scale, &g)
982            {
983                let to = spec.settle(v, spec.hard);
984                if to != *value {
985                    apply(change(*value, to, cause, true), value);
986                }
987            }
988            if response.has_focus()
989                && spec.state.is_editable()
990                && ui.input(|i| i.key_pressed(g.typed_entry))
991            {
992                open_typed_entry(ui, typing_id, spec.number(ui.ctx(), *value));
993            }
994            let text = spec.text(ui.ctx(), *value);
995            let past = *value < spec.soft.0 || *value > spec.soft.1;
996            label_shown = if vertical {
997                paint_vertical(ui, bar, &response, &spec, *value, past)
998            } else {
999                paint_bar_fitted(
1000                    ui,
1001                    bar,
1002                    &[&response],
1003                    &spec,
1004                    &[*value],
1005                    &text,
1006                    past,
1007                    Fit {
1008                        compact,
1009                        track: !scrub,
1010                    },
1011                )
1012            };
1013            if label_shown {
1014                paint_state(ui, bar, &spec);
1015            }
1016        }
1017        if *value != before {
1018            response.mark_changed();
1019        }
1020        let enabled = ui.is_enabled();
1021        let v = *value;
1022        response.widget_info(|| WidgetInfo::slider(enabled, v, &spec.label));
1023        access(ui, response.id, &spec, v, spec.soft);
1024        if vertical {
1025            ui.ctx().accesskit_node_builder(response.id, |node| {
1026                node.set_orientation(egui::accesskit::Orientation::Vertical);
1027            });
1028        }
1029        state_of(ui, &[&response], &spec, "slider");
1030        let mut response = crate::field::hover(ui, &response, &spec.state);
1031        if !label_shown {
1032            // Compact: the label is read in the tooltip.
1033            response = response.on_hover_text(&spec.label);
1034        }
1035        SliderOutput {
1036            response,
1037            changes,
1038            quad,
1039        }
1040    }
1041}
1042
1043impl Widget for Slider<'_> {
1044    fn ui(self, ui: &mut Ui) -> Response {
1045        self.show(ui).response
1046    }
1047}
1048
1049/// Asks the slider or knob whose response is `widget` to open its
1050/// typed entry, with its value, in its next pass: what the "Type a
1051/// value" item of its menu does, for a host that gives it a menu of its
1052/// own ([`Slider::menu`]).
1053pub fn request_typed_entry(ctx: &egui::Context, widget: Id) {
1054    TYPE_REQUEST.keyed(widget).set(ctx, true);
1055    ctx.request_repaint();
1056}
1057
1058/// A typed entry asked for, per widget ([`request_typed_entry`]).
1059const TYPE_REQUEST: Slot<bool> = Slot::new("core.slider.type_request");
1060
1061/// Whether a typed entry was asked for `widget`; the request is taken.
1062pub(crate) fn take_typed_request(ctx: &egui::Context, widget: Id) -> bool {
1063    let slot = TYPE_REQUEST.keyed(widget);
1064    let asked = slot.get(ctx).unwrap_or(false);
1065    if asked {
1066        slot.remove(ctx);
1067    }
1068    asked
1069}
1070
1071/// Whether this pass's click is the profile's reset click
1072/// ([`Gestures::reset_click`]).
1073pub(crate) fn reset_clicked(ui: &Ui, response: &Response, g: &Gestures) -> bool {
1074    g.reset_click.any()
1075        && response.clicked()
1076        && ui.input(|i| i.modifiers.matches_logically(g.reset_click))
1077}
1078
1079/// A value's menu, opened by a right click or the context menu key:
1080/// "Type a value" (asks the typed entry, [`request_typed_entry`]) and,
1081/// with `reset`, "Reset". Whether "Reset" was chosen.
1082pub(crate) fn value_menu(response: &Response, spec: &Spec, reset: bool) -> bool {
1083    let editable = spec.state.is_editable();
1084    let mut chosen = false;
1085    crate::pointer::claim::context_menu(response, |ui| {
1086        let ctx = ui.ctx().clone();
1087        if ui
1088            .add_enabled(
1089                editable,
1090                egui::Button::new(crate::strings::tr(&ctx, &crate::strings::SLIDER_TYPE_VALUE)),
1091            )
1092            .clicked()
1093        {
1094            request_typed_entry(&ctx, response.id);
1095            ui.close();
1096        }
1097        if reset
1098            && ui
1099                .add_enabled(
1100                    editable,
1101                    egui::Button::new(crate::strings::tr(&ctx, &crate::strings::RESET)),
1102                )
1103                .clicked()
1104        {
1105            chosen = true;
1106            ui.close();
1107        }
1108    });
1109    chosen
1110}
1111
1112/// The text of a slider's open typed entry (`typing_id`'s).
1113pub(crate) fn typing_text(ctx: &egui::Context, typing_id: Id) -> Option<String> {
1114    TYPING.keyed(typing_id).get(ctx)
1115}
1116
1117/// The id of a slider's typed entry (for tests).
1118pub fn typing_id(slider: Id) -> Id {
1119    slider.with("egui_pop_slider_typing")
1120}
1121
1122/// The width a horizontal slider takes when no size is given: what is
1123/// left in its row, but no more than shows of it. A row may be wider
1124/// than the panel drawing it (a panel's edge cuts it): there, the bar
1125/// ends at the edge, so its value is laid out where it can be seen.
1126fn room(ui: &Ui) -> f32 {
1127    let row = ui.available_rect_before_wrap();
1128    let shown = row.intersect(ui.clip_rect()).width();
1129    if shown >= MIN_WIDTH {
1130        row.width().min(shown)
1131    } else {
1132        row.width()
1133    }
1134}
1135
1136/// The bar and, when there is a quad, the square at its end.
1137fn split_quad(row: Rect, quad: bool, ui: &Ui) -> (Rect, Rect) {
1138    if !quad {
1139        return (row, Rect::NOTHING);
1140    }
1141    let side = row.height();
1142    let gap = ui.spacing().item_spacing.x.min(4.0);
1143    let bar = Rect::from_min_max(row.min, pos2(row.right() - side - gap, row.bottom()));
1144    let quad = Rect::from_min_max(pos2(row.right() - side, row.top()), row.max);
1145    (bar, quad)
1146}
1147
1148fn show_quad(ui: &mut Ui, rect: Rect, id: Id, mut quad: Quad<'_>) -> Response {
1149    let mut r = ui.interact(rect, id.with("egui_pop_slider_quad"), Sense::click());
1150    if r.clicked()
1151        && let Some(on) = quad.on.as_deref_mut()
1152    {
1153        *on = !*on;
1154        r.mark_changed();
1155    }
1156    let enabled = ui.is_enabled();
1157    let state = quad.on.as_deref().copied();
1158    let label = quad.label.as_str();
1159    match state {
1160        Some(s) => r.widget_info(|| WidgetInfo::selected(Role::CheckBox, enabled, s, label)),
1161        None => r.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, label)),
1162    }
1163    if ui.is_rect_visible(rect) {
1164        let kit = Kit::of(ui.ctx());
1165        let toggle = &kit.slider_toggle;
1166        let part = Part {
1167            rect,
1168            room: rect,
1169            state: State::from_response(&r).with(State::SELECTED, state == Some(true)),
1170            label: None,
1171        };
1172        let painter = clipped(ui, rect, toggle.style(part.state));
1173        let cx = KitCx {
1174            painter: &painter,
1175            ppp: ui.ctx().pixels_per_point(),
1176        };
1177        toggle.paint(&cx, &part);
1178        quad.icon.paint(
1179            &painter,
1180            rect.shrink(rect.height() * 0.2),
1181            toggle.style(part.state).text,
1182        );
1183    }
1184    r
1185}
1186
1187/// A painter clipped to a part, and to its focus ring when the ring
1188/// goes outside it.
1189fn clipped(ui: &Ui, rect: Rect, b: &BoxStyle) -> egui::Painter {
1190    let ring = if b.ring_width > 0.0 {
1191        (b.ring_offset + b.ring_width).max(0.0)
1192    } else {
1193        0.0
1194    };
1195    ui.painter_at(rect.expand(ring))
1196}
1197
1198/// The modifiers' factor on a step: 0.1 fine, 10 coarse, else 1.
1199pub(crate) fn modifier_scale(ui: &Ui, g: &Gestures) -> f64 {
1200    scale_of(ui, g.fine, g.coarse)
1201}
1202
1203/// The arrow keys' factor on a step, from their own modifiers.
1204fn key_scale(ui: &Ui, g: &Gestures) -> f64 {
1205    scale_of(ui, g.key_fine, g.key_coarse)
1206}
1207
1208fn scale_of(ui: &Ui, fine: Modifiers, coarse: Modifiers) -> f64 {
1209    let mods = ui.input(|i| i.modifiers);
1210    let held = |m: Modifiers| m.any() && mods.matches_logically(m);
1211    if held(fine) {
1212        0.1
1213    } else if held(coarse) {
1214        10.0
1215    } else {
1216        1.0
1217    }
1218}
1219
1220/// A drag's effect in a frame.
1221pub(crate) enum Drag {
1222    None,
1223    /// The value the pointer's motion leads to.
1224    Moved(f64),
1225    /// The drag ended; the value before it.
1226    Ended(f64),
1227    /// The cancel key ended it; the value before it.
1228    Cancelled(f64),
1229}
1230
1231/// The axis a bar lies along, and its length in points.
1232#[derive(Clone, Copy, Debug)]
1233pub(crate) enum Axis {
1234    Horizontal(f32),
1235    /// Up is more.
1236    Vertical(f32),
1237}
1238
1239/// A relative drag on `response`: the pointer's motion over `width`
1240/// (the bar's) moves the value over the soft range, within `bounds` (unless
1241/// already past them). The motion accumulates exactly, in bar
1242/// positions; only what is written is rounded.
1243pub(crate) fn drag(
1244    ui: &Ui,
1245    response: &Response,
1246    spec: &Spec,
1247    value: f64,
1248    bounds: (f64, f64),
1249    scale: f64,
1250    width: f32,
1251) -> Drag {
1252    drag_along(
1253        ui,
1254        response,
1255        spec,
1256        value,
1257        bounds,
1258        scale,
1259        Axis::Horizontal(width),
1260    )
1261}
1262
1263/// [`drag`] along either axis: up is more on a vertical bar.
1264pub(crate) fn drag_along(
1265    ui: &Ui,
1266    response: &Response,
1267    spec: &Spec,
1268    value: f64,
1269    bounds: (f64, f64),
1270    scale: f64,
1271    axis: Axis,
1272) -> Drag {
1273    let acc = DRAG_ACC.keyed(response.id);
1274    let start = DRAG_START.keyed(response.id);
1275    crate::pointer::drag_cursor(response, crate::pointer::DragKind::Value);
1276    if response.drag_started() {
1277        acc.set(ui.ctx(), spec.frac(value));
1278        start.set(ui.ctx(), value);
1279    }
1280    if response.drag_stopped() {
1281        let start = start.get(ui.ctx()).unwrap_or(value);
1282        // egui ends a drag on the cancel key.
1283        let cancel = gestures(ui.ctx()).cancel;
1284        return if crate::focus::cancel_pressed(ui.ctx(), cancel) {
1285            Drag::Cancelled(start)
1286        } else {
1287            Drag::Ended(start)
1288        };
1289    }
1290    if response.dragged() {
1291        let d = response.drag_delta();
1292        let (moved, length) = match axis {
1293            Axis::Horizontal(w) => (d.x, w),
1294            Axis::Vertical(h) => (-d.y, h),
1295        };
1296        let delta = f64::from(moved) / f64::from(length.max(1.0)) * scale;
1297        if delta != 0.0 {
1298            let slot = acc;
1299            let acc = slot.get(ui.ctx()).unwrap_or_else(|| spec.frac(value));
1300            let (lo, hi) = (spec.frac(bounds.0), spec.frac(bounds.1));
1301            let next = (acc + delta).clamp(lo.min(acc), hi.max(acc));
1302            slot.set(ui.ctx(), next);
1303            return Drag::Moved(spec.value_at(next));
1304        }
1305    }
1306    Drag::None
1307}
1308
1309/// The keys a focused slider, range slider or knob reads itself.
1310const READS: [Key; 8] = [
1311    Key::ArrowLeft,
1312    Key::ArrowRight,
1313    Key::ArrowUp,
1314    Key::ArrowDown,
1315    Key::PageUp,
1316    Key::PageDown,
1317    Key::Home,
1318    Key::End,
1319];
1320
1321/// The keys (when focused), the wheel (when focused or with its
1322/// modifier) and assistive actions: the value they lead to, kept in
1323/// `bounds` unless already past them, and what moved it.
1324pub(crate) fn keys_wheel_access(
1325    ui: &mut Ui,
1326    response: &Response,
1327    spec: &Spec,
1328    value: f64,
1329    bounds: (f64, f64),
1330    scale: f64,
1331    g: &Gestures,
1332) -> Option<(f64, Cause)> {
1333    let (lo, hi) = bounds;
1334    let mut v = value;
1335    let mut cause = None;
1336    if response.has_focus() {
1337        // The arrows step the value, they do not move the keyboard (egui's
1338        // arrow navigation), and the key dispatcher leaves them, Page Up,
1339        // Page Down, Home and End to the widget before a global binding.
1340        ui.memory_mut(|m| {
1341            m.set_focus_lock_filter(
1342                response.id,
1343                egui::EventFilter {
1344                    horizontal_arrows: true,
1345                    vertical_arrows: true,
1346                    ..Default::default()
1347                },
1348            );
1349        });
1350        crate::focus::reads_keys(ui.ctx(), response.id, &READS);
1351        let key_scale = key_scale(ui, g);
1352        ui.input(|i| {
1353            let count = |keys: &[Key]| keys.iter().map(|k| i.num_presses(*k) as f64).sum::<f64>();
1354            let steps =
1355                count(&[Key::ArrowRight, Key::ArrowUp]) - count(&[Key::ArrowLeft, Key::ArrowDown]);
1356            let pages = count(&[Key::PageUp]) - count(&[Key::PageDown]);
1357            if steps != 0.0 || pages != 0.0 {
1358                v = spec.stepped(v, steps, key_scale);
1359                v = spec.stepped(v, pages, 10.0);
1360                cause = Some(Cause::Key);
1361            }
1362            if i.key_pressed(Key::Home) {
1363                v = lo;
1364                cause = Some(Cause::Key);
1365            }
1366            if i.key_pressed(Key::End) {
1367                v = hi;
1368                cause = Some(Cause::Key);
1369            }
1370        });
1371    }
1372    // The wheel: the panel scrolls, unless the slider has the focus,
1373    // the wheel modifier is held over it or the profile has the wheel
1374    // step values; then each notch steps it, a touchpad's stream steps
1375    // it once a line's length ([`wheel_steps`]), and the panel does not
1376    // scroll. The panel modifiers always leave the wheel to the panel.
1377    let mods = ui.input(|i| i.modifiers);
1378    let wheel_held = g.wheel.any() && mods.matches_logically(g.wheel);
1379    let panel_held = g.panel.any() && mods.matches_logically(g.panel);
1380    if response.hovered() && !panel_held && (response.has_focus() || wheel_held || g.wheel_steps) {
1381        let steps = wheel_steps(ui, response.id);
1382        if steps != 0.0 {
1383            v = spec.stepped(v, steps, scale);
1384            cause = Some(Cause::Wheel);
1385        }
1386        // egui spreads a notch's scroll over the next frames: what is
1387        // left of it is eaten too, every frame the slider holds the
1388        // wheel, so the panel never drifts after the step.
1389        ui.input_mut(|i| {
1390            i.smooth_scroll_delta = egui::Vec2::ZERO;
1391            i.events
1392                .retain(|e| !matches!(e, egui::Event::MouseWheel { .. }));
1393        });
1394    }
1395    // Assistive technologies: increment, decrement, set a value.
1396    let id = response.id;
1397    let (inc, dec, set) = ui.input(|i| {
1398        use egui::accesskit::{Action, ActionData};
1399        let set = i
1400            .accesskit_action_requests(id, Action::SetValue)
1401            .filter_map(|r| match r.data {
1402                Some(ActionData::NumericValue(n)) => Some(n),
1403                _ => None,
1404            })
1405            .last();
1406        (
1407            i.num_accesskit_action_requests(id, Action::Increment),
1408            i.num_accesskit_action_requests(id, Action::Decrement),
1409            set,
1410        )
1411    });
1412    if inc + dec > 0 {
1413        v = spec.stepped(v, inc as f64 - dec as f64, 1.0);
1414        cause = Some(Cause::Access);
1415    }
1416    // Keys, the wheel and steps stay in the bounds, unless already past
1417    // them; a value set is only kept to the hard range.
1418    if cause.is_some() {
1419        v = v.clamp(lo.min(value), hi.max(value));
1420    }
1421    if let Some(n) = set {
1422        v = n;
1423        cause = Some(Cause::Access);
1424    }
1425    cause.map(|c| (v, c))
1426}
1427
1428/// A touchpad's scroll not yet a whole step, per widget, and when it
1429/// last came.
1430const WHEEL_REST: Slot<(f64, f64)> = Slot::new("core.slider.wheel_rest");
1431
1432/// A pause in a touchpad's stream longer than this, in seconds, drops
1433/// what was left of a step.
1434const WHEEL_REST_PAUSE: f64 = 0.4;
1435
1436/// This pass's wheel input over the widget `id`, in steps: one a notch
1437/// of a mouse wheel, and a touchpad's points (as the wheel device
1438/// setting tells them apart) summed over the frames, a step a line's
1439/// length (`line_scroll_speed`), what is left kept for the next pass.
1440pub(crate) fn wheel_steps(ui: &Ui, id: Id) -> f64 {
1441    use egui_pop_model::keymap::Pointer;
1442    let device = crate::pointer::map(ui.ctx()).wheel_device;
1443    let line = f64::from(
1444        ui.ctx()
1445            .options(|o| o.input_options.line_scroll_speed)
1446            .max(1.0),
1447    );
1448    let (notches, points, now) = ui.input(|i| {
1449        let mut notches = 0.0;
1450        let mut points = 0.0;
1451        for e in &i.events {
1452            if let egui::Event::MouseWheel { unit, delta, .. } = e {
1453                let d = delta.y + delta.x;
1454                match crate::pointer::wheel_pointer(*unit, device) {
1455                    Pointer::Scroll => {
1456                        points += f64::from(match unit {
1457                            egui::MouseWheelUnit::Point => d,
1458                            egui::MouseWheelUnit::Line => d * line as f32,
1459                            egui::MouseWheelUnit::Page => d * i.content_rect().height(),
1460                        });
1461                    }
1462                    _ => notches += f64::from(d.signum()),
1463                }
1464            }
1465        }
1466        (notches, points, i.time)
1467    });
1468    if points == 0.0 {
1469        return notches;
1470    }
1471    let slot = WHEEL_REST.keyed(id);
1472    let rest = match slot.get(ui.ctx()) {
1473        Some((rest, at)) if now - at <= WHEEL_REST_PAUSE => rest,
1474        _ => 0.0,
1475    };
1476    let total = rest + points / line;
1477    let whole = total.trunc();
1478    slot.set(ui.ctx(), (total - whole, now));
1479    notches + whole
1480}
1481
1482/// Opens the typed entry with `text`. The entry takes the keyboard on
1483/// the frame it first shows, and only then: a click elsewhere keeps it.
1484pub(crate) fn open_typed_entry(ui: &Ui, typing_id: Id, text: String) {
1485    TYPING.keyed(typing_id).set(ui.ctx(), text);
1486    TYPING_FOCUS.keyed(typing_id).set(ui.ctx(), true);
1487    ui.ctx().request_repaint();
1488}
1489
1490/// The id a value widget (a slider, a range slider, a knob, a scrub
1491/// field) senses under: keyed by `kind` and its label in `ui`'s id, not
1492/// egui's automatic id. The automatic id follows how many widgets came
1493/// before in every enclosing `Ui`: a widget appearing before it while it
1494/// is dragged (a "modified" mark, a reset button shown once the value
1495/// moves) would give it another id, and egui would end its drag. The
1496/// space it allocates still takes its automatic id, so the widgets after
1497/// it keep theirs. A second widget of the same kind and label in the same
1498/// `Ui` in a pass takes the next number, so two never share an id.
1499pub(crate) fn stable_id(ui: &Ui, kind: &'static str, label: &str) -> Id {
1500    let base = ui.make_persistent_id((kind, label));
1501    let ctx = ui.ctx();
1502    let viewport = ctx.viewport_id();
1503    let pass = ctx.cumulative_pass_nr_for(viewport);
1504    let n = ctx.data_mut(|d| {
1505        let seen =
1506            d.get_temp_mut_or_default::<StableIds>(Id::unique(("egui_pop.stable_ids", viewport)));
1507        if seen.pass != pass {
1508            seen.pass = pass;
1509            seen.taken.clear();
1510        }
1511        let n = seen.taken.entry(base).or_insert(0);
1512        *n += 1;
1513        *n - 1
1514    });
1515    if n == 0 { base } else { base.with(n) }
1516}
1517
1518/// The ids [`stable_id`] gave in a pass, and how many times each.
1519#[derive(Clone, Default)]
1520struct StableIds {
1521    pass: u64,
1522    taken: std::collections::HashMap<Id, u32>,
1523}
1524
1525/// Takes the auto id an open typed entry takes, so the widgets after a
1526/// slider keep their ids whether its entry is open or not: a click on
1527/// one of them while the entry is open must still find it on the next
1528/// frame (its focus would otherwise go to an id gone with the entry).
1529pub(crate) fn keep_auto_ids(ui: &mut Ui) {
1530    ui.skip_ahead_auto_ids(1);
1531}
1532
1533/// How a typed entry closed.
1534pub(crate) struct TypedEnd {
1535    /// The value typed (`None` when cancelled or not a value).
1536    pub value: Option<f64>,
1537    /// Closed by Enter: the keyboard goes back to the slider. Closed by
1538    /// leaving it (a click elsewhere, Tab), the keyboard stays where it
1539    /// went.
1540    pub refocus: bool,
1541}
1542
1543/// The typed entry over the bar, open until it closes: Enter or leaving
1544/// it commits the value typed, Escape closes it with nothing. While open
1545/// it claims the keyboard ([`crate::focus::claim_keyboard`]), so a key
1546/// dispatcher leaves Escape and Enter to it.
1547pub(crate) fn typed_entry(
1548    ui: &mut Ui,
1549    bar: Rect,
1550    typing_id: Id,
1551    mut text: String,
1552    spec: &Spec,
1553    current: f64,
1554) -> Option<TypedEnd> {
1555    // Placed over the bar without moving the cursor; it takes one auto
1556    // id, which a slider without its entry skips (`keep_auto_ids`).
1557    let edit = ui
1558        .place(
1559            bar,
1560            TextEdit::singleline(&mut text)
1561                .id(typing_id.with("edit"))
1562                .align(egui::Align2::CENTER_TOP),
1563        )
1564        .accessible_name(crate::strings::tr_args(
1565            ui.ctx(),
1566            &crate::strings::SLIDER_ENTRY,
1567            &[("label", spec.label.as_str())],
1568        ));
1569    if TYPING_FOCUS.keyed(typing_id).remove(ui.ctx()).is_some() {
1570        edit.request_focus();
1571    }
1572    // Escape and Enter are the entry's: read as pressed even when a host
1573    // took them before the entry was drawn, or when the focus plugin
1574    // swallowed Escape on its way out of the field.
1575    let (cancel, enter) = ui.input(|i| (pressed(i, Key::Escape), pressed(i, Key::Enter)));
1576    let cancel = cancel || crate::focus::escape_left(ui.ctx(), edit.id);
1577    if !cancel && !enter && (edit.has_focus() || held(ui, edit.id, typing_id)) {
1578        // Open: key dispatchers leave Escape and Enter to it.
1579        crate::focus::claim_keyboard(ui.ctx(), edit.id);
1580        TYPING.keyed(typing_id).set(ui.ctx(), text);
1581        return None;
1582    }
1583    TYPING_HELD.keyed(typing_id).remove(ui.ctx());
1584    TYPING.keyed(typing_id).remove(ui.ctx());
1585    if cancel || enter {
1586        // Spent here: nothing drawn after the entry acts on them.
1587        ui.input_mut(|i| {
1588            i.consume_key(Modifiers::NONE, Key::Escape);
1589            i.consume_key(Modifiers::NONE, Key::Enter);
1590        });
1591    }
1592    Some(TypedEnd {
1593        value: if cancel {
1594            None
1595        } else {
1596            spec.parse(&text, current)
1597        },
1598        refocus: enter && !cancel,
1599    })
1600}
1601
1602/// Whether an entry without the focus stays open: only when nobody took
1603/// the focus, which a panel redrawn for another writer's change can
1604/// cause for one frame (the focused field not drawn on a pass drops the
1605/// focus). The entry then takes the focus back and waits one frame; a
1606/// real blur commits it: a press or a click elsewhere, Tab, or another
1607/// widget holding the focus, or the focus still gone on the next frame.
1608fn held(ui: &Ui, edit: Id, typing_id: Id) -> bool {
1609    let moved = ui
1610        .input(|i| i.pointer.any_pressed() || i.pointer.any_released() || i.key_pressed(Key::Tab));
1611    let elsewhere = ui.memory(|m| m.focused()).is_some_and(|f| f != edit);
1612    let key = TYPING_HELD.keyed(typing_id);
1613    let now = ui.ctx().cumulative_pass_nr();
1614    let held_last = key.get(ui.ctx()).is_some_and(|p| p + 1 == now);
1615    if moved || elsewhere || held_last {
1616        return false;
1617    }
1618    key.set(ui.ctx(), now);
1619    ui.memory_mut(|m| m.request_focus(edit));
1620    ui.ctx().request_repaint();
1621    true
1622}
1623
1624/// Whether `key` was pressed this pass, in the events left or in the
1625/// input as it came (a host may have consumed it).
1626fn pressed(i: &egui::InputState, key: Key) -> bool {
1627    i.key_pressed(key)
1628        || i.raw
1629            .events
1630            .iter()
1631            .any(|e| matches!(e, egui::Event::Key { key: k, pressed: true, .. } if *k == key))
1632}
1633
1634/// The bar, drawn by the kit: the track (`slider`), the fill
1635/// (`slider-fill`, or the gradient), the thumbs (`slider-thumb`), the
1636/// label and the value inside (`slider-value`, in the `warning` tone
1637/// past the soft range). A range's fill runs between its thumbs.
1638pub(crate) fn paint_bar(
1639    ui: &Ui,
1640    rect: Rect,
1641    responses: &[&Response],
1642    spec: &Spec,
1643    thumbs: &[f64],
1644    text: &str,
1645    past: bool,
1646) {
1647    paint_bar_fitted(
1648        ui,
1649        rect,
1650        responses,
1651        spec,
1652        thumbs,
1653        text,
1654        past,
1655        Fit::default(),
1656    );
1657}
1658
1659/// How [`paint_bar_fitted`] fits the bar: `compact`, the value alone;
1660/// without `track`, no fill and no thumb (the scrub field).
1661#[derive(Clone, Copy, Debug)]
1662pub(crate) struct Fit {
1663    pub compact: bool,
1664    pub track: bool,
1665}
1666
1667impl Default for Fit {
1668    fn default() -> Self {
1669        Fit {
1670            compact: false,
1671            track: true,
1672        }
1673    }
1674}
1675
1676/// [`paint_bar`] fitted to its width: the label and the value when both
1677/// fit (and not `fit.compact`), else the value alone, without its unit
1678/// when even that does not fit; the fill and the thumbs unless the bar
1679/// has no track (`fit.track`). Says whether the label shows.
1680#[allow(
1681    clippy::too_many_arguments,
1682    reason = "paint_bar's arguments and how it fits"
1683)]
1684pub(crate) fn paint_bar_fitted(
1685    ui: &Ui,
1686    rect: Rect,
1687    responses: &[&Response],
1688    spec: &Spec,
1689    thumbs: &[f64],
1690    text: &str,
1691    past: bool,
1692    fit: Fit,
1693) -> bool {
1694    let Fit { compact, track } = fit;
1695    let kit = Kit::of(ui.ctx());
1696    let font = egui::TextStyle::Button.resolve(ui.style());
1697    let pad = kit.slider.data.padding_x.max(0.0);
1698    let measure = |t: &str| {
1699        ui.painter()
1700            .layout_no_wrap(t.to_owned(), font.clone(), Color32::PLACEHOLDER)
1701            .size()
1702            .x
1703    };
1704    // The value is measured as it is drawn: in the numbers' font
1705    // (`font.numeric`), wider than the label's.
1706    let galley =
1707        |t: &str| crate::fonts::number_galley(ui.ctx(), t, font.size, Color32::PLACEHOLDER);
1708    let value_pad = kit.slider_value.data.padding_x.max(0.0);
1709    let mut value = galley(text);
1710    let value_w = value.size().x;
1711    let gap = ui.spacing().item_spacing.x;
1712    let label_shown =
1713        !compact && measure(&spec.label) + value_w + gap + pad + value_pad <= rect.width();
1714    // Too narrow for the value with its unit: the number alone.
1715    if !label_shown && value_w + 2.0 * value_pad > rect.width() && !spec.unit.is_empty() {
1716        let number = text
1717            .strip_suffix(spec.unit.as_str())
1718            .map_or(text, str::trim_end);
1719        value = galley(number);
1720    }
1721    if !ui.is_rect_visible(rect) {
1722        return label_shown;
1723    }
1724    let tone = if past { Tone::Warning } else { Tone::Neutral };
1725    // The bar is in the states of every thumb (a range's two).
1726    let state = responses
1727        .iter()
1728        .fold(State::REST, |s, r| s | State::from_response(r))
1729        .toned(tone);
1730    let painter = clipped(ui, rect, kit.slider.style(state));
1731    let cx = KitCx {
1732        painter: &painter,
1733        ppp: ui.ctx().pixels_per_point(),
1734    };
1735    let label = painter.layout_no_wrap(spec.label.clone(), font.clone(), Color32::PLACEHOLDER);
1736    let bar = Part {
1737        rect,
1738        room: rect,
1739        state,
1740        label: label_shown.then_some(&label),
1741    };
1742    kit.slider.paint(&cx, &bar);
1743    // A scrub field has neither fill nor thumb: the value says it all.
1744    if track {
1745        let x_of = |v: f64| rect.left() + rect.width() * spec.frac(v).clamp(0.0, 1.0) as f32;
1746        // The fill is a strip along the bottom, so the label and the value
1747        // stay on the track's colour (one contrast pair).
1748        // A ramp colours one value's bar (a range has none).
1749        let tokens = Tokens::of(ui.ctx());
1750        let ramp = match thumbs {
1751            [_] => ramp::active(spec.ramp.as_ref(), &tokens),
1752            _ => None,
1753        };
1754        let taller = || {
1755            let strip = (rect.height() * 0.3).max(4.0);
1756            Rect::from_min_max(pos2(rect.left(), rect.bottom() - strip), rect.max)
1757        };
1758        if let (Some(r), RampMode::Track) = (ramp, spec.ramp_mode) {
1759            // The ramp across the track, as a gradient: the thumb marks
1760            // the value on it.
1761            r.paint(&painter, taller(), &tokens, false);
1762        } else if let (Some(g), None) = (&spec.gradient, ramp) {
1763            // A gradient's colours are the content: a taller strip.
1764            g.paint(&painter, taller());
1765        } else {
1766            let fill = &kit.slider_fill;
1767            let strip = match fill.data.height {
1768                h if h > 0.0 => h.min(rect.height()),
1769                _ => (rect.height() * 0.15).max(3.0),
1770            };
1771            let (from, to) = match thumbs {
1772                [v] => (rect.left(), x_of(*v)),
1773                [a, b, ..] => (x_of(*a), x_of(*b)),
1774                [] => (rect.left(), rect.left()),
1775            };
1776            let strip =
1777                Rect::from_min_max(pos2(from, rect.bottom() - strip), pos2(to, rect.bottom()));
1778            match (ramp, thumbs) {
1779                // The fill in the ramp's colour at the value, standing
1780                // against the track.
1781                (Some(r), [v]) => {
1782                    let track = backdrop(kit.slider.style(state).fill, &tokens);
1783                    let color = r.value_color(spec.frac(*v) as f32, &tokens, track);
1784                    painter.rect_filled(strip, fill.style(state).radius, color);
1785                }
1786                _ => fill.paint_part(
1787                    &cx,
1788                    &Part {
1789                        rect: strip,
1790                        room: rect,
1791                        state,
1792                        label: None,
1793                    },
1794                ),
1795            }
1796        }
1797        let thumb = &kit.slider_thumb;
1798        let width = thumb.data.width.max(0.0);
1799        for (i, v) in thumbs.iter().enumerate() {
1800            let x = x_of(*v);
1801            let state = responses
1802                .get(i)
1803                .map_or(State::REST, |r| State::from_response(r))
1804                .toned(tone);
1805            let r = Rect::from_min_max(
1806                pos2(x - width / 2.0, rect.top()),
1807                pos2(x + width / 2.0, rect.bottom()),
1808            );
1809            thumb.paint_part(
1810                &cx,
1811                &Part {
1812                    rect: r,
1813                    room: rect,
1814                    state,
1815                    label: None,
1816                },
1817            );
1818        }
1819    }
1820    kit.slider.paint_label(&cx, &bar);
1821    // The value's digits line up from one value to the next
1822    // (`font.numeric`): it does not jitter while dragged. Even a number
1823    // too wide for the bar is cut at the bar's ends, never drawn past.
1824    let painter = ui.painter_at(rect);
1825    let cx = KitCx {
1826        painter: &painter,
1827        ppp: cx.ppp,
1828    };
1829    kit.slider_value.paint_part(
1830        &cx,
1831        &Part {
1832            rect,
1833            room: rect,
1834            state,
1835            label: Some(&value),
1836        },
1837    );
1838    label_shown
1839}
1840
1841/// A vertical bar: the track drawn by the kit (`slider`), the fill
1842/// (`slider-fill`) rising from the bottom, the thumb across it
1843/// (`slider-thumb`), the value at the top and the label at the bottom,
1844/// each cut to the width. Says whether the label shows whole.
1845fn paint_vertical(
1846    ui: &Ui,
1847    rect: Rect,
1848    response: &Response,
1849    spec: &Spec,
1850    v: f64,
1851    past: bool,
1852) -> bool {
1853    let kit = Kit::of(ui.ctx());
1854    let font = egui::TextStyle::Button.resolve(ui.style());
1855    let tone = if past { Tone::Warning } else { Tone::Neutral };
1856    let state = State::from_response(response).toned(tone);
1857    let style = kit.slider.style(state);
1858    let line = ui.fonts_mut(|f| f.row_height(&font));
1859    let pad = 2.0;
1860    let fit = |text: String, color: Color32| {
1861        let mut job = egui::text::LayoutJob::simple_singleline(text, font.clone(), color);
1862        job.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 2.0 * pad).max(1.0));
1863        ui.painter().layout_job(job)
1864    };
1865    let label = fit(spec.label.clone(), style.text);
1866    let label_shown = !label.elided;
1867    if !ui.is_rect_visible(rect) {
1868        return label_shown;
1869    }
1870    let full = spec.text(ui.ctx(), v);
1871    let mut value = fit(full.clone(), style.text);
1872    if value.elided {
1873        value = fit(spec.number(ui.ctx(), v), style.text);
1874    }
1875    let value_band = Rect::from_min_max(rect.min, pos2(rect.right(), rect.top() + line + pad));
1876    let label_band = Rect::from_min_max(pos2(rect.left(), rect.bottom() - line - pad), rect.max);
1877    let track = Rect::from_min_max(
1878        pos2(rect.left(), value_band.bottom()),
1879        pos2(rect.right(), label_band.top()),
1880    );
1881    let painter = clipped(ui, rect, style);
1882    let cx = KitCx {
1883        painter: &painter,
1884        ppp: ui.ctx().pixels_per_point(),
1885    };
1886    if track.height() > 0.0 {
1887        kit.slider.paint(
1888            &cx,
1889            &Part {
1890                rect: track,
1891                room: track,
1892                state,
1893                label: None,
1894            },
1895        );
1896        let y = track.bottom() - track.height() * spec.frac(v).clamp(0.0, 1.0) as f32;
1897        let strip = match kit.slider_fill.data.height {
1898            h if h > 0.0 => h.min(track.width()),
1899            _ => (track.width() * 0.15).max(3.0),
1900        };
1901        let tokens = Tokens::of(ui.ctx());
1902        let ramp = ramp::active(spec.ramp.as_ref(), &tokens);
1903        let side = Rect::from_min_max(
1904            pos2(track.left(), track.top()),
1905            pos2(track.left() + strip.max(4.0), track.bottom()),
1906        );
1907        if let (Some(r), RampMode::Track) = (ramp, spec.ramp_mode) {
1908            // The ramp along the bar: a side strip, the thumb on it.
1909            r.paint(&painter, side, &tokens, true);
1910        } else if let Some(r) = ramp {
1911            let back = backdrop(style.fill, &tokens);
1912            let color = r.value_color(spec.frac(v) as f32, &tokens, back);
1913            painter.rect_filled(
1914                Rect::from_min_max(
1915                    pos2(track.left(), y),
1916                    pos2(track.left() + strip, track.bottom()),
1917                ),
1918                kit.slider_fill.style(state).radius,
1919                color,
1920            );
1921        } else if let Some(g) = &spec.gradient {
1922            // A gradient's colours run along the bar: a side strip.
1923            g.paint_vertical(&painter, side);
1924        } else {
1925            kit.slider_fill.paint_part(
1926                &cx,
1927                &Part {
1928                    rect: Rect::from_min_max(
1929                        pos2(track.left(), y),
1930                        pos2(track.left() + strip, track.bottom()),
1931                    ),
1932                    room: track,
1933                    state,
1934                    label: None,
1935                },
1936            );
1937        }
1938        // The thumb: a line across the track, in the thumb's colour.
1939        let thumb = kit.slider_thumb.style(state);
1940        let color = if thumb.fill == Color32::TRANSPARENT {
1941            style.text
1942        } else {
1943            thumb.fill
1944        };
1945        let thickness = kit.slider_thumb.data.width.max(2.0);
1946        painter.hline(track.x_range(), y, egui::Stroke::new(thickness, color));
1947    }
1948    let at = |band: Rect, g: &std::sync::Arc<egui::Galley>| {
1949        pos2(
1950            band.center().x - g.size().x / 2.0,
1951            band.center().y - g.size().y / 2.0,
1952        )
1953    };
1954    painter.galley(at(value_band, &value), value.clone(), style.text);
1955    painter.galley(at(label_band, &label), label.clone(), style.text);
1956    label_shown
1957}
1958
1959/// What a ramp's colour must stand against: the track's fill, or the
1960/// panel under a transparent track.
1961pub(crate) fn backdrop(fill: Color32, tokens: &Tokens) -> Color32 {
1962    if fill.a() < 128 {
1963        tokens.surface.panel
1964    } else {
1965        fill
1966    }
1967}
1968
1969/// Paints the field state on the bar: the edge, and the markers after
1970/// the label.
1971pub(crate) fn paint_state(ui: &Ui, bar: Rect, spec: &Spec) {
1972    if spec.state.is_plain() || !ui.is_rect_visible(bar) {
1973        return;
1974    }
1975    crate::field::paint_edge(ui, bar, &spec.state);
1976    let t = Tokens::of(ui.ctx());
1977    let font = egui::TextStyle::Button.resolve(ui.style());
1978    let label = ui
1979        .painter()
1980        .layout_no_wrap(spec.label.clone(), font.clone(), t.text.default)
1981        .size()
1982        .x;
1983    let side = font.size * 0.8;
1984    crate::field::paint_markers(
1985        ui,
1986        pos2(
1987            bar.left() + Kit::of(ui.ctx()).slider.data.padding_x + label + t.space.xs,
1988            bar.center().y,
1989        ),
1990        side,
1991        t.space.xs / 2.0,
1992        &spec.state,
1993    );
1994}
1995
1996/// The field state given to assistive technologies, reported to agents,
1997/// and the bar's place in the Tab order (one group for a range's two
1998/// thumbs).
1999pub(crate) fn state_of(ui: &Ui, responses: &[&Response], spec: &Spec, kind: &str) {
2000    let group = format!("{:?}", responses.first().map(|r| r.id));
2001    for r in responses {
2002        crate::field::access(ui.ctx(), r.id, &spec.state);
2003        crate::tab::stop(
2004            ui,
2005            r,
2006            crate::tab::TabStop::new()
2007                .group(group.clone())
2008                .skip(!spec.state.is_focusable()),
2009        );
2010    }
2011    if let Some(r) = responses.first() {
2012        crate::field::record(ui.ctx(), r.id, &spec.label, kind, &spec.state);
2013    }
2014    match responses {
2015        [r] => crate::a11y::input(ui.ctx(), r.id, &spec.label),
2016        // A range's thumbs are named each by its end ("Focal, minimum").
2017        thumbs => {
2018            for r in thumbs {
2019                crate::a11y::drawn(ui.ctx(), r.id);
2020            }
2021        }
2022    }
2023}
2024
2025/// The AccessKit node beyond egui's slider info: the range, the step,
2026/// the value text, and the actions.
2027pub(crate) fn access(ui: &Ui, id: Id, spec: &Spec, value: f64, (lo, hi): (f64, f64)) {
2028    let text = spec.text(ui.ctx(), value);
2029    ui.ctx().accesskit_node_builder(id, |node| {
2030        use egui::accesskit::Action;
2031        node.set_min_numeric_value(lo.min(value));
2032        node.set_max_numeric_value(hi.max(value));
2033        node.set_numeric_value_step(spec.step);
2034        node.set_value(text);
2035        node.add_action(Action::SetValue);
2036        if value < hi {
2037            node.add_action(Action::Increment);
2038        }
2039        if value > lo {
2040            node.add_action(Action::Decrement);
2041        }
2042    });
2043}
2044
2045#[cfg(test)]
2046mod tests {
2047    use super::{Curve, Spec, parse_typed};
2048
2049    #[test]
2050    fn typed_values_keep_the_number_and_drop_the_unit() {
2051        assert_eq!(parse_typed("1,5 EV"), Some(1.5));
2052        assert_eq!(parse_typed(" -0.25"), Some(-0.25));
2053        assert_eq!(parse_typed("+3%"), Some(3.0));
2054        assert_eq!(parse_typed("EV"), None);
2055        assert_eq!(parse_typed("x"), None, "no current value");
2056    }
2057
2058    #[test]
2059    fn a_logarithmic_bar_gives_equal_ratios_equal_lengths() {
2060        let mut s = Spec::new("ISO", 100.0..=6400.0);
2061        s.curve = Curve::Logarithmic;
2062        assert!((s.frac(800.0) - 0.5).abs() < 1e-9);
2063        assert!((s.value_at(0.5) - 800.0).abs() < 1e-6);
2064        // A hundredth of the bar per step.
2065        let up = s.stepped(800.0, 1.0, 1.0);
2066        assert!((s.frac(up) - 0.51).abs() < 1e-9);
2067        // Not above zero: linear.
2068        let mut z = Spec::new("Zero", 0.0..=10.0);
2069        z.curve = Curve::Logarithmic;
2070        assert!((z.frac(5.0) - 0.5).abs() < 1e-9);
2071    }
2072
2073    #[test]
2074    fn values_are_shown_signed_and_never_as_minus_zero() {
2075        let ctx = egui::Context::default();
2076        let mut s = Spec::new("Exposure", -3.0..=4.0);
2077        s.precision = 2;
2078        s.unit = "EV".into();
2079        assert_eq!(s.text(&ctx, -0.001), "0.00 EV");
2080        s.signed = true;
2081        assert_eq!(s.text(&ctx, 1.5), "+1.50 EV");
2082        assert_eq!(s.text(&ctx, 0.0), "0.00 EV");
2083        assert_eq!(s.text(&ctx, -1.5), "-1.50 EV");
2084    }
2085}