Keep shortcut edits atomic when a binding cannot be saved

This commit is contained in:
dotCooCoo committed 2026-11-26 13:01:10 -08:00
1 parent 8cb94baa2b
commit dadf72bbbe
6 files changed
+166 -31

No files matched your search

+53 -21
View File
@@ -102,6 +102,13 @@ pub enum AssignError {
UnknownScope(Scope),
/// The change needs a new [`Overrides`] entry and it already holds [`MAX_COMMANDS`].
Full,
/// A binding cannot be written and read back in the overrides format.
Unstorable {
/// The command whose bindings cannot be saved.
command: CommandRef,
/// The shortcut that cannot be saved.
trigger: Trigger,
},
/// A hold is a chord that types a character, alone or with Shift: never Space, Backtick, Cmd, Ctrl or Alt.
NotHoldable(Trigger),
}
@@ -115,6 +122,7 @@ impl fmt::Display for AssignError {
AssignError::Taken(h) => write!(f, "in use by {} other command(s)", h.len()),
AssignError::UnknownScope(s) => write!(f, "unknown scope {s}"),
AssignError::Full => write!(f, "more than {MAX_COMMANDS} changed commands"),
AssignError::Unstorable { command, trigger } => write!(f, "{trigger} for {} cannot be saved in its current scope", command.key()),
AssignError::NotHoldable(t) => write!(f, "{t} cannot be held"),
}
}
@@ -605,11 +613,21 @@ impl Keymap {
/// not have it, or when the change needs a new [`Overrides`] entry and the overrides are full
/// ([`AssignError::Full`]); nothing changes then.
pub fn remove(&mut self, command: &CommandRef, binding: &Binding) -> bool {
let Some(i) = self.find(command) else { return false };
self.try_remove(command, binding).unwrap_or(false)
}
/// Removes one binding and reports why an edit could not be saved. `Ok(false)` means the command did not have
/// that binding.
pub fn try_remove(&mut self, command: &CommandRef, binding: &Binding) -> Result<bool, AssignError> {
let i = self.find(command).ok_or(AssignError::UnknownCommand)?;
let gone = self.bound(i, binding);
let before = self.current[i].len();
let list: Vec<Bound> = self.current[i].iter().filter(|b| !self.same(b, &gone)).cloned().collect();
list.len() != before && self.commit(vec![(i, list)]).is_ok()
if list.len() == before {
return Ok(false);
}
self.commit(vec![(i, list)])?;
Ok(true)
}
/// Leaves a command without shortcuts, in every scope. `false` for an unknown command, or when
@@ -926,38 +944,52 @@ impl Keymap {
Ok(done)
}
/// Stores several commands' bindings, or none of them when the overrides lack room for the
/// new entries.
/// Prepares all entries before replacing live or stored bindings, including commands whose bindings were taken.
fn commit(&mut self, writes: Vec<(usize, Vec<Bound>)>) -> Result<(), AssignError> {
let needed = writes.iter().filter(|(i, list)| self.stored[*i].is_none() && !self.is_default(*i, list)).count();
let mut prepared = Vec::with_capacity(writes.len());
for (i, list) in writes {
let texts = self.store_texts(i, &list)?;
prepared.push((i, list, texts));
}
let needed = prepared.iter().filter(|(i, _, texts)| self.stored[*i].is_none() && texts.is_some()).count();
if self.overrides.len() + needed > MAX_COMMANDS {
return Err(AssignError::Full);
}
for (i, list) in writes {
self.store(i, list);
for (i, list, texts) in prepared {
self.remove_entries(i);
if let Some(texts) = texts {
self.overrides.insert(self.keys[i].clone(), texts);
self.stored[i] = Some(self.keys[i].clone());
}
self.set_current(i, list);
}
Ok(())
}
/// Writes a command's bindings to the overrides, dropping the entry when they equal the
/// Prepares a command's overrides, dropping the entry when its bindings equal the
/// defaults. Texts of the old entry this build cannot use stay in it, after the bindings and up
/// to [`MAX_BINDINGS`], unless the command is left without bindings: an entry of only such
/// texts loads as the defaults. Callers check for room first ([`Keymap::commit`]); texts always
/// fit, since a scope name, `": "` and the longest double press stay under
/// [`MAX_BINDING_TEXT`].
fn store(&mut self, i: usize, list: Vec<Bound>) {
/// to [`MAX_BINDINGS`], unless the command is left without bindings. An entry of only such texts loads as the defaults.
fn store_texts(&self, i: usize, list: &[Bound]) -> Result<Option<Vec<String>>, AssignError> {
let mut kept = if list.is_empty() { Vec::new() } else { self.unusable_texts(i) };
kept.truncate(MAX_BINDINGS.saturating_sub(list.len()));
self.remove_entries(i);
if !kept.is_empty() || !self.is_default(i, &list) {
let home = &self.catalog[i].scope;
let mut texts: Vec<String> = list.iter().map(|b| self.public(i, b).text(home)).collect();
texts.extend(kept);
if self.overrides.insert(self.keys[i].clone(), texts) {
self.stored[i] = Some(self.keys[i].clone());
if kept.is_empty() && self.is_default(i, list) {
return Ok(None);
}
let saved = self.stored[i].as_deref().and_then(|key| self.overrides.get(key)).unwrap_or_default();
let mut texts = Vec::with_capacity(list.len() + kept.len());
for bound in list {
let binding = self.public(i, bound);
let text = binding.to_string();
if Binding::parse(&text).as_ref() == Ok(&binding) {
texts.push(text);
} else if let Some(existing) = saved.iter().find(|text| Binding::parse(text).as_ref() == Ok(&binding)) {
texts.push(existing.clone());
} else {
return Err(AssignError::Unstorable { command: self.catalog[i].command.clone(), trigger: binding.trigger });
}
}
self.set_current(i, list);
texts.extend(kept);
Ok(Some(texts))
}
/// Removes a command's overrides entries: the one it reads and hand-written variants of its
+55
View File
@@ -26,6 +26,61 @@ fn app(id: &str, keys: &[&str]) -> CommandDef {
keys.iter().fold(CommandDef::new(id, id, Scope::app()), |e, k| e.with_default(b(k)))
}
#[test]
fn a_replacement_that_is_too_long_to_store_leaves_both_commands_intact() {
let context = "Text".repeat(16);
let scope = scope(&context);
let command = cmd("text.save");
let other = cmd("text.export");
let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap();
let held = Binding::new(trigger);
let catalog = || vec![app("text.save", &["Cmd+S"]), CommandDef::new("text.export", "Export Text", scope.clone()).with_default(held.clone())];
let mut km = Keymap::new(catalog(), Scopes::new().with_context(&context), Platform::Mac);
let original = Binding::in_scope(Trigger::parse("Cmd+K").unwrap(), scope.clone());
km.set_bindings(&command, vec![original.clone()], Policy::Keep).unwrap();
let saved = km.overrides().clone();
let replacement = Binding::in_scope(trigger, scope.clone());
assert!(matches!(km.set_bindings(&command, vec![replacement], Policy::Steal), Err(craft_keymap::AssignError::Unstorable { .. })));
assert_eq!(km.bindings(&command), std::slice::from_ref(&original));
assert_eq!(km.bindings(&other), std::slice::from_ref(&held));
assert_eq!(km.overrides(), &saved);
let mut reopened = Keymap::new(catalog(), Scopes::new().with_context(&context), Platform::Mac);
reopened.set_overrides(km.overrides().clone());
assert_eq!(reopened.bindings(&command), [original]);
}
#[test]
fn a_binding_that_would_reload_in_another_scope_is_refused() {
let command = cmd("text.save");
let mut km = Keymap::new(vec![app("text.save", &["Cmd+S"])], Scopes::new().with_context("Cmd+"), Platform::Mac);
let binding = Binding::in_scope(Trigger::parse("Cmd+:").unwrap(), scope("Cmd+"));
assert!(matches!(km.set_bindings(&command, vec![binding], Policy::Keep), Err(craft_keymap::AssignError::Unstorable { .. })));
assert_eq!(km.bindings(&command), [b("Cmd+S")]);
assert!(km.overrides().is_empty());
}
#[test]
fn editing_one_shortcut_keeps_a_saved_spelling_that_can_be_read_back() {
let command = cmd("text.save");
let catalog = || vec![app("text.save", &["Cmd+S"])];
let scopes = || Scopes::new().with_context("Cmd+");
let mut km = Keymap::new(catalog(), scopes(), Platform::Mac);
let scoped = Binding::in_scope(Trigger::parse("Cmd+:").unwrap(), scope("Cmd+"));
let stored = "Cmd+: Cmd + :";
let mut overrides = Overrides::new();
assert!(overrides.insert(command.key(), vec![stored.into(), "Cmd+S".into()]));
km.set_overrides(overrides);
assert!(km.bindings(&command).contains(&scoped));
assert!(km.remove(&command, &b("Cmd+S")));
assert_eq!(km.overrides().get(&command.key()).unwrap(), [stored]);
let mut reopened = Keymap::new(catalog(), scopes(), Platform::Mac);
reopened.set_overrides(km.overrides().clone());
assert_eq!(reopened.bindings(&command), [scoped]);
}
fn in_scope(id: &str, home: &str, keys: &[&str]) -> CommandDef {
keys.iter().fold(CommandDef::new(id, id, scope(home)), |e, k| e.with_default(b(k)))
}
+2
View File
@@ -476,6 +476,7 @@ impl<'a> ShortcutsDialog<'a> {
return Err(inactive());
}
state.assign_field(env);
state.edit_result()?;
}
serde_json::Value::Bool(false) => {}
_ => return Err(rejects()),
@@ -487,6 +488,7 @@ impl<'a> ShortcutsDialog<'a> {
return Err(rejects());
}
state.remove(env, &command, &wanted);
state.edit_result()?;
}
_ => return Err(FieldRefusal::Unknown.message(field)),
}
+33 -8
View File
@@ -659,11 +659,20 @@ impl DialogState {
let text = fill!(env, chord_is_used_by_label, ("chord", &chord), ("label", &env.holder_labels(&holders)));
self.conflict = Some(ConflictBar { command: command.clone(), old, binding, holders, text });
}
ConflictMode::Steal => self.apply_and_say(env, command, old, binding, Policy::Steal),
ConflictMode::Keep => self.apply_and_say(env, command, old, binding, Policy::Keep),
ConflictMode::Steal => {
self.apply_and_say(env, command, old, binding, Policy::Steal);
}
ConflictMode::Keep => {
self.apply_and_say(env, command, old, binding, Policy::Keep);
}
}
}
/// Reports the same refusal to an automation caller that the dialog shows to the user.
pub(crate) fn edit_result(&self) -> Result<(), String> {
self.message.as_ref().filter(|message| message.refused).map_or(Ok(()), |message| Err(message.text.clone()))
}
fn refuse(&mut self, text: String) {
self.message = Some(Message { text, refused: true, goto: None, undo: false, chord: None });
}
@@ -687,6 +696,10 @@ impl DialogState {
}
Err(e) => {
let text = assign_error(env, &e);
let chord = match &e {
AssignError::Unstorable { trigger, .. } => env.chord_text(trigger),
_ => chord,
};
self.refuse_chord(text, chord);
None
}
@@ -694,12 +707,12 @@ impl DialogState {
}
/// Applies with Steal or Keep and says what it did, with Go to Conflict (and Undo for Steal).
fn apply_and_say(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, binding: Binding, policy: Policy) {
fn apply_and_say(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, binding: Binding, policy: Policy) -> bool {
let chord = env.chord_text(&binding.trigger);
let Some(a) = self.apply(env, command, old, binding, policy) else { return };
let Some(a) = self.apply(env, command, old, binding, policy) else { return false };
let (holders, steal) = if policy == Policy::Steal { (&a.taken_from, true) } else { (&a.clashes, false) };
if holders.is_empty() {
return;
return true;
}
let label = env.holder_labels(holders);
let text = if steal {
@@ -709,6 +722,7 @@ impl DialogState {
};
let goto = holders.first().map(|h| h.command.clone());
self.message = Some(Message { text, refused: false, goto, undo: policy == Policy::Steal, chord: Some(chord) });
true
}
/// Take It.
@@ -722,8 +736,9 @@ impl DialogState {
pub(crate) fn take_it_and_go(&mut self, env: &mut Env) {
if let Some(c) = self.conflict.take() {
let first = c.holders.first().map(|h| h.command.clone());
self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal);
if let Some(holder) = first {
if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal)
&& let Some(holder) = first
{
self.go_to(env, &holder);
}
}
@@ -770,7 +785,14 @@ impl DialogState {
/// × on a chip, or Remove.
pub(crate) fn remove(&mut self, env: &mut Env, command: &CommandRef, binding: &Binding) {
self.edit(env, |s, km| s.remove(km, command, binding));
self.message = None;
let km = &mut *env.keymap;
let result = self.session.get_or_insert_with(|| EditSession::begin(km)).edit(km, |km| km.try_remove(command, binding));
match result {
Ok(true) => self.edited(env),
Ok(false) => {}
Err(error) => self.refuse(assign_error(env, &error)),
}
}
/// Remove in [`Layout::CommandLists`]: takes away the key picked among the selected command's keys.
@@ -1293,6 +1315,9 @@ fn assign_error(env: &Env, e: &AssignError) -> String {
AssignError::TooMany => fill!(env, a_command_can_have_at_most, ("n", &MAX_BINDINGS.to_string())),
AssignError::UnknownScope(s) => fill!(env, the_scope_scope_is_unknown, ("scope", s.as_str())),
AssignError::Full => word!(env, too_many_shortcuts_are_assigned),
AssignError::Unstorable { command, trigger } => {
fill!(env, shortcut_cannot_be_saved_in_its_scope, ("chord", &env.chord_text(trigger)), ("command", &env.label(command)))
}
AssignError::UnknownCommand => word!(env, this_command_is_unknown),
AssignError::Taken(holders) => fill!(env, also_used_by_label, ("label", &env.holder_labels(holders))),
AssignError::NotHoldable(t) => fill!(env, not_holdable, ("chord", &env.chord_text(t))),
+1
View File
@@ -113,6 +113,7 @@ craft_ui::words! {
also_used_by_label: template "keyboardShortcuts.alsoUsedByLabel" = "Also used by {label}";
chord_is_reserved_by_the_system: template "keyboardShortcuts.chordIsReservedByTheSystem" = "{chord} is reserved by the system";
a_command_can_have_at_most: template "keyboardShortcuts.aCommandCanHaveAtMost" = "A command can have at most {n} shortcuts";
shortcut_cannot_be_saved_in_its_scope: template "keyboardShortcuts.shortcutCannotBeSavedInItsScope" = "{chord} for {command} cannot be saved in its current scope";
the_scope_scope_is_unknown: template "keyboardShortcuts.theScopeScopeIsUnknown" = "The scope {scope} is unknown";
too_many_shortcuts_are_assigned: "keyboardShortcuts.tooManyShortcutsAreAssigned" = "Too many shortcuts are assigned";
this_command_is_unknown: "keyboardShortcuts.thisCommandIsUnknown" = "This command is unknown";
+22 -2
View File
@@ -1,11 +1,12 @@
//! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back.
use craft_keymap::{Binding, CommandRef, Platform};
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger};
use craft_menu::shortcuts::{Layout, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
use super::fixture::Rig;
use super::fixture::{Rig, options};
/// Records `key` with the command modifier in the New Shortcut field.
fn record(rig: &mut Rig, key: Key) {
@@ -18,6 +19,25 @@ fn keys(rig: &Rig) -> Vec<Binding> {
rig.shared.borrow().km.bindings(&CommandRef::from("object.front")).to_vec()
}
#[trial]
fn remove_identifies_the_retained_shortcut_that_blocks_saving() {
let context = "Text".repeat(16);
let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap();
let retained = Binding::in_scope(trigger, Scope::new(&context).unwrap());
let command =
CommandDef::new("text.save", "Save Text", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+S").unwrap());
let keymap = Keymap::new(vec![command], Scopes::new().with_context(&context), Platform::Mac);
let mut options = options();
options.layout = Layout::CommandLists;
let mut rig = Rig::new(keymap, options, None);
rig.click("Save Text");
rig.click("⌘S");
rig.click("Remove");
assert_eq!(rig.bindings("text.save"), [retained.to_string(), "Cmd+S".into()]);
assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save Text cannot be saved").is_empty()));
}
/// Production applies each change at once and has no Cancel: an Escape that rolled back would silently lose them.
#[trial]
fn command_lists_assign_remove_and_close_apply_each_change_at_once() {