Skip to main content

egui_pop_core/
pointer.rs

1//! Pointer gestures in a context: the table canvases read (a
2//! [`PointerMap`]: what each pointer chord does per canvas kind, with
3//! the options in force), and the wheel read raw.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! The application API publishes the map from the keymap and the
9//! pointer profile ([`set_map`]); without it, canvases follow the
10//! default profile (Document). egui's own scrolling follows the
11//! profile's modifiers ([`apply_input_options`]) and the wheel speed
12//! ([`apply_wheel_speed`]).
13//!
14//! egui merges a pinch with Ctrl and the wheel, and turns units into
15//! points before widgets see them; a profile needs both apart, so the
16//! canvases read the raw events ([`wheel_inputs`]): a wheel in lines is
17//! `Wheel`, a scroll in points `Scroll` (unless the wheel device setting
18//! says otherwise), a pinch `Pinch`, each with its modifiers.
19//!
20//! A widget that needs the secondary button for itself claims it on its
21//! rect ([`claim`]): context menus and the canvases' profile bindings
22//! leave that click or drag to it.
23//!
24//! A draggable shows the cursor of its kind of drag ([`drag`]), hovered
25//! only when dragging is its only action by default; the widget, the
26//! profile and the kit may change it: [`drag_cursor`], or
27//! `UiPop::drag_cursor`.
28//!
29//! ```
30//! use egui_pop_core::pointer;
31//! use egui_pop_model::keymap::Pointer;
32//! use egui_pop_model::pointer::SCOPE_IMAGE;
33//!
34//! let ctx = egui::Context::default();
35//! let map = pointer::map(&ctx);
36//! assert_eq!(map.profile, "document");
37//! let ctrl_wheel = pointer::chord(egui::Modifiers::COMMAND, Pointer::Wheel);
38//! assert_eq!(map.command(SCOPE_IMAGE, &ctrl_wheel).unwrap().as_str(), "gesture.image.zoom");
39//! ```
40
41use std::sync::{Arc, LazyLock};
42
43use egui::{Context, Event, Modifiers, MouseWheelUnit, PointerButton, Vec2};
44use egui_pop_model::ids::CommandId;
45use egui_pop_model::keymap::{Button, Chord, Pointer};
46use egui_pop_model::pointer::{InputModifiers, PointerMap, WheelDevice};
47
48use crate::state::Slot;
49
50pub mod claim;
51pub mod drag;
52pub mod view;
53
54pub use claim::{Secondary, SecondaryClaim, claim_secondary, claimed};
55pub use drag::{
56    DragCursor, DragCursorFor, DragKind, HoverPolicy, cursor_icon, drag_cursor, drag_cursor_icons,
57    ghost_shown, hold_drag_cursor, hover_drag_cursor, resolve_drag_cursor, set_ghost_shown,
58};
59
60const MAP: Slot<Arc<PointerMap>> = Slot::new("core.pointer.map");
61
62static DEFAULT: LazyLock<Arc<PointerMap>> = LazyLock::new(|| Arc::new(PointerMap::default()));
63
64/// The pointer map in a context: the one published, else the default
65/// profile's.
66pub fn map(ctx: &Context) -> Arc<PointerMap> {
67    MAP.get(ctx).unwrap_or_else(default_map)
68}
69
70/// The default profile's map, without a context.
71pub fn default_map() -> Arc<PointerMap> {
72    DEFAULT.clone()
73}
74
75/// Publishes a pointer map, and makes egui's scrolling follow its
76/// modifiers and its wheel speed.
77pub fn set_map(ctx: &Context, map: PointerMap) {
78    set_shared_map(ctx, Arc::new(map));
79}
80
81/// [`set_map`] with a map shared with its publisher, who can tell it
82/// is still there ([`published`]).
83pub fn set_shared_map(ctx: &Context, map: Arc<PointerMap>) {
84    apply_input_options(ctx, &map.input);
85    apply_wheel_speed(ctx, map.wheel_speed);
86    MAP.set(ctx, map);
87}
88
89/// The map published in a context, if one was.
90pub fn published(ctx: &Context) -> Option<Arc<PointerMap>> {
91    MAP.get(ctx)
92}
93
94/// egui's modifiers of a chord's: Ctrl is Cmd on macOS, as in the
95/// keymap.
96pub fn modifiers_of(chord: &Chord) -> Modifiers {
97    Modifiers {
98        alt: chord.alt,
99        ctrl: false,
100        shift: chord.shift,
101        mac_cmd: false,
102        command: chord.ctrl,
103    }
104}
105
106/// The chord of a pointer gesture with egui's modifiers held.
107pub fn chord(modifiers: Modifiers, pointer: Pointer) -> Chord {
108    let mut c = Chord::pointer_gesture(pointer);
109    c.ctrl = modifiers.ctrl || modifiers.command || modifiers.mac_cmd;
110    c.alt = modifiers.alt;
111    c.shift = modifiers.shift;
112    c
113}
114
115/// The four modifiers as an index (Ctrl or Cmd 1, Alt 2, Shift 4): the
116/// tables canvases keep per set of modifiers.
117pub fn index(modifiers: Modifiers) -> usize {
118    usize::from(modifiers.ctrl || modifiers.command || modifiers.mac_cmd)
119        | usize::from(modifiers.alt) << 1
120        | usize::from(modifiers.shift) << 2
121}
122
123/// A chord's modifiers as an [`index`].
124pub fn chord_index(chord: &Chord) -> usize {
125    usize::from(chord.ctrl) | usize::from(chord.alt) << 1 | usize::from(chord.shift) << 2
126}
127
128/// How many sets of modifiers an [`index`] tells apart.
129pub const MODIFIER_SETS: usize = 8;
130
131/// The keymap's button of egui's.
132pub fn button(b: PointerButton) -> Button {
133    match b {
134        PointerButton::Primary => Button::Primary,
135        PointerButton::Secondary => Button::Secondary,
136        PointerButton::Middle => Button::Middle,
137        PointerButton::Extra1 => Button::Back,
138        PointerButton::Extra2 => Button::Forward,
139    }
140}
141
142/// egui's button of the keymap's.
143pub fn egui_button(b: Button) -> PointerButton {
144    match b {
145        Button::Primary => PointerButton::Primary,
146        Button::Secondary => PointerButton::Secondary,
147        Button::Middle => PointerButton::Middle,
148        Button::Back => PointerButton::Extra1,
149        Button::Forward => PointerButton::Extra2,
150    }
151}
152
153/// One wheel, scroll or pinch event of this pass.
154#[derive(Clone, Copy, Debug, PartialEq)]
155pub struct WheelInput {
156    /// [`Pointer::Wheel`], [`Pointer::Scroll`] or [`Pointer::Pinch`].
157    pub pointer: Pointer,
158    pub modifiers: Modifiers,
159    /// The motion in points, as egui gives it (positive: the content
160    /// moves right and down); zero for a pinch.
161    pub delta: Vec2,
162    /// A pinch's zoom factor (above 1: in); 1 otherwise.
163    pub zoom: f32,
164}
165
166impl WheelInput {
167    /// Its chord.
168    pub fn chord(&self) -> Chord {
169        chord(self.modifiers, self.pointer)
170    }
171
172    /// The motion along one axis, the other's when it has none (a
173    /// vertical wheel moving sideways, a sideways one moving up).
174    pub fn along_y(&self) -> f32 {
175        if self.delta.y != 0.0 {
176            self.delta.y
177        } else {
178            self.delta.x
179        }
180    }
181
182    /// See [`WheelInput::along_y`].
183    pub fn along_x(&self) -> f32 {
184        if self.delta.x != 0.0 {
185            self.delta.x
186        } else {
187            self.delta.y
188        }
189    }
190}
191
192/// What the wheel device setting makes of a wheel event's unit.
193pub fn wheel_pointer(unit: MouseWheelUnit, device: WheelDevice) -> Pointer {
194    match (device, unit) {
195        (WheelDevice::Mouse, _) => Pointer::Wheel,
196        (WheelDevice::Trackpad, _) => Pointer::Scroll,
197        (WheelDevice::Auto, MouseWheelUnit::Point) => Pointer::Scroll,
198        (WheelDevice::Auto, MouseWheelUnit::Line | MouseWheelUnit::Page) => Pointer::Wheel,
199    }
200}
201
202/// This pass's wheel, scroll and pinch events, raw: unit and modifiers
203/// kept, egui's smoothing left out (a notch is one step).
204pub fn wheel_inputs(ctx: &Context) -> Vec<WheelInput> {
205    let device = map(ctx).wheel_device;
206    let line = ctx.options(|o| o.input_options.line_scroll_speed);
207    ctx.input(|i| {
208        let page = i.content_rect().height();
209        let mut out: Vec<WheelInput> = i
210            .events
211            .iter()
212            .filter_map(|e| match e {
213                Event::MouseWheel {
214                    unit,
215                    delta,
216                    modifiers,
217                    ..
218                } => Some(WheelInput {
219                    pointer: wheel_pointer(*unit, device),
220                    modifiers: *modifiers,
221                    delta: match unit {
222                        MouseWheelUnit::Point => *delta,
223                        MouseWheelUnit::Line => *delta * line,
224                        MouseWheelUnit::Page => *delta * page,
225                    },
226                    zoom: 1.0,
227                }),
228                Event::Zoom(factor) if *factor != 1.0 => Some(WheelInput {
229                    pointer: Pointer::Pinch,
230                    modifiers: i.modifiers,
231                    delta: Vec2::ZERO,
232                    zoom: *factor,
233                }),
234                _ => None,
235            })
236            .collect();
237        if let Some(touch) = i.multi_touch()
238            && touch.zoom_delta != 1.0
239        {
240            out.push(WheelInput {
241                pointer: Pointer::Pinch,
242                modifiers: i.modifiers,
243                delta: Vec2::ZERO,
244                zoom: touch.zoom_delta,
245            });
246        }
247        out
248    })
249}
250
251/// Takes this pass's wheel from what comes after (a canvas used it):
252/// the panel around does not scroll, egui's smoothing of earlier notches
253/// included.
254pub fn take_wheel(ctx: &Context) {
255    ctx.input_mut(|i| {
256        i.smooth_scroll_delta = Vec2::ZERO;
257        i.events
258            .retain(|e| !matches!(e, Event::MouseWheel { .. } | Event::Zoom(_)));
259    });
260}
261
262/// egui's modifiers of a chord's modifiers as text (`Ctrl`, `Alt+Shift`;
263/// empty or unreadable: none).
264pub fn modifiers_from_text(text: &str) -> Modifiers {
265    Chord::parse_modifiers(text)
266        .map(|c| modifiers_of(&c))
267        .unwrap_or(Modifiers::NONE)
268}
269
270/// Makes a wheel's lines worth `speed` times egui's own points a line, in scroll
271/// areas and in [`wheel_inputs`]. What a trackpad sends is in points already, and
272/// stays as it is. A speed that is not a positive number counts as 1.
273pub fn apply_wheel_speed(ctx: &Context, speed: f32) {
274    let speed = if speed.is_finite() && speed > 0.0 {
275        speed
276    } else {
277        1.0
278    };
279    let line = egui::InputOptions::default().line_scroll_speed * speed;
280    if ctx.options(|o| o.input_options.line_scroll_speed) != line {
281        ctx.options_mut(|o| o.input_options.line_scroll_speed = line);
282    }
283}
284
285/// Makes egui's scrolling (scroll areas, `zoom_delta`) follow a
286/// profile's modifiers.
287pub fn apply_input_options(ctx: &Context, input: &InputModifiers) {
288    let zoom = modifiers_from_text(&input.zoom);
289    let horizontal = modifiers_from_text(&input.horizontal_scroll);
290    let vertical = modifiers_from_text(&input.vertical_scroll);
291    let same = ctx.options(|o| {
292        o.input_options.zoom_modifier == zoom
293            && o.input_options.horizontal_scroll_modifier == horizontal
294            && o.input_options.vertical_scroll_modifier == vertical
295    });
296    if !same {
297        ctx.options_mut(|o| {
298            o.input_options.zoom_modifier = zoom;
299            o.input_options.horizontal_scroll_modifier = horizontal;
300            o.input_options.vertical_scroll_modifier = vertical;
301        });
302    }
303}
304
305/// What the pointer does in a scope with these modifiers held, for a
306/// canvas's hint: `Wheel: zoom · MiddleDrag: pan`, each gesture by its
307/// name and its command by `word` (none: left out). Clicks and drags of
308/// other buttons than these are left out too.
309pub fn hint(
310    map: &PointerMap,
311    scope: &str,
312    modifiers: Modifiers,
313    word: impl Fn(&CommandId) -> Option<String>,
314) -> String {
315    let held = chord(modifiers, Pointer::Wheel);
316    let mut parts: Vec<(Pointer, String)> = map
317        .scope(scope)
318        .filter(|b| b.chord.same_modifiers(&held))
319        .filter_map(|b| {
320            let p = b.chord.pointer()?;
321            Some((p, format!("{}: {}", p.name(), word(&b.command)?)))
322        })
323        .collect();
324    parts.sort_by_key(|(p, _)| *p);
325    parts
326        .into_iter()
327        .map(|(_, text)| text)
328        .collect::<Vec<_>>()
329        .join(" · ")
330}
331
332const HINT: Slot<(u64, String)> = Slot::new("core.pointer.hint");
333
334/// A canvas under the pointer says what the pointer does there now
335/// ([`hint`]), for a status line to show ([`hint_now`]).
336pub fn show_hint(ctx: &Context, text: &str) {
337    HINT.set(ctx, (ctx.cumulative_pass_nr(), text.to_string()));
338}
339
340/// The hint a canvas under the pointer gave in this pass or the last
341/// one, if any (and not empty).
342pub fn hint_now(ctx: &Context) -> Option<String> {
343    let (pass, text) = HINT.get(ctx)?;
344    (ctx.cumulative_pass_nr() <= pass + 1 && !text.is_empty()).then_some(text)
345}
346
347/// The `pointer` collector of the debug bridge: the profile in force,
348/// the hint shown now, the widgets' claims of the secondary button in
349/// force and the uses they said ([`claim`]).
350pub fn collector() -> crate::debug::FnCollector {
351    crate::debug::FnCollector::new(
352        "pointer",
353        "The pointer profile in force, the hint a canvas shows now, and the widgets that claim the secondary button: the claims in force (widget, rect, click and drag with what they do) and every use seen.",
354    )
355    .snapshot(|ctx| {
356        let mut out = claim::report(ctx);
357        out["profile"] = serde_json::json!(map(ctx).profile);
358        out["hint"] = serde_json::json!(hint_now(ctx));
359        out
360    })
361}
362
363/// For a web build's `eframe::WebOptions::should_prevent_default`: the
364/// browser never gets an event egui-pop handles, the wheel above all
365/// (Ctrl and the wheel would zoom the page, and a trackpad's pinch
366/// arrives the same way), as eframe's default does for every event.
367pub fn web_prevent_default(_event: &Event) -> bool {
368    true
369}