Skip to main content

egui_pop_viewport/
change.rs

1//! What the image tools share: the change a tool proposes, the hook that
2//! sees it before it is written, and the value's form in a step's
3//! arguments.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! The histogram's drag, the curve editor, the colour wheels, the zoom
9//! control and the navigator work alike, after the sliders
10//! (`egui_pop_core::slider`): each change is a [`Change`] (`from`, `to`,
11//! the [`Cause`], and whether the gesture is `done`), seen by the tool's
12//! `on_change` hook before it is written. The hook answers a
13//! [`Verdict`]: allow, veto, or redirect to another value. A drag's
14//! frames come with `done: false`; its end comes once more, from the
15//! value before the drag, with `done: true`, and a veto then puts the
16//! value back. Escape during a drag puts it back with no trace.
17//!
18//! [`StepValue`] gives each tool's value a JSON form, so that an
19//! application can run the finished changes as steps (ADR 0011; the
20//! `egui-pop-imaging` crate does it).
21
22use std::fmt;
23
24use serde_json::{Value as Json, json};
25
26pub use crate::hooks::Verdict;
27use crate::view::{View, Zoom};
28
29/// What made a tool's value change.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum Cause {
32    /// The pointer dragged (a point, a puck, the histogram, the frame).
33    Drag,
34    /// A key, when the tool has the focus.
35    Key,
36    /// The wheel.
37    Wheel,
38    /// A value typed (the luminance slider's entry).
39    Typed,
40    /// A point added.
41    Add,
42    /// A point deleted.
43    Delete,
44    /// Back to the default.
45    Reset,
46    /// The value picked under the pointer in the image (targeted
47    /// adjustment).
48    Pick,
49    /// A click that sets the value at once (the picker, the navigator).
50    Click,
51    /// A button or a menu of the tool (zoom in, fit).
52    Command,
53    /// An assistive technology's action (increment, decrement, set).
54    Access,
55}
56
57impl Cause {
58    /// Its name in step arguments (`drag`).
59    pub fn name(self) -> &'static str {
60        match self {
61            Cause::Drag => "drag",
62            Cause::Key => "key",
63            Cause::Wheel => "wheel",
64            Cause::Typed => "typed",
65            Cause::Add => "add",
66            Cause::Delete => "delete",
67            Cause::Reset => "reset",
68            Cause::Pick => "pick",
69            Cause::Click => "click",
70            Cause::Command => "command",
71            Cause::Access => "access",
72        }
73    }
74
75    /// The cause of a slider's change (the wheels' luminance).
76    pub fn of_slider(c: egui_pop_core::slider::Cause) -> Cause {
77        use egui_pop_core::slider::Cause as S;
78        match c {
79            S::Drag => Cause::Drag,
80            S::Key => Cause::Key,
81            S::Wheel => Cause::Wheel,
82            S::Typed => Cause::Typed,
83            S::Reset => Cause::Reset,
84            S::Access => Cause::Access,
85        }
86    }
87}
88
89/// A change a tool proposes, or made.
90#[derive(Clone, Debug, PartialEq)]
91pub struct Change<T> {
92    pub from: T,
93    pub to: T,
94    pub cause: Cause,
95    /// The gesture is over: every change but a drag's frames. A drag's
96    /// end comes as one done change from the value before it.
97    pub done: bool,
98}
99
100/// What a hook is: it sees a change and answers a verdict.
101type HookFn<'a, T> = dyn FnMut(&Change<T>) -> Verdict<T> + 'a;
102
103/// A hook seeing each change of a tool before it is written.
104pub(crate) struct Hook<'a, T>(pub(crate) Box<HookFn<'a, T>>);
105
106impl<T> fmt::Debug for Hook<'_, T> {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.write_str("Hook")
109    }
110}
111
112impl<'a, T> Hook<'a, T> {
113    pub(crate) fn new(hook: impl FnMut(&Change<T>) -> Verdict<T> + 'a) -> Hook<'a, T> {
114        Hook(Box::new(hook))
115    }
116}
117
118/// The change as the hook leaves it; `None` when vetoed.
119pub(crate) fn decide<T: Clone>(
120    hook: &mut Option<Hook<'_, T>>,
121    change: Change<T>,
122) -> Option<Change<T>> {
123    match hook.as_mut().map_or(Verdict::Allow, |h| (h.0)(&change)) {
124        Verdict::Allow => Some(change),
125        Verdict::Veto => None,
126        Verdict::Redirect(to) => Some(Change { to, ..change }),
127    }
128}
129
130/// A tool's value in a step's arguments and result.
131pub trait StepValue: Clone + PartialEq + Sized {
132    /// The value as JSON.
133    fn to_json(&self) -> Json;
134    /// The value read back from JSON (a redirect, a run-hook's result);
135    /// `None` when it is not one.
136    fn from_json(v: &Json) -> Option<Self>;
137}
138
139/// A number of a JSON value as `f32`.
140pub(crate) fn json_f32(v: &Json) -> Option<f32> {
141    v.as_f64().map(|x| x as f32)
142}
143
144/// Curve points, `[[x, y], ...]`.
145impl StepValue for Vec<[f32; 2]> {
146    fn to_json(&self) -> Json {
147        Json::Array(self.iter().map(|p| json!([p[0], p[1]])).collect())
148    }
149
150    fn from_json(v: &Json) -> Option<Self> {
151        v.as_array()?
152            .iter()
153            .map(|p| Some([json_f32(p.get(0)?)?, json_f32(p.get(1)?)?]))
154            .collect()
155    }
156}
157
158/// A view, `{"zoom": "fit" | <physical pixels per image pixel>,
159/// "center": [x, y]}`.
160impl StepValue for View {
161    fn to_json(&self) -> Json {
162        let zoom = match self.zoom {
163            Zoom::Fit => json!("fit"),
164            Zoom::Px(z) => json!(z),
165        };
166        json!({ "zoom": zoom, "center": [self.center[0], self.center[1]] })
167    }
168
169    fn from_json(v: &Json) -> Option<Self> {
170        let c = v.get("center")?;
171        let center = [c.get(0)?.as_f64()?, c.get(1)?.as_f64()?];
172        let zoom = match v.get("zoom")? {
173            Json::String(s) if s == "fit" => Zoom::Fit,
174            z => Zoom::Px(z.as_f64()?),
175        };
176        Some(View { zoom, center })
177    }
178}
179
180/// How finely a gesture moves: the sliders' modifiers (Ctrl or Cmd ten
181/// times finer, Shift ten times coarser; `egui_pop_core::slider::Gestures`).
182pub(crate) fn scale(ui: &egui::Ui) -> f32 {
183    let g = egui_pop_core::slider::gestures(ui.ctx());
184    let mods = ui.input(|i| i.modifiers);
185    let held = |m: egui::Modifiers| m.any() && mods.matches_logically(m);
186    if held(g.fine) {
187        0.1
188    } else if held(g.coarse) {
189        10.0
190    } else {
191        1.0
192    }
193}
194
195/// A drag's effect in a frame.
196#[derive(Clone, Copy, Debug, PartialEq)]
197pub(crate) enum Gesture {
198    None,
199    /// The pointer moved, in points, scaled by the modifiers.
200    Moved(egui::Vec2),
201    /// The drag ended.
202    Ended,
203    /// The cancel key ended it: put the value back, no trace.
204    Cancelled,
205}
206
207/// What a drag on `response` did this frame (its start is
208/// `response.drag_started()`).
209pub(crate) fn gesture(ui: &egui::Ui, response: &egui::Response) -> Gesture {
210    if response.drag_stopped() {
211        // egui ends a drag on the cancel key.
212        let cancel = egui_pop_core::slider::gestures(ui.ctx()).cancel;
213        return if egui_pop_core::focus::cancel_pressed(ui.ctx(), cancel) {
214            Gesture::Cancelled
215        } else {
216            Gesture::Ended
217        };
218    }
219    if response.dragged() {
220        let d = response.drag_delta() * scale(ui);
221        if d != egui::Vec2::ZERO {
222            return Gesture::Moved(d);
223        }
224    }
225    Gesture::None
226}
227
228/// Allocates a tool's rect and senses it under an id of its own, keyed by
229/// `salt` in `ui`'s id, rather than egui's automatic id. The automatic id
230/// follows how many widgets came before in every enclosing `Ui`: a widget
231/// appearing or going anywhere above while the tool is dragged (a mark, a
232/// card, a button shown once a value moves) would give the tool another
233/// id, and egui would end its drag.
234pub(crate) fn allocate(
235    ui: &mut egui::Ui,
236    size: egui::Vec2,
237    sense: egui::Sense,
238    salt: impl std::hash::Hash + std::fmt::Debug,
239) -> (egui::Rect, egui::Response) {
240    let (_, outer) = ui.allocate_space(size);
241    let rect = ui.layout().align_size_within_rect(size, outer);
242    let response = ui.interact(rect, tool_id(ui, salt), sense);
243    (rect, response)
244}
245
246/// The id [`allocate`] senses a tool under.
247pub(crate) fn tool_id(ui: &egui::Ui, salt: impl std::hash::Hash + std::fmt::Debug) -> egui::Id {
248    ui.make_persistent_id(("egui_pop.viewport.tool", salt))
249}
250
251/// Keeps the arrow keys on a focused tool (egui would move the focus).
252pub(crate) fn lock_arrows(ui: &egui::Ui, id: egui::Id) {
253    ui.memory_mut(|m| {
254        m.set_focus_lock_filter(
255            id,
256            egui::EventFilter {
257                horizontal_arrows: true,
258                vertical_arrows: true,
259                escape: false,
260                ..Default::default()
261            },
262        );
263    });
264}
265
266/// The arrow keys pressed this frame on a focused tool: `[right - left,
267/// up - down]`.
268pub(crate) fn arrows(ui: &egui::Ui) -> [f32; 2] {
269    use egui::Key;
270    ui.input(|i| {
271        let n = |k: Key| i.num_presses(k) as f32;
272        [
273            n(Key::ArrowRight) - n(Key::ArrowLeft),
274            n(Key::ArrowUp) - n(Key::ArrowDown),
275        ]
276    })
277}
278
279/// The increment and decrement actions an assistive technology asked
280/// of `id` this frame: increments minus decrements.
281pub(crate) fn access_steps(ui: &egui::Ui, id: egui::Id) -> f32 {
282    use egui::accesskit::Action;
283    ui.input(|i| {
284        i.num_accesskit_action_requests(id, Action::Increment) as f32
285            - i.num_accesskit_action_requests(id, Action::Decrement) as f32
286    })
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn values_round_trip_through_json() {
295        let pts = vec![[0.0f32, 0.0], [0.5, 0.25], [1.0, 1.0]];
296        assert_eq!(Vec::<[f32; 2]>::from_json(&pts.to_json()), Some(pts));
297        let v = View::at(0.5, [100.0, 200.0]);
298        assert_eq!(View::from_json(&v.to_json()), Some(v));
299        assert_eq!(View::from_json(&View::fit().to_json()), Some(View::fit()));
300        assert_eq!(View::from_json(&json!(3)), None);
301    }
302
303    #[test]
304    fn the_hook_allows_vetoes_or_redirects() {
305        let c = Change {
306            from: 1.0f32,
307            to: 2.0,
308            cause: Cause::Key,
309            done: true,
310        };
311        assert_eq!(decide(&mut None, c.clone()).map(|c| c.to), Some(2.0));
312        let mut veto = Some(Hook::new(|_: &Change<f32>| Verdict::Veto));
313        assert_eq!(decide(&mut veto, c.clone()), None);
314        let mut snap = Some(Hook::new(|c: &Change<f32>| {
315            Verdict::Redirect(c.to.round() + 1.0)
316        }));
317        assert_eq!(decide(&mut snap, c).map(|c| c.to), Some(3.0));
318    }
319}