Skip to main content

egui_pop_viewport/
wheel.rs

1//! Colour wheels: the lift, gamma and gain wheels of colour grading,
2//! and a hue and saturation picker, each with a luminance slider
3//! (egui-pop's slider, `egui_pop_core::slider`).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! A wheel's value is a [`WheelValue`]: a hue (degrees), a chroma (0 at
9//! the centre, 1 at the rim) and a luminance. What they mean is the
10//! application's (an offset added to shadows, a power, a gain, or a
11//! colour); the wheel draws them and handles the gestures.
12//!
13//! - [`ColorWheel::offset`]: neutral at the centre; a drag moves the
14//!   puck relatively (a click never makes it jump; Ctrl finer, Shift
15//!   coarser), Escape puts it back, a double click resets it; the
16//!   luminance slider is signed, around zero.
17//! - [`ColorWheel::picker`]: a press picks the hue and saturation under
18//!   the pointer, a drag follows it; the luminance slider runs from 0 to
19//!   1.
20//! - **Keys** when focused: the arrows move the puck by a step.
21//!
22//! Every change, of the puck or of the luminance, goes through the
23//! [`on_change`](ColorWheel::on_change) hook as a [`Change`] of the whole
24//! value: a drag's frames with `done: false`, its end once more from the
25//! value before it (a veto puts it back), and each key, reset and typed
26//! luminance. `egui-pop-imaging` runs the finished ones as the
27//! `wheel.change` step of an application.
28//!
29//! **Accessibility.** The disc is an AccessKit slider named by its
30//! label, whose value says the hue, the chroma and the luminance;
31//! increment and decrement change the chroma. The luminance slider is
32//! named after the wheel ("Lift luminance").
33//!
34//! ```
35//! use egui_pop_viewport::wheel::{ColorWheel, WheelValue};
36//!
37//! fn grading(ui: &mut egui::Ui, wheels: &mut [WheelValue; 3]) {
38//!     ui.horizontal(|ui| {
39//!         for (value, label) in wheels.iter_mut().zip(["Lift", "Gamma", "Gain"]) {
40//!             ColorWheel::offset(value, label).size(120.0).show(ui);
41//!         }
42//!     });
43//! }
44//! ```
45
46use std::ops::RangeInclusive;
47
48use egui::ecolor::Hsva;
49use egui::epaint::{Mesh, Vertex, WHITE_UV};
50use egui::{Color32, Pos2, Response, Role, Sense, Shape, Stroke, Ui, Vec2, WidgetInfo, vec2};
51use egui_pop_core::slider::{self, Slider};
52use egui_pop_core::state::Slot;
53use egui_pop_core::strings;
54
55/// A drag under way on a wheel, per wheel.
56const GRAB: Slot<Grab> = Slot::new("viewport.wheel.grab");
57use egui_pop_core::theme::Tokens;
58use serde_json::{Value as Json, json};
59
60use crate::change::{self, Cause, Change, Gesture, Hook, StepValue, Verdict};
61
62/// A wheel's value: a hue in degrees (0 to the right, counter-clockwise),
63/// a chroma (0 at the centre, 1 at the rim) and a luminance.
64#[derive(Clone, Copy, Debug, Default, PartialEq)]
65pub struct WheelValue {
66    pub hue: f32,
67    pub chroma: f32,
68    pub luminance: f32,
69}
70
71impl WheelValue {
72    /// The puck's position on the unit disc, `[x, y]` (y up).
73    pub fn xy(&self) -> [f32; 2] {
74        let a = self.hue.to_radians();
75        [self.chroma * a.cos(), self.chroma * a.sin()]
76    }
77
78    /// The value with the puck at `[x, y]` (y up), kept in the disc; the
79    /// hue is kept at the centre.
80    pub fn with_xy(self, [x, y]: [f32; 2]) -> WheelValue {
81        let chroma = (x * x + y * y).sqrt();
82        let hue = if chroma < 1e-6 {
83            self.hue
84        } else {
85            y.atan2(x).to_degrees().rem_euclid(360.0)
86        };
87        WheelValue {
88            hue,
89            chroma: chroma.min(1.0),
90            ..self
91        }
92    }
93}
94
95/// `{"hue": <degrees>, "chroma": <0..1>, "luminance": <value>}`.
96impl StepValue for WheelValue {
97    fn to_json(&self) -> Json {
98        json!({ "hue": self.hue, "chroma": self.chroma, "luminance": self.luminance })
99    }
100
101    fn from_json(v: &Json) -> Option<Self> {
102        Some(WheelValue {
103            hue: change::json_f32(v.get("hue")?)?,
104            chroma: change::json_f32(v.get("chroma")?)?,
105            luminance: change::json_f32(v.get("luminance")?)?,
106        })
107    }
108}
109
110/// How the disc answers the pointer.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum WheelMode {
113    /// Neutral at the centre; drags are relative (lift, gamma, gain).
114    Offset,
115    /// A press picks the colour under the pointer (hue and saturation).
116    Picker,
117}
118
119/// The wheels' colours, from the theme (`wheel.*`).
120#[derive(Clone, Copy, Debug, PartialEq)]
121pub struct WheelTokens {
122    pub ring: Color32,
123    pub puck: Color32,
124    pub puck_outline: Color32,
125}
126
127impl WheelTokens {
128    pub fn of(ctx: &egui::Context) -> WheelTokens {
129        let t = Tokens::of(ctx);
130        let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
131        WheelTokens {
132            ring: c("wheel.ring", t.border.strong),
133            puck: c("wheel.puck", t.text.strong),
134            puck_outline: c("wheel.puck-outline", t.surface.canvas),
135        }
136    }
137}
138
139/// A colour wheel, with its luminance slider.
140///
141/// Need (image): a colour wheel.
142/// Need (input): a colour picked on a wheel.
143#[derive(Debug)]
144pub struct ColorWheel<'a> {
145    value: &'a mut WheelValue,
146    label: String,
147    mode: WheelMode,
148    default: WheelValue,
149    size: f32,
150    luminance: Option<RangeInclusive<f64>>,
151    step: f32,
152    hook: Option<Hook<'a, WheelValue>>,
153}
154
155/// What a wheel did in a frame.
156#[derive(Debug)]
157pub struct WheelOutput {
158    /// The disc; `changed()` when the value changed.
159    pub response: Response,
160    /// The luminance slider, when shown.
161    pub luminance: Option<Response>,
162    /// The changes written this frame, after the hook.
163    pub changes: Vec<Change<WheelValue>>,
164}
165
166/// A gesture under way: the value before it, and where the pointer took
167/// the puck.
168#[derive(Clone, Copy, Debug)]
169struct Grab {
170    start: WheelValue,
171    at: [f32; 2],
172    cause: Cause,
173}
174
175impl<'a> ColorWheel<'a> {
176    fn new(value: &'a mut WheelValue, label: &str, mode: WheelMode) -> ColorWheel<'a> {
177        let luminance = match mode {
178            WheelMode::Offset => -1.0..=1.0,
179            WheelMode::Picker => 0.0..=1.0,
180        };
181        ColorWheel {
182            value,
183            label: label.to_string(),
184            mode,
185            default: WheelValue::default(),
186            size: 160.0,
187            luminance: Some(luminance),
188            step: 0.01,
189            hook: None,
190        }
191    }
192
193    /// A grading wheel (lift, gamma, gain): neutral at the centre,
194    /// relative drags, a signed luminance from -1 to 1.
195    pub fn offset(value: &'a mut WheelValue, label: &str) -> ColorWheel<'a> {
196        ColorWheel::new(value, label, WheelMode::Offset)
197    }
198
199    /// A hue and saturation picker: a press picks, a luminance from 0 to
200    /// 1.
201    pub fn picker(value: &'a mut WheelValue, label: &str) -> ColorWheel<'a> {
202        let mut w = ColorWheel::new(value, label, WheelMode::Picker);
203        w.default.luminance = 0.5;
204        w
205    }
206
207    /// What a double click goes back to (zero; a picker's luminance at
208    /// a half).
209    pub fn default(mut self, default: WheelValue) -> Self {
210        self.default = default;
211        self
212    }
213
214    /// The disc's diameter in points (160 by default); the slider is as
215    /// wide.
216    pub fn size(mut self, size: f32) -> Self {
217        self.size = size.max(48.0);
218        self
219    }
220
221    /// The luminance slider's range, or no slider (`None`).
222    pub fn luminance(mut self, range: Option<RangeInclusive<f64>>) -> Self {
223        self.luminance = range;
224        self
225    }
226
227    /// How far an arrow key moves the puck, in radii (a hundredth by
228    /// default).
229    pub fn step(mut self, step: f32) -> Self {
230        self.step = step.abs();
231        self
232    }
233
234    /// Sees each change before it is written: allow, veto or redirect
235    /// (another value; for a change of the luminance, its luminance is
236    /// taken).
237    pub fn on_change(
238        mut self,
239        hook: impl FnMut(&Change<WheelValue>) -> Verdict<WheelValue> + 'a,
240    ) -> Self {
241        self.hook = Some(Hook::new(hook));
242        self
243    }
244
245    /// Draws the wheel and its slider; says what changed.
246    pub fn show(self, ui: &mut Ui) -> WheelOutput {
247        let ColorWheel {
248            value,
249            label,
250            mode,
251            default,
252            size,
253            luminance,
254            step,
255            mut hook,
256        } = self;
257        let mut changes = Vec::new();
258        let inner = ui.vertical(|ui| {
259            ui.set_width(size);
260            let (rect, mut response) = change::allocate(
261                ui,
262                vec2(size, size),
263                Sense::click_and_drag(),
264                ("wheel", &label),
265            );
266            let radius = size / 2.0 - 4.0;
267            let center = rect.center();
268            let before = *value;
269            disc(
270                ui,
271                &response,
272                center,
273                radius,
274                mode,
275                default,
276                step,
277                value,
278                &mut hook,
279                &mut changes,
280            );
281            if response.clicked() || response.drag_started() {
282                response.request_focus();
283            }
284            egui_pop_core::pointer::drag_cursor(&response, egui_pop_core::pointer::DragKind::Point);
285            if *value != before {
286                response.mark_changed();
287            }
288            paint(ui, &response, center, radius, mode, *value);
289            let text = value_text(ui.ctx(), *value, mode);
290            let enabled = ui.is_enabled();
291            response.widget_info(|| {
292                let mut info = WidgetInfo::labeled(Role::Slider, enabled, &label);
293                info.current_text_value = Some(text.clone());
294                info
295            });
296            let chroma = value.chroma;
297            ui.ctx().accesskit_node_builder(response.id, |node| {
298                use egui::accesskit::Action;
299                node.set_numeric_value(f64::from(chroma));
300                node.set_min_numeric_value(0.0);
301                node.set_max_numeric_value(1.0);
302                node.set_numeric_value_step(f64::from(step));
303                node.add_action(Action::Increment);
304                node.add_action(Action::Decrement);
305            });
306            let slider = luminance.map(|range| {
307                let name = strings::tr_args(
308                    ui.ctx(),
309                    &crate::strings::WHEEL_LUMINANCE,
310                    &[("wheel", &label)],
311                );
312                luminance_slider(
313                    ui,
314                    &name,
315                    range,
316                    mode,
317                    default,
318                    value,
319                    &mut hook,
320                    &mut changes,
321                )
322            });
323            (response, slider)
324        });
325        let (response, luminance) = inner.inner;
326        WheelOutput {
327            response,
328            luminance,
329            changes,
330        }
331    }
332}
333
334/// The disc's gestures, keys and assistive actions.
335#[allow(
336    clippy::too_many_arguments,
337    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
338)]
339fn disc(
340    ui: &mut Ui,
341    response: &Response,
342    center: Pos2,
343    radius: f32,
344    mode: WheelMode,
345    default: WheelValue,
346    step: f32,
347    value: &mut WheelValue,
348    hook: &mut Option<Hook<'_, WheelValue>>,
349    changes: &mut Vec<Change<WheelValue>>,
350) {
351    let grab_id = GRAB.keyed(response.id);
352    let mut grab = grab_id.get(ui.ctx());
353    let mut propose = |value: &mut WheelValue, to: WheelValue, cause: Cause, done: bool| {
354        if to == *value {
355            return;
356        }
357        let c = Change {
358            from: *value,
359            to,
360            cause,
361            done,
362        };
363        if let Some(c) = change::decide(hook, c) {
364            *value = c.to;
365            changes.push(c);
366        }
367    };
368    let unit = |pos: Pos2| {
369        let r = radius.max(1.0);
370        [(pos.x - center.x) / r, (center.y - pos.y) / r]
371    };
372    let pressed = ui.input(|i| i.pointer.primary_pressed()) && response.is_pointer_button_down_on();
373    if pressed {
374        let at = match (mode, response.interact_pointer_pos()) {
375            (WheelMode::Picker, Some(pos)) => unit(pos),
376            _ => value.xy(),
377        };
378        grab = Some(Grab {
379            start: *value,
380            at,
381            cause: if mode == WheelMode::Picker {
382                Cause::Click
383            } else {
384                Cause::Drag
385            },
386        });
387        if mode == WheelMode::Picker {
388            let to = value.with_xy(at);
389            propose(value, to, Cause::Click, false);
390        }
391    }
392    match change::gesture(ui, response) {
393        Gesture::None => {}
394        Gesture::Moved(d) => {
395            if let Some(g) = grab.as_mut() {
396                let at = match (mode, response.interact_pointer_pos()) {
397                    (WheelMode::Picker, Some(pos)) => unit(pos),
398                    _ => {
399                        let r = radius.max(1.0);
400                        let p = [g.at[0] + d.x / r, g.at[1] - d.y / r];
401                        let len = (p[0] * p[0] + p[1] * p[1]).sqrt();
402                        if len > 1.0 {
403                            [p[0] / len, p[1] / len]
404                        } else {
405                            p
406                        }
407                    }
408                };
409                g.at = at;
410                g.cause = Cause::Drag;
411                let to = value.with_xy(at);
412                propose(value, to, Cause::Drag, false);
413            }
414        }
415        Gesture::Ended => {
416            if let Some(g) = grab.take() {
417                finish(g, value, &mut propose);
418            }
419        }
420        Gesture::Cancelled => {
421            if let Some(g) = grab.take() {
422                *value = g.start;
423            }
424        }
425    }
426    if response.clicked()
427        && let Some(g) = grab.take()
428    {
429        finish(g, value, &mut propose);
430    }
431    if response.double_clicked() {
432        grab = None;
433        propose(value, default, Cause::Reset, true);
434    }
435    if response.has_focus() {
436        change::lock_arrows(ui, response.id);
437        let [x, y] = change::arrows(ui);
438        if x != 0.0 || y != 0.0 {
439            let s = step * change::scale(ui);
440            let [px, py] = value.xy();
441            let to = value.with_xy([px + x * s, py + y * s]);
442            propose(value, to, Cause::Key, true);
443        }
444    }
445    let steps = change::access_steps(ui, response.id);
446    if steps != 0.0 {
447        let to = WheelValue {
448            chroma: (value.chroma + steps * step).clamp(0.0, 1.0),
449            ..*value
450        };
451        propose(value, to, Cause::Access, true);
452    }
453    match grab {
454        Some(g) => grab_id.set(ui.ctx(), g),
455        None => {
456            grab_id.remove(ui.ctx());
457        }
458    }
459}
460
461/// A gesture's end: one done change from the value before it (a veto
462/// leaves that value).
463fn finish(
464    grab: Grab,
465    value: &mut WheelValue,
466    propose: &mut impl FnMut(&mut WheelValue, WheelValue, Cause, bool),
467) {
468    if grab.start == *value {
469        return;
470    }
471    let end = *value;
472    *value = grab.start;
473    propose(value, end, grab.cause, true);
474}
475
476/// The luminance slider, its changes going through the wheel's hook.
477#[allow(
478    clippy::too_many_arguments,
479    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
480)]
481fn luminance_slider(
482    ui: &mut Ui,
483    name: &str,
484    range: RangeInclusive<f64>,
485    mode: WheelMode,
486    default: WheelValue,
487    value: &mut WheelValue,
488    hook: &mut Option<Hook<'_, WheelValue>>,
489    changes: &mut Vec<Change<WheelValue>>,
490) -> Response {
491    let base = *value;
492    let mut lum = f64::from(value.luminance);
493    let mut slider = Slider::new(&mut lum, name, range)
494        .step(0.01)
495        .default(f64::from(default.luminance))
496        .on_change(|c: &slider::Change| {
497            let at = |l: f64| WheelValue {
498                luminance: l as f32,
499                ..base
500            };
501            let proposed = Change {
502                from: at(c.from),
503                to: at(c.to),
504                cause: Cause::of_slider(c.cause),
505                done: c.done,
506            };
507            match change::decide(hook, proposed) {
508                Some(written) => {
509                    let to = f64::from(written.to.luminance);
510                    let redirected = written.to.luminance != at(c.to).luminance;
511                    changes.push(written);
512                    if redirected {
513                        slider::Verdict::Redirect(to)
514                    } else {
515                        slider::Verdict::Go
516                    }
517                }
518                None => slider::Verdict::Veto,
519            }
520        });
521    if mode == WheelMode::Offset {
522        slider = slider.signed();
523    }
524    let response = slider.show(ui).response;
525    value.luminance = lum as f32;
526    response
527}
528
529/// The disc: the colours, the ring, the centre, the puck, the focus.
530fn paint(
531    ui: &Ui,
532    response: &Response,
533    center: Pos2,
534    radius: f32,
535    mode: WheelMode,
536    value: WheelValue,
537) {
538    if !ui.is_rect_visible(response.rect) {
539        return;
540    }
541    let t = WheelTokens::of(ui.ctx());
542    let tokens = Tokens::of(ui.ctx());
543    let painter = ui.painter();
544    // A fan of triangles: the hue around the rim, towards the centre's
545    // colour (white for a picker, grey for a grading wheel). The
546    // colours are the content: not tokens.
547    let (middle, rim_s, rim_v) = match mode {
548        WheelMode::Picker => (Color32::WHITE, 1.0, 1.0),
549        WheelMode::Offset => (Color32::from_gray(128), 0.55, 0.8),
550    };
551    let segments = 96;
552    let mut mesh = Mesh::default();
553    mesh.vertices.push(Vertex {
554        pos: center,
555        uv: WHITE_UV,
556        color: middle,
557    });
558    for i in 0..=segments {
559        let turn = i as f32 / segments as f32;
560        let a = turn * std::f32::consts::TAU;
561        mesh.vertices.push(Vertex {
562            pos: center + radius * vec2(a.cos(), -a.sin()),
563            uv: WHITE_UV,
564            color: Hsva::new(turn, rim_s, rim_v, 1.0).into(),
565        });
566        if i > 0 {
567            mesh.add_triangle(0, i as u32, i as u32 + 1);
568        }
569    }
570    painter.add(Shape::mesh(mesh));
571    painter.circle_stroke(center, radius, Stroke::new(1.0, t.ring));
572    let tick = 4.0;
573    painter.line_segment(
574        [center - vec2(tick, 0.0), center + vec2(tick, 0.0)],
575        Stroke::new(1.0, t.ring),
576    );
577    painter.line_segment(
578        [center - vec2(0.0, tick), center + vec2(0.0, tick)],
579        Stroke::new(1.0, t.ring),
580    );
581    let [x, y] = value.xy();
582    let puck = center + radius * vec2(x, -y);
583    let fill: Color32 = match mode {
584        WheelMode::Picker => Hsva::new(value.hue / 360.0, value.chroma, 1.0, 1.0).into(),
585        WheelMode::Offset => t.puck,
586    };
587    let r = if response.hovered() || response.dragged() {
588        6.0
589    } else {
590        5.0
591    };
592    painter.circle(puck, r, fill, Stroke::new(2.0, t.puck_outline));
593    painter.circle_stroke(puck, r + 1.5, Stroke::new(1.0, t.puck));
594    if response.has_focus() {
595        egui_pop_core::focus::own_ring(&response.ctx, response.id);
596    }
597    if egui_pop_core::focus::shows_ring(response) {
598        painter.circle_stroke(center, radius + 2.0, Stroke::new(2.0, tokens.focus_ring));
599    }
600}
601
602/// What the wheel shows, for screen readers.
603fn value_text(ctx: &egui::Context, v: WheelValue, mode: WheelMode) -> String {
604    let luminance = match mode {
605        WheelMode::Offset => {
606            let n = strings::number(ctx, f64::from(v.luminance), 2);
607            if v.luminance > 0.0 {
608                format!("+{n}")
609            } else {
610                n
611            }
612        }
613        WheelMode::Picker => strings::number(ctx, f64::from(v.luminance), 2),
614    };
615    strings::tr_args(
616        ctx,
617        &crate::strings::WHEEL_VALUE,
618        &[
619            ("hue", &strings::number(ctx, f64::from(v.hue), 0)),
620            (
621                "chroma",
622                &strings::number(ctx, f64::from(v.chroma) * 100.0, 0),
623            ),
624            ("luminance", &luminance),
625        ],
626    )
627}
628
629/// The size a wheel takes with its slider, for layouts.
630pub fn wheel_size(ui: &Ui, size: f32, slider: bool) -> Vec2 {
631    let h = if slider {
632        size + ui.spacing().item_spacing.y + ui.spacing().interact_size.y
633    } else {
634        size
635    };
636    vec2(size, h)
637}
638
639#[cfg(test)]
640mod tests {
641    use super::*;
642
643    #[test]
644    fn the_puck_and_the_value_agree() {
645        let v = WheelValue {
646            hue: 90.0,
647            chroma: 0.5,
648            luminance: 0.1,
649        };
650        let [x, y] = v.xy();
651        assert!(x.abs() < 1e-6 && (y - 0.5).abs() < 1e-6);
652        let w = WheelValue::default().with_xy([0.0, -2.0]);
653        assert_eq!(w.chroma, 1.0, "kept in the disc");
654        assert!((w.hue - 270.0).abs() < 1e-4);
655        let centre = v.with_xy([0.0, 0.0]);
656        assert_eq!(centre.hue, 90.0, "the hue stays at the centre");
657        assert_eq!(WheelValue::from_json(&v.to_json()), Some(v));
658    }
659}