Skip to main content

egui_pop_core/
knob.rs

1//! A knob: one value on a rotary dial, from the same terms as a
2//! [`Slider`](crate::slider::Slider) (soft and hard range, step, unit,
3//! default, the `on_change` hook) and under the same history contract: a
4//! drag is one gesture, its frames `done: false` and its end once more
5//! `done: true` from the value before it; Escape during it puts the value
6//! back with no trace.
7//!
8//! <div class="warning">Experimental: may change in any release
9//! (docs/stability.md).</div>
10//!
11//! Gestures:
12//!
13//! - **Drag**, in one mode per knob ([`KnobDrag`]): right and up both
14//!   add (`Both`, the default: some people drag up, others sideways),
15//!   up only (`Vertical`), right only (`Horizontal`), or around the
16//!   centre (`Circular`, relative to the press).
17//!   The knob's own mode ([`Knob::drag`]), else the pointer profile's
18//!   (`options.knob_drag`). Where the press lands never changes the
19//!   mode, and a click never makes the value jump. The linear modes move
20//!   over the soft range in [`Knob::travel`] points (200 by default),
21//!   whatever the knob's size; the circular one over the dial's 270°
22//!   sweep, still near the centre.
23//! - **Fine and coarse**: the pointer profile's modifiers
24//!   (`gesture.value.fine`, Ctrl by default; `gesture.value.coarse`,
25//!   Shift by default) make a drag, the wheel and the arrows ten times
26//!   finer or coarser, as on a slider; pressed mid-drag, from where the
27//!   value is (no jump).
28//! - **Wheel**: as the slider's, by the pointer profile (in the guarded
29//!   profiles the panel scrolls unless the knob has the focus or the step
30//!   modifier is held), or over the knob whenever the pointer is, with
31//!   [`KnobWheel::Hover`], for places that do not scroll. A notch is a
32//!   step; a touchpad's scroll steps once a line's length.
33//! - **Keys** (arrows, Page Up and Page Down, Home and End),
34//!   **typed entry** (Enter) and **assistive actions**: as the slider's,
35//!   from the same pointer profile.
36//! - **Endless** ([`Knob::endless`]): no arc and no ends, ticks
37//!   turning with the value; the value wraps around the soft range
38//!   ([`Endless::Wrap`], an angle, a hue) or has no bounds
39//!   ([`Endless::Unbounded`]), and each change says how far it moved
40//!   (`Change::delta`, unwrapped), for a host that maps it to nudges.
41//! - **Hidden pointer** (opt-in, [`Knob::hide_pointer`] or
42//!   `Gestures::knob_hide_pointer`): a linear drag hides the pointer and
43//!   puts it back where the press was at its end
44//!   (`ViewportCommand::CursorVisible` and `CursorPosition`). Windows,
45//!   macOS and X11 do both; Wayland hides it but refuses to move an
46//!   unlocked pointer, so it reappears where the drag ended; on the web
47//!   neither command applies and the pointer stays visible.
48//! - **Double click**: back to the default; so does a click with the
49//!   profile's `gesture.value.reset` modifiers (`Ctrl+PrimaryClick` for
50//!   one), which no shipped profile binds.
51//! - **Right click** (or the context menu key): a menu, "Type a value"
52//!   (the typed entry) and "Reset" when there is a default
53//!   ([`Knob::menu`] turns it off).
54//!
55//! **Layout.** The dial takes the largest square of its room. In a room
56//! at least twice as wide as high, the label and the value stand beside
57//! it; in one taller than wide, the value is above and the label below
58//! (as a fader's); else the value is inside the dial and the label in
59//! the tooltip.
60//!
61//! **Accessibility.** An AccessKit slider named by its label, with its
62//! value, value text, range, step and the increment, decrement and
63//! set-value actions, as the slider's.
64//!
65//! ```
66//! use egui_pop_core::knob::Knob;
67//!
68//! fn knob(ui: &mut egui::Ui, ev: &mut f64) {
69//!     Knob::new(ev, "Exposure", -3.0..=4.0).step(0.01).unit("EV").signed().default(0.0).show(ui);
70//! }
71//! ```
72
73use std::f32::consts::PI;
74use std::ops::RangeInclusive;
75use std::sync::Arc;
76
77use egui::{
78    Color32, Galley, Pos2, Rect, Response, Sense, Shape, Stroke, Ui, Vec2, Widget, WidgetInfo,
79    pos2, vec2,
80};
81
82use crate::kit::{Kit, State, Tone};
83use crate::slider::{
84    Cause, Change, Drag, Hook, Ramp, RampMode, Spec, Thumb, Verdict, access, decide, gestures,
85    keep_auto_ids, keys_wheel_access, modifier_scale, open_typed_entry, ramp, ramp_builders,
86    reset_clicked, spec_builders, state_of, take_typed_request, typed_entry, typing_id,
87    typing_text, value_menu,
88};
89use crate::state::Slot;
90
91pub use egui_pop_model::pointer::KnobDrag;
92
93/// When the wheel turns a knob.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
95pub enum KnobWheel {
96    /// As the pointer profile says for sliders (`options.slider_wheel`):
97    /// in the guarded profiles the wheel scrolls the panel unless the
98    /// knob has the focus or the step modifier is held.
99    #[default]
100    Profile,
101    /// Whenever the pointer is over the knob, focused or not: for knobs
102    /// in places that do not scroll (a strip of controls, a HUD over an
103    /// image). The panel modifiers (`gesture.value.panel`) still give the
104    /// wheel to what is under the knob.
105    Hover,
106}
107
108/// How an endless knob's value goes past its soft range
109/// ([`Knob::endless`]).
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111pub enum Endless {
112    /// Around the soft range, as an angle or a hue: past the end is the
113    /// start again (`to` wrapped into `[start, end)`, the change's
114    /// `delta` unwrapped).
115    Wrap,
116    /// No bounds at all: the soft range is one turn of the face and the
117    /// span the drag's travel covers.
118    Unbounded,
119}
120
121/// The dial's sweep, in radians: from 7:30 to 4:30 through 12.
122pub const SWEEP: f32 = 1.5 * PI;
123
124/// Points of drag over the soft range, by default.
125pub const TRAVEL: f32 = 200.0;
126
127/// A drag's state, from its press to its end.
128#[derive(Clone, Copy, Debug, PartialEq)]
129struct Turn {
130    /// The value before the drag.
131    start: f64,
132    /// Where the drag has led, as a place on the soft range (0 to 1),
133    /// accumulated exactly.
134    frac: f64,
135    /// The mode, from the press to the end.
136    mode: KnobDrag,
137    /// The pointer's last angle, for a drag around; NaN near the centre.
138    angle: f32,
139    /// The pointer's last place.
140    at: Pos2,
141}
142
143const TURN: Slot<Turn> = Slot::new("core.knob.turn");
144/// An endless knob's drag: its place unwrapped, as last written.
145const UNWRAPPED: Slot<f64> = Slot::new("core.knob.unwrapped");
146
147/// A rotary knob over an `f64`.
148///
149/// Need (input): a rotary knob.
150#[derive(Debug)]
151pub struct Knob<'a> {
152    value: &'a mut f64,
153    spec: Spec,
154    default: Option<f64>,
155    hook: Option<Hook<'a>>,
156    size: Option<Vec2>,
157    travel: f32,
158    drag: Option<KnobDrag>,
159    wheel: KnobWheel,
160    menu: bool,
161    hide_pointer: Option<bool>,
162    endless: Option<Endless>,
163}
164
165impl<'a> Knob<'a> {
166    /// A knob spanning `soft`, which is also its hard range until
167    /// [`Knob::hard`] widens it.
168    pub fn new(value: &'a mut f64, label: &str, soft: RangeInclusive<f64>) -> Self {
169        Self {
170            value,
171            spec: Spec::new(label, soft),
172            default: None,
173            hook: None,
174            size: None,
175            travel: TRAVEL,
176            drag: None,
177            wheel: KnobWheel::Profile,
178            menu: true,
179            hide_pointer: None,
180            endless: None,
181        }
182    }
183
184    spec_builders!();
185    ramp_builders!();
186
187    /// What a double click goes back to.
188    pub fn default(mut self, default: f64) -> Self {
189        self.default = Some(default);
190        self
191    }
192
193    /// Sees every change before it is written, as the slider's hook.
194    pub fn on_change(mut self, hook: impl FnMut(&Change) -> Verdict + 'a) -> Self {
195        self.hook = Some(Hook(Box::new(hook)));
196        self
197    }
198
199    /// Its room, in points (a slot). By default two rows high and as wide
200    /// as the dial with its label and value beside it.
201    pub fn size(mut self, size: Vec2) -> Self {
202        self.size = Some(size);
203        self
204    }
205
206    /// How a drag turns this knob, over the pointer profile's
207    /// (`options.knob_drag`).
208    pub fn drag(mut self, mode: KnobDrag) -> Self {
209        self.drag = Some(mode);
210        self
211    }
212
213    /// When the wheel turns this knob; by default as the pointer profile
214    /// says.
215    pub fn wheel(mut self, wheel: KnobWheel) -> Self {
216        self.wheel = wheel;
217        self
218    }
219
220    /// Whether a right click (or the context menu key) opens the value's
221    /// menu: "Type a value", and "Reset" with a default. On by default;
222    /// off for a host that gives the knob a menu of its own (its "Type a
223    /// value" item calls [`request_typed_entry`](crate::slider::request_typed_entry)).
224    pub fn menu(mut self, on: bool) -> Self {
225        self.menu = on;
226        self
227    }
228
229    /// An endless knob: a face with no arc and no ends, ticks turning
230    /// with the value (one turn over the soft range), driven by the same
231    /// drag modes, travel, wheel and keys; its value wraps or has no
232    /// bounds ([`Endless`]), and each [`Change`] carries the motion in
233    /// `delta`, for a host that maps it to nudges (an encoder's
234    /// increments). Home and End do nothing on it; a circular drag's full
235    /// turn is the soft range. Its bar is always linear.
236    pub fn endless(mut self, ends: Endless) -> Self {
237        self.endless = Some(ends);
238        if ends == Endless::Unbounded {
239            self.spec.hard = (f64::NEG_INFINITY, f64::INFINITY);
240        }
241        self
242    }
243
244    /// Whether a drag hides the pointer and, at its end, puts it back
245    /// where the press was, so a long drag is not stopped by the edge of
246    /// the screen and the pointer does not wander off the knob; by
247    /// default the pointer profile's sliders' gestures say
248    /// (`Gestures::knob_hide_pointer`, off). Only in the linear modes:
249    /// a circular drag follows the pointer around the dial, which stays
250    /// in view. Where the platform refuses (module docs, "Hidden
251    /// pointer"), the pointer stays visible or reappears where the drag
252    /// ended.
253    pub fn hide_pointer(mut self, on: bool) -> Self {
254        self.hide_pointer = Some(on);
255        self
256    }
257
258    /// Points of drag over the soft range, in the linear modes
259    /// (`Vertical`, `Horizontal`, `Both`), whatever the knob's size.
260    pub fn travel(mut self, points: f32) -> Self {
261        if points > 0.0 {
262            self.travel = points;
263        }
264        self
265    }
266
267    /// Draws the knob; says what changed.
268    pub fn show(self, ui: &mut Ui) -> crate::slider::SliderOutput {
269        if self.spec.state.is_disabled() {
270            return ui
271                .scope(|ui| {
272                    ui.disable();
273                    self.draw(ui)
274                })
275                .inner;
276        }
277        self.draw(ui)
278    }
279
280    fn draw(self, ui: &mut Ui) -> crate::slider::SliderOutput {
281        let Knob {
282            value,
283            spec,
284            default,
285            mut hook,
286            size,
287            travel,
288            drag,
289            wheel,
290            menu,
291            hide_pointer,
292            endless,
293        } = self;
294        let mut spec = spec;
295        if endless.is_some() {
296            spec.curve = crate::slider::Curve::Linear;
297        }
298        // Where a value lands: kept to the hard range, or wrapped.
299        let fit = |v: f64| -> f64 {
300            match endless {
301                Some(Endless::Wrap) => {
302                    let (lo, hi) = spec.soft;
303                    let v = spec.settle(v, (f64::NEG_INFINITY, f64::INFINITY));
304                    if hi > lo {
305                        lo + (v - lo).rem_euclid(hi - lo)
306                    } else {
307                        v
308                    }
309                }
310                Some(Endless::Unbounded) => spec.settle(v, (f64::NEG_INFINITY, f64::INFINITY)),
311                None => spec.settle(v, spec.hard),
312            }
313        };
314        let row = ui.spacing().interact_size.y;
315        let wanted = size.unwrap_or(vec2(row * 2.0 * 3.0, row * 2.0));
316        let (_, rect) = ui.allocate_space(vec2(wanted.x.max(row), wanted.y.max(row)));
317        let id = crate::slider::stable_id(ui, "egui_pop.knob", &spec.label);
318        let layout = Layout::of(rect);
319        let mut response = ui.interact(rect, id, Sense::click_and_drag());
320        let before = *value;
321        let mut changes = Vec::new();
322        let mut apply = |change: Change, value: &mut f64| -> bool {
323            match decide(&mut hook, change, &spec) {
324                Some(c) => {
325                    *value = c.to;
326                    changes.push(c);
327                    true
328                }
329                None => false,
330            }
331        };
332        let moved = |from: f64, to: f64, delta: f64, cause: Cause, done: bool| Change {
333            thumb: Thumb::Value,
334            from,
335            to,
336            cause,
337            done,
338            delta,
339        };
340        let change =
341            |from: f64, to: f64, cause: Cause, done: bool| moved(from, to, to - from, cause, done);
342        let typing = typing_id(id);
343        if take_typed_request(ui.ctx(), id) && spec.state.is_editable() {
344            open_typed_entry(ui, typing, spec.number(ui.ctx(), *value));
345        }
346        if let Some(text) = typing_text(ui.ctx(), typing) {
347            let entry = Rect::from_center_size(rect.center(), vec2(rect.width(), row));
348            if let Some(end) = typed_entry(ui, entry, typing, text, &spec, *value) {
349                if let Some(v) = end.value {
350                    let to = fit(v);
351                    if to != *value {
352                        apply(change(*value, to, Cause::Typed, true), value);
353                    }
354                }
355                if end.refocus {
356                    response.request_focus();
357                }
358            }
359        } else {
360            keep_auto_ids(ui);
361            let g = gestures(ui.ctx());
362            // One fine and one coarse modifier for the drag, the wheel
363            // and the keys: the profile's (`gesture.value.fine` and
364            // `gesture.value.coarse`).
365            let scale = modifier_scale(ui, &g);
366            let mode = drag.unwrap_or(g.knob_drag);
367            let hide = hide_pointer.unwrap_or(g.knob_hide_pointer) && mode != KnobDrag::Circular;
368            let unwrapped = UNWRAPPED.keyed(response.id);
369            match turn(
370                ui,
371                &response,
372                &layout,
373                &spec,
374                *value,
375                scale,
376                travel,
377                mode,
378                hide,
379                endless.is_some(),
380            ) {
381                Drag::None => {}
382                Drag::Moved(v) if endless.is_some() => {
383                    // The drag's place unwrapped, from the value at its
384                    // start: each frame's delta is the motion since the
385                    // last one written.
386                    let u = spec.settle(v, (f64::NEG_INFINITY, f64::INFINITY));
387                    let last = unwrapped.get(ui.ctx()).unwrap_or(*value);
388                    if u != last
389                        && apply(moved(*value, fit(u), u - last, Cause::Drag, false), value)
390                    {
391                        unwrapped.set(ui.ctx(), u);
392                    }
393                }
394                Drag::Moved(v) => {
395                    let to = spec.settle(v, spec.hard);
396                    if to != *value {
397                        apply(change(*value, to, Cause::Drag, false), value);
398                    }
399                }
400                Drag::Ended(start) => {
401                    let total = unwrapped
402                        .get(ui.ctx())
403                        .map_or(*value - start, |u| u - start);
404                    unwrapped.remove(ui.ctx());
405                    if (start != *value || total != 0.0)
406                        && !apply(moved(start, *value, total, Cause::Drag, true), value)
407                    {
408                        *value = start;
409                        crate::binding::cancel_gesture(ui.ctx(), response.id);
410                    }
411                }
412                Drag::Cancelled(start) => {
413                    unwrapped.remove(ui.ctx());
414                    *value = start;
415                    crate::binding::cancel_gesture(ui.ctx(), response.id);
416                }
417            }
418            if g.reset_on_double_click
419                && response.double_clicked()
420                && let Some(d) = default
421                && d != *value
422            {
423                apply(change(*value, d, Cause::Reset, true), value);
424            }
425            if reset_clicked(ui, &response, &g)
426                && let Some(d) = default
427                && d != *value
428            {
429                apply(change(*value, d, Cause::Reset, true), value);
430            }
431            if response.clicked() {
432                response.request_focus();
433            }
434            if menu
435                && value_menu(&response, &spec, default.filter(|d| *d != *value).is_some())
436                && let Some(d) = default
437            {
438                apply(change(*value, d, Cause::Reset, true), value);
439            }
440            let mut wheel_g = g;
441            if wheel == KnobWheel::Hover {
442                wheel_g.wheel_steps = true;
443            }
444            let bounds = if endless.is_some() {
445                (f64::NEG_INFINITY, f64::INFINITY)
446            } else {
447                spec.soft
448            };
449            if let Some((v, cause)) =
450                keys_wheel_access(ui, &response, &spec, *value, bounds, scale, &wheel_g)
451            {
452                // Home and End lead nowhere on an endless knob.
453                if v.is_finite() {
454                    let to = fit(v);
455                    let delta = spec.settle(v, (f64::NEG_INFINITY, f64::INFINITY)) - *value;
456                    if to != *value || delta != 0.0 {
457                        apply(moved(*value, to, delta, cause, true), value);
458                    }
459                }
460            }
461            if response.has_focus()
462                && spec.state.is_editable()
463                && ui.input(|i| i.key_pressed(g.typed_entry))
464            {
465                open_typed_entry(ui, typing, spec.number(ui.ctx(), *value));
466            }
467            paint(ui, &layout, &response, &spec, *value, endless.is_some());
468        }
469        if *value != before {
470            response.mark_changed();
471        }
472        let enabled = ui.is_enabled();
473        let v = *value;
474        response.widget_info(|| WidgetInfo::slider(enabled, v, &spec.label));
475        access(ui, response.id, &spec, v, spec.soft);
476        state_of(ui, &[&response], &spec, "knob");
477        let mut response = crate::field::hover(ui, &response, &spec.state);
478        if layout.label.is_none() {
479            response = response.on_hover_text(&spec.label);
480        }
481        crate::slider::SliderOutput {
482            response,
483            changes,
484            quad: None,
485        }
486    }
487}
488
489impl Widget for Knob<'_> {
490    fn ui(self, ui: &mut Ui) -> Response {
491        self.show(ui).response
492    }
493}
494
495/// Where a knob's parts go in its room.
496#[derive(Clone, Copy, Debug)]
497struct Layout {
498    dial: Rect,
499    /// Where the value goes; `None`: inside the dial.
500    value: Option<Rect>,
501    /// Where the label goes; `None`: in the tooltip.
502    label: Option<Rect>,
503}
504
505impl Layout {
506    fn of(rect: Rect) -> Self {
507        let (w, h) = (rect.width(), rect.height());
508        if w >= 2.0 * h {
509            // Beside: the dial at the start, the label over the value.
510            let dial = Rect::from_min_size(rect.min, vec2(h, h));
511            let text = Rect::from_min_max(pos2(dial.right() + 4.0, rect.top()), rect.max);
512            let (label, value) = text.split_top_bottom_at_fraction(0.5);
513            Self {
514                dial,
515                value: Some(value),
516                label: Some(label),
517            }
518        } else if h >= 1.6 * w {
519            // A fader's order: the value above, the label below.
520            let band = (h - w) / 2.0;
521            let value = Rect::from_min_size(rect.min, vec2(w, band));
522            let dial = Rect::from_min_size(pos2(rect.left(), value.bottom()), vec2(w, w));
523            let label = Rect::from_min_max(pos2(rect.left(), dial.bottom()), rect.max);
524            Self {
525                dial,
526                value: Some(value),
527                label: Some(label),
528            }
529        } else {
530            let side = w.min(h);
531            Self {
532                dial: Rect::from_center_size(rect.center(), vec2(side, side)),
533                value: None,
534                label: None,
535            }
536        }
537    }
538
539    fn radius(&self) -> f32 {
540        (self.dial.width().min(self.dial.height()) / 2.0 - 2.0).max(1.0)
541    }
542}
543
544/// Within this distance of the centre, a circular drag does not turn.
545fn still_radius(layout: &Layout) -> f32 {
546    (layout.radius() * 0.25).max(4.0)
547}
548
549/// The angle of a place on the soft range (0 to 1), in screen radians
550/// (y down): 0 at 7:30, 1 at 4:30, through 12.
551fn angle_of(frac: f32) -> f32 {
552    // 7:30 is 135° below the right, clockwise on screen.
553    PI * 0.75 + frac.clamp(0.0, 1.0) * SWEEP
554}
555
556/// The pointer's angle around `centre`, in screen radians.
557fn pointer_angle(centre: Pos2, at: Pos2) -> f32 {
558    (at.y - centre.y).atan2(at.x - centre.x)
559}
560
561/// A drag's effect in a frame, in `mode` (taken at the press, kept to
562/// the end); `scale` (the modifiers') scales the motion.
563#[allow(
564    clippy::too_many_arguments,
565    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
566)]
567fn turn(
568    ui: &Ui,
569    response: &Response,
570    layout: &Layout,
571    spec: &Spec,
572    value: f64,
573    scale: f64,
574    travel: f32,
575    mode: KnobDrag,
576    hide: bool,
577    endless: bool,
578) -> Drag {
579    let slot = TURN.keyed(response.id);
580    let centre = layout.dial.center();
581    crate::pointer::drag_cursor(response, crate::pointer::DragKind::Value);
582    if response.drag_started() {
583        // From the press, not from where the drag is first seen: the
584        // motion up to then counts.
585        let at = ui
586            .input(|i| i.pointer.press_origin())
587            .or(response.interact_pointer_pos())
588            .unwrap_or(centre);
589        slot.set(
590            ui.ctx(),
591            Turn {
592                start: value,
593                frac: spec.frac(value),
594                mode,
595                angle: if at.distance(centre) < still_radius(layout) {
596                    f32::NAN
597                } else {
598                    pointer_angle(centre, at)
599                },
600                at,
601            },
602        );
603        if hide {
604            hide_pointer_from(ui.ctx(), at);
605        }
606    }
607    if response.drag_stopped() {
608        show_pointer(ui.ctx());
609        let start = slot.get(ui.ctx()).map_or(value, |t| t.start);
610        slot.remove(ui.ctx());
611        let cancel = gestures(ui.ctx()).cancel;
612        return if crate::focus::cancel_pressed(ui.ctx(), cancel) {
613            Drag::Cancelled(start)
614        } else {
615            Drag::Ended(start)
616        };
617    }
618    if response.dragged()
619        && let Some(mut t) = slot.get(ui.ctx())
620    {
621        let Some(at) = response.interact_pointer_pos() else {
622            return Drag::None;
623        };
624        // From the last place, the press's at first: the motion before
625        // egui calls it a drag counts.
626        let d = at - t.at;
627        t.at = at;
628        let along = |points: f32| f64::from(points / travel.max(1.0));
629        let delta = match t.mode {
630            KnobDrag::Vertical => along(-d.y),
631            KnobDrag::Horizontal => along(d.x),
632            KnobDrag::Both => along(d.x - d.y),
633            KnobDrag::Circular => {
634                // Near the centre a point of motion sweeps a wide angle:
635                // the turn waits there, and goes on from the angle it
636                // finds on the way out.
637                if at.distance(centre) < still_radius(layout) {
638                    t.angle = f32::NAN;
639                    0.0
640                } else {
641                    let now = pointer_angle(centre, at);
642                    let mut a = if t.angle.is_nan() { 0.0 } else { now - t.angle };
643                    // The short way round.
644                    if a > PI {
645                        a -= 2.0 * PI;
646                    } else if a < -PI {
647                        a += 2.0 * PI;
648                    }
649                    t.angle = now;
650                    // An endless face turns once over the soft range.
651                    f64::from(a / if endless { 2.0 * PI } else { SWEEP })
652                }
653            }
654        } * scale;
655        if delta != 0.0 {
656            let (lo, hi) = (spec.frac(spec.soft.0), spec.frac(spec.soft.1));
657            t.frac = if endless {
658                t.frac + delta
659            } else {
660                (t.frac + delta).clamp(lo.min(t.frac), hi.max(t.frac))
661            };
662            slot.set(ui.ctx(), t);
663            return Drag::Moved(spec.value_at(t.frac));
664        }
665        slot.set(ui.ctx(), t);
666    }
667    Drag::None
668}
669
670/// A hidden pointer: the viewport it was hidden in, and where to put it
671/// back.
672const HIDDEN: Slot<(egui::ViewportId, Pos2)> = Slot::new("core.knob.hidden");
673/// The guard showing a hidden pointer again is in place.
674const GUARD: Slot<bool> = Slot::new("core.knob.hidden_guard");
675
676/// Hides the pointer until the drag ends, to come back at `origin`.
677fn hide_pointer_from(ctx: &egui::Context, origin: Pos2) {
678    let viewport = ctx.viewport_id();
679    HIDDEN.set(ctx, (viewport, origin));
680    ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::CursorVisible(false));
681    if GUARD.get(ctx).is_none() {
682        GUARD.set(ctx, true);
683        // A knob that is no longer drawn never sees its drag end: once
684        // no button is down, the pointer comes back all the same.
685        ctx.on_begin_pass(
686            "egui_pop_knob_pointer",
687            Arc::new(|ui: &mut Ui| {
688                let ctx = ui.ctx();
689                if let Some((viewport, _)) = HIDDEN.get(ctx)
690                    && viewport == ctx.viewport_id()
691                    && !ctx.input(|i| i.pointer.any_down())
692                {
693                    show_pointer(ctx);
694                }
695            }),
696        );
697    }
698}
699
700/// Puts a hidden pointer back where its drag started, and shows it.
701fn show_pointer(ctx: &egui::Context) {
702    if let Some((viewport, origin)) = HIDDEN.get(ctx) {
703        HIDDEN.remove(ctx);
704        ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::CursorPosition(origin));
705        ctx.send_viewport_cmd_to(viewport, egui::ViewportCommand::CursorVisible(true));
706    }
707}
708
709/// The dial: the track's arc, the value's arc (from zero when the soft
710/// range holds it, else from the start), the pointer, the focus ring;
711/// then the label and the value where the layout puts them. Drawn with
712/// the slider's kit parts: `slider` (the dial), `slider-fill` (the
713/// value's arc), `slider-thumb` (the pointer), `slider-value` (the
714/// text).
715/// With a colour ramp, the value's arc and the pointer take its colour
716/// at the value, or the track's arc shows the whole ramp
717/// ([`RampMode::Track`]).
718/// An endless knob's face has no arcs: twelve ticks turn with the value,
719/// one turn over the soft range, the pointer the longest.
720fn paint(ui: &Ui, layout: &Layout, response: &Response, spec: &Spec, v: f64, endless: bool) {
721    let room = layout
722        .dial
723        .union(layout.value.unwrap_or(layout.dial))
724        .union(layout.label.unwrap_or(layout.dial));
725    if !ui.is_rect_visible(room) {
726        return;
727    }
728    let kit = Kit::of(ui.ctx());
729    let past = !endless && (v < spec.soft.0 || v > spec.soft.1);
730    let tone = if past { Tone::Warning } else { Tone::Neutral };
731    let state = State::from_response(response).toned(tone);
732    let dial = kit.slider.style(state);
733    let fill = kit.slider_fill.style(state);
734    let thumb = kit.slider_thumb.style(state);
735    let painter = ui.painter_at(room.expand(4.0));
736    let centre = layout.dial.center();
737    let r = layout.radius();
738    let width = (r * 0.18).clamp(2.0, 5.0);
739    // The body, then the track's arc.
740    painter.circle(
741        centre,
742        r - width,
743        dial.fill,
744        Stroke::new(dial.border_width, dial.border_color),
745    );
746    let track = if dial.border_color == Color32::TRANSPARENT {
747        dial.text.gamma_multiply(0.3)
748    } else {
749        dial.border_color
750    };
751    let pointer = if thumb.fill == Color32::TRANSPARENT {
752        dial.text
753    } else {
754        thumb.fill
755    };
756    if endless {
757        // 12 o'clock at the soft range's start, clockwise for more.
758        let turn = -PI / 2.0 + (spec.frac(v).rem_euclid(1.0) as f32) * 2.0 * PI;
759        for k in 1..12 {
760            let a = turn + k as f32 * PI / 6.0;
761            let dir = vec2(a.cos(), a.sin());
762            painter.line_segment(
763                [
764                    centre + (r - width) * 0.72 * dir,
765                    centre + (r - width) * 0.9 * dir,
766                ],
767                Stroke::new((width * 0.5).max(1.0), track),
768            );
769        }
770        let dir = vec2(turn.cos(), turn.sin());
771        painter.line_segment(
772            [
773                centre + (r - width) * 0.25 * dir,
774                centre + (r - width) * 0.9 * dir,
775            ],
776            Stroke::new(width.max(2.0), pointer),
777        );
778    } else {
779        let tokens = crate::theme::Tokens::of(ui.ctx());
780        let colours = match ramp::active(spec.ramp.as_ref(), &tokens) {
781            // The ramp along the track's arc; the pointer marks the value.
782            Some(ramp) if spec.ramp_mode == RampMode::Track => Arcs {
783                track,
784                ramp: Some((ramp, &tokens)),
785                fill: Color32::TRANSPARENT,
786                pointer,
787            },
788            // The value's arc and the pointer in the ramp's colour at the
789            // value, standing against the dial.
790            Some(ramp) => {
791                let back = crate::slider::backdrop(dial.fill, &tokens);
792                let c = ramp.value_color(spec.frac(v) as f32, &tokens, back);
793                Arcs {
794                    track,
795                    ramp: None,
796                    fill: c,
797                    pointer: c,
798                }
799            }
800            None => Arcs {
801                track,
802                ramp: None,
803                fill: if fill.fill == Color32::TRANSPARENT {
804                    dial.text
805                } else {
806                    fill.fill
807                },
808                pointer,
809            },
810        };
811        paint_arcs(&painter, centre, r, width, &colours, spec, v);
812    }
813    if crate::focus::shows_ring(response) {
814        let ring = kit.slider.style(state.with(State::FOCUS, true));
815        let color = if ring.ring_width > 0.0 {
816            ring.ring_color
817        } else {
818            ui.visuals().selection.stroke.color
819        };
820        painter.circle_stroke(
821            centre,
822            r + 1.5,
823            Stroke::new(ring.ring_width.max(1.5), color),
824        );
825    }
826    paint_text(ui, &painter, layout, spec, v, dial.text, r);
827}
828
829/// The colours of a dial's arcs.
830struct Arcs<'r> {
831    track: Color32,
832    /// The ramp drawn along the track's arc, over `track`.
833    ramp: Option<(&'r Ramp, &'r crate::theme::Tokens)>,
834    /// The value's arc; none when transparent.
835    fill: Color32,
836    pointer: Color32,
837}
838
839/// The track's arc, the value's arc (from zero when the soft range holds
840/// it, else from the start) and the pointer.
841fn paint_arcs(
842    painter: &egui::Painter,
843    centre: Pos2,
844    r: f32,
845    width: f32,
846    colours: &Arcs<'_>,
847    spec: &Spec,
848    v: f64,
849) {
850    let arc = |from: f32, to: f32, radius: f32| -> Vec<Pos2> {
851        let n = (((to - from).abs() / SWEEP) * 48.0).ceil().max(2.0) as usize;
852        (0..=n)
853            .map(|i| {
854                let a = from + (to - from) * i as f32 / n as f32;
855                centre + radius * vec2(a.cos(), a.sin())
856            })
857            .collect()
858    };
859    if let Some((ramp, tokens)) = colours.ramp {
860        // Short pieces, each in the ramp's colour at its middle.
861        const N: usize = 48;
862        for i in 0..N {
863            let (a, b) = (i as f32 / N as f32, (i + 1) as f32 / N as f32);
864            let c = ramp.color_at((a + b) / 2.0, tokens);
865            painter.add(Shape::line(
866                arc(angle_of(a), angle_of(b), r - width / 2.0),
867                Stroke::new(width, c),
868            ));
869        }
870    } else {
871        painter.add(Shape::line(
872            arc(angle_of(0.0), angle_of(1.0), r - width / 2.0),
873            Stroke::new(width, colours.track),
874        ));
875    }
876    let at = spec.frac(v) as f32;
877    let zero = if spec.soft.0 < 0.0 && spec.soft.1 > 0.0 {
878        spec.frac(0.0) as f32
879    } else {
880        0.0
881    };
882    if (at - zero).abs() > f32::EPSILON && colours.fill != Color32::TRANSPARENT {
883        painter.add(Shape::line(
884            arc(angle_of(zero), angle_of(at), r - width / 2.0),
885            Stroke::new(width, colours.fill),
886        ));
887    }
888    let a = angle_of(at);
889    painter.line_segment(
890        [
891            centre + (r - width) * 0.25 * vec2(a.cos(), a.sin()),
892            centre + (r - width) * 0.9 * vec2(a.cos(), a.sin()),
893        ],
894        Stroke::new(width.max(2.0), colours.pointer),
895    );
896}
897
898/// The label and the value, where the layout puts them.
899fn paint_text(
900    ui: &Ui,
901    painter: &egui::Painter,
902    layout: &Layout,
903    spec: &Spec,
904    v: f64,
905    color: Color32,
906    r: f32,
907) {
908    let centre = layout.dial.center();
909    let font = egui::TextStyle::Button.resolve(ui.style());
910    let fit = |text: String, room: Rect, color: Color32| -> Arc<Galley> {
911        let mut job = egui::text::LayoutJob::simple_singleline(text, font.clone(), color);
912        job.wrap = egui::text::TextWrapping::truncate_at_width(room.width().max(1.0));
913        ui.painter().layout_job(job)
914    };
915    let place = |g: &Arc<Galley>, room: Rect, centred: bool| {
916        let x = if centred {
917            room.center().x - g.size().x / 2.0
918        } else {
919            room.left()
920        };
921        painter.galley(
922            pos2(x, room.center().y - g.size().y / 2.0),
923            g.clone(),
924            color,
925        );
926    };
927    let text = spec.text(ui.ctx(), v);
928    let centred = layout
929        .value
930        .is_some_and(|r| r.width() < 2.0 * layout.dial.width());
931    if let Some(room) = layout.value {
932        let mut g = fit(text, room, color);
933        if g.elided {
934            g = fit(spec.number(ui.ctx(), v), room, color);
935        }
936        place(&g, room, centred);
937    } else if r > font.size * 1.2 {
938        // Inside the dial: the number only.
939        let inner = Rect::from_center_size(centre, Vec2::splat(r * 1.3));
940        let g = fit(spec.number(ui.ctx(), v), inner, color);
941        place(&g, inner, true);
942    }
943    if let Some(room) = layout.label {
944        let g = fit(spec.label.clone(), room, color.gamma_multiply(0.75));
945        place(&g, room, centred);
946    }
947}