Skip to main content

egui_pop_api/
pointer.rs

1//! Pointer gestures in an application, owned by egui-pop: the pointer
2//! profile setting (`input.pointer_profile`: Document, darktable,
3//! Photoshop, Lightroom Classic, Blender / node editors, Trackpad;
4//! Document unless the application picks another with
5//! [`AppBuilder::pointer_profile`]; a retired id such as `adobe` names
6//! its successor, `lightroom`), the options
7//! each profile gives its default for (`input.slider_wheel`,
8//! `input.image_double_click`, `input.dock_drag`: what a plain drag of a
9//! floating palette does, its default the application's with
10//! [`AppBuilder::dock_drag`]), the wheel device (`input.wheel_device`) and
11//! speed (`input.wheel_speed`),
12//! and the gesture commands (`gesture.image.zoom`...) the profile binds
13//! to pointer chords in the keymap's default layer
14//! (`docs/pointer-gestures.md`).
15//!
16//! <div class="warning">Experimental: may change in any release
17//! (docs/stability.md).</div>
18//!
19//! The user's changes are ordinary user-layer bindings, made in the
20//! shortcuts editor: they stay over the profile. When the profile
21//! changes and some exist, a dialog asks whether to keep them on the
22//! new profile or drop them (`pointer.overrides`, `{ "value": "keep" |
23//! "drop" }`).
24//!
25//! The application publishes what is in force to its context
26//! (`egui_pop_core::pointer::set_map`) after each change of the keymap
27//! or of these settings: the canvases read it.
28//!
29//! [`AppBuilder::pointer_profile`]: crate::AppBuilder::pointer_profile
30//! [`AppBuilder::dock_drag`]: crate::AppBuilder::dock_drag
31
32use std::sync::Arc;
33
34use egui_pop_core::lock;
35use egui_pop_core::strings;
36use egui_pop_model::commands::{CommandSpec, Origin};
37use egui_pop_model::ids::{CommandId, SettingId};
38use egui_pop_model::keymap::{Keymap, Layer};
39use egui_pop_model::pointer::{
40    self, DockDrag, GESTURES, ImageDoubleClick, PROFILE_OWNER, PointerMap, Profile, SliderWheel,
41    WheelDevice,
42};
43use egui_pop_model::values::{Change, Descriptor, Set, Value};
44use serde_json::json;
45
46use crate::app::AppHandle;
47use crate::ctx::{Ctx, CtxError};
48use crate::dialogs::{Choose, ChooseOption, DIALOGS};
49use crate::strings as txt;
50
51/// The setting: the pointer profile, by id.
52pub const SETTING_PROFILE: SettingId = SettingId::from_static("input.pointer_profile");
53/// The setting: the wheel over sliders (`profile`, `guarded`, `value`).
54pub const SETTING_SLIDER_WHEEL: SettingId = SettingId::from_static("input.slider_wheel");
55/// The setting: a double click on the image (`profile`, `fit`, `leave`,
56/// `nothing`).
57pub const SETTING_IMAGE_DOUBLE_CLICK: SettingId =
58    SettingId::from_static("input.image_double_click");
59/// The setting: what a plain drag of a floating palette does
60/// (`profile`, `modifier-docks`, `modifier-floats`, `dwell`;
61/// [`DockDrag`]).
62pub const SETTING_DOCK_DRAG: SettingId = SettingId::from_static("input.dock_drag");
63/// The setting: what sends wheel events (`auto`, `mouse`, `trackpad`).
64pub const SETTING_WHEEL_DEVICE: SettingId = SettingId::from_static("input.wheel_device");
65/// The setting: what a mouse wheel's lines are multiplied by.
66pub const SETTING_WHEEL_SPEED: SettingId = SettingId::from_static("input.wheel_speed");
67
68/// The lines a notch moves on a system nobody changed, which is 1 on the speed.
69pub const SYSTEM_WHEEL_LINES: u32 = 3;
70
71/// The least and the most of `input.wheel_speed`.
72const WHEEL_SPEEDS: (f64, f64) = (0.25, 5.0);
73
74/// Keeps or drops the user's pointer gesture changes (`{ "value":
75/// "keep" | "drop" }`): what the dialog shown on a change of profile
76/// runs.
77pub const CMD_OVERRIDES: CommandId = CommandId::from_static("pointer.overrides");
78
79/// The category gesture commands are listed under.
80pub const CATEGORY: &str = "Pointer";
81
82/// An option's choice that follows the profile.
83pub const FROM_PROFILE: &str = "profile";
84
85fn path(id: &SettingId) -> String {
86    format!("settings/{id}")
87}
88
89fn choice(app: &AppHandle, id: &SettingId) -> Option<String> {
90    lock(&app.store())
91        .get(&path(id))
92        .and_then(|e| e.value.as_choice().map(str::to_string))
93}
94
95/// The profile the setting asks for (its id; it may name no shipped
96/// profile; an alias is given as the profile it names).
97pub fn profile_id(app: &AppHandle) -> String {
98    choice(app, &SETTING_PROFILE)
99        .map(|id| pointer::canonical_id(&id).to_string())
100        .unwrap_or_else(|| pointer::DEFAULT_PROFILE.into())
101}
102
103/// The profile in force: the setting's, else the default.
104pub fn profile(app: &AppHandle) -> &'static Profile {
105    pointer::profile(&profile_id(app)).unwrap_or_else(pointer::default_profile)
106}
107
108/// Asks for a palette drag mode (the `input.dock_drag` setting:
109/// `profile` or one of [`DockDrag::CHOICES`]), said once as
110/// `pop.settings.changed` and in force from the next pass.
111pub fn set_dock_drag(app: &AppHandle, value: &str) -> Result<(), String> {
112    if value != FROM_PROFILE && DockDrag::parse(value).is_none() {
113        return Err(format!("`{value}` is not a palette drag mode"));
114    }
115    lock(&app.store())
116        .set(
117            Set::new(
118                &path(&SETTING_DOCK_DRAG),
119                Change::To(Value::Choice(value.into())),
120                Origin::User,
121            )
122            .by(&egui_pop_model::ids::OwnerId::FRAMEWORK),
123        )
124        .map(|_| ())
125        .map_err(|e| e.to_string())
126}
127
128/// Asks for a profile (the setting), applied before the next frame. An
129/// alias (`adobe`) asks for the profile it names (`lightroom`).
130pub fn set_profile(app: &AppHandle, id: &str) -> Result<(), String> {
131    if pointer::profile(id).is_none() {
132        return Err(format!("`{id}` is not a pointer profile"));
133    }
134    let id = pointer::canonical_id(id);
135    lock(&app.store())
136        .set(
137            Set::new(
138                &path(&SETTING_PROFILE),
139                Change::To(Value::Choice(id.into())),
140                Origin::User,
141            )
142            .by(&egui_pop_model::ids::OwnerId::FRAMEWORK),
143        )
144        .map(|_| ())
145        .map_err(|e| e.to_string())
146}
147
148/// The options in force: the settings', or the profile's where they
149/// say `profile`.
150pub fn options(app: &AppHandle, profile: &Profile) -> (pointer::Options, WheelDevice) {
151    let mut o = profile.options;
152    if let Some(w) = choice(app, &SETTING_SLIDER_WHEEL).and_then(|c| SliderWheel::parse(&c)) {
153        o.slider_wheel = w;
154    }
155    if let Some(d) =
156        choice(app, &SETTING_IMAGE_DOUBLE_CLICK).and_then(|c| ImageDoubleClick::parse(&c))
157    {
158        o.image_double_click = d;
159    }
160    if let Some(d) = choice(app, &SETTING_DOCK_DRAG).and_then(|c| DockDrag::parse(&c)) {
161        o.dock_drag = d;
162    }
163    let device = choice(app, &SETTING_WHEEL_DEVICE)
164        .and_then(|c| WheelDevice::parse(&c))
165        .unwrap_or_default();
166    (o, device)
167}
168
169/// The speed the system's lines a notch seed: [`SYSTEM_WHEEL_LINES`] are 1, and
170/// what the setting cannot hold is its nearest end.
171pub fn wheel_speed_of_lines(lines: u32) -> f64 {
172    (f64::from(lines) / f64::from(SYSTEM_WHEEL_LINES)).clamp(WHEEL_SPEEDS.0, WHEEL_SPEEDS.1)
173}
174
175/// The wheel speed in force: the setting's, else 1.
176pub fn wheel_speed(app: &AppHandle) -> f32 {
177    lock(&app.store())
178        .get(&path(&SETTING_WHEEL_SPEED))
179        .and_then(|e| e.value.as_f64())
180        .map_or(1.0, |v| v as f32)
181}
182
183/// The gesture commands whose bindings the user changed.
184pub fn overrides(app: &AppHandle) -> Vec<CommandId> {
185    GESTURES
186        .iter()
187        .filter(|g| app.rebound_in(Layer::User, &g.id))
188        .map(|g| g.id.clone())
189        .collect()
190}
191
192/// Puts a profile's bindings in the keymap's default layer, in place of
193/// the previous profile's. `None` when no shipped profile has that id
194/// (the keymap is left as it was).
195pub(crate) fn load_profile(keymap: &mut Keymap, id: &str) -> Option<&'static Profile> {
196    let p = pointer::profile(id)?;
197    let d = keymap.load(&PROFILE_OWNER, Layer::Default, &pointer::profile_doc(p));
198    for e in d.all() {
199        log::warn!(target: "egui_pop", "pointer profile `{id}`: {}", e.message);
200    }
201    Some(p)
202}
203
204/// The map in force: the keymap's pointer bindings, the profile's
205/// modifiers, the options.
206pub(crate) fn map(app: &AppHandle, keymap: &Keymap) -> PointerMap {
207    let p = profile(app);
208    let mut m = PointerMap::from_keymap(keymap, p);
209    let (options, device) = options(app, p);
210    m.options = options;
211    m.wheel_device = device;
212    m.wheel_speed = wheel_speed(app);
213    m.keys_dispatched = true;
214    m
215}
216
217/// What the application last loaded and published.
218#[derive(Debug, Default)]
219pub(crate) struct Sync {
220    /// The profile whose bindings are in the default layer, once the
221    /// settings were read.
222    pub loaded: Option<String>,
223    /// The map last published, and what it was made from (the rebuild
224    /// count, the settings).
225    pub published: Option<(Arc<PointerMap>, u64, String)>,
226}
227
228/// The settings a published map depends on, as text.
229pub(crate) fn settings_print(app: &AppHandle) -> String {
230    [
231        &SETTING_PROFILE,
232        &SETTING_SLIDER_WHEEL,
233        &SETTING_IMAGE_DOUBLE_CLICK,
234        &SETTING_DOCK_DRAG,
235        &SETTING_WHEEL_DEVICE,
236    ]
237    .iter()
238    .map(|id| choice(app, id).unwrap_or_default())
239    .chain([wheel_speed(app).to_string()])
240    .collect::<Vec<_>>()
241    .join("|")
242}
243
244/// After a change of profile, when the user changed gestures: asks
245/// whether to keep them on the new profile or drop them. They stay
246/// until answered.
247pub(crate) fn ask_about_overrides(app: &AppHandle, profile: &Profile) {
248    let changed = overrides(app);
249    if changed.is_empty() {
250        return;
251    }
252    let Some(dialogs) = app.service(&DIALOGS) else {
253        return;
254    };
255    let ctx = app.egui();
256    let title = strings::tr_args(
257        &ctx,
258        &txt::POINTER_OVERRIDES_TITLE,
259        &[("profile", &profile.title)],
260    );
261    let detail = strings::tr_with(
262        &ctx,
263        &txt::POINTER_OVERRIDES_DETAIL,
264        &[("count", changed.len().into())],
265    );
266    dialogs.open(
267        Choose::with_options(
268            &title,
269            vec![
270                ChooseOption::new(&strings::tr(&ctx, &txt::POINTER_KEEP), json!("keep")),
271                ChooseOption::new(&strings::tr(&ctx, &txt::POINTER_DROP), json!("drop")),
272            ],
273            CMD_OVERRIDES,
274        )
275        .detail(&detail)
276        .args(json!({ "profile": profile.id })),
277    );
278}
279
280/// The framework's registrations: the settings, the gesture commands,
281/// the default profile's bindings. The wheel speed's default is the system's
282/// lines a notch; the palette drag mode's the application's, else the
283/// profile's.
284pub(crate) fn register(
285    ctx: &mut Ctx<'_>,
286    default_profile: &str,
287    system_wheel_lines: u32,
288    dock_drag: Option<DockDrag>,
289) -> Result<(), CtxError> {
290    let ids = pointer::ids();
291    let default_profile = pointer::canonical_id(default_profile);
292    let default = if ids.contains(&default_profile) {
293        default_profile
294    } else {
295        log::warn!(
296            target: "egui_pop",
297            "`{default_profile}` is not a pointer profile: `{}` is used",
298            pointer::DEFAULT_PROFILE
299        );
300        pointer::DEFAULT_PROFILE
301    };
302    ctx.setting(
303        SETTING_PROFILE,
304        Descriptor::choice("Pointer profile", &ids, default).description(
305            "What the wheel, a pinch and the mouse buttons do on the image, the node graph and sliders, as in darktable, Photoshop, Lightroom Classic, document tools (GIMP, Inkscape, the web), Blender and node editors, or on a trackpad. The shortcuts editor shows and changes each gesture.",
306        ),
307    )?;
308    let mut wheel = vec![FROM_PROFILE];
309    wheel.extend(SliderWheel::CHOICES);
310    ctx.setting(
311        SETTING_SLIDER_WHEEL,
312        Descriptor::choice("Wheel over sliders", &wheel, FROM_PROFILE).description(
313            "Whether the wheel over a slider scrolls the panel (guarded: the slider steps only with the focus or the step keys) or changes the value (value); profile: as the pointer profile says.",
314        ),
315    )?;
316    let mut double = vec![FROM_PROFILE];
317    double.extend(ImageDoubleClick::CHOICES);
318    ctx.setting(
319        SETTING_IMAGE_DOUBLE_CLICK,
320        Descriptor::choice("Double click on the image", &double, FROM_PROFILE).description(
321            "What a double click on the image does: fit it, leave the view (back to the browser, as darktable does), or nothing; profile: as the pointer profile says.",
322        ),
323    )?;
324    let mut drag = vec![FROM_PROFILE];
325    drag.extend(DockDrag::CHOICES);
326    ctx.setting(
327        SETTING_DOCK_DRAG,
328        Descriptor::choice(
329            "Dragging a floating panel",
330            &drag,
331            dock_drag.map_or(FROM_PROFILE, DockDrag::as_str),
332        )
333        .description(
334            "A floating panel dragged by its title: modifier-docks moves it, docking only with the dock keys held (Ctrl, or Cmd on macOS); modifier-floats docks it, the keys keep it floating; dwell docks it after a rest on a target; profile as the pointer profile says.",
335        ),
336    )?;
337    ctx.setting(
338        SETTING_WHEEL_DEVICE,
339        Descriptor::choice("Wheel device", &WheelDevice::CHOICES, "auto").description(
340            "What sends wheel events: auto tells a mouse wheel (lines) from a trackpad (points); some mice send points too, and choosing mouse or trackpad settles it.",
341        ),
342    )?;
343    ctx.setting(
344        SETTING_WHEEL_SPEED,
345        Descriptor::float(
346            "Wheel speed",
347            WHEEL_SPEEDS.0,
348            WHEEL_SPEEDS.1,
349            wheel_speed_of_lines(system_wheel_lines),
350        )
351        .description(
352            "How far a notch of a mouse wheel goes, in scrolling and on the canvases, 1 being the usual distance. What a trackpad sends is left as it is.",
353        )
354        .step(0.25),
355    )?;
356    for g in GESTURES {
357        ctx.declare(
358            CommandSpec::new(g.id.clone(), g.title, CATEGORY)
359                .description(g.description)
360                .hidden()
361                .no_agent(),
362        )?;
363    }
364    ctx.command(
365        CommandSpec::new(CMD_OVERRIDES, "Keep or drop pointer gesture changes", CATEGORY)
366            .description(
367                "Keeps the pointer gestures the user changed on the current profile, or drops them (`value`: keep or drop).",
368            )
369            .hidden()
370            .args(json!({ "value": "keep" })),
371        |call| {
372            let value = call
373                .args
374                .get("value")
375                .and_then(|v| v.as_str())
376                .unwrap_or("keep");
377            let changed = overrides(call.app);
378            match value {
379                "keep" => Ok(json!({ "kept": changed.len() })),
380                "drop" => {
381                    for id in &changed {
382                        call.app.reset_keys_in(Layer::User, id.clone());
383                    }
384                    Ok(json!({ "dropped": changed.len() }))
385                }
386                other => Err(format!("`{other}` is neither keep nor drop")),
387            }
388        },
389    )?;
390    load_profile(&mut ctx.reg.keymap.borrow_mut(), default);
391    Ok(())
392}