Skip to main content

egui_pop_viewport/
curve.rs

1//! A curve editor: control points the user adds, moves and deletes,
2//! through a spline the application supplies ([`Spline`]), over an
3//! optional histogram, with the targeted adjustment of photo editors (a
4//! value picked under the pointer in the image selects or adds the
5//! point to drag).
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! Points are `[x, y]` in 0..1, sorted by `x`, at least two. The editor
11//! owns no curve maths: [`Spline::eval`] draws the curve through them
12//! ([`MonotoneCubic`] by default, [`Linear`] for straight segments).
13//!
14//! Gestures:
15//!
16//! - **On a point**: a press selects it, a drag moves it between its
17//!   neighbours (Ctrl finer, Shift coarser; Escape puts it back), a
18//!   double click or a right click deletes it (two points stay). The
19//!   editor claims the secondary click on its rect
20//!   (`egui_pop_core::pointer::claim`): a context menu around it does
21//!   not open there.
22//! - **On the curve**: a press adds a point there, and a drag moves it
23//!   at once.
24//! - **Elsewhere**: a double click puts the curve back to its default
25//!   ([`CurveEditor::default_points`], the identity unless given).
26//! - **Keys** when focused ([`CurveKeys`]): Page Down and Page Up select
27//!   the next and the previous point, the arrows move the selected one
28//!   (Ctrl finer, Shift coarser), Insert adds a point halfway to the
29//!   next one, Delete or Backspace deletes it, R resets the curve.
30//! - **Pick** ([`CurveEditor::pick`]): the application passes the value
31//!   under the pointer in the image; the editor marks it and highlights
32//!   the nearest point; pressing selects that point, or adds one on the
33//!   curve there, and the application's vertical drag moves it.
34//!
35//! Every change goes through the [`on_change`](CurveEditor::on_change)
36//! hook ([`Change`] of the whole list of points): a drag's frames with
37//! `done: false`, its end once more from the points before it with
38//! `done: true` (a veto puts them back), and each key, addition,
39//! deletion and reset. `egui-pop-imaging` runs the finished ones as the
40//! `curve.change` step of an application.
41//!
42//! **Accessibility.** The editor is an AccessKit slider named by its
43//! label, whose value says which point is selected and where; increment
44//! and decrement move that point's output by a step, set-value sets it.
45//!
46//! ```
47//! use egui_pop_viewport::curve::{CurveEditor, Pick, PickAction};
48//!
49//! fn tone(ui: &mut egui::Ui, points: &mut Vec<[f32; 2]>, luma_bins: &[f32], under: Option<f32>) {
50//!     CurveEditor::new(points, "Tone curve")
51//!         .histogram(luma_bins)
52//!         .pick(under.map(|x| Pick { x, action: PickAction::Hover }))
53//!         .show(ui);
54//! }
55//! ```
56
57use egui::{
58    Color32, Id, Key, Modifiers, Pos2, Rect, Response, Role, Sense, Shape, Stroke, StrokeKind, Ui,
59    Vec2, Widget, WidgetInfo, pos2, vec2,
60};
61use egui_pop_core::pointer::claim::{self, SecondaryClaim};
62use egui_pop_core::state::Slot;
63use egui_pop_core::strings::{self, Arg};
64use egui_pop_core::theme::Tokens;
65
66use crate::change::{self, Cause, Change, Gesture, Hook, Verdict};
67
68/// The curve's maths, supplied by the application.
69pub trait Spline {
70    /// The curve's output at `x` (0..1), through `points` (sorted by
71    /// `x`, at least two).
72    fn eval(&self, points: &[[f32; 2]], x: f32) -> f32;
73}
74
75/// Straight segments between the points, flat past the ends.
76#[derive(Clone, Copy, Debug, Default)]
77pub struct Linear;
78
79impl Spline for Linear {
80    fn eval(&self, points: &[[f32; 2]], x: f32) -> f32 {
81        let Some(i) = segment(points, x) else {
82            return ends(points, x);
83        };
84        let ([x0, y0], [x1, y1]) = (points[i], points[i + 1]);
85        let t = if x1 > x0 { (x - x0) / (x1 - x0) } else { 0.0 };
86        y0 + (y1 - y0) * t
87    }
88}
89
90/// A monotone cubic (Fritsch and Carlson): smooth, through every
91/// point, and never overshooting between two of them, so a rising set
92/// of points gives a rising curve. Flat past the ends.
93#[derive(Clone, Copy, Debug, Default)]
94pub struct MonotoneCubic;
95
96impl Spline for MonotoneCubic {
97    fn eval(&self, points: &[[f32; 2]], x: f32) -> f32 {
98        let Some(i) = segment(points, x) else {
99            return ends(points, x);
100        };
101        let n = points.len();
102        let slope = |k: usize| {
103            let ([x0, y0], [x1, y1]) = (points[k], points[k + 1]);
104            if x1 > x0 { (y1 - y0) / (x1 - x0) } else { 0.0 }
105        };
106        // The tangent at point k: the mean of the slopes around it, set
107        // to zero at a peak or a valley and limited so the segment stays
108        // monotone.
109        let tangent = |k: usize| {
110            if k == 0 {
111                return slope(0);
112            }
113            if k == n - 1 {
114                return slope(n - 2);
115            }
116            let (a, b) = (slope(k - 1), slope(k));
117            if a * b <= 0.0 {
118                0.0
119            } else {
120                // The harmonic mean keeps it within 3 times either slope.
121                2.0 * a * b / (a + b)
122            }
123        };
124        let ([x0, y0], [x1, y1]) = (points[i], points[i + 1]);
125        let h = x1 - x0;
126        if h <= 0.0 {
127            return y0;
128        }
129        let s = slope(i);
130        let (mut m0, mut m1) = (tangent(i), tangent(i + 1));
131        if s == 0.0 {
132            m0 = 0.0;
133            m1 = 0.0;
134        } else {
135            let (a, b) = (m0 / s, m1 / s);
136            let r = a * a + b * b;
137            if r > 9.0 {
138                let t = 3.0 / r.sqrt();
139                m0 = t * a * s;
140                m1 = t * b * s;
141            }
142        }
143        let t = (x - x0) / h;
144        let (t2, t3) = (t * t, t * t * t);
145        (2.0 * t3 - 3.0 * t2 + 1.0) * y0
146            + (t3 - 2.0 * t2 + t) * h * m0
147            + (-2.0 * t3 + 3.0 * t2) * y1
148            + (t3 - t2) * h * m1
149    }
150}
151
152/// The segment `i..i+1` holding `x`, or `None` past the ends.
153fn segment(points: &[[f32; 2]], x: f32) -> Option<usize> {
154    if points.len() < 2 || x < points[0][0] || x > points[points.len() - 1][0] {
155        return None;
156    }
157    Some(
158        points
159            .windows(2)
160            .position(|w| x <= w[1][0])
161            .unwrap_or(points.len() - 2),
162    )
163}
164
165/// The value past the ends: the end's own.
166fn ends(points: &[[f32; 2]], x: f32) -> f32 {
167    match points {
168        [] => x,
169        [p] => p[1],
170        [first, .., last] => {
171            if x <= first[0] {
172                first[1]
173            } else {
174                last[1]
175            }
176        }
177    }
178}
179
180/// The identity: output equals input.
181pub fn identity() -> Vec<[f32; 2]> {
182    vec![[0.0, 0.0], [1.0, 1.0]]
183}
184
185/// The smallest distance kept between two points' inputs.
186pub const MIN_GAP: f32 = 0.01;
187
188/// The index of the point whose input is nearest `x`, within
189/// `tolerance`.
190pub fn nearest(points: &[[f32; 2]], x: f32, tolerance: f32) -> Option<usize> {
191    points
192        .iter()
193        .enumerate()
194        .map(|(i, p)| (i, (p[0] - x).abs()))
195        .filter(|(_, d)| *d <= tolerance)
196        .min_by(|a, b| a.1.total_cmp(&b.1))
197        .map(|(i, _)| i)
198}
199
200/// Inserts a point in order; its index, or `None` when it is too close
201/// to another point's input.
202pub fn insert(points: &mut Vec<[f32; 2]>, p: [f32; 2]) -> Option<usize> {
203    let p = [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0)];
204    if points.iter().any(|q| (q[0] - p[0]).abs() < MIN_GAP) {
205        return None;
206    }
207    let i = points
208        .iter()
209        .position(|q| q[0] > p[0])
210        .unwrap_or(points.len());
211    points.insert(i, p);
212    Some(i)
213}
214
215/// Point `i` moved to `to`, kept inside 0..1 and between its
216/// neighbours' inputs.
217pub fn moved(points: &[[f32; 2]], i: usize, to: [f32; 2]) -> [f32; 2] {
218    let lo = if i == 0 {
219        0.0
220    } else {
221        points[i - 1][0] + MIN_GAP
222    };
223    let hi = if i + 1 >= points.len() {
224        1.0
225    } else {
226        points[i + 1][0] - MIN_GAP
227    };
228    let x = if lo <= hi {
229        to[0].clamp(lo, hi)
230    } else {
231        points[i][0]
232    };
233    [x, to[1].clamp(0.0, 1.0)]
234}
235
236/// What the application does with the value picked in the image.
237#[derive(Clone, Copy, Debug, PartialEq)]
238pub enum PickAction {
239    /// The pointer is over the image: mark the value, highlight the
240    /// nearest point.
241    Hover,
242    /// The pointer pressed: select the nearest point, or add one on the
243    /// curve; the gesture begins.
244    Press,
245    /// The pointer moved during the gesture: move the selected point's
246    /// output by this much (0..1 units, up positive).
247    Move(f32),
248    /// The gesture ended.
249    Release,
250    /// The gesture was given up: the points go back.
251    Cancel,
252}
253
254/// A value picked under the pointer in the image (its input on the
255/// curve, 0..1) and what the pointer does.
256#[derive(Clone, Copy, Debug, PartialEq)]
257pub struct Pick {
258    pub x: f32,
259    pub action: PickAction,
260}
261
262/// The editor's keys, as data so a profile can remap them
263/// ([`set_keys`]).
264#[derive(Clone, Copy, Debug, PartialEq)]
265pub struct CurveKeys {
266    pub next: Key,
267    pub previous: Key,
268    pub add: Key,
269    pub delete: [Key; 2],
270    pub reset: Key,
271}
272
273impl Default for CurveKeys {
274    fn default() -> Self {
275        CurveKeys {
276            next: Key::PageDown,
277            previous: Key::PageUp,
278            add: Key::Insert,
279            delete: [Key::Delete, Key::Backspace],
280            reset: Key::R,
281        }
282    }
283}
284
285const KEYS: Slot<CurveKeys> = Slot::new("viewport.curve.keys");
286/// An editor's selection and drag, per editor.
287const MEMORY: Slot<Memory> = Slot::new("viewport.curve.memory");
288
289/// The curve editors' keys in a context (the defaults until set).
290pub fn keys(ctx: &egui::Context) -> CurveKeys {
291    KEYS.get_or_default(ctx)
292}
293
294/// Remaps the curve editors' keys in a context (an input profile).
295pub fn set_keys(ctx: &egui::Context, keys: CurveKeys) {
296    KEYS.set(ctx, keys);
297}
298
299/// The curve editor's colours, from the theme (`curve.*`).
300#[derive(Clone, Copy, Debug, PartialEq)]
301pub struct CurveTokens {
302    pub background: Color32,
303    pub grid: Color32,
304    pub identity: Color32,
305    pub line: Color32,
306    pub point: Color32,
307    pub point_selected: Color32,
308    pub pick: Color32,
309}
310
311impl CurveTokens {
312    pub fn of(ctx: &egui::Context) -> CurveTokens {
313        let t = Tokens::of(ctx);
314        let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
315        CurveTokens {
316            background: c("curve.background", t.surface.sunken),
317            grid: c("curve.grid", t.border.default),
318            identity: c("curve.identity", t.border.default),
319            line: c("curve.line", t.text.default),
320            point: c("curve.point", t.text.default),
321            point_selected: c("curve.point-selected", t.accent.default),
322            pick: c("curve.pick", t.status.warning),
323        }
324    }
325}
326
327type Points = Vec<[f32; 2]>;
328
329static MONOTONE: MonotoneCubic = MonotoneCubic;
330
331/// The curve editor.
332///
333/// Need (image): a curve editor.
334#[derive(Debug)]
335pub struct CurveEditor<'a> {
336    points: &'a mut Points,
337    label: String,
338    spline: &'a dyn Spline,
339    defaults: Option<Points>,
340    histogram: Option<&'a [f32]>,
341    pick: Option<Pick>,
342    size: Option<Vec2>,
343    color: Option<Color32>,
344    step: f32,
345    max_points: usize,
346    hook: Option<Hook<'a, Points>>,
347}
348
349impl std::fmt::Debug for dyn Spline + '_ {
350    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
351        f.write_str("Spline")
352    }
353}
354
355/// What the editor did in a frame.
356#[derive(Debug)]
357pub struct CurveOutput {
358    /// The editor; `changed()` when the points changed.
359    pub response: Response,
360    /// The changes written this frame, after the hook.
361    pub changes: Vec<Change<Points>>,
362    /// The point selected after this frame.
363    pub selected: Option<usize>,
364}
365
366/// A gesture under way: the points before it, the point moved, where it
367/// was and how far the pointer took it.
368#[derive(Clone, Debug)]
369struct Grab {
370    start: Points,
371    index: usize,
372    origin: [f32; 2],
373    moved: [f32; 2],
374    cause: Cause,
375}
376
377/// What the editor keeps between frames.
378#[derive(Clone, Debug, Default)]
379struct Memory {
380    selected: Option<usize>,
381    grab: Option<Grab>,
382}
383
384impl<'a> CurveEditor<'a> {
385    /// An editor of `points`, named `label` for screen readers.
386    pub fn new(points: &'a mut Vec<[f32; 2]>, label: &str) -> CurveEditor<'a> {
387        CurveEditor {
388            points,
389            label: label.to_string(),
390            spline: &MONOTONE,
391            defaults: None,
392            histogram: None,
393            pick: None,
394            size: None,
395            color: None,
396            step: 0.01,
397            max_points: 20,
398            hook: None,
399        }
400    }
401
402    /// The curve's maths ([`MonotoneCubic`] by default).
403    pub fn spline(mut self, spline: &'a dyn Spline) -> Self {
404        self.spline = spline;
405        self
406    }
407
408    /// The points a reset goes back to (the identity by default).
409    pub fn default_points(mut self, points: Vec<[f32; 2]>) -> Self {
410        self.defaults = Some(points);
411        self
412    }
413
414    /// Bins drawn behind the curve (any scale).
415    pub fn histogram(mut self, bins: &'a [f32]) -> Self {
416        self.histogram = Some(bins);
417        self
418    }
419
420    /// The value picked under the pointer in the image, and what the
421    /// pointer does (the targeted adjustment).
422    pub fn pick(mut self, pick: Option<Pick>) -> Self {
423        self.pick = pick;
424        self
425    }
426
427    /// The size in points (default: the available width, square, at
428    /// most 320).
429    pub fn size(mut self, size: Vec2) -> Self {
430        self.size = Some(size);
431        self
432    }
433
434    /// The curve's colour (a channel's; `curve.line` by default).
435    pub fn color(mut self, color: Color32) -> Self {
436        self.color = Some(color);
437        self
438    }
439
440    /// How far an arrow key moves a point (a hundredth by default).
441    pub fn step(mut self, step: f32) -> Self {
442        self.step = step.abs();
443        self
444    }
445
446    /// The most points the curve may have (20 by default).
447    pub fn max_points(mut self, n: usize) -> Self {
448        self.max_points = n.max(2);
449        self
450    }
451
452    /// Sees each change before it is written: allow, veto or redirect
453    /// (other points).
454    pub fn on_change(mut self, hook: impl FnMut(&Change<Points>) -> Verdict<Points> + 'a) -> Self {
455        self.hook = Some(Hook::new(hook));
456        self
457    }
458
459    /// Draws the editor; says what changed.
460    pub fn show(self, ui: &mut Ui) -> CurveOutput {
461        let CurveEditor {
462            points,
463            label,
464            spline,
465            defaults,
466            histogram,
467            pick,
468            size,
469            color,
470            step,
471            max_points,
472            mut hook,
473        } = self;
474        let size = size.unwrap_or_else(|| {
475            let w = ui.available_width().clamp(120.0, 320.0);
476            vec2(w, w)
477        });
478        let (rect, mut response) =
479            change::allocate(ui, size, Sense::click_and_drag(), ("curve", &label));
480        // The right click deletes a point: no context menu around opens
481        // over the editor.
482        claim::claim_secondary(
483            &response,
484            SecondaryClaim::new(strings::tr(ui.ctx(), &crate::strings::CURVE_EDITOR)).click(
485                strings::tr(ui.ctx(), &crate::strings::CURVE_SECONDARY_CLICK),
486            ),
487        );
488        let id = response.id;
489        let area = rect.shrink(6.0);
490        let mem_id = MEMORY.keyed(id);
491        let mut mem = mem_id.get_or_default(ui.ctx());
492        if mem.selected.is_some_and(|i| i >= points.len()) {
493            mem.selected = None;
494        }
495        let defaults = defaults.unwrap_or_else(identity);
496        let mut ed = Edit {
497            points,
498            hook: &mut hook,
499            changes: Vec::new(),
500        };
501        if ed.points.len() >= 2 {
502            let map = Map { area };
503            pointer(
504                ui, &response, &map, spline, &defaults, max_points, &mut mem, &mut ed,
505            );
506            if let Some(p) = pick {
507                picked(p, spline, max_points, &mut mem, &mut ed);
508            }
509            if response.has_focus() {
510                change::lock_arrows(ui, id);
511                keyboard(ui, spline, &defaults, step, max_points, &mut mem, &mut ed);
512            }
513            access(ui, id, step, &mut mem, &mut ed);
514        }
515        if response.clicked() || response.drag_started() {
516            response.request_focus();
517        }
518        egui_pop_core::pointer::drag_cursor(&response, egui_pop_core::pointer::DragKind::Point);
519        if !ed.changes.is_empty() {
520            response.mark_changed();
521        }
522        let changes = ed.changes;
523        let points: &[[f32; 2]] = &ed.points[..];
524        paint(
525            ui, rect, area, &response, points, spline, histogram, pick, color, &mem,
526        );
527        let value = value_text(ui.ctx(), points, mem.selected);
528        let enabled = ui.is_enabled();
529        response.widget_info(|| {
530            let mut info = WidgetInfo::labeled(Role::Slider, enabled, &label);
531            info.current_text_value = Some(value.clone());
532            info
533        });
534        let selected = mem.selected;
535        let out_value = selected.and_then(|i| points.get(i)).map(|p| p[1]);
536        ui.ctx().accesskit_node_builder(id, |node| {
537            use egui::accesskit::Action;
538            node.set_min_numeric_value(0.0);
539            node.set_max_numeric_value(1.0);
540            node.set_numeric_value_step(f64::from(step));
541            if let Some(v) = out_value {
542                node.set_numeric_value(f64::from(v));
543                node.add_action(Action::Increment);
544                node.add_action(Action::Decrement);
545                node.add_action(Action::SetValue);
546            }
547        });
548        mem_id.set(ui.ctx(), mem);
549        CurveOutput {
550            response,
551            changes,
552            selected,
553        }
554    }
555}
556
557impl Widget for CurveEditor<'_> {
558    fn ui(self, ui: &mut Ui) -> Response {
559        self.show(ui).response
560    }
561}
562
563/// The points being edited, the hook, and what was written.
564struct Edit<'e, 'a> {
565    points: &'e mut Points,
566    hook: &'e mut Option<Hook<'a, Points>>,
567    changes: Vec<Change<Points>>,
568}
569
570impl Edit<'_, '_> {
571    /// Proposes `to`; writes what the hook leaves. Whether written.
572    fn propose(&mut self, to: Points, cause: Cause, done: bool) -> bool {
573        if to == *self.points {
574            return false;
575        }
576        let change = Change {
577            from: self.points.clone(),
578            to,
579            cause,
580            done,
581        };
582        match change::decide(self.hook, change) {
583            Some(c) => {
584                self.points.clone_from(&c.to);
585                self.changes.push(c);
586                true
587            }
588            None => false,
589        }
590    }
591
592    /// A gesture's end: one done change from the points before it; a
593    /// veto puts them back.
594    fn finish(&mut self, grab: Grab) {
595        if grab.start == *self.points {
596            return;
597        }
598        let change = Change {
599            from: grab.start.clone(),
600            to: self.points.clone(),
601            cause: grab.cause,
602            done: true,
603        };
604        match change::decide(self.hook, change) {
605            Some(c) => {
606                self.points.clone_from(&c.to);
607                self.changes.push(c);
608            }
609            None => self.points.clone_from(&grab.start),
610        }
611    }
612
613    /// Back to the points before the gesture, with no trace.
614    fn cancel(&mut self, grab: Grab) {
615        self.points.clone_from(&grab.start);
616    }
617
618    /// Moves the grabbed point by the pointer's motion (frames).
619    fn drag(&mut self, grab: &mut Grab, delta: [f32; 2]) {
620        grab.moved = [grab.moved[0] + delta[0], grab.moved[1] + delta[1]];
621        if grab.index >= self.points.len() {
622            return;
623        }
624        let want = [
625            grab.origin[0] + grab.moved[0],
626            grab.origin[1] + grab.moved[1],
627        ];
628        let mut to = self.points.clone();
629        to[grab.index] = moved(&to, grab.index, want);
630        self.propose(to, grab.cause, false);
631    }
632}
633
634/// Between curve units and the screen.
635struct Map {
636    area: Rect,
637}
638
639impl Map {
640    fn to_screen(&self, p: [f32; 2]) -> Pos2 {
641        pos2(
642            self.area.left() + p[0] * self.area.width(),
643            self.area.bottom() - p[1] * self.area.height(),
644        )
645    }
646
647    fn unit_at(&self, pos: Pos2) -> [f32; 2] {
648        [
649            (pos.x - self.area.left()) / self.area.width().max(1.0),
650            (self.area.bottom() - pos.y) / self.area.height().max(1.0),
651        ]
652    }
653
654    /// A motion in points as curve units.
655    fn delta(&self, d: Vec2) -> [f32; 2] {
656        [
657            d.x / self.area.width().max(1.0),
658            -d.y / self.area.height().max(1.0),
659        ]
660    }
661}
662
663/// How close, in points, a press must be to a point or the curve.
664const HIT: f32 = 8.0;
665
666/// The pointer: grab, drag, add, delete, reset.
667#[allow(
668    clippy::too_many_arguments,
669    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
670)]
671fn pointer(
672    ui: &Ui,
673    response: &Response,
674    map: &Map,
675    spline: &dyn Spline,
676    defaults: &Points,
677    max_points: usize,
678    mem: &mut Memory,
679    ed: &mut Edit<'_, '_>,
680) {
681    let hit_point = |pos: Pos2, points: &[[f32; 2]]| {
682        points
683            .iter()
684            .enumerate()
685            .map(|(i, p)| (i, map.to_screen(*p).distance(pos)))
686            .filter(|(_, d)| *d <= HIT)
687            .min_by(|a, b| a.1.total_cmp(&b.1))
688            .map(|(i, _)| i)
689    };
690    let pressed = ui.input(|i| i.pointer.primary_pressed());
691    let pos = response.interact_pointer_pos().or(response.hover_pos());
692    if pressed
693        && response.is_pointer_button_down_on()
694        && let Some(pos) = pos
695    {
696        if let Some(i) = hit_point(pos, ed.points) {
697            mem.selected = Some(i);
698            mem.grab = Some(Grab {
699                start: ed.points.clone(),
700                index: i,
701                origin: ed.points[i],
702                moved: [0.0, 0.0],
703                cause: Cause::Drag,
704            });
705        } else {
706            let at = map.unit_at(pos);
707            let on_curve = map
708                .to_screen([at[0], spline.eval(ed.points, at[0])])
709                .distance(pos)
710                <= HIT;
711            if on_curve && ed.points.len() < max_points && (0.0..=1.0).contains(&at[0]) {
712                let start = ed.points.clone();
713                let mut to = start.clone();
714                let y = spline.eval(&start, at[0]);
715                if let Some(i) = insert(&mut to, [at[0], y]) {
716                    let p = to[i];
717                    if ed.propose(to, Cause::Add, false) {
718                        mem.selected = Some(i);
719                        mem.grab = Some(Grab {
720                            start,
721                            index: i,
722                            origin: p,
723                            moved: [0.0, 0.0],
724                            cause: Cause::Add,
725                        });
726                    }
727                }
728            }
729        }
730    }
731    match change::gesture(ui, response) {
732        Gesture::None => {}
733        Gesture::Moved(d) => {
734            if let Some(mut grab) = mem.grab.take() {
735                ed.drag(&mut grab, map.delta(d));
736                mem.grab = Some(grab);
737            }
738        }
739        Gesture::Ended => {
740            if let Some(grab) = mem.grab.take() {
741                ed.finish(grab);
742            }
743        }
744        Gesture::Cancelled => {
745            if let Some(grab) = mem.grab.take() {
746                ed.cancel(grab);
747            }
748        }
749    }
750    // A press and release without a drag: the gesture (a selection, a
751    // point added) ends.
752    if (response.clicked() || response.secondary_clicked())
753        && let Some(grab) = mem.grab.take()
754    {
755        ed.finish(grab);
756    }
757    let delete_at = |pos: Option<Pos2>, points: &[[f32; 2]]| pos.and_then(|p| hit_point(p, points));
758    if response.double_clicked() || response.secondary_clicked() {
759        match delete_at(pos, ed.points) {
760            Some(i) if ed.points.len() > 2 => {
761                let mut to = ed.points.clone();
762                to.remove(i);
763                if ed.propose(to, Cause::Delete, true) {
764                    mem.selected = Some(i.min(ed.points.len() - 1));
765                }
766            }
767            None if response.double_clicked() => {
768                ed.propose(defaults.clone(), Cause::Reset, true);
769                mem.selected = None;
770            }
771            _ => {}
772        }
773    }
774}
775
776/// The value picked in the image.
777fn picked(
778    p: Pick,
779    spline: &dyn Spline,
780    max_points: usize,
781    mem: &mut Memory,
782    ed: &mut Edit<'_, '_>,
783) {
784    match p.action {
785        PickAction::Hover => {}
786        PickAction::Press => {
787            let start = ed.points.clone();
788            let index = match nearest(ed.points, p.x, PICK_TOLERANCE) {
789                Some(i) => Some(i),
790                None if ed.points.len() < max_points => {
791                    let mut to = start.clone();
792                    let y = spline.eval(&start, p.x);
793                    insert(&mut to, [p.x, y]).filter(|_| ed.propose(to.clone(), Cause::Pick, false))
794                }
795                None => None,
796            };
797            if let Some(i) = index {
798                mem.selected = Some(i);
799                mem.grab = Some(Grab {
800                    start,
801                    index: i,
802                    origin: ed.points[i],
803                    moved: [0.0, 0.0],
804                    cause: Cause::Pick,
805                });
806            }
807        }
808        PickAction::Move(dy) => {
809            if let Some(mut grab) = mem.grab.take() {
810                ed.drag(&mut grab, [0.0, dy]);
811                mem.grab = Some(grab);
812            }
813        }
814        PickAction::Release => {
815            if let Some(grab) = mem.grab.take() {
816                ed.finish(grab);
817            }
818        }
819        PickAction::Cancel => {
820            if let Some(grab) = mem.grab.take() {
821                ed.cancel(grab);
822            }
823        }
824    }
825}
826
827/// How close a picked value must be to a point's input to take it.
828pub const PICK_TOLERANCE: f32 = 0.04;
829
830/// The keys, when focused.
831fn keyboard(
832    ui: &mut Ui,
833    spline: &dyn Spline,
834    defaults: &Points,
835    step: f32,
836    max_points: usize,
837    mem: &mut Memory,
838    ed: &mut Edit<'_, '_>,
839) {
840    let k = keys(ui.ctx());
841    let take = |key: Key| ui.input_mut(|i| i.consume_key(Modifiers::NONE, key));
842    let n = ed.points.len();
843    if take(k.next) {
844        mem.selected = Some(mem.selected.map_or(0, |i| (i + 1).min(n - 1)));
845    }
846    if take(k.previous) {
847        mem.selected = Some(mem.selected.map_or(n - 1, |i| i.saturating_sub(1)));
848    }
849    if take(k.reset) {
850        ed.propose(defaults.clone(), Cause::Reset, true);
851        mem.selected = None;
852    }
853    let n = ed.points.len();
854    if take(k.add) && n < max_points {
855        let i = mem.selected.unwrap_or(0).min(n - 2);
856        let x = (ed.points[i][0] + ed.points[i + 1][0]) / 2.0;
857        let mut to = ed.points.clone();
858        if let Some(j) = insert(&mut to, [x, spline.eval(ed.points, x)])
859            && ed.propose(to, Cause::Add, true)
860        {
861            mem.selected = Some(j);
862        }
863    }
864    if (take(k.delete[0]) || take(k.delete[1]))
865        && let Some(i) = mem.selected
866        && ed.points.len() > 2
867    {
868        let mut to = ed.points.clone();
869        to.remove(i);
870        if ed.propose(to, Cause::Delete, true) {
871            mem.selected = Some(i.min(ed.points.len() - 1));
872        }
873    }
874    let [dx, dy] = change::arrows(ui);
875    if (dx != 0.0 || dy != 0.0)
876        && let Some(i) = mem.selected
877        && i < ed.points.len()
878    {
879        let s = step * change::scale(ui);
880        let p = ed.points[i];
881        let mut to = ed.points.clone();
882        to[i] = moved(&to, i, [p[0] + dx * s, p[1] + dy * s]);
883        ed.propose(to, Cause::Key, true);
884    }
885}
886
887/// Assistive technologies: increment, decrement or set the selected
888/// point's output.
889fn access(ui: &Ui, id: Id, step: f32, mem: &mut Memory, ed: &mut Edit<'_, '_>) {
890    let Some(i) = mem.selected.filter(|i| *i < ed.points.len()) else {
891        return;
892    };
893    let steps = change::access_steps(ui, id);
894    let set = ui.input(|inp| {
895        use egui::accesskit::{Action, ActionData};
896        inp.accesskit_action_requests(id, Action::SetValue)
897            .filter_map(|r| match r.data {
898                Some(ActionData::NumericValue(n)) => Some(n as f32),
899                _ => None,
900            })
901            .last()
902    });
903    let p = ed.points[i];
904    let y = set.unwrap_or(p[1] + steps * step);
905    if y != p[1] {
906        let mut to = ed.points.clone();
907        to[i] = moved(&to, i, [p[0], y]);
908        ed.propose(to, Cause::Access, true);
909    }
910}
911
912/// The background, the grid, the histogram, the identity, the curve,
913/// the points and the pick.
914#[allow(
915    clippy::too_many_arguments,
916    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
917)]
918fn paint(
919    ui: &Ui,
920    rect: Rect,
921    area: Rect,
922    response: &Response,
923    points: &[[f32; 2]],
924    spline: &dyn Spline,
925    histogram: Option<&[f32]>,
926    pick: Option<Pick>,
927    color: Option<Color32>,
928    mem: &Memory,
929) {
930    if !ui.is_rect_visible(rect) {
931        return;
932    }
933    let t = CurveTokens::of(ui.ctx());
934    let tokens = Tokens::of(ui.ctx());
935    let painter = ui.painter_at(rect);
936    let map = Map { area };
937    let radius = tokens.radius.widget;
938    painter.rect_filled(rect, radius, t.background);
939    let hair = 1.0 / ui.ctx().pixels_per_point();
940    for q in 1..4 {
941        let f = q as f32 / 4.0;
942        let x = area.left() + area.width() * f;
943        let y = area.bottom() - area.height() * f;
944        painter.line_segment(
945            [pos2(x, area.top()), pos2(x, area.bottom())],
946            Stroke::new(hair, t.grid),
947        );
948        painter.line_segment(
949            [pos2(area.left(), y), pos2(area.right(), y)],
950            Stroke::new(hair, t.grid),
951        );
952    }
953    if let Some(bins) = histogram.filter(|b| !b.is_empty()) {
954        let max = bins.iter().copied().fold(0.0f32, f32::max);
955        let h = crate::histogram::heights(bins, max, true);
956        let n = h.len() as f32;
957        let fill = t.grid.gamma_multiply(0.6);
958        for (i, v) in h.iter().enumerate() {
959            let x0 = area.left() + area.width() * i as f32 / n;
960            let x1 = area.left() + area.width() * (i + 1) as f32 / n;
961            let top = area.bottom() - area.height() * v;
962            painter.rect_filled(
963                Rect::from_min_max(pos2(x0, top), pos2(x1, area.bottom())),
964                0.0,
965                fill,
966            );
967        }
968    }
969    painter.line_segment(
970        [area.left_bottom(), area.right_top()],
971        Stroke::new(1.0, t.identity),
972    );
973    let line_color = color.unwrap_or(t.line);
974    if points.len() >= 2 {
975        let samples = (area.width().round() as usize).clamp(32, 1024);
976        let line: Vec<Pos2> = (0..=samples)
977            .map(|s| {
978                let x = s as f32 / samples as f32;
979                map.to_screen([x, spline.eval(points, x).clamp(0.0, 1.0)])
980            })
981            .collect();
982        painter.add(Shape::line(line, Stroke::new(1.5, line_color)));
983    }
984    let picked = pick.and_then(|p| {
985        let x = p.x.clamp(0.0, 1.0);
986        let at = map.to_screen([x, 0.0]).x;
987        painter.line_segment(
988            [pos2(at, area.top()), pos2(at, area.bottom())],
989            Stroke::new(1.0, t.pick),
990        );
991        if points.len() >= 2 {
992            let y = spline.eval(points, x).clamp(0.0, 1.0);
993            painter.circle_stroke(map.to_screen([x, y]), 3.0, Stroke::new(1.0, t.pick));
994        }
995        nearest(points, x, PICK_TOLERANCE)
996    });
997    let hovered = response
998        .hover_pos()
999        .and_then(|pos| {
1000            points
1001                .iter()
1002                .enumerate()
1003                .map(|(i, p)| (i, map.to_screen(*p).distance(pos)))
1004                .filter(|(_, d)| *d <= HIT)
1005                .min_by(|a, b| a.1.total_cmp(&b.1))
1006        })
1007        .map(|(i, _)| i);
1008    for (i, p) in points.iter().enumerate() {
1009        let c = map.to_screen(*p);
1010        let selected = mem.selected == Some(i);
1011        let lit = selected || picked == Some(i) || hovered == Some(i);
1012        let r = if lit { 5.0 } else { 4.0 };
1013        if selected {
1014            painter.circle_filled(c, r, t.point_selected);
1015        } else {
1016            painter.circle_filled(c, r, t.background);
1017            let ring = if lit { t.point_selected } else { t.point };
1018            painter.circle_stroke(c, r, Stroke::new(1.5, ring));
1019        }
1020    }
1021    if response.has_focus() {
1022        egui_pop_core::focus::own_ring(&response.ctx, response.id);
1023    }
1024    if egui_pop_core::focus::shows_ring(response) {
1025        painter.rect_stroke(
1026            rect,
1027            radius,
1028            Stroke::new(2.0, tokens.focus_ring),
1029            StrokeKind::Inside,
1030        );
1031    }
1032}
1033
1034/// What the editor shows, for screen readers.
1035fn value_text(ctx: &egui::Context, points: &[[f32; 2]], selected: Option<usize>) -> String {
1036    let n = Arg::from(points.len());
1037    match selected.and_then(|i| points.get(i).map(|p| (i, p))) {
1038        Some((i, p)) => {
1039            let pc = |v: f32| strings::number(ctx, f64::from(v) * 100.0, 0);
1040            strings::tr_with(
1041                ctx,
1042                &crate::strings::CURVE_VALUE_SELECTED,
1043                &[
1044                    ("point", (i + 1).into()),
1045                    ("points", n),
1046                    ("input", Arg::Str(&pc(p[0]))),
1047                    ("output", Arg::Str(&pc(p[1]))),
1048                ],
1049            )
1050        }
1051        None => strings::tr_with(ctx, &crate::strings::CURVE_VALUE, &[("points", n)]),
1052    }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057    use super::*;
1058
1059    #[test]
1060    fn splines_go_through_their_points_and_stay_flat_past_the_ends() {
1061        let pts = vec![[0.1f32, 0.2], [0.5, 0.7], [0.9, 0.8]];
1062        for s in [&Linear as &dyn Spline, &MonotoneCubic] {
1063            for p in &pts {
1064                assert!((s.eval(&pts, p[0]) - p[1]).abs() < 1e-5);
1065            }
1066            assert_eq!(s.eval(&pts, 0.0), 0.2);
1067            assert_eq!(s.eval(&pts, 1.0), 0.8);
1068        }
1069        assert!((Linear.eval(&pts, 0.3) - 0.45).abs() < 1e-5);
1070    }
1071
1072    #[test]
1073    fn the_monotone_cubic_never_overshoots() {
1074        let pts = vec![[0.0f32, 0.0], [0.4, 0.1], [0.5, 0.9], [1.0, 1.0]];
1075        let mut last = -1.0;
1076        for i in 0..=200 {
1077            let y = MonotoneCubic.eval(&pts, i as f32 / 200.0);
1078            assert!(y >= last - 1e-6, "falls at {i}: {y} < {last}");
1079            assert!((-1e-6..=1.0 + 1e-6).contains(&y));
1080            last = y;
1081        }
1082    }
1083
1084    #[test]
1085    fn points_stay_ordered_and_apart() {
1086        let mut pts = identity();
1087        assert_eq!(insert(&mut pts, [0.5, 0.6]), Some(1));
1088        assert_eq!(insert(&mut pts, [0.505, 0.6]), None, "too close");
1089        assert_eq!(moved(&pts, 1, [2.0, -1.0]), [1.0 - MIN_GAP, 0.0]);
1090        assert_eq!(moved(&pts, 0, [0.7, 0.5]), [0.5 - MIN_GAP, 0.5]);
1091        assert_eq!(nearest(&pts, 0.52, 0.04), Some(1));
1092        assert_eq!(nearest(&pts, 0.3, 0.04), None);
1093    }
1094}