Skip to main content

egui_pop_core/pointer/view/
canvas.rs

1//! The gestures of a zoomable image canvas, implemented once: the image
2//! viewport (`egui_pop_viewport::Viewport`) and each pane of the library's
3//! comparison run these functions over their own [`ZoomPan`], so the
4//! same gesture makes the same [`View`] change in each.
5//!
6//! - **a drag** pans as the profile says (any button with the pan key,
7//!   Space, held);
8//! - **a click** and **a double click** run the profile's view action
9//!   (darktable's middle click cycles the zoom);
10//! - **the wheel**, a scroll and a pinch zoom around the pointer (holding
11//!   at 100 % while the wheel goes on, unless free) or pan;
12//! - **the keys** (with the keyboard): a ladder step up or down, fit,
13//!   100 %, 200 %, and the arrows to pan.
14
15use egui::{Context, Key, Modifiers, PointerButton, Pos2, Response, Ui, Vec2};
16
17use super::model::{self, Mapping, View};
18use super::{ViewAction, ViewGestures, ViewWheel, slot, view_wheel, wheel_factor};
19use crate::model::keymap::Button;
20use crate::model::pointer::{ImageDoubleClick, PointerMap, SCOPE_IMAGE};
21use crate::pointer::claim::{self, Secondary};
22use crate::state::Slot;
23
24/// What made a view change.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Cause {
27    Pan,
28    Wheel,
29    Pinch,
30    Key,
31    DoubleClick,
32    /// A click the pointer profile gives a view action (a middle click
33    /// cycling the zoom).
34    Click,
35    /// The application called the view (a command).
36    Command,
37}
38
39impl Cause {
40    pub fn name(self) -> &'static str {
41        match self {
42            Cause::Pan => "pan",
43            Cause::Wheel => "wheel",
44            Cause::Pinch => "pinch",
45            Cause::Key => "key",
46            Cause::DoubleClick => "double-click",
47            Cause::Click => "click",
48            Cause::Command => "command",
49        }
50    }
51}
52
53/// Where a change stands in its gesture.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum Phase {
56    /// A gesture starts (a drag); the value is the one before it.
57    Begin,
58    /// A gesture goes on.
59    Update,
60    /// A gesture ends; the value is the final one.
61    End,
62    /// A gesture is cancelled; the value is the one before it, restored.
63    Cancel,
64    /// A change in one step (a wheel notch, a key, a double click, a
65    /// command).
66    Once,
67}
68
69impl Phase {
70    pub fn name(self) -> &'static str {
71        match self {
72            Phase::Begin => "begin",
73            Phase::Update => "update",
74            Phase::End => "end",
75            Phase::Cancel => "cancel",
76            Phase::Once => "once",
77        }
78    }
79}
80
81/// An image canvas's gestures, as data so an input profile can remap
82/// them: the pointer's from the profile in force, the keys as by default.
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub struct CanvasGestures {
85    /// The button that drags a handle and the comparison's split, and
86    /// clicks a handle.
87    pub pan_button: PointerButton,
88    /// Held: a drag pans anywhere, handles included.
89    pub pan_key: Key,
90    /// During a gesture: back to where it started, no trace.
91    pub cancel: Key,
92    /// The pointer's gestures on the canvas (the profile's
93    /// `canvas.image` scope, a plain primary double click from its
94    /// option when the scope binds none).
95    pub pointer: ViewGestures,
96    /// Keys when the canvas has the focus: the next ladder step up.
97    pub zoom_in: &'static [Key],
98    /// The next ladder step down.
99    pub zoom_out: &'static [Key],
100    /// Fit the image.
101    pub fit: Key,
102    /// 100 %.
103    pub actual: Key,
104    /// 200 %.
105    pub double: Key,
106    /// Held with the arrows: pan five times further.
107    pub coarse: Modifiers,
108    /// Held: shows the "before" image (a quasimode).
109    pub before: Key,
110}
111
112impl CanvasGestures {
113    /// What a pointer map says, the keys as by default.
114    pub fn from_map(map: &PointerMap) -> CanvasGestures {
115        let mut pointer = ViewGestures::from_map(map, SCOPE_IMAGE);
116        let primary = &mut pointer.double_click[0][slot(Button::Primary)];
117        if *primary == ViewAction::Nothing {
118            *primary = match map.options.image_double_click {
119                ImageDoubleClick::Fit => ViewAction::Fit,
120                ImageDoubleClick::Leave => ViewAction::Leave,
121                ImageDoubleClick::Nothing => ViewAction::Nothing,
122            };
123        }
124        CanvasGestures {
125            pan_button: PointerButton::Primary,
126            pan_key: Key::Space,
127            cancel: Key::Escape,
128            pointer,
129            zoom_in: &[Key::Plus, Key::Equals],
130            zoom_out: &[Key::Minus],
131            fit: Key::Num0,
132            actual: Key::Num1,
133            double: Key::Num2,
134            coarse: Modifiers::SHIFT,
135            before: Key::Backslash,
136        }
137    }
138}
139
140impl Default for CanvasGestures {
141    /// The default pointer profile's.
142    fn default() -> Self {
143        CanvasGestures::from_map(&crate::pointer::default_map())
144    }
145}
146
147const GESTURES: Slot<CanvasGestures> = Slot::new("viewport.gestures");
148
149/// The image canvases' gestures in a context: those set, else the
150/// pointer profile's.
151pub fn canvas_gestures(ctx: &Context) -> CanvasGestures {
152    GESTURES
153        .get(ctx)
154        .unwrap_or_else(|| CanvasGestures::from_map(&crate::pointer::map(ctx)))
155}
156
157/// Sets the image canvases' gestures in a context, over the pointer
158/// profile's.
159pub fn set_canvas_gestures(ctx: &Context, gestures: CanvasGestures) {
160    GESTURES.set(ctx, gestures);
161}
162
163/// What a canvas keeps between frames for its gestures.
164#[derive(Clone, Copy, Debug, Default, PartialEq)]
165pub struct GestureState {
166    /// A pan going on, and the view it started from (Escape goes back
167    /// to it).
168    pub pan: Option<View>,
169    /// The wheel landed on 100 % and is held there until it stops.
170    pub detent: bool,
171}
172
173/// A zoomable, pannable view the canvas gestures drive: its view and
174/// mapping this frame, and what it does with a change.
175pub trait ZoomPan {
176    /// The view shown now.
177    fn view(&self) -> View;
178    /// The mapping of the view shown now.
179    fn mapping(&self) -> Mapping;
180    /// The gestures' memory between frames.
181    fn gesture(&mut self) -> &mut GestureState;
182    /// Proposes a change; returns whether it was applied (a hook may
183    /// refuse it). A `Cancel` is always applied.
184    fn change(&mut self, to: View, cause: Cause, phase: Phase) -> bool;
185    /// A gesture begins or ends without a change of its own.
186    fn signal(&mut self, phase: Phase, cause: Cause) {
187        let _ = (phase, cause);
188    }
189    /// The profile's "leave the view" ([`ViewAction::Leave`]).
190    fn leave(&mut self) {}
191    /// A double click at `at`: the view it leads to. By default, the
192    /// profile's action (`default`); a hook may run it or not.
193    fn double_click(
194        &mut self,
195        at: Pos2,
196        default: &mut dyn FnMut() -> Option<View>,
197    ) -> Option<View> {
198        let _ = at;
199        default()
200    }
201}
202
203/// The buttons a gesture can use.
204const BUTTONS: [PointerButton; 5] = [
205    PointerButton::Primary,
206    PointerButton::Secondary,
207    PointerButton::Middle,
208    PointerButton::Extra1,
209    PointerButton::Extra2,
210];
211
212/// Whether the pan key is held over the canvas (a drag then pans,
213/// whatever is under the pointer).
214pub fn pan_key_held(ui: &Ui, response: &Response, g: &CanvasGestures) -> bool {
215    response.hovered() && ui.input(|i| i.key_down(g.pan_key))
216}
217
218/// A widget over the image (an overlay of the application's) claimed
219/// this gesture of the secondary button where it started: the profile's
220/// binding leaves it to that widget.
221fn claimed(ui: &Ui, b: PointerButton, gesture: Secondary) -> bool {
222    b == PointerButton::Secondary && claim::claimed(ui.ctx(), gesture).is_some()
223}
224
225/// The button of a drag that starts this frame and pans with the keys
226/// held, as the profile says (or any button with the pan key held).
227fn pan_starts(ui: &Ui, response: &Response, g: &CanvasGestures, pan_key: bool) -> bool {
228    if pan_key && response.drag_started() {
229        return true;
230    }
231    let modifiers = ui.input(|i| i.modifiers);
232    BUTTONS.into_iter().any(|b| {
233        response.drag_started_by(b)
234            && g.pointer.drag_pans(b, modifiers)
235            && !claimed(ui, b, Secondary::Drag)
236    })
237}
238
239/// A drag that pans (as the profile says, or with the pan key held):
240/// the image follows the pointer; Escape puts it back.
241pub fn pan(ui: &Ui, response: &Response, g: &CanvasGestures, pan_key: bool, t: &mut impl ZoomPan) {
242    if pan_starts(ui, response, g, pan_key) && t.gesture().pan.is_none() {
243        t.gesture().pan = Some(t.view());
244        t.signal(Phase::Begin, Cause::Pan);
245    }
246    let Some(start) = t.gesture().pan else {
247        return;
248    };
249    if crate::focus::cancel_pressed(ui.ctx(), g.cancel) {
250        t.gesture().pan = None;
251        t.change(start, Cause::Pan, Phase::Cancel);
252        return;
253    }
254    let delta = response.drag_delta();
255    if delta != Vec2::ZERO {
256        let to = t.mapping().panned(delta);
257        t.change(to, Cause::Pan, Phase::Update);
258    }
259    if response.drag_stopped() || !response.dragged() && !response.drag_started() {
260        t.gesture().pan = None;
261        t.signal(Phase::End, Cause::Pan);
262    }
263}
264
265/// The view a click-like action leads to from `view` (`None`: no
266/// change).
267pub fn click_view(action: ViewAction, at: Pos2, view: &View, m: &Mapping) -> Option<View> {
268    match action {
269        ViewAction::Fit => Some(View::fit()),
270        ViewAction::ZoomToggle => Some(if view.is_fit() {
271            m.zoom_around(at, 1.0)
272        } else {
273            View::fit()
274        }),
275        // 100 %, then 200 %, then fit (from fit or any other zoom: 100 %).
276        ViewAction::ZoomCycle => Some(if view.is_fit() {
277            m.zoom_around(at, 1.0)
278        } else if (m.zoom - 1.0).abs() < 1e-6 {
279            m.zoom_around(at, 2.0)
280        } else if (m.zoom - 2.0).abs() < 1e-6 {
281            View::fit()
282        } else {
283            m.zoom_around(at, 1.0)
284        }),
285        _ => None,
286    }
287}
288
289/// A click the profile gives a view action (a middle click cycling the
290/// zoom, a primary click toggling fit and 100 %).
291pub fn click(ui: &Ui, response: &Response, g: &CanvasGestures, t: &mut impl ZoomPan) {
292    let modifiers = ui.input(|i| i.modifiers);
293    for b in BUTTONS {
294        if !response.clicked_by(b) || claimed(ui, b, Secondary::Click) {
295            continue;
296        }
297        let action = g.pointer.click_action(b, modifiers);
298        let m = t.mapping();
299        let at = response.hover_pos().unwrap_or(m.rect.center());
300        if action == ViewAction::Leave {
301            t.leave();
302        } else if let Some(to) = click_view(action, at, &t.view(), &m) {
303            t.change(to, Cause::Click, Phase::Once);
304        }
305    }
306}
307
308/// A primary double click: the profile's view action (fit, 100 % and
309/// back, the zoom cycle, leave), through [`ZoomPan::double_click`].
310pub fn double_click(ui: &Ui, response: &Response, g: &CanvasGestures, t: &mut impl ZoomPan) {
311    if !response.double_clicked() {
312        return;
313    }
314    let modifiers = ui.input(|i| i.modifiers);
315    let action = g
316        .pointer
317        .double_click_action(PointerButton::Primary, modifiers);
318    let m = t.mapping();
319    let at = response.hover_pos().unwrap_or(m.rect.center());
320    let fit = t.view().is_fit();
321    // The default action: leaving the view is a signal, sent only when
322    // the default runs (without a hook, or when the hook calls it).
323    let mut leave = false;
324    let mut default = || match action {
325        ViewAction::Leave => {
326            leave = true;
327            None
328        }
329        ViewAction::Fit => Some(View::fit()),
330        ViewAction::ZoomToggle => Some(if fit {
331            m.zoom_around(at, 1.0)
332        } else {
333            View::fit()
334        }),
335        ViewAction::ZoomCycle => Some(if fit {
336            m.zoom_around(at, 1.0)
337        } else if (m.zoom - 1.0).abs() < 1e-6 {
338            m.zoom_around(at, 2.0)
339        } else {
340            View::fit()
341        }),
342        _ => None,
343    };
344    let to = t.double_click(at, &mut default);
345    if leave {
346        t.leave();
347    }
348    if let Some(to) = to {
349        t.change(to, Cause::DoubleClick, Phase::Once);
350    }
351}
352
353/// The wheel, a scroll and a pinch, raw, as the profile says: zoom
354/// around the pointer (holding at 100 % while the wheel goes on, unless
355/// free), or pan. Only while the canvas is hovered: the wheel is then
356/// taken from the panel around.
357pub fn wheel(ui: &Ui, response: &Response, g: &CanvasGestures, t: &mut impl ZoomPan) {
358    if !response.hovered() {
359        t.gesture().detent = false;
360        return;
361    }
362    let steps = view_wheel(ui.ctx(), &g.pointer);
363    let mut moved = false;
364    for step in steps {
365        moved = true;
366        let m = t.mapping();
367        let pointer = response.hover_pos().unwrap_or(m.rect.center());
368        match step {
369            ViewWheel::Zoom {
370                points,
371                free,
372                pinch,
373            } => {
374                let cause = if pinch { Cause::Pinch } else { Cause::Wheel };
375                if !free && t.gesture().detent {
376                    // Held on 100 % until the wheel stops.
377                    continue;
378                }
379                let z = if free {
380                    (m.zoom * wheel_factor(points)).clamp(model::MIN_ZOOM, model::MAX_ZOOM)
381                } else {
382                    model::wheel_zoom(m.zoom, points)
383                };
384                if !free {
385                    t.gesture().detent = z == 1.0 && m.zoom != 1.0;
386                }
387                t.change(m.zoom_around(pointer, z), cause, Phase::Once);
388            }
389            ViewWheel::Pan(delta) => {
390                t.change(m.panned(delta), Cause::Wheel, Phase::Once);
391            }
392        }
393    }
394    if !moved {
395        t.gesture().detent = false;
396    }
397}
398
399/// The keys, for a canvas with the keyboard (the caller says when): a
400/// ladder step up or down, fit, 100 % and 200 % around the centre, and
401/// with `arrows` the arrows pan (Shift: further). Not during a pan.
402pub fn keys(ui: &Ui, g: &CanvasGestures, arrows: bool, t: &mut impl ZoomPan) {
403    if t.gesture().pan.is_some() {
404        return;
405    }
406    let m = t.mapping();
407    let center = m.rect.center();
408    let pressed = |k: Key| ui.input(|i| i.key_pressed(k));
409    let to = if g.zoom_in.iter().any(|k| pressed(*k)) {
410        Some(m.zoom_around(center, model::zoom_in(m.zoom)))
411    } else if g.zoom_out.iter().any(|k| pressed(*k)) {
412        Some(m.zoom_around(center, model::zoom_out(m.zoom)))
413    } else if pressed(g.fit) {
414        Some(View::fit())
415    } else if pressed(g.actual) {
416        Some(m.zoom_around(center, 1.0))
417    } else if pressed(g.double) {
418        Some(m.zoom_around(center, 2.0))
419    } else if arrows {
420        let coarse = !g.coarse.is_none() && ui.input(|i| i.modifiers.matches_logically(g.coarse));
421        let step = m.rect.size() * if coarse { 0.5 } else { 0.1 };
422        let mut d = Vec2::ZERO;
423        if pressed(Key::ArrowLeft) {
424            d.x += step.x;
425        }
426        if pressed(Key::ArrowRight) {
427            d.x -= step.x;
428        }
429        if pressed(Key::ArrowUp) {
430            d.y += step.y;
431        }
432        if pressed(Key::ArrowDown) {
433            d.y -= step.y;
434        }
435        (d != Vec2::ZERO).then(|| m.panned(d))
436    } else {
437        None
438    };
439    if let Some(to) = to {
440        t.change(to, Cause::Key, Phase::Once);
441    }
442}