1use 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
51pub const SETTING_PROFILE: SettingId = SettingId::from_static("input.pointer_profile");
53pub const SETTING_SLIDER_WHEEL: SettingId = SettingId::from_static("input.slider_wheel");
55pub const SETTING_IMAGE_DOUBLE_CLICK: SettingId =
58 SettingId::from_static("input.image_double_click");
59pub const SETTING_DOCK_DRAG: SettingId = SettingId::from_static("input.dock_drag");
63pub const SETTING_WHEEL_DEVICE: SettingId = SettingId::from_static("input.wheel_device");
65pub const SETTING_WHEEL_SPEED: SettingId = SettingId::from_static("input.wheel_speed");
67
68pub const SYSTEM_WHEEL_LINES: u32 = 3;
70
71const WHEEL_SPEEDS: (f64, f64) = (0.25, 5.0);
73
74pub const CMD_OVERRIDES: CommandId = CommandId::from_static("pointer.overrides");
78
79pub const CATEGORY: &str = "Pointer";
81
82pub 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
95pub 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
103pub fn profile(app: &AppHandle) -> &'static Profile {
105 pointer::profile(&profile_id(app)).unwrap_or_else(pointer::default_profile)
106}
107
108pub 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
128pub 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
148pub 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
169pub 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
175pub 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
183pub 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
192pub(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
204pub(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#[derive(Debug, Default)]
219pub(crate) struct Sync {
220 pub loaded: Option<String>,
223 pub published: Option<(Arc<PointerMap>, u64, String)>,
226}
227
228pub(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
244pub(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
280pub(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}