PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Keyboard Shortcuts: the dialog switches sets through the engine too (#8286)
David Mann83b30879148d
diff --git a/crates/engine/src/shortcut_sets.rs b/crates/engine/src/shortcut_sets.rsindex ba681f271..c91c3fefc 100644--- a/crates/engine/src/shortcut_sets.rs+++ b/crates/engine/src/shortcut_sets.rs@@ -35,18 +35,29 @@ pub struct ShortcutSet {}impl ShortcutSet {- /// The bindings `p` uses now, without the actions' function keys (they belong to the+ /// A set of these bindings, without the actions' function keys (they belong to the/// actions, as in an `.atn` file, not to a set).+ pub fn from_bindings(shortcuts: &BTreeMap<String, String>, alternates: &BTreeMap<String, Vec<String>>) -> Self {+ let shortcuts = shortcuts.iter().filter(|(id, _)| !is_action_key(id)).map(|(id, k)| (id.clone(), k.clone())).collect();+ Self { shortcuts, alternate_shortcuts: alternates.clone() }+ }++ /// The bindings `p` uses now, without the actions' function keys.pub fn of(p: &Preferences) -> Self {- let shortcuts = p.shortcuts.iter().filter(|(id, _)| !is_action_key(id)).map(|(id, k)| (id.clone(), k.clone())).collect();- Self { shortcuts, alternate_shortcuts: p.alternate_shortcuts.clone() }+ Self::from_bindings(&p.shortcuts, &p.alternate_shortcuts)+ }++ /// Put this set's bindings in place of `shortcuts` / `alternates`, keeping the actions'+ /// function keys: switching sets with `useSet` and in the Keyboard Shortcuts dialog.+ pub fn apply(&self, shortcuts: &mut BTreeMap<String, String>, alternates: &mut BTreeMap<String, Vec<String>>) {+ shortcuts.retain(|id, _| is_action_key(id));+ shortcuts.extend(self.shortcuts.iter().filter(|(id, _)| !is_action_key(id)).map(|(id, k)| (id.clone(), k.clone())));+ *alternates = self.alternate_shortcuts.clone();}/// Use this set's bindings in `p`, keeping the actions' function keys.pub fn load_into(&self, p: &mut Preferences) {- p.shortcuts.retain(|id, _| is_action_key(id));- p.shortcuts.extend(self.shortcuts.iter().filter(|(id, _)| !is_action_key(id)).map(|(id, k)| (id.clone(), k.clone())));- p.alternate_shortcuts = self.alternate_shortcuts.clone();+ self.apply(&mut p.shortcuts, &mut p.alternate_shortcuts);}/// Check every key (a set from a call or a hand-edited file must not hold garbage).@@ -91,15 +102,22 @@ fn saved(p: &Preferences) -> Option<&ShortcutSet> {p.shortcut_sets.get(&p.shortcut_set)}-/// Do the bindings differ from the set in use?-pub fn modified(p: &Preferences) -> bool {- let now = ShortcutSet::of(p);- match saved(p) {- Some(s) => *s != now,+/// Do these bindings differ from the set `active` of `sets` ("" or a missing name: the+/// defaults)? The actions' function keys don't count, on either side (a set saved before they+/// were left out may still hold some). The Keyboard Shortcuts dialog's "(modified)" too.+pub fn differs(sets: &BTreeMap<String, ShortcutSet>, active: &str, shortcuts: &BTreeMap<String, String>, alternates: &BTreeMap<String, Vec<String>>) -> bool {+ let now = ShortcutSet::from_bindings(shortcuts, alternates);+ match sets.get(active) {+ Some(s) => ShortcutSet::from_bindings(&s.shortcuts, &s.alternate_shortcuts) != now,None => now != ShortcutSet::default(),}}+/// Do the bindings differ from the set in use?+pub fn modified(p: &Preferences) -> bool {+ differs(&p.shortcut_sets, &p.shortcut_set, &p.shortcuts, &p.alternate_shortcuts)+}+/// Before the call's binding changes: `useSet` loads a set ("" or [`DEFAULTS_NAME`]: the/// defaults) and makes it the one in use. Returns whether it changed anything.pub fn load(next: &mut Preferences, p: &Value) -> Result<bool, String> {@@ -131,7 +149,8 @@ pub fn store(next: &mut Preferences, p: &Value) -> Result<bool, String> {let name = set_name(name)?;let set: ShortcutSet = serde_json::from_value(s.clone()).map_err(|e| format!("set `{name}`: {e}"))?;set.validate().map_err(|e| format!("set `{name}`: {e}"))?;- sets.insert(name, set);+ // Like `saveSet`, a set holds no action keys.+ sets.insert(name, ShortcutSet::from_bindings(&set.shortcuts, &set.alternate_shortcuts));}next.shortcut_sets = sets;changed = true;@@ -300,6 +319,21 @@ mod tests {assert!(modified(&p), "F9 differs from the defaults");}+ #[test]+ fn sets_from_the_dialog_or_an_old_file_hold_no_action_keys() {+ // The dialog's OK sends its sets as `sets`; an action key in one is dropped.+ let mut p = prefs();+ let sets = json!({"Mine": {"shortcuts": {"edit.copy": "F9", "actions.play:Sepia": "F2"}}});+ store(&mut p, &json!({"sets": sets, "activeSet": "Mine"})).unwrap();+ assert_eq!(p.shortcut_sets["Mine"].shortcuts, BTreeMap::from([("edit.copy".to_string(), "F9".to_string())]));+ // A set saved before action keys were left out still holds one: it doesn't count.+ p.shortcut_sets.get_mut("Mine").unwrap().shortcuts.insert("actions.play:Old".into(), "F5".into());+ p.shortcuts = BTreeMap::from([("edit.copy".to_string(), "F9".to_string()), ("actions.play:Sepia".to_string(), "F2".to_string())]);+ assert!(!modified(&p), "neither side's action keys count");+ p.shortcuts.insert("edit.copy".into(), "F8".into());+ assert!(modified(&p), "a real edit does");+ }+#[test]fn switching_sets_keeps_action_function_keys() {// An action's F-key belongs to the action (as in an .atn file), not to a shortcut set.diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rsindex f699bce37..7f255ea6e 100644--- a/crates/ui-egui/src/prefs_ui.rs+++ b/crates/ui-egui/src/prefs_ui.rs@@ -2204,11 +2204,9 @@ fn set_row(if !active.is_empty() && !sets.contains_key(&active) {active.clear();}- let now = ShortcutSet { shortcuts: overrides.clone(), alternate_shortcuts: alternates.clone() };- let modified = match sets.get(&active) {- Some(s) => *s != now,- None => now != ShortcutSet::default(),- };+ // The engine decides what a set holds and when it is modified (not the actions' F-keys).+ let now = ShortcutSet::from_bindings(overrides, alternates);+ let modified = shortcut_sets::differs(&sets, &active, overrides, alternates);let defaults = tl!("PhotoCraft Defaults").to_string();let shown = |name: &str| -> String {let base = if name.is_empty() { defaults.clone() } else { name.to_string() };@@ -2224,9 +2222,8 @@ fn set_row(let mut chosen = active.clone();let pairs: Vec<(String, &str)> = names.iter().map(|(n, l)| (n.clone(), l.as_str())).collect();if crate::widgets::dropdown(ui, "shortcut-set", &mut chosen, &pairs, 220.0) && chosen != active {- let set = sets.get(&chosen).cloned().unwrap_or_default();- *overrides = set.shortcuts;- *alternates = set.alternate_shortcuts;+ // As `useSet`: the set's bindings, keeping the actions' F-keys.+ sets.get(&chosen).cloned().unwrap_or_default().apply(overrides, alternates);active = chosen;message.clear();}diff --git a/crates/ui-egui/src/shortcut_set_tests.rs b/crates/ui-egui/src/shortcut_set_tests.rsindex b00f3839f..2158a4209 100644--- a/crates/ui-egui/src/shortcut_set_tests.rs+++ b/crates/ui-egui/src/shortcut_set_tests.rs@@ -6,7 +6,7 @@ use std::cell::RefCell;use std::rc::Rc;use egui_kittest::Harness;-use egui_kittest::kittest::Queryable;+use egui_kittest::kittest::{NodeT, Queryable};use serde_json::{Value, json};use crate::PhotocraftApp;@@ -126,3 +126,102 @@ fn export_and_summarize_write_the_dialogs_bindings() {// Nothing changed the preferences.assert!(h.state().session.prefs().shortcuts.is_empty());}++/// The Set dropdown's shown label: the set in use, with "(modified)" after an edit.+fn shown_set(h: &Harness<'_, PhotocraftApp>) -> String {+ let at = h.query_all_by_label("Set:").next().expect("the Set label").rect().center();+ let combo = h+ .query_all_by_role(egui::accesskit::Role::ComboBox)+ .min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at)))+ .expect("the Set dropdown");+ let node = combo.accesskit_node();+ node.value().or(node.label()).map(|s| s.to_string()).unwrap_or_default()+}++/// Pick `label` in the Set dropdown, as the user does: open it, click the option.+fn pick_set(h: &mut Harness<'_, PhotocraftApp>, label: &str) {+ // The dialog settles where it opens first.+ h.run_steps(6);+ let at = h.query_all_by_label("Set:").next().expect("the Set label").rect().center();+ let at = h+ .query_all_by_role(egui::accesskit::Role::ComboBox)+ .min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at)))+ .expect("the Set dropdown")+ .rect()+ .center();+ h.hover_at(at);+ h.run_steps(1);+ h.drag_at(at);+ h.run_steps(1);+ h.drop_at(at);+ h.run_steps(3);+ let option = h.query_all_by_label(label).rfind(|n| n.accesskit_node().role() != egui::accesskit::Role::ComboBox);+ option.expect("the set in the open list").click();+ h.run_steps(3);+}++/// #7004: an action's F-key belongs to the action, so picking another set in the dialog keeps+/// it (as `useSet` does) and assigning one doesn't mark the set "(modified)".+#[test]+fn the_set_dropdown_keeps_action_function_keys_like_use_set() {+ let (mut h, first, _) = dialog(vec![]);+ h.state_mut().ui.dialogs.retain(|d| d.id != first);+ h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.copy": "F9"}, "saveSet": "A"})).unwrap();+ // B, from a settings file written before sets left action keys out: it holds an old key for+ // the action, and gives F2 to a command.+ h.state_mut().session.edit_prefs(|p| {+ let b = photocraft_engine::shortcut_sets::ShortcutSet {+ shortcuts: [("actions.play:Sepia".to_string(), "F5".to_string()), ("layer.renameLayer".to_string(), "F2".to_string())].into(),+ alternate_shortcuts: Default::default(),+ };+ p.shortcut_sets.insert("B".into(), b);+ });+ h.state_mut().run("edit.keyboardShortcuts", json!({"useSet": ""})).unwrap();+ crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap();+ let ctx = h.ctx.clone();+ let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();+ h.run_steps(4);+ assert_eq!(shown_set(&h), "PhotoCraft Defaults", "an action key doesn't modify the defaults");+ pick_set(&mut h, "A");+ assert_eq!(field(&h, id, "activeSet"), json!("A"));+ assert_eq!(field(&h, id, "overrides"), json!({"edit.copy": "F9", "actions.play:Sepia": "F2"}), "A's keys, and the action's");+ assert_eq!(shown_set(&h), "A");+ pick_set(&mut h, "PhotoCraft Defaults");+ assert_eq!(field(&h, id, "overrides"), json!({"actions.play:Sepia": "F2"}), "kept switching to the defaults");+ pick_set(&mut h, "B");+ // What wins is what `useSet` gives: the action keeps F2, B's old action key is dropped and+ // its own F2 binding stays.+ let mut engine = h.state().session.prefs().clone();+ photocraft_engine::shortcut_sets::load(&mut engine, &json!({"useSet": "B"})).unwrap();+ assert_eq!(field(&h, id, "overrides"), json!(engine.shortcuts));+ assert_eq!(field(&h, id, "overrides"), json!({"actions.play:Sepia": "F2", "layer.renameLayer": "F2"}));+ assert_eq!(shown_set(&h), "B", "B's old action key doesn't count either");+ crate::dialogs::confirm(h.state_mut(), id).unwrap();+ let p = h.state().session.prefs();+ assert_eq!((p.shortcut_set.as_str(), p.shortcuts.get("actions.play:Sepia").map(String::as_str)), ("B", Some("F2")));+ assert!(p.shortcut_sets.values().all(|s| !s.shortcuts.keys().any(|k| k.starts_with("actions.play:"))), "OK saves no action key in a set");+}++/// A real edit still marks the set "(modified)"; Save and New Set… store it without the actions'+/// F-keys.+#[test]+fn an_edit_still_marks_the_set_modified_and_sets_save_no_action_keys() {+ let (mut h, first, _) = dialog(vec![]);+ h.state_mut().ui.dialogs.retain(|d| d.id != first);+ h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"edit.copy": "F9"}, "saveSet": "A"})).unwrap();+ crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap();+ let ctx = h.ctx.clone();+ let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap();+ h.run_steps(4);+ assert_eq!(shown_set(&h), "A");+ set_field(&mut h, id, "overrides", json!({"edit.copy": "F8", "actions.play:Sepia": "F2"}));+ assert_eq!(shown_set(&h), "A (modified)");+ click(&mut h, "Save");+ assert_eq!(field(&h, id, "sets")["A"]["shortcuts"], json!({"edit.copy": "F8"}));+ assert_eq!(shown_set(&h), "A");+ click(&mut h, "New Set…");+ set_field(&mut h, id, "newSetName", json!("C"));+ click(&mut h, "Create");+ assert_eq!(field(&h, id, "sets")["C"]["shortcuts"], json!({"edit.copy": "F8"}));+ assert_eq!(shown_set(&h), "C");+}