Merge pull request #3948 from dotCooCoo/fix/shortcut-automation-replace-b-verify

Replace a keyboard shortcut through dialog automation
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 11:34:37 +07:00
commit 88ee49fdb0
12 files changed
+593 -43

No files matched your search

+12 -2
View File
@@ -104,8 +104,8 @@ impl EditSession {
new: Binding,
policy: Policy,
) -> Result<Assigned, AssignError> {
let list: Vec<Binding> = keymap.bindings(command).into_iter().map(|b| if b == *old { new.clone() } else { b }).collect();
self.edit(keymap, |km| km.set_bindings(command, list, policy))
let bindings = replacing(keymap, command, old, &new);
self.edit(keymap, |km| km.set_bindings(command, bindings, policy))
}
/// Removes one binding of a command as one undo step.
@@ -180,6 +180,16 @@ impl EditSession {
}
}
/// Checks whether the replacement that [`EditSession::replace`] would make can be saved under `policy`.
/// This leaves the keymap and its undo history untouched.
pub fn check_replace(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding, policy: Policy) -> Result<(), AssignError> {
keymap.check_set_bindings(command, replacing(keymap, command, old, new), policy)
}
fn replacing(keymap: &Keymap, command: &CommandRef, old: &Binding, new: &Binding) -> Vec<Binding> {
keymap.bindings(command).into_iter().map(|binding| if binding == *old { new.clone() } else { binding }).collect()
}
/// The other commands whose bindings clash with `binding` given to `command`: what
/// [`Policy::Steal`] would take and [`Policy::Keep`] would leave clashing. Tools of the command's
/// group and twins sharing a default key are not listed. A dialog shows these while the user
+26 -8
View File
@@ -229,6 +229,8 @@ pub struct Conflict {
/// A binding with its scope resolved.
type Bound = (Trigger, Scope);
type BindingWrites = Vec<(usize, Vec<Bound>)>;
type StoredBindingWrites = Vec<(usize, Vec<Bound>, Option<Vec<String>>)>;
/// Whether `trigger` can start a command: any press can; a hold needs a chord that types a character, alone or with
/// Shift, since the others are taken by the system and by text fields.
@@ -592,11 +594,24 @@ impl Keymap {
}
let mut list = self.current[i].clone();
list.push(new.clone());
self.apply(i, list, &[new], policy)
let (assigned, writes) = self.plan_writes(i, list, &[new], policy)?;
self.commit(writes)?;
Ok(assigned)
}
/// Replaces all bindings of a command.
pub fn set_bindings(&mut self, command: &CommandRef, bindings: Vec<Binding>, policy: Policy) -> Result<Assigned, AssignError> {
let (assigned, writes) = self.plan_set_bindings(command, bindings, policy)?;
self.commit(writes)?;
Ok(assigned)
}
pub(crate) fn check_set_bindings(&self, command: &CommandRef, bindings: Vec<Binding>, policy: Policy) -> Result<(), AssignError> {
let (_, writes) = self.plan_set_bindings(command, bindings, policy)?;
self.prepare_writes(writes).map(|_| ())
}
fn plan_set_bindings(&self, command: &CommandRef, bindings: Vec<Binding>, policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> {
let i = self.find(command).ok_or(AssignError::UnknownCommand)?;
if bindings.len() > MAX_BINDINGS {
return Err(AssignError::TooMany);
@@ -606,7 +621,7 @@ impl Keymap {
let kept: Vec<Bound> = self.hidden(i).into_iter().filter(|h| !list.iter().any(|b| self.same(b, h))).collect();
list.extend(kept);
let new: Vec<Bound> = list.iter().filter(|b| !self.current[i].iter().any(|c| self.same(c, b))).cloned().collect();
self.apply(i, list, &new, policy)
self.plan_writes(i, list, &new, policy)
}
/// Removes one binding (matched by effective trigger and scope). `false` when the command does
@@ -898,7 +913,7 @@ impl Keymap {
out.len() < MAX_CONFLICTS
}
fn apply(&mut self, i: usize, list: Vec<Bound>, new: &[Bound], policy: Policy) -> Result<Assigned, AssignError> {
fn plan_writes(&self, i: usize, list: Vec<Bound>, new: &[Bound], policy: Policy) -> Result<(Assigned, BindingWrites), AssignError> {
if list.len() > MAX_BINDINGS {
return Err(AssignError::TooMany);
}
@@ -916,7 +931,7 @@ impl Keymap {
let holders: Vec<Holder> =
clashes.iter().map(|(j, b)| Holder { command: self.catalog[*j].command.clone(), binding: self.public(*j, b) }).collect();
let mut done = Assigned::default();
let mut writes: Vec<(usize, Vec<Bound>)> = Vec::new();
let mut writes = Vec::new();
match policy {
Policy::Refuse if !holders.is_empty() => return Err(AssignError::Taken(holders)),
Policy::Refuse => {}
@@ -940,12 +955,11 @@ impl Keymap {
}
}
writes.push((i, list));
self.commit(writes)?;
Ok(done)
Ok((done, writes))
}
/// 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> {
fn prepare_writes(&self, writes: BindingWrites) -> Result<StoredBindingWrites, AssignError> {
let mut prepared = Vec::with_capacity(writes.len());
for (i, list) in writes {
let texts = self.store_texts(i, &list)?;
@@ -955,7 +969,11 @@ impl Keymap {
if self.overrides.len() + needed > MAX_COMMANDS {
return Err(AssignError::Full);
}
for (i, list, texts) in prepared {
Ok(prepared)
}
fn commit(&mut self, writes: BindingWrites) -> Result<(), AssignError> {
for (i, list, texts) in self.prepare_writes(writes)? {
self.remove_entries(i);
if let Some(texts) = texts {
self.overrides.insert(self.keys[i].clone(), texts);
+15 -1
View File
@@ -1,6 +1,7 @@
//! Integration tests of craft-keymap: editor.
use craft_keymap::{Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes};
use craft_keymap::editor::check_replace;
use craft_keymap::{AssignError, Binding, CommandDef, CommandRef, EditSession, Keymap, Platform, Policy, Scope, Scopes};
fn b(text: &str) -> Binding {
Binding::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
@@ -20,6 +21,19 @@ fn keys(km: &Keymap, id: &str) -> Vec<String> {
km.bindings(&CommandRef::new(id)).iter().map(|b| b.to_string()).collect()
}
#[test]
fn checking_a_replacement_does_not_take_the_other_commands_shortcut() {
let km = keymap(Platform::Mac);
let save = CommandRef::new("file.save");
let old = b("Cmd+S");
let new = b("Cmd+C");
assert!(matches!(check_replace(&km, &save, &old, &new, Policy::Refuse), Err(AssignError::Taken(_))));
assert!(check_replace(&km, &save, &old, &new, Policy::Steal).is_ok());
assert_eq!(keys(&km, "file.save"), ["Cmd+S"]);
assert_eq!(keys(&km, "edit.copy"), ["Cmd+C"]);
assert!(km.overrides().is_empty());
}
#[test]
fn edits_undo_redo_and_cancel() {
let mut km = keymap(Platform::Windows);
+8
View File
@@ -135,6 +135,14 @@ The module documentation lists every `Outcome`, `Options` and the words (`Shortc
app translates. The dialog never opens a file dialog or touches the file system. Enable
`screen-testing` for the stories and the `it` trials.
Automation can select a command and set `replace` to `{"old":"Text: Cmd+B","new":"Cmd+K"}`
through `ShortcutsDialog::set_json_field`. The old text must identify exactly one current binding;
the new trigger keeps its scope and regular or Hold column. An equivalent trigger changes nothing,
and a changed replacement has one Undo step. Ask mode leaves the original binding until the user
answers the conflict bar; Steal and Keep follow the host's configured policy. A stale confirmation
cannot replace bindings that changed after its prompt opened. Unavailable edits and replacements
that cannot be stored return a refusal.
## Windows, Linux and web: the in-window bar
`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by
+33 -4
View File
@@ -444,10 +444,14 @@ impl<'a> ShortcutsDialog<'a> {
self
}
/// Sets the value `field` names in `state`, as the user editing that control would
/// (`search`, `area`, `command`, `pressed`; `assign` true presses Assign; `remove` takes the text
/// of one of the command's keys, as [`DialogSnapshot::keys`] reports it), for automation. It builds the words `Env` that `DialogState::set_field` needs. `Err` says why
/// the field was refused.
/// Sets a dialog field for automation, as the user editing `search`, `area`, `command` or `pressed` would.
/// `assign` true presses Assign.
/// `remove` takes one of the selected command's keys as reported by [`DialogSnapshot::keys`]. `replace` takes
/// an object with `old` in the same form and `new` as [`Trigger`] text. It preserves the old scope and keeps
/// hold shortcuts in the Hold column. In [`ConflictMode::Ask`], a conflict leaves the old binding in place
/// until the user confirms. Hosts can use [`ConflictMode::Steal`] or [`ConflictMode::Keep`] for immediate
/// handling. Replacing a shortcut with an equivalent trigger leaves it alone. A replacement that changes
/// the shortcut can be undone in one step. `Err` says why the field was refused.
pub fn set_json_field(self, ui: &Ui, state: &mut DialogState, field: &str, value: &serde_json::Value) -> Result<(), String> {
use craft_ui::dialog::FieldRefusal;
let rejects = || FieldRefusal::Rejects(value).message(field);
@@ -490,6 +494,31 @@ impl<'a> ShortcutsDialog<'a> {
state.remove(env, &command, &wanted);
state.edit_result()?;
}
"replace" => {
if !env.options.editable || !state.is_showing() || state.modal() || state.is_recording() || env.has_app_tab(state.tab) {
return Err(inactive());
}
let command = state.selected.clone().ok_or_else(inactive)?;
let text = |key: &str| value.get(key).and_then(serde_json::Value::as_str).ok_or_else(rejects);
let old_text = text("old")?;
let bindings = env.keymap.bindings(&command);
let mut matches = bindings.iter().filter(|binding| binding.to_string() == old_text);
let old = matches.next().ok_or_else(rejects)?;
let trigger = Trigger::parse(text("new")?).map_err(|_| rejects())?;
if matches.next().is_some() || trigger.is_hold() != old.trigger.is_hold() {
return Err(rejects());
}
let platform = env.keymap.platform();
let effective = trigger.effective(platform);
if effective == old.trigger.effective(platform) {
return Ok(());
}
if bindings.iter().any(|binding| binding.scope == old.scope && binding.trigger.effective(platform) == effective) {
return Err(rejects());
}
let new = Binding { trigger, scope: old.scope.clone() };
state.replace_for_automation(env, &command, old, new)?;
}
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
+1 -1
View File
@@ -120,7 +120,7 @@ pub struct DialogSnapshot {
pub selected: Option<CommandRef>,
/// Commands whose bindings differ from the defaults, with their binding texts.
pub overrides: Vec<(CommandRef, Vec<String>)>,
/// The conflict bar's chord and the commands holding it, while it shows.
/// The pending conflict's chord and the commands holding it. Another prompt or app tab can hide the conflict bar.
pub conflict: Option<(String, Vec<CommandRef>)>,
/// Whether a chord is being recorded, and the command it is for.
pub recording: Option<CommandRef>,
+124 -7
View File
@@ -7,13 +7,15 @@ use craft_keymap::editor::{self, DOUBLE_PRESS, EditSession, Recorded, Recorder};
use craft_keymap::import::{self, ForeignEntry, ForeignSet, ImportOptions, ImportPlan, ImportReport, Start};
use craft_keymap::profiles::{Builtins, ProfileError, Profiles, set_name};
use craft_keymap::{
AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Policy, Scope, Trigger,
AssignError, Assigned, Binding, BindingError, Chord, CommandRef, Holder, Key, Keymap, MAX_BINDINGS, Overrides, ParseError, Platform, Policy,
Scope, Trigger,
};
use craft_ui::primitives::ChordText;
use super::keyboard::KeyboardState;
use super::pages::TabSet;
use super::rows::{self, AreaEntry, AreaId, Built, Filter, RowCache, View};
use super::words::Say;
use super::words::{Say, around_chord};
use super::{ConflictMode, HoldSetting, JSON_FORMAT, Layout, Options, Outcome, summary};
/// What the dialog edits this frame.
@@ -28,6 +30,10 @@ pub(crate) struct Env<'e> {
}
impl Env<'_> {
pub(crate) fn has_app_tab(&self, id: Option<&str>) -> bool {
id.is_some_and(|id| self.tabs.as_ref().is_some_and(|tabs| (0..tabs.len()).any(|i| tabs.describe(i).is_some_and(|(tab, _)| tab == id))))
}
fn chord_text(&self, t: &Trigger) -> String {
self.text.trigger(t, self.keymap.platform())
}
@@ -129,14 +135,43 @@ pub(crate) struct FieldChord {
/// The conflict bar, for one pending chord.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ConflictBar {
pub revision: u64,
pub command: CommandRef,
pub old: Option<Binding>,
pub binding: Binding,
pub holders: Vec<Holder>,
pub can_steal: bool,
pub can_keep: bool,
before: Option<ConflictBasis>,
/// "{chord} is used by {label}".
pub text: String,
}
impl ConflictBar {
pub(crate) fn notice_text(&self, env: &Env) -> String {
if self.before.is_some() { self.text.clone() } else { around_chord(env.text.rtl(), &self.text, &env.chord_text(&self.binding.trigger)) }
}
}
/// The existing bindings and home scopes that an automation conflict was opened against.
#[derive(Clone, Debug, PartialEq)]
struct ConflictBasis {
bindings: Vec<Vec<Binding>>,
scopes: Vec<Option<Scope>>,
platform: Platform,
}
impl ConflictBasis {
fn of(keymap: &Keymap, command: &CommandRef, holders: &[Holder]) -> Self {
let scopes = std::iter::once(command)
.chain(holders.iter().map(|holder| &holder.command))
.map(|command| keymap.bindable(command).map(|entry| entry.scope.clone()))
.collect();
let bindings = std::iter::once(command).chain(holders.iter().map(|holder| &holder.command)).map(|command| keymap.bindings(command)).collect();
Self { bindings, scopes, platform: keymap.platform() }
}
}
/// A line under the table after an action.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Message {
@@ -269,6 +304,7 @@ pub struct DialogState {
pub(crate) recording: Option<Recording>,
pub(crate) field: Option<FieldChord>,
pub(crate) conflict: Option<ConflictBar>,
conflict_revision: u64,
pub(crate) prompt: Option<Prompt>,
pub(crate) message: Option<Message>,
pub(crate) review: Option<Review>,
@@ -320,6 +356,7 @@ impl DialogState {
recording: None,
field: None,
conflict: None,
conflict_revision: 0,
prompt: None,
message: None,
review: None,
@@ -679,6 +716,49 @@ impl DialogState {
self.commit_with(env, command, old, binding, mode);
}
/// Checks that a replacement can be saved before offering conflict confirmation to an automation caller.
pub(crate) fn replace_for_automation(&mut self, env: &mut Env, command: &CommandRef, old: &Binding, binding: Binding) -> Result<(), String> {
let mut actions = None;
if env.options.conflicts == ConflictMode::Ask && !editor::holders(env.keymap, command, &binding).is_empty() {
let preview = |policy| editor::check_replace(env.keymap, command, old, &binding, policy);
let steal = preview(Policy::Steal);
let keep = preview(Policy::Keep).is_ok();
if let Err(error) = &steal
&& (!keep || !env.options.allow_keep)
{
let text = assign_error(env, error);
self.conflict = None;
self.refuse(text.clone());
return Err(text);
}
actions = Some((steal.is_ok(), keep));
}
self.commit(env, command, Some(old.clone()), binding);
if let (Some(conflict), Some((steal, keep))) = (&mut self.conflict, actions) {
conflict.can_steal = steal;
conflict.can_keep = keep;
conflict.before = Some(ConflictBasis::of(env.keymap, command, &conflict.holders));
let chord = |trigger| {
let text = env.chord_text(trigger);
if env.text.rtl() { ChordText::new(text).isolated() } else { text }
};
let label = env.label(command);
let target = match env.keymap.bindable(command) {
Some(entry) => fill!(env, label_scope, ("label", &label), ("scope", &env.text.scope_name(old.scope_or(&entry.scope)))),
None => label,
};
conflict.text = fill!(
env,
replace_old_for_command_with_chord_used_by_label,
("old", &chord(&old.trigger)),
("command", &target),
("chord", &chord(&conflict.binding.trigger)),
("label", &env.holder_labels(&conflict.holders))
);
}
self.edit_result()
}
fn commit_with(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, binding: Binding, mode: ConflictMode) {
self.conflict = None;
self.message = None;
@@ -701,7 +781,18 @@ impl DialogState {
match mode {
ConflictMode::Ask => {
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 });
self.conflict_revision = self.conflict_revision.wrapping_add(1);
self.conflict = Some(ConflictBar {
revision: self.conflict_revision,
command: command.clone(),
old,
binding,
holders,
can_steal: true,
can_keep: true,
before: None,
text,
});
}
ConflictMode::Steal => {
self.apply_and_say(env, command, old, binding, Policy::Steal);
@@ -771,14 +862,14 @@ impl DialogState {
/// Take It.
pub(crate) fn take_it(&mut self, env: &mut Env) {
if let Some(c) = self.conflict.take() {
if let Some(c) = self.accept_conflict(env) {
self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal);
}
}
/// Accept and Go to Conflict.
pub(crate) fn take_it_and_go(&mut self, env: &mut Env) {
if let Some(c) = self.conflict.take() {
if let Some(c) = self.accept_conflict(env) {
let first = c.holders.first().map(|h| h.command.clone());
if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal)
&& let Some(holder) = first
@@ -793,11 +884,37 @@ impl DialogState {
if !env.options.allow_keep {
return;
}
if let Some(c) = self.conflict.take() {
if let Some(c) = self.accept_conflict(env) {
self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Keep);
}
}
/// The pending conflict the user can currently answer.
pub(crate) fn visible_conflict(&self, env: &Env) -> Option<&ConflictBar> {
self.conflict.as_ref().filter(|conflict| {
conflict.before.is_none() || (env.options.editable && !self.modal() && !self.is_recording() && !env.has_app_tab(self.tab))
})
}
fn accept_conflict(&mut self, env: &Env) -> Option<ConflictBar> {
self.visible_conflict(env)?;
let conflict = self.conflict.take()?;
if let Some(before) = &conflict.before {
let holders = editor::holders(env.keymap, &conflict.command, &conflict.binding);
if holders != conflict.holders || ConflictBasis::of(env.keymap, &conflict.command, &holders) != *before {
self.refuse(word!(env, the_shortcuts_changed_try_replacing_again));
return None;
}
if let (Some(accept), Some(command)) = (&env.options.accept, env.keymap.bindable(&conflict.command))
&& let Err(text) = accept(command, &conflict.binding)
{
self.refuse(text);
return None;
}
}
Some(conflict)
}
/// ✕ on the conflict bar: nothing was applied, so nothing changes.
pub(crate) fn dismiss_conflict(&mut self) {
self.conflict = None;
@@ -982,7 +1099,7 @@ impl DialogState {
pub(crate) fn escape(&mut self, env: &mut Env) {
if self.recording.is_some() {
self.stop_recording();
} else if self.conflict.is_some() {
} else if self.visible_conflict(env).is_some() {
self.conflict = None;
} else if self.prompt.is_some() {
self.prompt = None;
+29 -19
View File
@@ -49,30 +49,40 @@ fn prompt(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) {
}
fn conflict_bar(ui: &mut Ui, env: &mut Env<'_>, state: &mut DialogState) {
let Some(conflict) = state.conflict.clone() else { return };
enum Action {
Take,
TakeAndGo,
Keep,
Dismiss,
}
let Some(conflict) = state.visible_conflict(env).cloned() else { return };
let words = env.text.words();
let chord = env.text.trigger(&conflict.binding.trigger, env.keymap.platform());
let text = around_chord(env.text.rtl(), &conflict.text, &chord);
let text = conflict.notice_text(env);
let keep = conflict.can_keep && env.options.allow_keep;
let mut notice = Notice::new(Tone::Warn, text)
.id_salt("shortcuts.conflict")
.id_salt(("shortcuts.conflict", conflict.revision, keep))
.layout(NoticeLayout::Inline)
.announce(Politeness::Polite)
.action(NoticeAction::new(words.take_it.clone()))
.action(NoticeAction::new(words.accept_and_go_to_conflict.clone()));
let keep = env.options.allow_keep;
if keep {
notice = notice.action(NoticeAction::new(words.keep_both.clone()));
.announce(Politeness::Polite);
let mut actions = Vec::new();
for (available, label, action) in [
(conflict.can_steal, &words.take_it, Action::Take),
(conflict.can_steal, &words.accept_and_go_to_conflict, Action::TakeAndGo),
(keep, &words.keep_both, Action::Keep),
(true, &words.undo_changes, Action::Dismiss),
] {
if available {
notice = notice.action(NoticeAction::new(label.clone()));
actions.push(action);
}
}
// Photoshop's wording for turning the new shortcut down is "Undo Changes", the notice's last action.
let undo_at = if keep { 3 } else { 2 };
notice = notice.action(NoticeAction::new(words.undo_changes.clone()));
let out = notice.show(ui);
match out.action {
Some(0) => state.take_it(env),
Some(1) => state.take_it_and_go(env),
Some(2) if keep => state.keep_both(env),
Some(at) if at == undo_at => state.dismiss_conflict(),
_ => {}
match out.action.and_then(|at| actions.get(at)) {
Some(Action::Take) => state.take_it(env),
Some(Action::TakeAndGo) => state.take_it_and_go(env),
Some(Action::Keep) => state.keep_both(env),
Some(Action::Dismiss) => state.dismiss_conflict(),
None => {}
}
}
+2
View File
@@ -123,6 +123,8 @@ craft_ui::words! {
keep_both: "keyboardShortcuts.keepBoth" = "Keep Both";
go_to_conflict: "keyboardShortcuts.goToConflict" = "Go to Conflict";
undo_changes: "keyboardShortcuts.undoChanges" = "Undo Changes";
replace_old_for_command_with_chord_used_by_label: template "keyboardShortcuts.replaceOldForCommandWithChordUsedByLabel" = "Replace {old} for {command} with {chord}, which is used by {label}";
the_shortcuts_changed_try_replacing_again: "keyboardShortcuts.theShortcutsChangedTryReplacingAgain" = "The shortcuts changed. Try the replacement again.";
dismiss: "keyboardShortcuts.dismiss" = "Dismiss";
// Saved shortcuts that could not be used.
key_no_command_has_this_name: template "keyboardShortcuts.keyNoCommandHasThisName" = "{key}: no command has this name";
+10
View File
@@ -258,6 +258,16 @@ impl Rig {
self.shared.borrow().sets.as_ref().map(|(p, _)| p.active().to_string())
}
/// Sets an automation field in the next dialog pass.
pub(crate) fn set_json_field(&mut self, field: &'static str, value: serde_json::Value) -> Result<(), String> {
let result = Rc::new(RefCell::new(None));
let out = result.clone();
let job: Job = Box::new(move |dialog, ui, state| *out.borrow_mut() = Some(dialog.set_json_field(ui, state, field, &value)));
self.shared.borrow_mut().jobs.push(job);
self.fixture.idle(2);
result.take().expect("the automation job ran")
}
/// Runs `job` with the dialog in the next pass and returns what it returns.
pub(crate) fn import_json(&mut self, json: &str) -> Result<String, ProfileError> {
let result = Rc::new(RefCell::new(None));
+297 -1
View File
@@ -9,11 +9,307 @@ pub(crate) mod rows;
pub(crate) mod sets;
pub(crate) mod tabs;
use craft_keymap::Platform;
use std::cell::Cell;
use std::rc::Rc;
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Policy, Scope, Scopes, Trigger};
use craft_menu::shortcuts::HoldSetting;
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
use serde_json::json;
use fixture::Rig;
#[trial]
fn automation_replaces_a_shortcut_in_its_scope_as_one_undo_step() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("type.bold")).unwrap();
let original = rig.bindings("type.bold");
let old = &original[0];
assert!(rig.set_json_field("replace", json!({"old": old, "new": "not a trigger"})).is_err());
assert!(rig.set_json_field("replace", json!({"old": "Cmd+B", "new": "Cmd+K"})).is_err());
assert!(rig.set_json_field("replace", json!({"old": old, "new": "Hold K"})).is_err());
assert_eq!(rig.bindings("type.bold"), original);
rig.set_json_field("replace", json!({"old": old, "new": "Cmd+K"})).unwrap();
assert_eq!(rig.bindings("type.bold"), ["Text: Cmd+K"]);
rig.click("Undo");
assert_eq!(rig.bindings("type.bold"), original);
let shared = rig.shared.borrow();
assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo);
}
#[trial]
fn an_automation_replacement_waits_for_conflict_confirmation() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save (Application) with").is_empty()));
rig.click("Take It");
assert_eq!(rig.bindings("file.save"), ["Cmd+E"]);
assert!(rig.bindings("file.export").is_empty());
rig.click("Undo");
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
}
#[trial]
fn confirming_an_automation_replacement_preserves_shortcuts_that_changed_after_the_prompt() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
let third = CommandRef::from("object.front");
rig.shared.borrow_mut().km.assign(&third, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap();
rig.pass();
rig.answer("Take It");
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
assert_eq!(rig.bindings("object.front"), ["Cmd+E"]);
let shared = rig.shared.borrow();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none());
}
#[trial]
fn confirming_an_automation_replacement_cannot_change_shortcuts_in_a_new_scope() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
let mut catalog = rig.shared.borrow().km.catalog().to_vec();
for command in &mut catalog {
if matches!(command.command.key().as_str(), "file.save" | "file.export") {
command.scope = Scope::new("Text").unwrap();
}
}
rig.shared.borrow_mut().km = Keymap::new(catalog, Scopes::new().with_context("Text"), Platform::Mac);
rig.pass();
rig.answer("Take It");
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
let shared = rig.shared.borrow();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none());
}
#[trial]
fn a_holder_binding_change_retires_its_pending_replacement_confirmation() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
rig.shared.borrow_mut().km.assign(&CommandRef::from("file.export"), Binding::parse("Cmd+K").unwrap(), Policy::Keep).unwrap();
rig.pass();
rig.answer("Take It");
assert_eq!(rig.bindings("file.save"), ["Cmd+S"], "a stale confirmation cannot replace the original shortcut");
assert_eq!(rig.bindings("file.export"), ["Cmd+E", "Cmd+K"], "the changed holder keeps all its current shortcuts");
let shared = rig.shared.borrow();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none());
}
#[trial]
fn a_superseding_replacement_has_its_own_confirmation_actions() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
let old_action = rig.find("Take It").node;
rig.shared.borrow_mut().options.allow_keep = false;
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+Shift+S"})).unwrap();
assert_ne!(rig.find("Take It").node, old_action);
assert!(!rig.has("Keep Both"));
let dismiss = rig.find("Undo Changes").node;
rig.shared.borrow_mut().options.allow_keep = true;
rig.pass();
assert_ne!(rig.find("Keep Both").node, dismiss);
}
#[trial]
fn escape_dismisses_a_visible_prompt_before_a_hidden_replacement() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+E"})).unwrap();
assert!(rig.has("Take It"));
rig.click("Reset All…");
assert!(rig.has("Reset All"));
assert!(!rig.has("Take It"));
rig.press(Modifiers::NONE, Key::Escape);
assert!(!rig.has("Reset All"));
assert!(rig.has("Take It"));
assert_eq!(rig.bindings("file.save"), ["Cmd+K"]);
}
#[trial]
fn automation_offers_only_keep_both_when_taking_the_shortcut_cannot_be_saved() {
let scope = "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(&scope).unwrap());
let save = CommandDef::new("file.save", "Save", Scope::app()).with_default(Binding::parse("Cmd+S").unwrap());
let export = CommandDef::new("file.export", "Export", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+E").unwrap());
let keymap = Keymap::new(vec![save, export], Scopes::new().with_context(&scope), Platform::Mac);
let mut rig = Rig::new(keymap, fixture::options(), None);
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
assert!(!rig.has("Take It"));
assert!(!rig.has("Accept and Go to Conflict"));
rig.click("Keep Both");
assert_eq!(rig.bindings("file.save"), ["Cmd+E"]);
assert_eq!(rig.bindings("file.export"), [retained.to_string(), "Cmd+E".into()]);
}
#[trial]
fn automation_replacement_preserves_the_shortcut_when_the_app_rejects_it() {
let mut rig = Rig::tuned(Platform::Mac, |options| options.accept = Some(Box::new(|_, _| Err("That shortcut is unavailable".into()))));
rig.set_json_field("command", json!("file.save")).unwrap();
let result = rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"}));
assert_eq!(result, Err("That shortcut is unavailable".into()));
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
}
#[trial]
fn confirming_an_automation_replacement_checks_the_current_app_rule() {
let accepted = Rc::new(Cell::new(true));
let rule = accepted.clone();
let mut rig = Rig::tuned(Platform::Mac, |options| {
options.accept = Some(Box::new(move |_, _| if rule.get() { Ok(()) } else { Err("That shortcut is unavailable".into()) }));
});
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
accepted.set(false);
rig.answer("Take It");
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
let shared = rig.shared.borrow();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none());
}
#[trial]
fn a_pending_automation_conflict_cannot_be_applied_from_a_read_only_dialog() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).unwrap();
assert!(rig.has("Take It"));
rig.shared.borrow_mut().options.editable = false;
rig.pass();
assert!(!rig.has("Take It"));
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
rig.press(Modifiers::NONE, Key::Escape);
assert!(!rig.is_open());
}
#[trial]
fn automation_cannot_replace_a_shortcut_while_reset_confirmation_is_open() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).unwrap();
rig.click("Reset All…");
assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+B"})).is_err());
assert_eq!(rig.bindings("file.save"), ["Cmd+K"]);
}
#[trial]
fn an_automation_hold_replacement_is_dismissed_when_holds_are_disabled() {
let mut keymap = fixture::keymap(Platform::Mac);
keymap.set_holds(true);
for (command, binding) in [("file.save", "Hold K"), ("file.export", "Hold L")] {
keymap.assign(&CommandRef::from(command), Binding::parse(binding).unwrap(), Policy::Keep).unwrap();
}
let mut rig = Rig::with_holds(keymap, fixture::options(), HoldSetting::new(true, 0.5, 0.2..=2.0));
rig.set_json_field("command", json!("file.save")).unwrap();
let original = rig.bindings("file.save");
assert!(rig.set_json_field("replace", json!({"old": "Hold K", "new": "Cmd+E"})).is_err());
rig.set_json_field("replace", json!({"old": "Hold K", "new": "Hold L"})).unwrap();
assert!(rig.has("Take It"));
rig.click("Hold Shortcuts");
assert!(!rig.has("Take It"));
rig.click("Hold Shortcuts");
assert_eq!(rig.bindings("file.save"), original);
}
#[trial]
fn automation_does_not_replace_a_binding_while_the_recorder_owns_it() {
let mut rig = Rig::mac();
rig.set_json_field("command", json!("file.save")).unwrap();
rig.click("Save: ⌘S");
assert!(rig.shared.borrow().state.is_recording());
assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+K"})).is_err());
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
rig.press(Modifiers::COMMAND, Key::L);
assert_eq!(rig.bindings("file.save"), ["Cmd+L"]);
assert!(!rig.shared.borrow().state.is_recording());
}
#[trial]
fn automation_rejects_oversize_replacements_but_can_replace_an_oversize_default() {
let scope = "Text".repeat(16);
let original = Binding::in_scope(Trigger::parse("Cmd+S").unwrap(), Scope::new(&scope).unwrap());
let trigger = "Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash";
let oversize = Binding::in_scope(Trigger::parse(trigger).unwrap(), Scope::new(&scope).unwrap());
let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone());
let repair = CommandDef::new("text.fix", "Fix Text", Scope::app()).with_default(oversize.clone()).with_default(Binding::parse("Cmd+K").unwrap());
let export = CommandDef::new("text.export", "Export Text", Scope::app()).with_default(Binding::parse("Cmd+L").unwrap());
let keymap = Keymap::new(vec![command, repair, export], Scopes::new().with_context(&scope), Platform::Mac);
let mut rig = Rig::new(keymap, fixture::options(), None);
rig.set_json_field("command", json!("text.save")).unwrap();
assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": trigger})).is_err());
assert_eq!(rig.bindings("text.save"), [original.to_string()]);
rig.set_json_field("command", json!("text.fix")).unwrap();
assert!(rig.set_json_field("replace", json!({"old": "Cmd+K", "new": "Cmd+L"})).is_err());
assert!(!rig.has("Take It"));
assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]);
let adjusted = format!("{scope}: Cmd+J");
rig.set_json_field("replace", json!({"old": oversize.to_string(), "new": "Cmd+J"})).unwrap();
assert_eq!(rig.bindings("text.fix"), [adjusted.clone(), "Cmd+K".into()]);
rig.set_json_field("replace", json!({"old": adjusted, "new": trigger})).unwrap();
assert_eq!(rig.bindings("text.fix"), [oversize.to_string(), "Cmd+K".into()]);
assert!(rig.shared.borrow().km.overrides().is_empty());
}
#[trial]
fn automation_rejects_a_shortcut_that_would_reload_in_a_different_scope() {
let scope = "Cmd+";
let original = Binding::in_scope(Trigger::parse("K").unwrap(), Scope::new(scope).unwrap());
let command = CommandDef::new("text.save", "Save Text", Scope::app()).with_default(original.clone());
let keymap = Keymap::new(vec![command], Scopes::new().with_context(scope), Platform::Mac);
let mut rig = Rig::new(keymap, fixture::options(), None);
rig.set_json_field("command", json!("text.save")).unwrap();
assert!(rig.set_json_field("replace", json!({"old": original.to_string(), "new": "Cmd+:"})).is_err());
assert_eq!(rig.bindings("text.save"), [original.to_string()]);
}
#[trial]
fn an_automation_replacement_with_the_same_effective_shortcut_is_a_noop() {
let mut rig = Rig::tuned(Platform::Windows, |_| {});
rig.set_json_field("command", json!("file.save")).unwrap();
rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Ctrl+S"})).unwrap();
assert_eq!(rig.bindings("file.save"), ["Cmd+S"]);
let shared = rig.shared.borrow();
assert!(!shared.state.snapshot(&shared.km).unwrap().can_undo);
}
#[trial]
fn an_automation_replacement_does_not_offer_to_take_a_shortcut_the_command_already_has() {
let mut keymap = fixture::keymap(Platform::Mac);
let save = CommandRef::from("file.save");
keymap.assign(&save, Binding::parse("Cmd+E").unwrap(), Policy::Keep).unwrap();
let mut rig = Rig::new(keymap, fixture::options(), None);
rig.set_json_field("command", json!("file.save")).unwrap();
let original = rig.bindings("file.save");
assert!(rig.set_json_field("replace", json!({"old": "Cmd+S", "new": "Cmd+E"})).is_err());
assert!(!rig.has("Take It"));
assert_eq!(rig.bindings("file.save"), original);
assert_eq!(rig.bindings("file.export"), ["Cmd+E"]);
}
/// A read-only shortcuts reference does not stretch to the window's height: it opens at a moderate, fixed height and
/// scrolls inside it.
#[trial]
+36
View File
@@ -1,5 +1,8 @@
//! The app's pages share the Keyboard Shortcuts dialog's width and navigation.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_host::target::Os;
use craft_keymap::{Platform, Profiles};
use craft_menu::shortcuts::{Area, DialogState, DialogTab, ShortcutsDialog};
@@ -8,9 +11,42 @@ use craft_ui::contract::Role;
use craft_ui::runtime::egui::access::AccessTree;
use craft_ui::runtime::env::RootEnv;
use craft_ui::testing::{Fixture, Frames, pointer, trial};
use serde_json::json;
use super::fixture;
#[trial]
fn shortcut_replacement_is_unavailable_on_an_app_tab() {
for (tab, app_tab) in [("menus", true), ("unknown", false)] {
let result = Rc::new(RefCell::new(None));
let observed = result.clone();
let drawn = Rc::new(Cell::new(false));
let app_page_drawn = drawn.clone();
let mut keys = fixture::keymap(Platform::Mac);
let mut state = DialogState::new().with_tab(tab);
let mut fixture = Fixture::new(move |ui| {
let mut tabs = [DialogTab::new("menus", "Menus", |_| {
app_page_drawn.set(true);
false
})];
if observed.borrow().is_none() {
ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(ui, &mut state, "command", &json!("file.save")).unwrap();
let answer = ShortcutsDialog::new(&mut keys).tabs(&mut tabs).set_json_field(
ui,
&mut state,
"replace",
&json!({"old": "Cmd+S", "new": "Cmd+E"}),
);
*observed.borrow_mut() = Some(answer);
}
ShortcutsDialog::new(&mut keys).tabs(&mut tabs).show(ui, &mut state);
});
fixture.settle();
assert_eq!(drawn.get(), app_tab);
assert_eq!(result.borrow().as_ref().unwrap().is_err(), app_tab);
}
}
fn dialog_at_125_percent(toolbar_label: &str) -> (Frames, impl FnMut(&mut egui::Ui) + '_) {
// Use the Windows test context and a 1600 × 1000 physical-pixel window at 125%.
let mut os = Fixture::new(|_| {});