Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

fix(ui): preview shortcut chords and wait for complete modifier input (#1810)

ealitt6eaf723041b9
diff --git a/assets/locales/de.json b/assets/locales/de.json
index 61385fd774..3d6f872e15 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -1900,6 +1900,12 @@
"ui.sent_to_slicer": "An {slicer} gesendet",
"ui.sheet_gap": "Spalt",
"ui.shell": "Hülle",
+ "ui.shortcut_capture_add_key": "Eine normale Taste hinzufügen. Escape bricht ab.",
+ "ui.shortcut_capture_hint": "Eine Belegung anklicken, dann Modifikatortasten und eine Taste drücken. Weitere Modifikatoren innerhalb einer Sekunde hinzufügen; zum Bestätigen alle Tasten loslassen. Escape bricht ab.",
+ "ui.shortcut_capture_press": "Modifikatortasten und eine Taste drücken. Escape bricht ab.",
+ "ui.shortcut_capture_release": "Zum Bestätigen alle Tasten loslassen. Escape bricht ab.",
+ "ui.shortcut_capture_settling": "Tastenkürzel wird bestätigt… Escape bricht ab.",
+ "ui.shortcut_multiple_keys": "Modifikatortasten und nur eine weitere Taste verwenden. Zum Wiederholen die Belegung anklicken.",
"ui.show": "Einblenden",
"ui.showAll": "Alle einblenden",
"ui.showAllBodies": "Alle Volumenkörper einblenden",
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 795c41511c..89346efff1 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -2126,6 +2126,12 @@
"ui.sent_to_slicer": "Sent to {slicer}",
"ui.sheet_gap": "Gap",
"ui.shell": "Shell",
+ "ui.shortcut_capture_add_key": "Add one ordinary key. Escape cancels.",
+ "ui.shortcut_capture_hint": "Click a binding, then press modifiers and one key. Add modifiers within one second; release all keys to confirm. Escape cancels.",
+ "ui.shortcut_capture_press": "Press modifiers and one key. Escape cancels.",
+ "ui.shortcut_capture_release": "Release all keys to confirm. Escape cancels.",
+ "ui.shortcut_capture_settling": "Confirming shortcut… Escape cancels.",
+ "ui.shortcut_multiple_keys": "Use modifiers and only one other key. Click the binding to try again.",
"ui.show": "Show",
"ui.showAll": "Show All",
"ui.showAllBodies": "Show All Bodies",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 6fc0cba32f..f7ac2c22e9 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -2126,6 +2126,12 @@
"ui.sent_to_slicer": "{slicer} に送信しました",
"ui.sheet_gap": "ギャップ",
"ui.shell": "シェル",
+ "ui.shortcut_capture_add_key": "通常のキーを1つ追加してください。Escでキャンセルします。",
+ "ui.shortcut_capture_hint": "割り当てをクリックし、修飾キーと1つのキーを押します。1秒以内に修飾キーを追加し、すべて離して確定します。Escでキャンセルします。",
+ "ui.shortcut_capture_press": "修飾キーと1つのキーを押してください。Escでキャンセルします。",
+ "ui.shortcut_capture_release": "すべてのキーを離すと確定します。Escでキャンセルします。",
+ "ui.shortcut_capture_settling": "ショートカットを確定中… Escでキャンセルします。",
+ "ui.shortcut_multiple_keys": "修飾キーと、それ以外のキー1つだけを使用してください。割り当てをクリックしてやり直してください。",
"ui.show": "表示",
"ui.showAll": "すべて表示",
"ui.showAllBodies": "すべてのボディを表示",
diff --git a/assets/locales/ko.json b/assets/locales/ko.json
index c0dd6d1a76..f3e19f26cf 100644
--- a/assets/locales/ko.json
+++ b/assets/locales/ko.json
@@ -1775,6 +1775,12 @@
"ui.sent_to_slicer": "{slicer}(으)로 보냈습니다",
"ui.sheet_gap": "틈",
"ui.shell": "쉘",
+ "ui.shortcut_capture_add_key": "일반 키 하나를 추가하세요. Esc를 누르면 취소됩니다.",
+ "ui.shortcut_capture_hint": "단축키를 클릭한 다음 보조 키와 일반 키 하나를 누르세요. 1초 이내에 보조 키를 추가하고 모든 키를 놓아 확정하세요. Esc를 누르면 취소됩니다.",
+ "ui.shortcut_capture_press": "보조 키와 일반 키 하나를 누르세요. Esc를 누르면 취소됩니다.",
+ "ui.shortcut_capture_release": "모든 키를 놓아 확정하세요. Esc를 누르면 취소됩니다.",
+ "ui.shortcut_capture_settling": "단축키 확인 중… Esc를 누르면 취소됩니다.",
+ "ui.shortcut_multiple_keys": "보조 키와 일반 키 하나만 사용하세요. 단축키를 클릭하여 다시 시도하세요.",
"ui.show": "표시",
"ui.showAll": "모두 표시",
"ui.showAllBodies": "모두 표시",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index 0c63042a18..10b2344004 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -2126,6 +2126,12 @@
"ui.sent_to_slicer": "已发送到 {slicer}",
"ui.sheet_gap": "间隙",
"ui.shell": "抽壳",
+ "ui.shortcut_capture_add_key": "请再按一个普通键。按 Esc 取消。",
+ "ui.shortcut_capture_hint": "点击快捷键,然后按下修饰键和一个普通键。在一秒内添加修饰键,松开所有键以确认。按 Esc 取消。",
+ "ui.shortcut_capture_press": "请按修饰键和一个普通键。按 Esc 取消。",
+ "ui.shortcut_capture_release": "松开所有键以确认。按 Esc 取消。",
+ "ui.shortcut_capture_settling": "正在确认快捷键… 按 Esc 取消。",
+ "ui.shortcut_multiple_keys": "请使用修饰键和一个普通键。点击快捷键重试。",
"ui.show": "显示",
"ui.showAll": "显示全部",
"ui.showAllBodies": "显示所有实体",
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index 9534fd477e..c4efbd375b 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -166,7 +166,7 @@ pub(crate) fn cmd(app: &SolveApp, id: &str, label: &str) -> Item {
let shortcut = match id {
"edit.undo" => "Ctrl+Z".to_string(),
"edit.redo" => "Ctrl+Y".to_string(),
- _ => crate::keymap::effective(app, id).unwrap_or_default(),
+ _ => crate::keymap::display_for(app, id).unwrap_or_default(),
};
Item {
id: id.into(),
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index fcc8076490..210bc02808 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -675,9 +675,26 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
}
"ui.key" => {
let Some(key) = s("key").and_then(key_from) else { return err("unknown key") };
- let modifiers = egui::Modifiers { shift: b("shift"), command: b("cmd"), ctrl: b("cmd") || b("ctrl"), ..Default::default() };
- app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
- app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers });
+ // Preserve the control channel's legacy primary-modifier alias. An explicit
+ // ctrl flag opts into physical Control/Command state (ctrl:false for Cmd alone).
+ let explicit_ctrl = p.get("ctrl").is_some();
+ let ctrl = if explicit_ctrl { b("ctrl") } else { b("cmd") };
+ let modifiers = egui::Modifiers { shift: b("shift"), alt: b("alt"), ctrl, command: b("cmd") || ctrl, mac_cmd: b("cmd") && explicit_ctrl };
+ let pressed = match p.get("pressed") {
+ None => None,
+ Some(Value::Bool(pressed)) => Some(*pressed),
+ Some(_) => return err("pressed must be a boolean"),
+ };
+ app.synthetic.push(egui::Event::ModifiersChanged(modifiers));
+ if pressed != Some(false) {
+ app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
+ }
+ if pressed != Some(true) {
+ app.synthetic.push(egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers });
+ }
+ if pressed.is_none() {
+ app.synthetic.push(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ }
ok(Value::Null)
}
"ui.text" => {
diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs
index 1020a456d1..eaa3b45943 100644
--- a/crates/ui-egui/src/keymap.rs
+++ b/crates/ui-egui/src/keymap.rs
@@ -61,11 +61,118 @@ pub struct Keymap {
filter: String,
/// The command waiting for a key press.
capturing: Option<String>,
+ recorder: Recorder,
/// A key that another command uses: (command, key, the other commands).
conflict: Option<(String, String, Vec<String>)>,
message: Option<String>,
}
+/// A chord is one ordinary key plus modifier state, as in the platform key-event model.
+/// The one-second settling period is an editor affordance, not a shortcut activation delay.
+const RECORD_SETTLE_SECONDS: f64 = 1.0;
+
+#[derive(Default)]
+struct Recorder {
+ key: Option<egui::Key>,
+ modifiers: egui::Modifiers,
+ changed_at: f64,
+}
+
+enum Recording {
+ Waiting,
+ Cancelled,
+ MultipleKeys,
+ Complete(String),
+}
+
+impl Recorder {
+ fn add_modifiers(&mut self, modifiers: egui::Modifiers, now: f64) {
+ if self.key.is_none() {
+ // Before the ordinary key, preview only what is currently held. A modifier
+ // pressed and released while choosing a chord must not become part of it.
+ self.modifiers = modifiers;
+ } else {
+ let combined = self.modifiers | modifiers;
+ if combined != self.modifiers {
+ self.modifiers = combined;
+ self.changed_at = now;
+ }
+ }
+ }
+
+ fn preview(&self) -> Option<String> {
+ match self.key {
+ Some(key) => Some(format!("{}…", display(&key_name(key, self.modifiers)))),
+ None if !self.modifiers.is_none() => Some(format!("{}…", display(&modifier_prefix(self.modifiers)))),
+ None => None,
+ }
+ }
+
+ fn hint(&self, input: &egui::InputState) -> &'static str {
+ if self.key.is_none() {
+ if self.modifiers.is_none() { "ui.shortcut_capture_press" } else { "ui.shortcut_capture_add_key" }
+ } else if !input.keys_down.is_empty() || !input.modifiers.is_none() {
+ "ui.shortcut_capture_release"
+ } else {
+ "ui.shortcut_capture_settling"
+ }
+ }
+
+ fn update(&mut self, input: &egui::InputState) -> Recording {
+ // Cancel on an actual focus loss. The control channel can legitimately open the
+ // recorder while the window is already in the background.
+ if input.events.iter().any(|event| matches!(event, egui::Event::WindowFocused(false))) {
+ return Recording::Cancelled;
+ }
+ for event in &input.events {
+ match event {
+ egui::Event::ModifiersChanged(modifiers) => self.add_modifiers(*modifiers, input.time),
+ // egui also emits physical left/right modifier key events. They carry
+ // modifier state but must never occupy the chord's ordinary-key slot.
+ egui::Event::Key {
+ key:
+ egui::Key::ShiftLeft
+ | egui::Key::ShiftRight
+ | egui::Key::ControlLeft
+ | egui::Key::ControlRight
+ | egui::Key::AltLeft
+ | egui::Key::AltRight
+ | egui::Key::SuperLeft
+ | egui::Key::SuperRight,
+ modifiers,
+ ..
+ } => self.add_modifiers(*modifiers, input.time),
+ egui::Event::Key { key, pressed, repeat, modifiers, .. } => {
+ if *pressed && *key == egui::Key::Escape {
+ return Recording::Cancelled;
+ }
+ if *pressed && !repeat {
+ if self.key.is_some_and(|previous| previous != *key) {
+ return Recording::MultipleKeys;
+ }
+ if self.key.is_none() {
+ self.key = Some(*key);
+ self.modifiers = *modifiers;
+ self.changed_at = input.time;
+ }
+ }
+ self.add_modifiers(*modifiers, input.time);
+ }
+ _ => {}
+ }
+ }
+ self.add_modifiers(input.modifiers, input.time);
+ if let Some(key) = self.key
+ && input.keys_down.is_empty()
+ && input.modifiers.is_none()
+ && input.time - self.changed_at >= RECORD_SETTLE_SECONDS
+ {
+ return Recording::Complete(key_name(key, self.modifiers));
+ }
+ Recording::Waiting
+ }
+}
+
impl Keymap {
pub fn prefs(&self) -> Value {
json!(self.custom)
@@ -78,17 +185,27 @@ impl Keymap {
/// A key press as a shortcut name: `E`, `Shift+E`, `Ctrl+Alt+K`, `F5`, `Delete`.
pub fn key_name(key: egui::Key, mods: egui::Modifiers) -> String {
+ let mut s = modifier_prefix(mods);
+ s.push_str(key.name());
+ s
+}
+
+fn modifier_prefix(mods: egui::Modifiers) -> String {
let mut s = String::new();
if mods.command || mods.ctrl {
s.push_str("Ctrl+");
}
+ // Keep the historical Ctrl/Cmd alias for existing bindings, but don't discard a
+ // physical Control pressed together with macOS Command.
+ if mods.mac_cmd && mods.ctrl {
+ s.push_str("Cmd+");
+ }
if mods.alt {
s.push_str("Alt+");
}
if mods.shift {
s.push_str("Shift+");
}
- s.push_str(key.name());
s
}
@@ -106,6 +223,28 @@ fn effective_for_spec<'a>(app: &'a SolveApp, command: &CommandSpec) -> Option<&'
app.keymap.custom.get(command.id).map(String::as_str).or(command.shortcut).filter(|key| !key.is_empty())
}
+/// Presentation only: stored Ctrl bindings retain their historical primary-modifier alias.
+/// A recorded macOS Control+Command chord includes both names explicitly.
+pub fn display(key: &str) -> String {
+ display_for_platform(key, cfg!(target_os = "macos"))
+}
+
+fn display_for_platform(key: &str, mac: bool) -> String {
+ let both = key.starts_with("Ctrl+Cmd+");
+ key.split('+')
+ .map(|part| match (mac, part) {
+ (true, "Ctrl") if !both => "Cmd",
+ (true, "Alt") => "Option",
+ _ => part,
+ })
+ .collect::<Vec<_>>()
+ .join("+")
+}
+
+pub fn display_for(app: &SolveApp, id: &str) -> Option<String> {
+ effective(app, id).map(|key| display(&key))
+}
+
/// Commands bound to `key` now.
pub fn commands_for(app: &SolveApp, key: &str) -> Vec<&'static str> {
command_specs().into_iter().filter(|c| effective(app, c.id).as_deref() == Some(key)).map(|c| c.id).collect()
@@ -206,18 +345,31 @@ pub fn reset(app: &mut SolveApp, id: Option<&str>) {
/// reset; a key another command uses is reported and taken over only on request.
pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
- // A key press while waiting for one binds it (Esc cancels).
+ // Keep a pending chord until it has settled and all keys are released. Modifier-only
+ // input never starts the timer, so modifiers can be assembled at the user's own pace.
if let Some(id) = app.keymap.capturing.clone() {
- let press = ctx.input(|i| {
- i.events.iter().find_map(|e| match e {
- egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*key, *modifiers)),
- _ => None,
- })
- });
- if let Some((k, m)) = press {
- app.keymap.capturing = None;
- if k != egui::Key::Escape {
- let name = key_name(k, m);
+ match ctx.input(|i| app.keymap.recorder.update(i)) {
+ Recording::Waiting => {
+ if app.keymap.recorder.key.is_some() {
+ let remaining = ctx.input(|i| RECORD_SETTLE_SECONDS - (i.time - app.keymap.recorder.changed_at));
+ if remaining > 0.0
+ && let Ok(delay) = std::time::Duration::try_from_secs_f64(remaining)
+ {
+ ctx.request_repaint_after(delay);
+ }
+ }
+ }
+ Recording::Cancelled => {
+ app.keymap.capturing = None;
+ // Escape cancels recording first, without also closing Preferences.
+ ctx.input_mut(|i| i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Escape, .. })));
+ }
+ Recording::MultipleKeys => {
+ app.keymap.capturing = None;
+ app.keymap.message = Some(app.tr("ui.shortcut_multiple_keys").to_string());
+ }
+ Recording::Complete(name) => {
+ app.keymap.capturing = None;
match bind(app, &id, &name, false) {
Ok(()) => app.keymap.message = None,
Err(e) if e.contains("already used") => {
@@ -228,6 +380,11 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
+ // The recorder owns these events. In particular, Enter/Space must not activate
+ // the focused binding button again or type into the filter while still pending.
+ ctx.input_mut(|i| {
+ i.events.retain(|event| !matches!(event, egui::Event::Key { .. } | egui::Event::Text(_) | egui::Event::Paste(_)));
+ });
}
let mut action: Option<(String, &str)> = None;
ui_kit::scope(ui, |ui| {
@@ -249,6 +406,10 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
&actions,
);
crate::scenario::publish_target("keymap:filter", filter.rect);
+ crate::scenario::publish_handle("shortcut:filter", filter.rect.center());
+ if filter.clicked() {
+ action = Some((String::new(), "cancel"));
+ }
if let Some(index) = toolbar_action {
action = Some((
String::new(),
@@ -264,7 +425,7 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
}
if let Some((id, key, _)) = app.keymap.conflict.clone() {
ui.horizontal_wrapped(|ui| {
- let replace = ui_kit::button(ui, crate::i18n::format("keymap.use_anyway", &[("key", &key)]), ui_kit::Button::Normal);
+ let replace = ui_kit::button(ui, crate::i18n::format("keymap.use_anyway", &[("key", &display(&key))]), ui_kit::Button::Normal);
crate::scenario::publish_target("keymap:replace", replace.rect);
if replace.clicked() {
action = Some((format!("{id}\n{key}"), "replace"));
@@ -275,6 +436,13 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
});
}
ui_kit::text(ui, app.tr_label("Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation)."), ui_kit::Text::Note("navigation"));
+ if !app.keymap.read_only {
+ ui_kit::text(ui, app.tr("ui.shortcut_capture_hint"), ui_kit::Text::Note("shortcut_capture_help"));
+ if app.keymap.capturing.is_some() {
+ let hint = ctx.input(|input| app.keymap.recorder.hint(input));
+ ui_kit::text(ui, app.tr(hint), ui_kit::Text::Hint("shortcut_capture_state"));
+ }
+ }
let q = app.keymap.filter.to_lowercase();
let commands: Vec<_> = command_specs()
.into_iter()
@@ -287,7 +455,8 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get();
let key_width = commands
.iter()
- .map(|(_, key, _)| ui_kit::ContentWidth::button(ui, key))
+ .map(|(_, key, _)| ui_kit::ContentWidth::button(ui, &display(key)))
+ .chain(app.keymap.recorder.preview().filter(|_| app.keymap.capturing.is_some()).map(|text| ui_kit::ContentWidth::button(ui, &text)))
.fold(ui_kit::ContentWidth::button(ui, app.tr_label("press a key…")), f32::max)
.max(ui_kit::ContentWidth::label(ui, app.tr_label("Keyboard Shortcuts")) + t.space_8);
let action_width = if app.keymap.read_only {
@@ -314,11 +483,11 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
let capturing = app.keymap.capturing.as_deref() == Some(c.id);
let changed = app.keymap.custom.contains_key(c.id);
let text = if capturing {
- app.tr_label("press a key…").to_string()
+ app.keymap.recorder.preview().unwrap_or_else(|| app.tr_label("press a key…").to_string())
} else if key.is_empty() {
"—".to_string()
} else {
- key.to_string()
+ display(key)
};
row.cell(|ui| {
if app.keymap.read_only {
@@ -331,7 +500,11 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
ui_kit::button(ui, &text, ui_kit::Button::Normal).on_hover_text(app.tr_label("Click, then press the new key"))
};
crate::scenario::publish_target(&format!("keymap:capture:{}", c.id), capture.rect);
+ if ui.is_rect_visible(capture.rect) {
+ crate::scenario::publish_handle(&format!("shortcut:{}", c.id), capture.rect.center());
+ }
if capture.clicked() {
+ capture.surrender_focus();
action = Some((c.id.to_string(), "capture"));
}
}
@@ -357,9 +530,15 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
});
});
});
+ crate::scenario::publish_count("shortcut_recording", f64::from(app.keymap.capturing.is_some()));
+ if action.is_some() {
+ app.keymap.capturing = None;
+ app.keymap.recorder = Recorder::default();
+ }
match action {
Some((id, "capture")) => {
app.keymap.capturing = Some(id);
+ app.keymap.recorder = Recorder::default();
app.keymap.conflict = None;
app.keymap.message = None;
}
@@ -402,6 +581,7 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
/// Stop waiting for a key (the dialog closed).
pub fn stop_capture(app: &mut SolveApp) {
app.keymap.capturing = None;
+ app.keymap.recorder = Recorder::default();
app.keymap.conflict = None;
app.keymap.message = None;
}
@@ -419,6 +599,274 @@ mod tests {
SolveApp::new(solidcraft_engine::Session::default(), Default::default())
}
+ fn recorder_frame(a: &mut SolveApp, ctx: &egui::Context, time: f64, events: Vec<egui::Event>) {
+ let raw = egui::RawInput { time: Some(time), events, ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| page(a, ui));
+ out.textures_delta.clear();
+ }
+
+ #[test]
+ fn recorder_waits_for_late_modifiers_instead_of_binding_the_first_key_down() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("solid.chamfer".into());
+ recorder_frame(
+ &mut a,
+ &ctx,
+ 0.0,
+ vec![egui::Event::Key { key: egui::Key::M, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],
+ );
+ assert!(a.keymap.capturing.is_some(), "the first key-down must remain a preview");
+ assert_eq!(effective(&a, "solid.chamfer"), None);
+ }
+
+ fn event(key: egui::Key, pressed: bool, modifiers: egui::Modifiers) -> egui::Event {
+ egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }
+ }
+
+ #[test]
+ fn control_input_preserves_primary_alias_and_explicit_physical_modifiers() {
+ for (step, ctrl, mac_cmd) in [
+ (json!({"key":"F12","pressed":true,"cmd":true}), true, false),
+ (json!({"key":"F12","pressed":true,"cmd":true,"ctrl":false}), false, true),
+ (json!({"key":"F12","pressed":true,"cmd":true,"ctrl":true}), true, true),
+ (json!({"key":"F12","pressed":true,"ctrl":true}), true, false),
+ ] {
+ let mut h = crate::scenario::Harness::new();
+ h.step(&step).unwrap();
+ let modifiers = h.ctx.input(|i| i.modifiers);
+ assert_eq!(modifiers.ctrl, ctrl, "{step}");
+ assert_eq!(modifiers.mac_cmd, mac_cmd, "{step}");
+ assert!(modifiers.command, "{step}");
+ }
+ }
+
+ #[test]
+ fn recorder_previews_each_modifier_and_explains_the_next_step() {
+ let mut h = crate::scenario::Harness::new();
+ h.call("ui.prefs", json!({"open":"Keyboard Shortcuts"}));
+ h.step(&json!({"click":{"handle":"shortcut:filter"}})).unwrap();
+ h.call("ui.text", json!({"text":"solid.chamfer"}));
+ h.step(&json!({"click":{"handle":"shortcut:solid.chamfer"}})).unwrap();
+ h.call("ui.key", json!({"key":"ShiftLeft","pressed":true,"shift":true}));
+ assert!(h.widget("Shift+…").is_some(), "show Shift immediately, before any ordinary key");
+ assert!(h.widget("Add one ordinary key. Escape cancels.").is_some());
+ h.call("ui.key", json!({"key":"SuperLeft","pressed":true,"shift":true,"cmd":true,"ctrl":false}));
+ let preview = if cfg!(target_os = "macos") { "Cmd+Shift+…" } else { "Ctrl+Shift+…" };
+ assert!(h.widget(preview).is_some(), "show each newly held modifier");
+ h.call("ui.key", json!({"key":"SuperLeft","pressed":false,"shift":true}));
+ assert!(h.widget("Shift+…").is_some(), "remove released modifiers before an ordinary key");
+ h.call("ui.key", json!({"key":"ShiftLeft","pressed":false}));
+ assert!(h.widget("press a key…").is_some());
+ assert_eq!(effective(&h.app, "solid.chamfer"), None);
+ h.call("ui.key", json!({"key":"ShiftRight","pressed":true,"shift":true}));
+ h.call("ui.key", json!({"key":"C","pressed":true,"shift":true}));
+ assert!(h.widget("Shift+C…").is_some());
+ assert!(h.widget("Release all keys to confirm. Escape cancels.").is_some());
+ h.call("ui.key", json!({"key":"C","pressed":false,"shift":true}));
+ h.call("ui.key", json!({"key":"ShiftRight","pressed":false}));
+ assert!(h.widget("Confirming shortcut… Escape cancels.").is_some());
+ assert!(h.widget("Shift+C…").is_some(), "retain the proposed chord until confirmed");
+ assert_eq!(effective(&h.app, "solid.chamfer"), None);
+ h.frames(65);
+ assert_eq!(effective(&h.app, "solid.chamfer").as_deref(), Some("Shift+C"));
+ assert!(h.widget("Shift+C").is_some());
+ }
+
+ #[test]
+ fn physical_modifier_keys_are_not_the_ordinary_key_in_a_chord() {
+ use egui::Key;
+ for (key, mods, expected) in [
+ (Key::ShiftLeft, egui::Modifiers::SHIFT, "Shift+C"),
+ (Key::ShiftRight, egui::Modifiers::SHIFT, "Shift+C"),
+ (Key::ControlLeft, egui::Modifiers::CTRL, "Ctrl+C"),
+ (Key::ControlRight, egui::Modifiers::CTRL, "Ctrl+C"),
+ (Key::AltLeft, egui::Modifiers::ALT, "Alt+C"),
+ (Key::AltRight, egui::Modifiers::ALT, "Alt+C"),
+ (Key::SuperLeft, egui::Modifiers::MAC_CMD | egui::Modifiers::COMMAND, "Ctrl+C"),
+ (Key::SuperRight, egui::Modifiers::MAC_CMD | egui::Modifiers::COMMAND, "Ctrl+C"),
+ ] {
+ let ctx = egui::Context::default();
+ let mut recorder = Recorder::default();
+ for (time, events, complete) in [
+ (0.0, vec![egui::Event::ModifiersChanged(mods), event(key, true, mods)], false),
+ (5.0, vec![], false),
+ (5.1, vec![event(Key::C, true, mods)], false),
+ (5.2, vec![event(Key::C, false, mods)], false),
+ (5.3, vec![event(key, false, egui::Modifiers::NONE), egui::Event::ModifiersChanged(egui::Modifiers::NONE)], false),
+ (6.2, vec![], true),
+ ] {
+ let raw = egui::RawInput { time: Some(time), events, ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| {
+ let result = ui.input(|input| recorder.update(input));
+ if complete {
+ assert!(matches!(result, Recording::Complete(ref binding) if binding == expected), "{key:?}");
+ } else {
+ assert!(matches!(result, Recording::Waiting), "{key:?} at {time}");
+ }
+ });
+ out.textures_delta.clear();
+ if time <= 5.0 {
+ assert!(recorder.key.is_none(), "{key:?} must not be recorded as an ordinary key");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn recorder_accumulates_late_modifiers_and_settles_for_one_second() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("sketch.mirror".into());
+ recorder_frame(&mut a, &ctx, 0.0, vec![event(egui::Key::M, true, egui::Modifiers::NONE)]);
+ recorder_frame(&mut a, &ctx, 0.4, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT)]);
+ let mods = egui::Modifiers { shift: true, mac_cmd: true, command: true, ..Default::default() };
+ recorder_frame(&mut a, &ctx, 0.8, vec![egui::Event::ModifiersChanged(mods)]);
+ recorder_frame(&mut a, &ctx, 1.0, vec![event(egui::Key::M, false, mods), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
+ recorder_frame(&mut a, &ctx, 1.79, vec![]);
+ assert!(a.keymap.capturing.is_some());
+ assert_eq!(effective(&a, "sketch.mirror"), None);
+ recorder_frame(&mut a, &ctx, 1.81, vec![]);
+ assert!(a.keymap.capturing.is_none());
+ assert_eq!(effective(&a, "sketch.mirror").as_deref(), Some("Ctrl+Shift+M"));
+ let mut reloaded = app();
+ reloaded.keymap.load(&a.keymap.prefs());
+ assert_eq!(effective(&reloaded, "sketch.mirror"), effective(&a, "sketch.mirror"));
+ }
+
+ #[test]
+ fn recorder_waits_indefinitely_for_modifier_only_input_and_for_release() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("sketch.mirror".into());
+ let mods = egui::Modifiers { shift: true, ctrl: true, alt: true, mac_cmd: true, command: true };
+ recorder_frame(&mut a, &ctx, 0.0, vec![egui::Event::ModifiersChanged(mods)]);
+ recorder_frame(&mut a, &ctx, 10.0, vec![]);
+ assert!(a.keymap.capturing.is_some());
+ assert_eq!(effective(&a, "sketch.mirror"), None);
+ recorder_frame(&mut a, &ctx, 12.0, vec![event(egui::Key::M, true, mods)]);
+ let mut repeat = event(egui::Key::M, true, mods);
+ if let egui::Event::Key { repeat, .. } = &mut repeat {
+ *repeat = true;
+ }
+ recorder_frame(&mut a, &ctx, 14.0, vec![repeat]);
+ assert!(a.keymap.capturing.is_some(), "held keys must not confirm");
+ recorder_frame(&mut a, &ctx, 14.1, vec![event(egui::Key::M, false, mods)]);
+ assert!(a.keymap.capturing.is_some(), "held modifiers must not confirm");
+ recorder_frame(&mut a, &ctx, 14.2, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
+ assert_eq!(effective(&a, "sketch.mirror").as_deref(), Some("Ctrl+Cmd+Alt+Shift+M"));
+ }
+
+ #[test]
+ fn recorder_rejects_two_ordinary_keys_and_escape_preserves_the_old_binding() {
+ for second in [egui::Key::N, egui::Key::Escape] {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("solid.extrude".into());
+ recorder_frame(&mut a, &ctx, 0.0, vec![event(egui::Key::M, true, egui::Modifiers::SHIFT)]);
+ recorder_frame(&mut a, &ctx, 0.5, vec![event(second, true, egui::Modifiers::SHIFT)]);
+ assert!(a.keymap.capturing.is_none());
+ assert_eq!(effective(&a, "solid.extrude").as_deref(), Some("E"));
+ assert_eq!(a.keymap.message.is_some(), second != egui::Key::Escape);
+ }
+ }
+
+ #[test]
+ fn recorder_conflicts_only_after_settling_and_plain_keys_still_work() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("solid.chamfer".into());
+ recorder_frame(&mut a, &ctx, 0.0, vec![event(egui::Key::M, true, egui::Modifiers::NONE), event(egui::Key::M, false, egui::Modifiers::NONE)]);
+ assert!(a.keymap.conflict.is_none());
+ recorder_frame(&mut a, &ctx, 1.1, vec![]);
+ assert_eq!(a.keymap.conflict.as_ref().map(|(_, key, _)| key.as_str()), Some("M"));
+ assert_eq!(effective(&a, "solid.move").as_deref(), Some("M"));
+ assert_eq!(effective(&a, "solid.chamfer"), None);
+ stop_capture(&mut a);
+ a.keymap.capturing = Some("solid.extrude".into());
+ recorder_frame(&mut a, &ctx, 2.0, vec![event(egui::Key::K, true, egui::Modifiers::NONE), event(egui::Key::K, false, egui::Modifiers::NONE)]);
+ recorder_frame(&mut a, &ctx, 3.1, vec![]);
+ assert_eq!(effective(&a, "solid.extrude").as_deref(), Some("K"));
+ }
+
+ #[test]
+ fn recorder_cancels_on_focus_loss_and_dialog_close() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("solid.extrude".into());
+ recorder_frame(&mut a, &ctx, 0.0, vec![event(egui::Key::K, true, egui::Modifiers::SHIFT)]);
+ let raw = egui::RawInput { time: Some(0.5), focused: false, events: vec![egui::Event::WindowFocused(false)], ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| page(&mut a, ui));
+ out.textures_delta.clear();
+ assert!(a.keymap.capturing.is_none());
+ assert_eq!(effective(&a, "solid.extrude").as_deref(), Some("E"));
+ stop_capture(&mut a);
+ assert!(a.keymap.recorder.key.is_none());
+ }
+
+ #[test]
+ fn escape_cancels_only_recording_and_no_command_fires_during_capture() {
+ let mut h = crate::scenario::Harness::new();
+ h.call("ui.prefs", json!({"open": "Keyboard Shortcuts"}));
+ h.app.keymap.capturing = Some("solid.chamfer".into());
+ h.call("ui.key", json!({"key": "C", "pressed": true}));
+ h.frames(2);
+ assert!(h.app.tool.is_none() && h.app.dialog.is_none());
+ assert!(h.app.session.active_sketch.is_none(), "C must not start a sketch while recording");
+ h.call("ui.key", json!({"key": "Escape"}));
+ h.frames(3);
+ assert!(h.app.prefs_window.open, "Escape should cancel the recorder, not close Preferences");
+ assert!(h.app.keymap.capturing.is_none());
+ assert_eq!(effective(&h.app, "solid.chamfer"), None);
+ }
+
+ #[test]
+ fn a_background_control_channel_recording_waits_for_an_actual_focus_loss() {
+ let mut a = app();
+ let ctx = egui::Context::default();
+ a.keymap.capturing = Some("sketch.mirror".into());
+ let raw =
+ egui::RawInput { time: Some(0.0), focused: false, events: vec![event(egui::Key::M, true, egui::Modifiers::SHIFT)], ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| page(&mut a, ui));
+ out.textures_delta.clear();
+ assert!(a.keymap.capturing.is_some());
+ assert_eq!(effective(&a, "sketch.mirror"), None);
+ }
+
+ #[test]
+ fn enter_and_space_are_recorded_without_reactivating_the_focused_button() {
+ for key in ["Enter", "Space"] {
+ let mut h = crate::scenario::Harness::new();
+ h.call("ui.prefs", json!({"open": "Keyboard Shortcuts"}));
+ h.step(&json!({"click":{"handle":"shortcut:filter"}})).unwrap();
+ h.call("ui.text", json!({"text":"sketch.mirror"}));
+ h.step(&json!({"click":{"handle":"shortcut:sketch.mirror"}})).unwrap();
+ h.call("ui.key", json!({"key":key}));
+ assert!(h.app.keymap.capturing.is_some(), "{key} should still be pending");
+ h.frames(65);
+ assert_eq!(effective(&h.app, "sketch.mirror").as_deref(), Some(key));
+ assert!(h.app.prefs_window.open);
+ }
+ }
+
+ #[test]
+ fn chord_display_and_legacy_primary_modifier_bindings_are_compatible() {
+ assert_eq!(display_for_platform("Ctrl+Alt+Shift+M", true), "Cmd+Option+Shift+M");
+ assert_eq!(display_for_platform("Ctrl+Cmd+Alt+Shift+M", true), "Ctrl+Cmd+Option+Shift+M");
+ assert_eq!(display_for_platform("Ctrl+Alt+Shift+M", false), "Ctrl+Alt+Shift+M");
+ let mut a = app();
+ a.keymap.load(&json!({"solid.chamfer":"Shift+C", "solid.extrude":"Ctrl+Alt+E"}));
+ assert_eq!(effective(&a, "solid.chamfer").as_deref(), Some("Shift+C"));
+ let mods = egui::Modifiers { mac_cmd: true, command: true, alt: true, ..Default::default() };
+ assert_eq!(commands_for(&a, &key_name(egui::Key::E, mods)), vec!["solid.extrude"]);
+ let extra = egui::Modifiers { shift: true, ..mods };
+ assert!(commands_for(&a, &key_name(egui::Key::E, extra)).is_empty());
+ let both = egui::Modifiers { ctrl: true, ..extra };
+ bind(&mut a, "sketch.mirror", &key_name(egui::Key::M, both), false).unwrap();
+ assert_eq!(commands_for(&a, &key_name(egui::Key::M, both)), vec!["sketch.mirror"]);
+ assert!(commands_for(&a, &key_name(egui::Key::M, extra)).is_empty());
+ }
+
#[test]
fn shortcut_page_only_builds_visible_rows_and_reveals_filtered_rows() {
let mut h = crate::scenario::Harness::new();
@@ -536,6 +984,25 @@ mod card_tests {
use super::*;
use crate::scenario::{self, Harness};
+ #[test]
+ fn live_chord_column_fits_all_modifiers() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.keymap.filter = "sketch.mirror".into();
+ h.call("ui.prefs", json!({"open":"Keyboard Shortcuts"}));
+ h.step(&json!({"click":{"handle":"keymap:capture:sketch.mirror"}})).unwrap();
+ h.step(&json!({"key":"M","pressed":true,"shift":true,"cmd":true,"ctrl":true,"alt":true})).unwrap();
+ let preview = h.app.keymap.recorder.preview().unwrap();
+ let cell = scenario::rect_of("dialog:table:keymap:sketch.mirror:cell:Keyboard Shortcuts").unwrap();
+ let ctx = crate::fonts::test_context();
+ let mut needed = 0.0;
+ let mut out = ctx.run_ui(Default::default(), |ui| {
+ ui_kit::scope(ui, |ui| needed = ui_kit::ContentWidth::button(ui, &preview));
+ });
+ out.textures_delta.clear();
+ assert!(cell.width() >= needed, "preview {preview}: cell {} < {needed}", cell.width());
+ }
+
#[test]
fn shortcut_card_captures_clears_resets_and_esc_cancels_capture_only() {
let mut h = Harness::new();
@@ -546,6 +1013,9 @@ mod card_tests {
h.step(&json!({"click":{"handle":format!("keymap:{action}:solid.extrude")}})).unwrap();
if action == "capture" {
h.step(&json!({"key":"E","shift":true})).unwrap();
+ assert_eq!(effective(&h.app, "solid.extrude").as_deref(), Some("E"), "retain the binding during the grace period");
+ h.step(&json!({"key":"ShiftLeft","pressed":false})).unwrap();
+ h.frames(65);
}
assert_eq!(effective(&h.app, "solid.extrude").unwrap_or_default(), expected);
}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index fe5e16c188..e06ccbd5ad 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -285,6 +285,7 @@ fn window_page<const INDEX: usize>(ui: &mut egui::Ui, app: &mut SolveApp) {
crate::scenario::publish_target("prefs:page:Selection", rect);
}
if app.prefs_window.section != INDEX {
+ crate::keymap::stop_capture(app);
app.keymap.read_only = false;
app.prefs_window.section = INDEX;
}
@@ -1589,6 +1590,22 @@ mod tests {
}
}
+ #[test]
+ fn changing_preferences_page_cancels_shortcut_capture() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ h.call("ui.prefs", json!({"open":"Keyboard Shortcuts"}));
+ h.step(&json!({"click":{"handle":"keymap:filter"}})).unwrap();
+ h.step(&json!({"text":"solid.extrude"})).unwrap();
+ h.step(&json!({"click":{"handle":"keymap:capture:solid.extrude"}})).unwrap();
+ h.step(&json!({"key":"M","pressed":true})).unwrap();
+ h.step(&json!({"click":{"handle":"prefs:page:General"}})).unwrap();
+ assert!(!crate::keymap::capturing(&h.app));
+ assert_eq!(crate::keymap::effective(&h.app, "solid.extrude").as_deref(), Some("E"));
+ h.frames(65);
+ assert_eq!(crate::keymap::effective(&h.app, "solid.extrude").as_deref(), Some("E"));
+ }
+
#[test]
fn display_quality_cards_show_increasing_facet_detail() {
let mut app = super::SolveApp::new(Default::default(), Default::default());
diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs
index 5e0170f30c..1e9bb49cc4 100644
--- a/crates/ui-egui/src/scenario.rs
+++ b/crates/ui-egui/src/scenario.rs
@@ -3,7 +3,7 @@
//! drags, toolbar starts) the way a person would use it, with checks on the result.
//!
//! A scenario is a JSON list of steps:
-//! - `{"start": "solid.extrude"}`: a toolbar click; `{"key": "E", "shift"?, "cmd"?}`; `{"text": "20"}`
+//! - `{"start": "solid.extrude"}`: a toolbar click; `{"key": "E", "shift"?, "cmd"?, "ctrl"?, "alt"?, "pressed"?}`; `{"text": "20"}`
//! - `{"widget": "Revolute", "near"?: "Type"}`: click a dialog field, choice or button by its
//! text (with `near`: the one in that label's row)
//! - `{"click": AT, "double"?, "shift"?, "ctrl"?, "button"?}`, `{"move": AT, "shift"?, "alt"?, "ctrl"?, "cmd"?}`,
@@ -31,6 +31,7 @@
//! "close"}`: the app dies (or closes) and a new one starts on the same folders
//! - `{"script": "examples/…/x.json"}`: run a command script through the engine; `"$DIR"` in a
//! `call` step's string parameters is the scenario's folder
+//! - `{"frames": 20}`: advance up to 600 frames at the harness clock (60 Hz)
//! - `{"note": "…"}`: a comment; `{"pending": "why"}`: the scenario waits for a fix (its test
//! is ignored)
//! - `{"expect": {…}}`: checks, see [`check`]; `{"until": {…}}` waits (frames) until they pass
@@ -415,7 +416,22 @@ impl Harness {
if let Some(id) = s.get("start").and_then(Value::as_str) {
self.call("ui.start", json!({ "command": id }))
} else if let Some(k) = s.get("key").and_then(Value::as_str) {
- self.call("ui.key", json!({"key": k, "shift": flag("shift"), "cmd": flag("cmd")}))
+ {
+ let mut params = json!({"key": k, "shift": flag("shift"), "cmd": flag("cmd"), "alt": flag("alt")});
+ if let Some(ctrl) = s.get("ctrl") {
+ params["ctrl"] = ctrl.clone();
+ }
+ if let Some(pressed) = s.get("pressed") {
+ params["pressed"] = pressed.clone();
+ }
+ self.call("ui.key", params)
+ }
+ } else if let Some(n) = s.get("frames").and_then(Value::as_u64) {
+ if n > 600 {
+ return Err("frames must be at most 600".into());
+ }
+ self.frames(n as usize);
+ return Ok(());
} else if let Some(t) = s.get("text").and_then(Value::as_str) {
self.call("ui.text", json!({ "text": t }))
} else if let Some(at) = s.get("click") {
@@ -1075,6 +1091,14 @@ pub fn check(h: &mut Harness, e: &Value) -> Result<(), String> {
return Err(format!("browser selection: {}", r["result"]));
}
}
+ "shortcuts" => {
+ for (id, want) in v.as_object().ok_or("shortcuts takes a command-to-key object")? {
+ let got = h.call("ui.shortcut", json!({"command": id}));
+ if got["result"]["key"] != *want {
+ return Err(format!("shortcut {id}: got {}, want {want}", got["result"]["key"]));
+ }
+ }
+ }
"query" => {
// {command, params?, path: [keys or indices], value}: a command's result at path.
let cmd = v["command"].as_str().ok_or("query needs `command`")?;
diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs
index 7f672672b7..8660046e77 100644
--- a/crates/ui-egui/src/shortcut_box.rs
+++ b/crates/ui-egui/src/shortcut_box.rs
@@ -480,7 +480,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let mut item = ui_kit::MenuItem::new(id, label, icon);
item.enabled = enabled.get(index).copied().unwrap_or(false);
item.highlighted = index == app.sbox.index;
- let shortcut = crate::keymap::effective(app, id).unwrap_or_default();
+ let shortcut = crate::keymap::display_for(app, id).unwrap_or_default();
item.shortcut = &shortcut;
let path = place.map_or_else(|| id.to_string(), |(tab, panel)| format!("{tab} › {panel}"));
let response = item.search_row(ui, &query, &path, None);
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index 4ea8f286bd..3dd514d8fa 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -1526,7 +1526,14 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
}
for c in cmds {
let info = c.info(&app.session);
- let response = crate::ui_kit::command_menu_button(ui, c.id, c.label, c.icon, c.shortcut.unwrap_or(""), info.enabled);
+ let response = crate::ui_kit::command_menu_button(
+ ui,
+ c.id,
+ c.label,
+ c.icon,
+ &crate::keymap::display_for(app, c.id).unwrap_or_default(),
+ info.enabled,
+ );
crate::scenario::publish_handle(&format!("toolbar:{}", c.id), response.rect.center());
if response.clicked() {
app.start(c.id);
@@ -1621,8 +1628,7 @@ fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft
let name = app.tr_label(command.label);
let name_width =
ui.painter().layout_no_wrap(name.to_string(), crate::fonts::semibold(crate::theme::Tokens::get().font_heading), t.text).size().x;
- let key_width = command
- .shortcut
+ let key_width = crate::keymap::display_for(app, command.id)
.map(|key| {
ui.painter().layout_no_wrap(key.to_string(), FontId::monospace(crate::theme::Tokens::get().font_body), t.text_dim).size().x + 24.0
})
@@ -1631,7 +1637,7 @@ fn ribbon_tooltip(app: &SolveApp, response: egui::Response, command: &solidcraft
ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(vec2(name_width, 20.0), Sense::hover());
ribbon_text(ui, rect.center(), name, t.font_heading, t.text, true);
- if let Some(key) = command.shortcut {
+ if let Some(key) = crate::keymap::display_for(app, command.id) {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
egui::Frame::NONE
.fill(t.panel_header)
@@ -1702,8 +1708,7 @@ fn dropdown_width(app: &SolveApp, ui: &egui::Ui, cmds: &[&'static solidcraft_eng
cmds.iter()
.map(|c| {
let label = ui.painter().layout_no_wrap(app.tr_label(c.label).to_string(), font.clone(), t.text).size().x;
- let key = c
- .shortcut
+ let key = crate::keymap::display_for(app, c.id)
.map(|k| ui.painter().layout_no_wrap(k.to_string(), FontId::monospace(t.font_button), t.text).size().x + 24.0)
.unwrap_or(0.0);
6.0 + 20.0 + 8.0 + label + key + 30.0
@@ -1740,7 +1745,8 @@ fn dropdown_row(app: &SolveApp, ui: &mut egui::Ui, c: &'static solidcraft_engine
let mut row = crate::ui_kit::MenuItem::new(c.id, &label, c.icon);
row.enabled = info.enabled;
row.highlighted = hot;
- row.shortcut = c.shortcut.unwrap_or("");
+ let shortcut = crate::keymap::display_for(app, c.id).unwrap_or_default();
+ row.shortcut = &shortcut;
row.paint(ui, rect, &resp, 26.0);
if hot {
crate::scenario::publish_handle(&format!("dropdown_hot:{}", c.id), rect.center());
diff --git a/crates/ui-egui/tests/scenarios/shortcut_recorder_grace_period.json b/crates/ui-egui/tests/scenarios/shortcut_recorder_grace_period.json
new file mode 100644
index 0000000000..af282e1bc1
--- /dev/null
+++ b/crates/ui-egui/tests/scenarios/shortcut_recorder_grace_period.json
@@ -0,0 +1,51 @@
+[
+ {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}},
+ {"call":"ui.prefs","params":{"open":"Keyboard Shortcuts"}},
+ {"click":{"handle":"shortcut:filter"}},
+ {"text":"sketch.mirror"},
+ {"click":{"handle":"shortcut:sketch.mirror"}},
+ {"key":"M","pressed":true},
+ {"frames":20},
+ {"key":"ShiftLeft","pressed":true,"shift":true},
+ {"frames":20},
+ {"key":"SuperLeft","pressed":true,"shift":true,"cmd":true,"ctrl":false},
+ {"key":"M","pressed":false,"shift":true,"cmd":true,"ctrl":false},
+ {"key":"SuperLeft","pressed":false,"shift":true},
+ {"key":"ShiftLeft","pressed":false},
+ {"expect":{"count":{"name":"shortcut_recording","value":1},"shortcuts":{"sketch.mirror":null},"tool":null,"dialog":null}},
+ {"frames":65},
+ {"expect":{"count":{"name":"shortcut_recording","value":0},"shortcuts":{"sketch.mirror":"Ctrl+Shift+M"}}},
+ {"call":"ui.prefs","params":{"button":"ok"}},
+ {"key":"M","shift":true,"cmd":true,"ctrl":false},
+ {"expect":{"dialog":"SketchModify(Mirror)","tool":null}},
+ {"key":"Escape"},
+ {"key":"C"},
+ {"expect":{"tool":"sketch.circle.center"}},
+ {"key":"Escape"},
+ {"call":"ui.prefs","params":{"open":"Keyboard Shortcuts"}},
+ {"click":{"handle":"shortcut:filter"}},
+ {"call":"ui.key","params":{"key":"A","cmd":true,"ctrl":false}},
+ {"text":"solid.chamfer"},
+ {"click":{"handle":"shortcut:solid.chamfer"}},
+ {"key":"ShiftLeft","pressed":true,"shift":true},
+ {"expect":{"shown":"Shift+…"}},
+ {"frames":65},
+ {"expect":{"count":{"name":"shortcut_recording","value":1},"shortcuts":{"solid.chamfer":null}}},
+ {"expect":{"shown":"Add one ordinary key. Escape cancels."}},
+ {"key":"C","shift":true},
+ {"expect":{"shown":"Shift+C…"}},
+ {"expect":{"shown":"Release all keys to confirm. Escape cancels."}},
+ {"key":"ShiftLeft","pressed":false},
+ {"expect":{"shown":"Confirming shortcut… Escape cancels."}},
+ {"frames":65},
+ {"expect":{"count":{"name":"shortcut_recording","value":0},"shortcuts":{"solid.chamfer":"Shift+C"}}},
+ {"call":"ui.prefs","params":{"button":"ok"}},
+ {"key":"C","shift":true},
+ {"expect":{"tool":null,"dialog":"chamfer: true"}},
+ {"click":{"handle":"dialog:Distance"}},
+ {"key":"C"},
+ {"expect":{"tool":null,"dialog":"chamfer: true"}},
+ {"key":"Escape"},
+ {"key":"C","shift":true,"cmd":true,"ctrl":false},
+ {"expect":{"tool":null,"dialog":null}}
+]
diff --git a/docs/book/src/guide/shortcuts.md b/docs/book/src/guide/shortcuts.md
index 221eafcf1d..beaaaf5abc 100644
--- a/docs/book/src/guide/shortcuts.md
+++ b/docs/book/src/guide/shortcuts.md
@@ -2,6 +2,32 @@
Command shortcuts can be changed in File › Keyboard Shortcuts; these are the defaults.
+Click a binding to record a new shortcut. A shortcut can contain Shift, Ctrl/Cmd and
+Alt/Option modifiers plus exactly one other key. Hold the modifiers, then press the final
+key; you can take your time assembling the modifiers before that key. The recorder also
+allows modifiers to arrive after the ordinary key: it previews the chord and waits one
+second after the last added modifier, and until all keys are released, before confirming.
+For example, record Shift+Cmd+M for Sketch Mirror on macOS. Escape cancels recording without
+changing the old binding. Pressing two different ordinary keys cancels the attempt.
+
+The binding button shows modifiers immediately as you press them, even before adding the
+ordinary key. Releasing a modifier before that key removes it from the preview. A status
+line tells you to add a key, release all keys, or wait for confirmation; the proposed chord
+stays visible during confirmation. Nothing is saved while the preview is still pending.
+
+On macOS, the editor, Help list, toolbar hints, context menus and S search display Cmd and
+Option. Existing settings retain SolidCraft's Ctrl/Cmd alias for the primary modifier;
+Control and Command pressed together are recorded explicitly as Ctrl+Cmd. Conflicting
+bindings still require confirmation, and built-in reserved shortcuts remain reserved.
+Recording changes app settings, not the design file.
+
+This follows the usual [modifier-before-key convention documented by Apple](https://support.apple.com/en-ie/102650)
+and the [key-event and modifier-state model documented by W3C](https://www.w3.org/TR/uievents/#keys-modifiers).
+The one-second grace period is SolidCraft's recording aid, not a standard-mandated delay;
+using an already assigned shortcut has no added delay. Operating systems and browsers can
+intercept reserved combinations before SolidCraft receives them. Choose a different chord
+if that happens; recording is cancelled if the app loses focus.
+
| Key | Command | Key | Command |
|---|---|---|---|
| L | Line | E | Extrude |
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 22bbc08461..359f6ea445 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -218,7 +218,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.
| `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:<command id>` (the button alone: `button:<command id>`; a drop-down row: `dropdown:<command id>`, highlighted `dropdown_hot:<command id>`, its pin `dropdown_pin:<command id>`; Customize Toolbar's check boxes `customize:<command id>`), ribbon tabs `tab:<name>` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL; contextual SKETCH; workspace RENDER), panel labels `panel:<tab>:<panel>` (also `ribbon:section:<TAB>:<SECTION>`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row:<label>` and fold arrows `fold:<label>`, manipulator handles; signed-axis tips `axis_view:z`, `axis_view:-y`; optional cube facets `navigation_cube:top`, `navigation_cube:top_front_right`, controls `navigation_cube:control:home` (and other actions), plus signed-axis aliases for visible cube faces; Preferences navigator picker `prefs:navigator`, options `prefs:navigator:Signed axes` and `prefs:navigator:Cube`; in the Motion Study dialog, where the chart puts its first and last step `motion:chart_start` and `motion:chart_end`, the Check collisions button `motion:check` and each collision found `motion:collision:<n>` |
| `ui.editFeature` | `feature` (id or name) | what double-clicking a timeline item does: rolls back to it and opens its dialog filled in (sketches open in sketch mode) |
| `ui.scroll` | `x`, `y`, `delta?` | wheel zoom at the cursor |
-| `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `shift?` | |
+| `ui.key` | `key` (egui key name, `Enter`, `Escape`…), `cmd?`, `ctrl?`, `shift?`, `alt?`, `pressed?` | By default, press and release, then release modifiers. With `pressed: true` or `false`, send only that edge; modifiers remain as given. `cmd` retains the legacy primary-modifier alias unless `ctrl` is explicit: `cmd:true, ctrl:false` sends physical Command, and both true sends Control+Command. `ui.move` can change modifiers between edges. |
| `ui.text` | `text` | typed text |
| `ui.screenshot` | `path?` | PNG of the window (needs a presented frame: a minimised or fully covered window answers at once with `hidden: true` and an error; use `ui.render`) |
| `ui.render` | `path`, `width?`, `height?`, `grid?`, `axes?` | Render of the model with the current camera (no window needed), drawn on the app's GPU device with the viewport's pipelines (the reply's `renderer`: `gpu`, or `gpu-software` on a software adapter), in the window's theme (light or dark; `solidcraft-cli snapshot` keeps the light colours); cut by the section the viewport shows (`inspect.section`, an open Section Analysis dialog's preview, a sketch's Slice), with the cut face capped. The ground grid and the origin's axes are drawn as the window shows them (`ui.set` `showGrid` and `showOrigin`, `hiddenOrigin`); `grid` and `axes` (booleans) say otherwise for this render |