Skip to main content

egui_pop_core/pointer/
view.rs

1//! A view's pointer gestures (the image viewport's, the node graph's, the
2//! library's comparison): what the profile in force makes the wheel, a
3//! scroll, a pinch, each click, double click and drag do, and the one
4//! wheel path every zoomable view reads ([`view_wheel`]), so the same
5//! gesture does the same thing in each.
6//!
7//! The image canvases share more: the view model ([`View`], [`Mapping`],
8//! the zoom ladder) and the gestures themselves ([`CanvasGestures`], run
9//! over a [`ZoomPan`] by [`pan`], [`click`], [`double_click`], [`wheel`]
10//! and [`keys`]), so the image viewport and each pane of the library's
11//! comparison change their view the same way.
12//!
13//! <div class="warning">Experimental: may change in any release
14//! (docs/stability.md).</div>
15
16use egui::{Context, Modifiers, PointerButton, Vec2};
17
18use super::{MODIFIER_SETS, WheelInput, button, chord_index, index, take_wheel, wheel_inputs};
19use crate::model::ids::CommandId;
20use crate::model::keymap::{Button, Pointer};
21use crate::model::pointer::{PointerMap, gesture};
22
23mod canvas;
24mod model;
25
26pub use canvas::{
27    CanvasGestures, Cause, GestureState, Phase, ZoomPan, canvas_gestures, click, click_view,
28    double_click, keys, pan, pan_key_held, set_canvas_gestures, wheel,
29};
30pub use model::{
31    MAX_ZOOM, MIN_ZOOM, Mapping, View, ZOOM_LADDER, Zoom, fit_zoom, wheel_zoom, zoom_in, zoom_out,
32};
33
34/// What a pointer gesture does to a view.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub enum ViewAction {
37    /// Nothing: the wheel goes to the panel around.
38    #[default]
39    Nothing,
40    /// Zooms around the pointer, holding at the stops (fit, 100 %).
41    Zoom,
42    /// Zooms around the pointer without stops.
43    ZoomFree,
44    /// Pans by the wheel's motion, or following a drag.
45    Pan,
46    /// Pans horizontally by the wheel's motion.
47    PanX,
48    /// Pans vertically by the wheel's motion.
49    PanY,
50    /// 100 %, 200 %, fit, around the pointer.
51    ZoomCycle,
52    /// Fits the content.
53    Fit,
54    /// Fit, or 100 % around the pointer when fitting.
55    ZoomToggle,
56    /// Asks the application to leave the view (a signal; the view does
57    /// not change).
58    Leave,
59}
60
61impl ViewAction {
62    /// The action of a gesture command, in either view's scope.
63    pub fn of(command: &CommandId) -> ViewAction {
64        let pairs = [
65            (gesture::IMAGE_ZOOM, ViewAction::Zoom),
66            (gesture::IMAGE_ZOOM_FREE, ViewAction::ZoomFree),
67            (gesture::IMAGE_PAN, ViewAction::Pan),
68            (gesture::IMAGE_PAN_X, ViewAction::PanX),
69            (gesture::IMAGE_PAN_Y, ViewAction::PanY),
70            (gesture::IMAGE_ZOOM_CYCLE, ViewAction::ZoomCycle),
71            (gesture::IMAGE_FIT, ViewAction::Fit),
72            (gesture::IMAGE_ZOOM_TOGGLE, ViewAction::ZoomToggle),
73            (gesture::GRAPH_ZOOM, ViewAction::Zoom),
74            (gesture::GRAPH_PAN, ViewAction::Pan),
75            (gesture::GRAPH_PAN_X, ViewAction::PanX),
76            (gesture::GRAPH_PAN_Y, ViewAction::PanY),
77            (gesture::GRAPH_FIT, ViewAction::Fit),
78        ];
79        pairs
80            .into_iter()
81            .find(|(c, _)| c == command)
82            .map_or(ViewAction::Nothing, |(_, a)| a)
83    }
84
85    /// A zoom of any kind.
86    pub fn zooms(self) -> bool {
87        matches!(self, ViewAction::Zoom | ViewAction::ZoomFree)
88    }
89
90    /// A pan by the wheel of any kind.
91    pub fn pans(self) -> bool {
92        matches!(self, ViewAction::Pan | ViewAction::PanX | ViewAction::PanY)
93    }
94}
95
96/// A view's pointer gestures: per set of modifiers ([`index`]), what
97/// the wheel, a scroll and a pinch do, what a click and a double click
98/// of each button do, and which buttons' drags pan.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub struct ViewGestures {
101    pub wheel: [ViewAction; MODIFIER_SETS],
102    pub scroll: [ViewAction; MODIFIER_SETS],
103    pub pinch: [ViewAction; MODIFIER_SETS],
104    /// Per set of modifiers, per button (`Button::ALL`'s order).
105    pub click: [[ViewAction; 5]; MODIFIER_SETS],
106    pub double_click: [[ViewAction; 5]; MODIFIER_SETS],
107    pub drag_pan: [[bool; 5]; MODIFIER_SETS],
108}
109
110/// A button's place in [`ViewGestures`]' per-button tables.
111pub fn slot(b: Button) -> usize {
112    Button::ALL.iter().position(|x| *x == b).unwrap_or(0)
113}
114
115impl ViewGestures {
116    /// A scope's bindings in a pointer map.
117    pub fn from_map(map: &PointerMap, scope: &str) -> ViewGestures {
118        let mut g = ViewGestures::default();
119        for b in map.scope(scope) {
120            let Some(p) = b.chord.pointer() else { continue };
121            let i = chord_index(&b.chord);
122            let action = ViewAction::of(&b.command);
123            match p {
124                Pointer::Wheel => g.wheel[i] = action,
125                Pointer::Scroll => g.scroll[i] = action,
126                Pointer::Pinch => g.pinch[i] = action,
127                Pointer::Click(button) => g.click[i][slot(button)] = action,
128                Pointer::DoubleClick(button) => g.double_click[i][slot(button)] = action,
129                Pointer::Drag(button) => g.drag_pan[i][slot(button)] = action == ViewAction::Pan,
130            }
131        }
132        g
133    }
134
135    /// What a wheel, scroll or pinch input does.
136    pub fn wheel_action(&self, input: &WheelInput) -> ViewAction {
137        let i = index(input.modifiers);
138        match input.pointer {
139            Pointer::Wheel => self.wheel[i],
140            Pointer::Scroll => self.scroll[i],
141            Pointer::Pinch => self.pinch[i],
142            _ => ViewAction::Nothing,
143        }
144    }
145
146    /// Whether a drag of this button with these modifiers pans.
147    pub fn drag_pans(&self, b: PointerButton, modifiers: Modifiers) -> bool {
148        self.drag_pan[index(modifiers)][slot(button(b))]
149    }
150
151    /// What a click of this button with these modifiers does.
152    pub fn click_action(&self, b: PointerButton, modifiers: Modifiers) -> ViewAction {
153        self.click[index(modifiers)][slot(button(b))]
154    }
155
156    /// What a double click of this button with these modifiers does.
157    pub fn double_click_action(&self, b: PointerButton, modifiers: Modifiers) -> ViewAction {
158        self.double_click[index(modifiers)][slot(button(b))]
159    }
160}
161
162/// How fast the wheel zooms: the factor per point of scroll is
163/// `exp(points × WHEEL_RATE)` ([`wheel_factor`]).
164pub const WHEEL_RATE: f64 = 0.0015;
165
166/// The zoom factor of a wheel motion of `points` (positive zooms in).
167pub fn wheel_factor(points: f32) -> f64 {
168    (f64::from(points) * WHEEL_RATE).exp()
169}
170
171/// One wheel, scroll or pinch input as a view's gestures read it.
172#[derive(Clone, Copy, Debug, PartialEq)]
173pub enum ViewWheel {
174    /// Zoom around the pointer by [`wheel_factor`]`(points)`; `free`:
175    /// without the view's stops (a free zoom, a pinch).
176    Zoom {
177        points: f32,
178        free: bool,
179        pinch: bool,
180    },
181    /// Pan by this motion, in points.
182    Pan(Vec2),
183}
184
185/// This pass's wheel, scroll and pinch inputs as `gestures` say, in
186/// order; the wheel is taken from the panel around (call it only when
187/// the view is hovered). The one wheel path of the zoomable views.
188pub fn view_wheel(ctx: &Context, gestures: &ViewGestures) -> Vec<ViewWheel> {
189    let inputs = wheel_inputs(ctx);
190    // The view takes the wheel: the panel around it does not scroll.
191    take_wheel(ctx);
192    inputs
193        .iter()
194        .filter_map(|input| wheel_step(gestures, input))
195        .collect()
196}
197
198/// What one input does with `gestures` ([`view_wheel`]).
199pub fn wheel_step(gestures: &ViewGestures, input: &WheelInput) -> Option<ViewWheel> {
200    let action = gestures.wheel_action(input);
201    let pinch = input.pointer == Pointer::Pinch;
202    match action {
203        ViewAction::Zoom | ViewAction::ZoomFree => Some(ViewWheel::Zoom {
204            // A pinch's factor as the wheel's motion.
205            points: if pinch {
206                (f64::from(input.zoom).ln() / WHEEL_RATE) as f32
207            } else {
208                input.along_y()
209            },
210            free: action == ViewAction::ZoomFree || pinch,
211            pinch,
212        }),
213        ViewAction::Pan => Some(ViewWheel::Pan(input.delta)),
214        ViewAction::PanX => Some(ViewWheel::Pan(Vec2::new(input.along_x(), 0.0))),
215        ViewAction::PanY => Some(ViewWheel::Pan(Vec2::new(0.0, input.along_y()))),
216        _ => None,
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::model::pointer::{self, SCOPE_IMAGE};
224
225    fn wheel(modifiers: Modifiers, y: f32) -> WheelInput {
226        WheelInput {
227            pointer: Pointer::Wheel,
228            modifiers,
229            delta: Vec2::new(0.0, y),
230            zoom: 1.0,
231        }
232    }
233
234    #[test]
235    fn the_profile_says_what_the_wheel_does() {
236        let darktable = PointerMap::from_profile(pointer::profile("darktable").unwrap());
237        let g = ViewGestures::from_map(&darktable, SCOPE_IMAGE);
238        assert_eq!(
239            wheel_step(&g, &wheel(Modifiers::NONE, 50.0)),
240            Some(ViewWheel::Zoom {
241                points: 50.0,
242                free: false,
243                pinch: false
244            })
245        );
246        let document = PointerMap::from_profile(pointer::default_profile());
247        let g = ViewGestures::from_map(&document, SCOPE_IMAGE);
248        assert_eq!(
249            wheel_step(&g, &wheel(Modifiers::NONE, 50.0)),
250            Some(ViewWheel::Pan(Vec2::new(0.0, 50.0)))
251        );
252        assert!(matches!(
253            wheel_step(&g, &wheel(Modifiers::COMMAND, 50.0)),
254            Some(ViewWheel::Zoom { .. })
255        ));
256    }
257}