Skip to main content

egui_pop_model/
pointer.rs

1//! Pointer gesture profiles: what the wheel, a scroll, a pinch and the
2//! buttons do on each kind of canvas, as named presets of keymap
3//! bindings (`docs/pointer-gestures.md`).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! A **gesture** is a command like any other (`gesture.image.zoom`),
9//! bound to a pointer chord (`Ctrl+Wheel`, [`crate::keymap::Pointer`])
10//! in the scope of a canvas kind (`surface:canvas.image`). A
11//! **profile** ([`Profile`], a `pointer-profile` document) is a set of
12//! those bindings for the default layer, the options it implies (the
13//! wheel over sliders, a double click on the image) and the modifiers
14//! egui's own scrolling follows. Six ship with the library
15//! ([`builtin`]): Document (the default), darktable, Photoshop,
16//! Lightroom Classic, Blender / node editors and Trackpad, each
17//! following the application it is named after. A retired id still
18//! names its successor ([`ALIASES`]: `adobe` is `lightroom`). The
19//! user's overrides are ordinary user-layer bindings on top. A profile
20//! also says which cursor each kind of drag shows, hovered and dragged
21//! ([`DragKind`], [`PointerMap::drag_cursor`]).
22//!
23//! A canvas reads the resolved table, a [`PointerMap`], built from the
24//! keymap ([`PointerMap::from_keymap`]) or from a profile alone
25//! ([`PointerMap::from_profile`]).
26//!
27//! ```
28//! use egui_pop_model::keymap::Chord;
29//! use egui_pop_model::pointer::{self, PointerMap, SCOPE_IMAGE};
30//!
31//! let darktable = pointer::profile("darktable").unwrap();
32//! let map = PointerMap::from_profile(darktable);
33//! let wheel = Chord::parse("Wheel").unwrap();
34//! assert_eq!(map.command(SCOPE_IMAGE, &wheel).unwrap().as_str(), "gesture.image.zoom");
35//! let document = PointerMap::from_profile(pointer::default_profile());
36//! assert_eq!(document.command(SCOPE_IMAGE, &wheel).unwrap().as_str(), "gesture.image.pan");
37//! ```
38
39use std::collections::BTreeMap;
40use std::sync::LazyLock;
41
42use serde::{Deserialize, Serialize};
43
44use crate::doc::{self, DocError, Schema};
45use crate::ids::{CommandId, OwnerId};
46use crate::keymap::{Chord, DocBinding, KeyScope, Keymap, Layer};
47
48/// The image viewport's scope.
49pub const SCOPE_IMAGE: &str = "canvas.image";
50/// The node graph's scope.
51pub const SCOPE_GRAPH: &str = "canvas.graph";
52/// Sliders and other values' scope.
53pub const SCOPE_VALUE: &str = "widget.value";
54/// Stacked sections' scope.
55pub const SCOPE_SECTIONS: &str = "widget.sections";
56/// Floating palettes' scope: the drag of a palette's band or tab.
57pub const SCOPE_PALETTE: &str = "workbench.palette";
58/// Every scope a profile binds, in the order the editor shows them.
59pub const SCOPES: [&str; 5] = [
60    SCOPE_IMAGE,
61    SCOPE_GRAPH,
62    SCOPE_VALUE,
63    SCOPE_SECTIONS,
64    SCOPE_PALETTE,
65];
66
67/// The profile a library or an application gets unless it picks one.
68pub const DEFAULT_PROFILE: &str = "document";
69
70/// The navigation commands every canvas takes (the node graph, the
71/// image viewport, plots; `docs/design/navigation.md`), whose keys a
72/// profile gives ([`Profile::view_keys`]).
73pub const VIEW_COMMANDS: [&str; 10] = [
74    "view.fit",
75    "view.frame_selection",
76    "view.zoom_in",
77    "view.zoom_out",
78    "view.zoom_100",
79    "view.pan_left",
80    "view.pan_right",
81    "view.pan_up",
82    "view.pan_down",
83    "view.hand",
84];
85
86/// When a profile's navigation keys apply: a canvas is in use and no
87/// file browser, text input or modal has the keyboard (a file browser's
88/// `Ctrl+1` to `Ctrl+9` are its view modes, Photoshop's `Ctrl+1` is 100 %).
89pub const VIEW_KEYS_WHEN: &str =
90    "canvasActive && !fileBrowserFocused && !textInputFocus && !modalOpen";
91
92/// Gesture commands, by canvas kind.
93pub mod gesture {
94    use crate::ids::CommandId;
95
96    /// Zooms around the pointer, holding at fit and 100 %.
97    pub const IMAGE_ZOOM: CommandId = CommandId::from_static("gesture.image.zoom");
98    /// Zooms around the pointer without holding anywhere.
99    pub const IMAGE_ZOOM_FREE: CommandId = CommandId::from_static("gesture.image.zoom_free");
100    /// Pans: by the wheel's motion, or following a drag.
101    pub const IMAGE_PAN: CommandId = CommandId::from_static("gesture.image.pan");
102    /// Pans horizontally by the wheel's motion.
103    pub const IMAGE_PAN_X: CommandId = CommandId::from_static("gesture.image.pan_x");
104    /// Pans vertically by the wheel's motion.
105    pub const IMAGE_PAN_Y: CommandId = CommandId::from_static("gesture.image.pan_y");
106    /// 100 %, then 200 %, then fit, around the pointer.
107    pub const IMAGE_ZOOM_CYCLE: CommandId = CommandId::from_static("gesture.image.zoom_cycle");
108    /// Fits the image.
109    pub const IMAGE_FIT: CommandId = CommandId::from_static("gesture.image.fit");
110    /// Fit, or 100 % around the pointer when fitting.
111    pub const IMAGE_ZOOM_TOGGLE: CommandId = CommandId::from_static("gesture.image.zoom_toggle");
112    /// Zooms around the pointer.
113    pub const GRAPH_ZOOM: CommandId = CommandId::from_static("gesture.graph.zoom");
114    /// Pans: by the wheel's motion, or following a drag.
115    pub const GRAPH_PAN: CommandId = CommandId::from_static("gesture.graph.pan");
116    pub const GRAPH_PAN_X: CommandId = CommandId::from_static("gesture.graph.pan_x");
117    pub const GRAPH_PAN_Y: CommandId = CommandId::from_static("gesture.graph.pan_y");
118    /// Fits the graph.
119    pub const GRAPH_FIT: CommandId = CommandId::from_static("gesture.graph.fit");
120    /// The wheel steps the value under the pointer; its modifiers are
121    /// the ones that make the wheel step a slider without the focus.
122    pub const VALUE_STEP: CommandId = CommandId::from_static("gesture.value.step");
123    /// Its modifiers make drags, arrows and the wheel ten times finer.
124    pub const VALUE_FINE: CommandId = CommandId::from_static("gesture.value.fine");
125    /// Its modifiers make them ten times coarser.
126    pub const VALUE_COARSE: CommandId = CommandId::from_static("gesture.value.coarse");
127    /// The wheel scrolls the panel, even over a value.
128    pub const VALUE_PANEL: CommandId = CommandId::from_static("gesture.value.panel");
129    /// A primary click with its modifiers puts a value back to its
130    /// default (`Ctrl+PrimaryClick`, as in Reason or Kontakt). No shipped
131    /// profile binds it: a double click resets in all of them.
132    pub const VALUE_RESET: CommandId = CommandId::from_static("gesture.value.reset");
133    /// A drag on a boundary or a title moves the sections below as a block.
134    pub const SECTIONS_PULL: CommandId = CommandId::from_static("gesture.sections.pull");
135    /// The keys held while a floating palette is dragged that dock it
136    /// (or join another palette's group), or keep it floating, as the
137    /// palette's drag mode says ([`super::DockDrag`]).
138    pub const WORKBENCH_DOCK: CommandId = CommandId::from_static("gesture.workbench.dock");
139}
140
141/// A gesture command as declared: its id, its scope, its title and what
142/// it does.
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct GestureSpec {
145    pub id: CommandId,
146    pub scope: &'static str,
147    pub title: &'static str,
148    pub description: &'static str,
149}
150
151/// Every gesture command.
152pub const GESTURES: &[GestureSpec] = &[
153    GestureSpec {
154        id: gesture::IMAGE_ZOOM,
155        scope: SCOPE_IMAGE,
156        title: "Image: zoom at the pointer",
157        description: "Zooms the image around the pointer, holding at fit and 100 %.",
158    },
159    GestureSpec {
160        id: gesture::IMAGE_ZOOM_FREE,
161        scope: SCOPE_IMAGE,
162        title: "Image: zoom without stops",
163        description: "Zooms the image around the pointer, holding nowhere.",
164    },
165    GestureSpec {
166        id: gesture::IMAGE_PAN,
167        scope: SCOPE_IMAGE,
168        title: "Image: pan",
169        description: "Moves the image with the wheel or a drag.",
170    },
171    GestureSpec {
172        id: gesture::IMAGE_PAN_X,
173        scope: SCOPE_IMAGE,
174        title: "Image: pan horizontally",
175        description: "Moves the image sideways with the wheel.",
176    },
177    GestureSpec {
178        id: gesture::IMAGE_PAN_Y,
179        scope: SCOPE_IMAGE,
180        title: "Image: pan vertically",
181        description: "Moves the image up and down with the wheel.",
182    },
183    GestureSpec {
184        id: gesture::IMAGE_ZOOM_CYCLE,
185        scope: SCOPE_IMAGE,
186        title: "Image: zoom cycle",
187        description: "Goes to 100 %, then 200 %, then fit, around the pointer.",
188    },
189    GestureSpec {
190        id: gesture::IMAGE_FIT,
191        scope: SCOPE_IMAGE,
192        title: "Image: fit",
193        description: "Fits the whole image in the view.",
194    },
195    GestureSpec {
196        id: gesture::IMAGE_ZOOM_TOGGLE,
197        scope: SCOPE_IMAGE,
198        title: "Image: fit or 100 %",
199        description: "Goes to 100 % around the pointer when the image fits, else fits it.",
200    },
201    GestureSpec {
202        id: gesture::GRAPH_ZOOM,
203        scope: SCOPE_GRAPH,
204        title: "Node graph: zoom at the pointer",
205        description: "Zooms the graph around the pointer.",
206    },
207    GestureSpec {
208        id: gesture::GRAPH_PAN,
209        scope: SCOPE_GRAPH,
210        title: "Node graph: pan",
211        description: "Moves the graph with the wheel or a drag.",
212    },
213    GestureSpec {
214        id: gesture::GRAPH_PAN_X,
215        scope: SCOPE_GRAPH,
216        title: "Node graph: pan horizontally",
217        description: "Moves the graph sideways with the wheel.",
218    },
219    GestureSpec {
220        id: gesture::GRAPH_PAN_Y,
221        scope: SCOPE_GRAPH,
222        title: "Node graph: pan vertically",
223        description: "Moves the graph up and down with the wheel.",
224    },
225    GestureSpec {
226        id: gesture::GRAPH_FIT,
227        scope: SCOPE_GRAPH,
228        title: "Node graph: fit",
229        description: "Fits the whole graph in the view.",
230    },
231    GestureSpec {
232        id: gesture::VALUE_STEP,
233        scope: SCOPE_VALUE,
234        title: "Values: step with the wheel",
235        description: "The wheel with these keys steps the slider under the pointer, focused or not.",
236    },
237    GestureSpec {
238        id: gesture::VALUE_FINE,
239        scope: SCOPE_VALUE,
240        title: "Values: finer",
241        description: "These keys make a slider's drag, arrows and wheel ten times finer.",
242    },
243    GestureSpec {
244        id: gesture::VALUE_COARSE,
245        scope: SCOPE_VALUE,
246        title: "Values: coarser",
247        description: "These keys make a slider's drag, arrows and wheel ten times coarser.",
248    },
249    GestureSpec {
250        id: gesture::VALUE_PANEL,
251        scope: SCOPE_VALUE,
252        title: "Values: scroll the panel",
253        description: "The wheel with these keys scrolls the panel, even over a slider.",
254    },
255    GestureSpec {
256        id: gesture::VALUE_RESET,
257        scope: SCOPE_VALUE,
258        title: "Values: reset with a click",
259        description: "A click with these keys puts a slider or a knob back to its default.",
260    },
261    GestureSpec {
262        id: gesture::SECTIONS_PULL,
263        scope: SCOPE_SECTIONS,
264        title: "Sections: pull as a block",
265        description: "A drag on a boundary or a title with these keys moves the sections below as a block, keeping their heights.",
266    },
267    GestureSpec {
268        id: gesture::WORKBENCH_DOCK,
269        scope: SCOPE_PALETTE,
270        title: "Palettes: dock while dragging",
271        description: "Held while a floating palette is dragged, these keys show where it docks or joins another palette, and let go there it does; with the drag mode modifier-floats, they keep it floating instead.",
272    },
273];
274
275/// The gesture command of an id, when it is one.
276pub fn gesture_spec(id: &CommandId) -> Option<&'static GestureSpec> {
277    GESTURES.iter().find(|g| g.id == *id)
278}
279
280/// What the wheel does over a slider without the focus.
281#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
282#[serde(rename_all = "kebab-case")]
283pub enum SliderWheel {
284    /// It scrolls the panel; it steps a slider only when the slider has
285    /// the focus or the step modifiers are held (`gesture.value.step`).
286    #[default]
287    Guarded,
288    /// It steps the slider under the pointer (darktable); the panel
289    /// scrolls with `gesture.value.panel`'s modifiers.
290    Value,
291}
292
293impl SliderWheel {
294    pub const CHOICES: [&'static str; 2] = ["guarded", "value"];
295
296    pub fn as_str(self) -> &'static str {
297        match self {
298            SliderWheel::Guarded => "guarded",
299            SliderWheel::Value => "value",
300        }
301    }
302
303    pub fn parse(text: &str) -> Option<SliderWheel> {
304        match text {
305            "guarded" => Some(SliderWheel::Guarded),
306            "value" => Some(SliderWheel::Value),
307            _ => None,
308        }
309    }
310}
311
312/// How a drag turns a knob. The same travel, in points, covers the soft
313/// range in every mode; where the press lands never changes the mode.
314#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
315#[serde(rename_all = "kebab-case")]
316pub enum KnobDrag {
317    /// Up is more (the audio convention).
318    Vertical,
319    /// Right is more.
320    Horizontal,
321    /// Right and up both add.
322    #[default]
323    Both,
324    /// Around the dial's centre, relative to the press: the value never
325    /// jumps to where the pointer is.
326    Circular,
327}
328
329impl KnobDrag {
330    pub const CHOICES: [&'static str; 4] = ["vertical", "horizontal", "both", "circular"];
331
332    pub fn as_str(self) -> &'static str {
333        match self {
334            KnobDrag::Vertical => "vertical",
335            KnobDrag::Horizontal => "horizontal",
336            KnobDrag::Both => "both",
337            KnobDrag::Circular => "circular",
338        }
339    }
340
341    pub fn parse(text: &str) -> Option<KnobDrag> {
342        match text {
343            "vertical" => Some(KnobDrag::Vertical),
344            "horizontal" => Some(KnobDrag::Horizontal),
345            "both" => Some(KnobDrag::Both),
346            "circular" => Some(KnobDrag::Circular),
347            _ => None,
348        }
349    }
350}
351
352/// What a primary double click on the image (not on a handle) does.
353#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
354#[serde(rename_all = "kebab-case")]
355pub enum ImageDoubleClick {
356    /// Fits the image.
357    #[default]
358    Fit,
359    /// Asks the application to leave the view (darktable goes back to
360    /// the lighttable); the viewport signals it and changes nothing.
361    Leave,
362    /// Nothing.
363    Nothing,
364}
365
366impl ImageDoubleClick {
367    pub const CHOICES: [&'static str; 3] = ["fit", "leave", "nothing"];
368
369    pub fn as_str(self) -> &'static str {
370        match self {
371            ImageDoubleClick::Fit => "fit",
372            ImageDoubleClick::Leave => "leave",
373            ImageDoubleClick::Nothing => "nothing",
374        }
375    }
376
377    pub fn parse(text: &str) -> Option<ImageDoubleClick> {
378        match text {
379            "fit" => Some(ImageDoubleClick::Fit),
380            "leave" => Some(ImageDoubleClick::Leave),
381            "nothing" => Some(ImageDoubleClick::Nothing),
382            _ => None,
383        }
384    }
385}
386
387/// What the wheel events come from. egui does not say which device sent
388/// a wheel event; its unit is the cheapest hint (a mouse wheel sends
389/// lines, a trackpad points), not a reliable one (some mice and browsers
390/// send points).
391#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
392#[serde(rename_all = "kebab-case")]
393pub enum WheelDevice {
394    /// Lines are a wheel (`Wheel`), points a trackpad (`Scroll`).
395    #[default]
396    Auto,
397    /// Every wheel event is a mouse wheel.
398    Mouse,
399    /// Every wheel event is a trackpad's scroll.
400    Trackpad,
401}
402
403impl WheelDevice {
404    pub const CHOICES: [&'static str; 3] = ["auto", "mouse", "trackpad"];
405
406    pub fn as_str(self) -> &'static str {
407        match self {
408            WheelDevice::Auto => "auto",
409            WheelDevice::Mouse => "mouse",
410            WheelDevice::Trackpad => "trackpad",
411        }
412    }
413
414    pub fn parse(text: &str) -> Option<WheelDevice> {
415        match text {
416            "auto" => Some(WheelDevice::Auto),
417            "mouse" => Some(WheelDevice::Mouse),
418            "trackpad" => Some(WheelDevice::Trackpad),
419            _ => None,
420        }
421    }
422}
423
424/// What a plain drag of a floating palette does, and what the dock keys
425/// (`gesture.workbench.dock`) change (`docs/design/drag-move-vs-dock.md`).
426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
427#[serde(rename_all = "kebab-case")]
428pub enum DockDrag {
429    /// A plain drag only moves; the dock keys held show the targets and
430    /// dock (egui-pop's default).
431    #[default]
432    ModifierDocks,
433    /// A plain drag docks over a target; the dock keys held keep the
434    /// palette floating (Photoshop, Visual Studio).
435    ModifierFloats,
436    /// Docking arms once the pointer rested on a target for a moment
437    /// (touch and pen, with no key at hand).
438    Dwell,
439}
440
441impl DockDrag {
442    pub const CHOICES: [&'static str; 3] = ["modifier-docks", "modifier-floats", "dwell"];
443
444    pub fn as_str(self) -> &'static str {
445        match self {
446            DockDrag::ModifierDocks => "modifier-docks",
447            DockDrag::ModifierFloats => "modifier-floats",
448            DockDrag::Dwell => "dwell",
449        }
450    }
451
452    pub fn parse(text: &str) -> Option<DockDrag> {
453        match text {
454            "modifier-docks" => Some(DockDrag::ModifierDocks),
455            "modifier-floats" => Some(DockDrag::ModifierFloats),
456            "dwell" => Some(DockDrag::Dwell),
457            _ => None,
458        }
459    }
460}
461
462/// The options a profile gives its default for (each also a setting).
463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
464#[serde(default)]
465pub struct Options {
466    pub slider_wheel: SliderWheel,
467    pub image_double_click: ImageDoubleClick,
468    /// How a drag turns a knob, unless the knob says
469    /// (`Knob::drag`).
470    pub knob_drag: KnobDrag,
471    /// What a plain drag of a floating palette does.
472    pub dock_drag: DockDrag,
473}
474
475/// The modifiers egui's own scrolling follows (`egui::InputOptions`),
476/// as chords' modifiers (`Ctrl`, `Shift`, `Alt+Shift`; empty: none):
477/// plain egui widgets (scroll areas) agree with the profile.
478#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
479#[serde(default)]
480pub struct InputModifiers {
481    /// Held: the wheel zooms instead of scrolling.
482    pub zoom: String,
483    /// Held: the wheel scrolls horizontally.
484    pub horizontal_scroll: String,
485    /// Held: the wheel scrolls vertically only.
486    pub vertical_scroll: String,
487}
488
489impl Default for InputModifiers {
490    /// egui's.
491    fn default() -> Self {
492        InputModifiers {
493            zoom: "Ctrl".into(),
494            horizontal_scroll: "Shift".into(),
495            vertical_scroll: "Alt".into(),
496        }
497    }
498}
499
500/// The modifiers that scale a value's arrow-key steps, when they differ
501/// from its drag's (`gesture.value.fine` and `gesture.value.coarse`),
502/// as chords' modifiers (`Alt`, `Shift`; empty: the drag's). Lightroom
503/// Classic, for one, makes a Shift drag finer but Shift with the arrows
504/// coarser. Profiles bind pointer gestures only: this is data the
505/// slider reads, not a keymap binding.
506#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
507#[serde(default)]
508pub struct ValueKeys {
509    /// Held with the arrows: ten times finer.
510    pub fine: String,
511    /// Held with the arrows: ten times coarser.
512    pub coarse: String,
513}
514
515/// What a drag does to what it holds: the meaning a drag's cursor is
516/// keyed by, whatever the widget. A widget names the kind of each of its
517/// drags; the profile in force says which cursor each kind shows,
518/// hovered and dragged, and when the hover cursor shows
519/// ([`DragKind::cursors`], [`Profile::drag_cursors`], [`HoverPolicy`]).
520#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
521#[serde(rename_all = "kebab-case")]
522#[non_exhaustive]
523pub enum DragKind {
524    /// Content panned under a fixed frame: an image, a graph's canvas,
525    /// a timeline's lanes. An open hand, closed while dragging.
526    Pan,
527    /// Content scrubbed under a fixed playhead (a deck's waveform). An
528    /// open hand, closed while dragging.
529    Scrub,
530    /// An item moved where the pointer takes it: a node, a clip, a band,
531    /// a navigator's view frame. Move (a four-way arrow).
532    Move,
533    /// An item carried to a place to drop it: a row, a tab, a wire's
534    /// end. The arrow until it moves, then a closed hand.
535    Carry,
536    /// A value dragged along a line: a slider, a playhead on a ruler.
537    /// The arrow until it moves, then a horizontal resize.
538    Value,
539    /// A point placed under the pointer: a colour wheel's puck, a
540    /// curve's point. The arrow until it moves, then a crosshair.
541    Point,
542    /// A rubber band selecting what it covers. The arrow until it moves,
543    /// then a crosshair.
544    Select,
545    /// Text selected by dragging over it. An I-beam.
546    Text,
547    /// An edge or a separator resized sideways.
548    ResizeHorizontal,
549    /// An edge or a separator resized up and down.
550    ResizeVertical,
551    /// A corner resized along the top-left to bottom-right diagonal.
552    ResizeNwSe,
553    /// A corner resized along the top-right to bottom-left diagonal.
554    ResizeNeSw,
555    /// A separator between panes side by side, dragged sideways: a
556    /// splitter, a side area's or a flyout's edge. A column resize.
557    SplitColumns,
558    /// A separator between panes one above the other, dragged up and
559    /// down. A row resize.
560    SplitRows,
561}
562
563impl DragKind {
564    /// Every kind, in the order the docs list them.
565    pub const ALL: [DragKind; 14] = [
566        DragKind::Pan,
567        DragKind::Scrub,
568        DragKind::Move,
569        DragKind::Carry,
570        DragKind::Value,
571        DragKind::Point,
572        DragKind::Select,
573        DragKind::Text,
574        DragKind::ResizeHorizontal,
575        DragKind::ResizeVertical,
576        DragKind::ResizeNwSe,
577        DragKind::ResizeNeSw,
578        DragKind::SplitColumns,
579        DragKind::SplitRows,
580    ];
581
582    /// Its name in a profile document: `pan`, `resize-horizontal`.
583    pub fn as_str(self) -> &'static str {
584        match self {
585            DragKind::Pan => "pan",
586            DragKind::Scrub => "scrub",
587            DragKind::Move => "move",
588            DragKind::Carry => "carry",
589            DragKind::Value => "value",
590            DragKind::Point => "point",
591            DragKind::Select => "select",
592            DragKind::Text => "text",
593            DragKind::ResizeHorizontal => "resize-horizontal",
594            DragKind::ResizeVertical => "resize-vertical",
595            DragKind::ResizeNwSe => "resize-nw-se",
596            DragKind::ResizeNeSw => "resize-ne-sw",
597            DragKind::SplitColumns => "split-columns",
598            DragKind::SplitRows => "split-rows",
599        }
600    }
601
602    pub fn parse(text: &str) -> Option<DragKind> {
603        DragKind::ALL.into_iter().find(|k| k.as_str() == text)
604    }
605
606    /// The cursors it shows unless a kit or a profile says otherwise, as
607    /// CSS cursor names ([`CURSOR_NAMES`]), with its hover policy:
608    /// [`HoverPolicy::Always`] for text (an I-beam over text, which a
609    /// click also places the caret in), [`HoverPolicy::OnlyAction`] for
610    /// the others.
611    pub fn cursors(self) -> DragCursor {
612        let (hover, drag) = match self {
613            DragKind::Pan | DragKind::Scrub => ("grab", "grabbing"),
614            DragKind::Move => ("move", "move"),
615            DragKind::Carry => ("default", "grabbing"),
616            DragKind::Value => ("default", "ew-resize"),
617            DragKind::Point | DragKind::Select => ("default", "crosshair"),
618            DragKind::Text => ("text", "text"),
619            DragKind::ResizeHorizontal => ("ew-resize", "ew-resize"),
620            DragKind::ResizeVertical => ("ns-resize", "ns-resize"),
621            DragKind::ResizeNwSe => ("nwse-resize", "nwse-resize"),
622            DragKind::ResizeNeSw => ("nesw-resize", "nesw-resize"),
623            DragKind::SplitColumns => ("col-resize", "col-resize"),
624            DragKind::SplitRows => ("row-resize", "row-resize"),
625        };
626        let policy = match self {
627            DragKind::Text => HoverPolicy::Always,
628            _ => HoverPolicy::OnlyAction,
629        };
630        DragCursor {
631            hover: hover.into(),
632            drag: drag.into(),
633            policy: Some(policy),
634        }
635    }
636}
637
638/// When a draggable shows its hover cursor, before any drag. While it is
639/// dragged it always shows its drag cursor.
640#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
641#[serde(rename_all = "kebab-case")]
642#[non_exhaustive]
643pub enum HoverPolicy {
644    /// Only when dragging is the element's only action: nothing happens
645    /// on a click or a double click on it (a splitter, a resize grip, an
646    /// item's handle). Where a click does something (select, set a
647    /// value, move the playhead), the arrow stays until the drag starts.
648    /// The default.
649    #[default]
650    OnlyAction,
651    /// Whenever it is hovered, whatever a click does.
652    Always,
653    /// Never: the arrow until the drag starts.
654    Never,
655}
656
657impl HoverPolicy {
658    /// Every policy.
659    pub const ALL: [HoverPolicy; 3] = [
660        HoverPolicy::OnlyAction,
661        HoverPolicy::Always,
662        HoverPolicy::Never,
663    ];
664
665    /// Its name in a profile or a kit: `only-action`, `always`, `never`.
666    pub fn as_str(self) -> &'static str {
667        match self {
668            HoverPolicy::OnlyAction => "only-action",
669            HoverPolicy::Always => "always",
670            HoverPolicy::Never => "never",
671        }
672    }
673
674    pub fn parse(text: &str) -> Option<HoverPolicy> {
675        HoverPolicy::ALL.into_iter().find(|p| p.as_str() == text)
676    }
677
678    /// Whether the hover cursor shows over an element that also does
679    /// something on a click or a double click (`clicks`), or not.
680    pub fn shows(self, clicks: bool) -> bool {
681        match self {
682            HoverPolicy::OnlyAction => !clicks,
683            HoverPolicy::Always => true,
684            HoverPolicy::Never => false,
685        }
686    }
687}
688
689/// The cursor names a profile may give: CSS's (`grab`, `ew-resize`),
690/// which egui shows on every platform.
691pub const CURSOR_NAMES: [&str; 35] = [
692    "alias",
693    "all-scroll",
694    "cell",
695    "context-menu",
696    "copy",
697    "crosshair",
698    "default",
699    "grab",
700    "grabbing",
701    "help",
702    "move",
703    "no-drop",
704    "none",
705    "not-allowed",
706    "pointer",
707    "progress",
708    "ew-resize",
709    "nesw-resize",
710    "nwse-resize",
711    "ns-resize",
712    "e-resize",
713    "se-resize",
714    "s-resize",
715    "sw-resize",
716    "w-resize",
717    "nw-resize",
718    "n-resize",
719    "ne-resize",
720    "col-resize",
721    "row-resize",
722    "text",
723    "vertical-text",
724    "wait",
725    "zoom-in",
726    "zoom-out",
727];
728
729/// The cursors of a drag kind: hovered, and while dragging (kept until
730/// the drag ends, wherever the pointer goes), and when the hover one
731/// shows. Names from [`CURSOR_NAMES`]; in a kit or a profile, an empty
732/// or unknown name and no policy keep the level below's
733/// ([`DragCursor::over`]).
734#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
735#[serde(default)]
736pub struct DragCursor {
737    /// Over what can be dragged, nothing being dragged; `default` asks
738    /// for none (the arrow, or what another widget asks for).
739    pub hover: String,
740    /// While dragging.
741    pub drag: String,
742    /// When the hover cursor shows ([`HoverPolicy`]).
743    #[serde(skip_serializing_if = "Option::is_none")]
744    pub policy: Option<HoverPolicy>,
745}
746
747impl DragCursor {
748    /// `self` with what `over` gives on top: each of its names that is
749    /// one of [`CURSOR_NAMES`], its policy if it has one. How each level
750    /// (the kind's own, the kit's, the profile's) overrides the one
751    /// below.
752    #[must_use]
753    pub fn over(mut self, over: &DragCursor) -> DragCursor {
754        let known = |n: &String| CURSOR_NAMES.contains(&n.as_str());
755        if known(&over.hover) {
756            self.hover.clone_from(&over.hover);
757        }
758        if known(&over.drag) {
759            self.drag.clone_from(&over.drag);
760        }
761        if over.policy.is_some() {
762            self.policy = over.policy;
763        }
764        self
765    }
766
767    /// Its policy, the default one when it has none.
768    pub fn hover_policy(&self) -> HoverPolicy {
769        self.policy.unwrap_or_default()
770    }
771}
772
773/// A pointer profile, as shipped or saved: the `pointer-profile`
774/// document.
775#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
776pub struct Profile {
777    /// Stable, never translated: `darktable`.
778    pub id: String,
779    pub title: String,
780    /// What it does, in one sentence.
781    #[serde(default)]
782    pub description: String,
783    #[serde(default)]
784    pub options: Options,
785    #[serde(default)]
786    pub input: InputModifiers,
787    #[serde(default)]
788    pub value_keys: ValueKeys,
789    /// The drag cursors it changes, by kind (`{"move": {"hover":
790    /// "default"}}`, `{"pan": {"policy": "always"}}`); the others keep
791    /// the kit's ([`DragKind::cursors`] by default).
792    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
793    pub drag_cursors: BTreeMap<DragKind, DragCursor>,
794    /// Default-layer bindings, as in a keymap document.
795    #[serde(default)]
796    pub bindings: Vec<DocBinding>,
797    /// The navigation commands' keys ([`VIEW_COMMANDS`]), by command
798    /// (`{"view.fit": ["Home", "Shift+1"]}`), after the application the
799    /// profile is named after; default-layer bindings like the others,
800    /// active while a canvas is in use ([`VIEW_KEYS_WHEN`]).
801    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
802    pub view_keys: BTreeMap<String, Vec<String>>,
803}
804
805/// The `pointer-profile` document's schema.
806pub fn schema() -> Schema {
807    Schema::new("pointer-profile", 1).migration(0, doc::same)
808}
809
810/// Reads a profile document.
811pub fn parse_profile(text: &str) -> Result<Profile, DocError> {
812    schema().load::<Profile>(text).map(|l| l.value)
813}
814
815const SHIPPED: [&str; 6] = [
816    include_str!("../profiles/document.json"),
817    include_str!("../profiles/darktable.json"),
818    include_str!("../profiles/photoshop.json"),
819    include_str!("../profiles/lightroom.json"),
820    include_str!("../profiles/blender.json"),
821    include_str!("../profiles/trackpad.json"),
822];
823
824static BUILTIN: LazyLock<Vec<Profile>> = LazyLock::new(|| {
825    SHIPPED
826        .iter()
827        .map(|text| parse_profile(text).expect("a shipped profile parses"))
828        .collect()
829});
830
831/// The profiles shipped with the library, the default first.
832pub fn builtin() -> &'static [Profile] {
833    &BUILTIN
834}
835
836/// Retired profile ids and the shipped profile each now names: `adobe`
837/// was split into `photoshop` and `lightroom` (2026-10-22) and is read
838/// as `lightroom`, the closer of the two for a photo editor. Aliases are
839/// accepted wherever an id is, and listed nowhere ([`ids`]).
840pub const ALIASES: &[(&str, &str)] = &[("adobe", "lightroom")];
841
842/// The id a profile id stands for: itself, or the profile an alias
843/// names.
844pub fn canonical_id(id: &str) -> &str {
845    ALIASES
846        .iter()
847        .find(|(alias, _)| *alias == id)
848        .map_or(id, |(_, to)| to)
849}
850
851/// A shipped profile by id (an alias gives the profile it names).
852pub fn profile(id: &str) -> Option<&'static Profile> {
853    let id = canonical_id(id);
854    builtin().iter().find(|p| p.id == id)
855}
856
857/// The `settings` document's migration from version 1: a saved profile
858/// id that is now an alias becomes the profile it names.
859pub(crate) fn settings_profile_aliases(
860    mut json: serde_json::Value,
861) -> Result<serde_json::Value, String> {
862    if let Some(v) = json
863        .get_mut("values")
864        .and_then(|values| values.get_mut("settings/input.pointer_profile"))
865        && let Some(id) = v.as_str()
866    {
867        let to = canonical_id(id);
868        if to != id {
869            *v = serde_json::Value::String(to.into());
870        }
871    }
872    Ok(json)
873}
874
875/// The default profile ([`DEFAULT_PROFILE`]).
876pub fn default_profile() -> &'static Profile {
877    profile(DEFAULT_PROFILE).expect("the default profile ships")
878}
879
880/// The ids of the shipped profiles, the default first.
881pub fn ids() -> Vec<&'static str> {
882    builtin().iter().map(|p| p.id.as_str()).collect()
883}
884
885/// Who owns a profile's bindings in the keymap's default layer.
886pub const PROFILE_OWNER: OwnerId = OwnerId::from_static("pointer-profile");
887
888/// One resolved pointer binding.
889#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
890pub struct PointerBinding {
891    /// The canvas kind (`canvas.image`), without `surface:`.
892    pub scope: String,
893    pub chord: Chord,
894    pub command: CommandId,
895    /// Where it comes from (the user's override, the profile).
896    pub layer: Layer,
897}
898
899/// What every pointer gesture does, per canvas kind, with the options in
900/// force: what canvases read.
901#[derive(Clone, Debug, PartialEq, Serialize)]
902pub struct PointerMap {
903    /// The profile in use.
904    pub profile: String,
905    pub options: Options,
906    pub input: InputModifiers,
907    /// The modifiers of a value's arrow-key steps, when not its drag's.
908    pub value_keys: ValueKeys,
909    pub wheel_device: WheelDevice,
910    /// What a wheel's lines are multiplied by (`input.wheel_speed`); 1: egui's own
911    /// points a line.
912    pub wheel_speed: f32,
913    pub bindings: Vec<PointerBinding>,
914    /// The profile's drag cursors ([`Profile::drag_cursors`]); read them
915    /// with [`PointerMap::drag_cursor`].
916    pub drag_cursors: BTreeMap<DragKind, DragCursor>,
917    /// The navigation commands' keys in force ([`VIEW_COMMANDS`]), by
918    /// command: the profile's, or the keymap's with the user's changes.
919    pub view_keys: BTreeMap<String, Vec<Chord>>,
920    /// The application's keymap dispatches the navigation keys (and
921    /// sends the commands to the canvas in use): a canvas does not read
922    /// them itself. Off for a map made from a profile alone.
923    pub keys_dispatched: bool,
924}
925
926impl Default for PointerMap {
927    /// The default profile's.
928    fn default() -> Self {
929        PointerMap::from_profile(default_profile())
930    }
931}
932
933impl PointerMap {
934    /// A profile's bindings alone (no user override), with its options.
935    pub fn from_profile(profile: &Profile) -> PointerMap {
936        let mut k = Keymap::new();
937        let _ = k.load(&PROFILE_OWNER, Layer::Default, &profile_doc(profile));
938        PointerMap::from_keymap(&k, profile)
939    }
940
941    /// The keymap's pointer bindings, the profile's options.
942    pub fn from_keymap(keymap: &Keymap, profile: &Profile) -> PointerMap {
943        let bindings = keymap
944            .pointer_bindings()
945            .into_iter()
946            .filter_map(|b| {
947                let KeyScope::Surface(scope) = &b.options.scope else {
948                    return None;
949                };
950                let crate::keymap::Action::Run(command) = &b.action else {
951                    return None;
952                };
953                Some(PointerBinding {
954                    scope: scope.clone(),
955                    chord: b.keys.0[0].clone(),
956                    command: command.clone(),
957                    layer: b.layer,
958                })
959            })
960            .collect();
961        let view_keys = VIEW_COMMANDS
962            .iter()
963            .map(|id| {
964                let chords = CommandId::new(*id)
965                    .map(|c| keymap.keys_for(&c))
966                    .unwrap_or_default()
967                    .into_iter()
968                    .filter(|k| k.0.len() == 1 && !k.0[0].is_pointer())
969                    .map(|k| k.0[0].clone())
970                    .collect();
971                ((*id).to_string(), chords)
972            })
973            .collect();
974        PointerMap {
975            profile: profile.id.clone(),
976            options: profile.options,
977            input: profile.input.clone(),
978            value_keys: profile.value_keys.clone(),
979            wheel_device: WheelDevice::Auto,
980            wheel_speed: 1.0,
981            bindings,
982            drag_cursors: profile.drag_cursors.clone(),
983            view_keys,
984            keys_dispatched: false,
985        }
986    }
987
988    /// The keys of a navigation command (`view.fit`) in force.
989    pub fn view_keys(&self, command: &str) -> &[Chord] {
990        self.view_keys.get(command).map_or(&[], Vec::as_slice)
991    }
992
993    /// The cursors a drag kind shows: the profile's, each name it leaves
994    /// empty or does not know, and its policy when it gives none, the
995    /// kind's own ([`DragKind::cursors`]).
996    pub fn drag_cursor(&self, kind: DragKind) -> DragCursor {
997        self.drag_cursor_over(kind, kind.cursors())
998    }
999
1000    /// The profile's cursors of a drag kind over `below` (a kit's):
1001    /// what the profile gives wins, the rest is `below`'s
1002    /// ([`DragCursor::over`]).
1003    pub fn drag_cursor_over(&self, kind: DragKind, below: DragCursor) -> DragCursor {
1004        match self.drag_cursors.get(&kind) {
1005            Some(o) => below.over(o),
1006            None => below,
1007        }
1008    }
1009
1010    /// The command a pointer chord runs in a scope.
1011    pub fn command(&self, scope: &str, chord: &Chord) -> Option<&CommandId> {
1012        self.bindings
1013            .iter()
1014            .find(|b| b.scope == scope && b.chord == *chord)
1015            .map(|b| &b.command)
1016    }
1017
1018    /// The chords running a command in a scope.
1019    pub fn chords<'a>(
1020        &'a self,
1021        scope: &'a str,
1022        command: &'a CommandId,
1023    ) -> impl Iterator<Item = &'a Chord> + 'a {
1024        self.bindings
1025            .iter()
1026            .filter(move |b| b.scope == scope && b.command == *command)
1027            .map(|b| &b.chord)
1028    }
1029
1030    /// A scope's bindings.
1031    pub fn scope<'a>(&'a self, scope: &'a str) -> impl Iterator<Item = &'a PointerBinding> + 'a {
1032        self.bindings.iter().filter(move |b| b.scope == scope)
1033    }
1034}
1035
1036/// A profile's bindings as a keymap document: its pointer gestures,
1037/// then its navigation keys.
1038pub fn profile_doc(profile: &Profile) -> crate::keymap::KeymapDoc {
1039    let mut bindings = profile.bindings.clone();
1040    for (command, keys) in &profile.view_keys {
1041        for k in keys {
1042            bindings.push(DocBinding {
1043                keys: k.clone(),
1044                command: Some(command.clone()),
1045                when: VIEW_KEYS_WHEN.to_string(),
1046                scope: String::new(),
1047                typing: crate::keymap::Typing::Auto,
1048                through_modal: false,
1049            });
1050        }
1051    }
1052    crate::keymap::KeymapDoc { bindings }
1053}