From ef8eb9ffe9b3485345786646e7b2536add3deef5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 23:32:54 -0600 Subject: [PATCH 1/3] test: make native menu and layout checks portable --- apps/rustgis/src/menu.rs | 13 ++++++++++--- crates/engine/src/tests/layout_report_text.rs | 15 ++++++++++++++- crates/render/src/layout/tests.rs | 12 +++++++++--- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/apps/rustgis/src/menu.rs b/apps/rustgis/src/menu.rs index 5481e7ab6b..188a15f4dd 100644 --- a/apps/rustgis/src/menu.rs +++ b/apps/rustgis/src/menu.rs @@ -38,7 +38,7 @@ pub enum Action { Cut, Copy, Paste, - /// Selects all of a focused text field (⌘A, as egui reads it). + /// Presses ⌘A: a focused text field or select.all takes it. SelectAll, /// Closes the window: the save prompt asks first. CloseWindow, @@ -496,7 +496,8 @@ mod tests { use rustgis_engine::{Project, Session}; /// Every item runs a command that exists, with parameters that parse; a fixed shortcut isn't - /// one the keymap gives another command; every shortcut shown has ⌘ and a key code. + /// one the keymap gives another command (Select All forwards its own); every shortcut shown + /// has ⌘ and a key code. #[test] fn items_name_commands_that_exist() { let mut app = RustGisApp::new(Session::new(Project::default())); @@ -530,7 +531,13 @@ mod tests { if let Some((key, shift)) = fixed { let k = KeyboardShortcut::new(if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }, key); let taken = app.shortcut_command(k); - assert!(taken.is_none(), "{label}: the keymap gives {key:?} to {taken:?}"); + if action == SelectAll { + // The menu forwards ⌘A as a key event: the text field or select.all takes + // it, just as when typed. This binding is intentional, not a collision. + assert_eq!(taken.as_deref(), Some("select.all"), "{label}: its forwarded key"); + } else { + assert!(taken.is_none(), "{label}: the keymap gives {key:?} to {taken:?}"); + } } } } diff --git a/crates/engine/src/tests/layout_report_text.rs b/crates/engine/src/tests/layout_report_text.rs index 47ef1fc848..40baee5136 100644 --- a/crates/engine/src/tests/layout_report_text.rs +++ b/crates/engine/src/tests/layout_report_text.rs @@ -100,10 +100,23 @@ fn a_report_image_says_the_text_of_its_first_page_alone() { assert_eq!(reported(&mut s, "png"), [of_page(&s, 0, id)]); } +/// The one-digit/two-digit wrap boundary uses the built-in face in a fresh process: installed +/// fonts can fit both in the box, which would test font discovery rather than page expansion. #[test] fn a_report_measures_each_layout_page_with_its_own_page_number() { + if std::env::var_os("RUSTGIS_REPORT_PAGE_NUMBER_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tests::layout_report_text::a_report_measures_each_layout_page_with_its_own_page_number", "--nocapture"]) + .env("RUSTGIS_REPORT_PAGE_NUMBER_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } let mut s = sheet(); - // One line while the page number has one digit; two from page 10. + // Two lines, both drawn, while the page number has one digit; a third, cut off, from page 10. let id = text(&mut s, 0, &["{page}"; 8].join(" "), 18.0, 6.0); s.run("layout.update", &json!({"element": id, "wrap": true, "size": 10})).unwrap(); report(&mut s, &["Sheet"]); diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index a7e86737f1..402c39b66f 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5972,7 +5972,7 @@ const PINNED_LEGEND_MEASURES: [u64; 18] = [ 0x0de9_b39c_7273_61da, // 14: no-data rows, two columns 0x6de4_4bc0_7e82_51cc, // 15: across the right edge 0xbf3a_eef4_592a_7206, // 16: shorter than its title - 0x7249_b531_f330_3a30, // 17: nothing to list + 0x4ad5_1f0c_6756_5855, // 17: nothing to list, zero heights canonicalized 0x18ef_3e69_73a3_50c9, // 18: what the frame draws, no-data asked ]; @@ -6025,8 +6025,14 @@ fn legends_draw_as_before() { }; let sizes = legend_sizes_with_no_data_mm(&mut maps[0], scale, *all_classes, *hide_other, (*show_no_data, *text_size), (exclude, labels)); - // The first three only: these are the column counts main measures. - said.push_str(&format!("{:?}\n", sizes.map(|s| [s[0], s[1], s[2]]))); + // The first three only: these are the column counts main measures. Adding positive zero + // canonicalizes signed zero, which empty sums/maxima can give different signs on different + // architectures, without rounding any other dimension or changing the drawing pins. + let sizes = sizes.map(|s| [s[0], s[1], s[2]].map(|(w, h)| (w + 0.0, h + 0.0))); + if page == 17 { + assert_eq!(sizes, Some([(0.0, 0.0); 3]), "the empty legend has no rows"); + } + said.push_str(&format!("{sizes:?}\n")); measured.push((format!("page {page}"), fnv_bytes(said.as_bytes()))); } let mut wrong = crate::layout::pin_mismatches("drawing", &drawn, &PINNED_LEGEND_PIXELS); From 2287fd87929841da6151ffb9cb21138098066fa8 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 16:31:38 -0600 Subject: [PATCH 2/3] fix(macos): preserve Select All and stabilize native layout checks --- apps/rustgis/src/main.rs | 5 +- apps/rustgis/src/menu.rs | 22 +++- crates/ui-egui/src/lib.rs | 9 +- crates/ui-egui/src/shortcutfile.rs | 36 +++++- crates/ui-egui/src/shortcutui.rs | 48 ++++++-- .../integration/shortcut_customization.rs | 115 ++++++++++++++++++ docs/user-guide/workspace.md | 8 +- 7 files changed, 224 insertions(+), 19 deletions(-) diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 89a8e2c061..8a69188a2d 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -789,12 +789,13 @@ fn main() -> eframe::Result { Ok(_) => Some("the settings folder can't lock files, so a second copy of RustGIS couldn't be told apart".into()), Err(no) => Some(no.why.clone()), }; - // The keys the macOS menu bar keeps, before the stored shortcuts load: the keymap leaves them - // out and the shortcut editor refuses them. + // The macOS menu's keys, before stored shortcuts load: consumed keys stay out of the keymap; + // a forwarded key may keep its own command, and the editor refuses other commands on it. #[cfg(target_os = "macos")] let app = { let mut app = app; app.ui.reserved_shortcuts = menu::reserved(); + app.ui.forwarded_shortcuts = menu::forwarded(); app }; let mut app = app.with_services(services); diff --git a/apps/rustgis/src/menu.rs b/apps/rustgis/src/menu.rs index 188a15f4dd..4372bbb9dd 100644 --- a/apps/rustgis/src/menu.rs +++ b/apps/rustgis/src/menu.rs @@ -427,7 +427,8 @@ pub fn clipboard_text() -> Option { } /// The key combinations the menu bar keeps: its items' fixed ones and macOS's own (Hide, Hide -/// Others, Minimize). A shortcut on one would never reach the app. +/// Others, Minimize). A shortcut on one would never reach the app, except the menu's own +/// commands whose keys it forwards ([`forwarded`]). pub fn reserved() -> Vec { let cmd = |m: Modifiers, key: Key| KeyboardShortcut::new(Modifiers::COMMAND | m, key); let mut keys: Vec = MENUS @@ -442,6 +443,22 @@ pub fn reserved() -> Vec { keys } +/// Fixed menu keys sent back as key events: they may keep their own command in the keymap, +/// while a focused text field still takes them first. Other commands cannot take these keys. +pub fn forwarded() -> Vec<(KeyboardShortcut, &'static str)> { + MENUS + .iter() + .flat_map(|(_, rows)| rows.iter()) + .filter_map(|row| match *row { + Item(_, SelectAll, Some((key, shift))) => Some(( + KeyboardShortcut::new(if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }, key), + "select.all", + )), + _ => None, + }) + .collect() +} + /// Whether a native panel (a file dialog) has the keys rather than the app's window. fn panel_has_keys() -> bool { use objc2::MainThreadMarker; @@ -501,6 +518,9 @@ mod tests { #[test] fn items_name_commands_that_exist() { let mut app = RustGisApp::new(Session::new(Project::default())); + app.ui.reserved_shortcuts = reserved(); + app.ui.forwarded_shortcuts = forwarded(); + let mut app = app.with_services(Default::default()); // Those that open a native file dialog, quit or go online aren't run here. const NOT_RUN: &[&str] = &["ui.open", "ui.save", "ui.saveAs", "ui.addData", "ui.quit", "ui.checkUpdate"]; let mut seen = 0; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c795fb356f..9b20b983ac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -995,8 +995,12 @@ pub struct UiState { /// (#2390): on unless turned off. pub sharp_tiles: bool, /// Key combinations the native menu bar keeps for itself (macOS: Quit, Close Window, Hide…): - /// a shortcut on one would never reach the app, so the shortcut editor refuses them. + /// a shortcut on one would never reach the app, so the shortcut editor refuses them, except + /// their own commands in `forwarded_shortcuts`. pub reserved_shortcuts: Vec, + /// Native menu keys forwarded to the app: only their own command may use the chord. A + /// focused text field still takes the event before the command, as when the key is typed. + pub forwarded_shortcuts: Vec<(egui::KeyboardShortcut, &'static str)>, /// Files whose layers are being listed or chosen, the first one shown. pub choosing: Vec, /// The project last opened or saved on this computer, for Start With › Last Project. @@ -1284,6 +1288,7 @@ impl Default for UiState { download_grids: false, sharp_tiles: true, reserved_shortcuts: Vec::new(), + forwarded_shortcuts: Vec::new(), choosing: Vec::new(), last_project: None, start_projection: String::new(), @@ -1987,7 +1992,6 @@ impl RustGisApp { rustgis_engine::render::rustgis_tiles::earthdata::set_secret_store(services.secrets.clone()); rustgis_engine::render::rustgis_tiles::copernicus::set_secret_store(services.secrets.clone()); self.services = services; - shortcutui::load(&mut self); sourcespane::load_connections(&mut self); autosave::load(&mut self); if let Some(lang) = self.services.load_pref.as_ref().and_then(|load| load("language")) { @@ -1995,6 +1999,7 @@ impl RustGisApp { } // Theme readers and startup notices keep translated text, so select the language before reading. i18n::set_current(self.chosen_lang()); + shortcutui::load(&mut self); // After the language, so a notice about the saved value is in it. threadsui::load(&mut self); // A stored value that is neither `auto` nor a known worldview means `auto`; `china`, as diff --git a/crates/ui-egui/src/shortcutfile.rs b/crates/ui-egui/src/shortcutfile.rs index f14d422e57..90777db62d 100644 --- a/crates/ui-egui/src/shortcutfile.rs +++ b/crates/ui-egui/src/shortcutfile.rs @@ -87,8 +87,9 @@ fn input(p: &Value) -> Result { String::from_utf8(bytes).map_err(|e| e.to_string()) } -/// Validate every record before exposing a preview or changing the live map. -fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> { +/// Validate every record before exposing a preview or changing the live map, then apply only +/// bindings the native menu permits. A skipped assignment cannot displace a current binding. +fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value, Vec), String> { if text.len() > MAX_FILE_BYTES { return Err(tl!("Shortcut file exceeds the size limit.").into()); } @@ -105,11 +106,32 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> { if !merged.apply_preferences(&changes) { return Err(tl!("Shortcut file contains invalid or reserved bindings.").into()); } + // Validation above includes every record, even those this platform will leave out. + let mut skipped = Vec::new(); + for change in &doc.bindings { + let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?; + if !change.remove && shortcutui::reserved(app, chord, &change.command) { + skipped.push(chord); + } + } + let mut kept = Vec::new(); + for change in &doc.bindings { + let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?; + // A rejected rebind must not apply the removal of the default it replaces. + let blocked = if change.remove { skipped.contains(&chord) } else { shortcutui::reserved(app, chord, &change.command) }; + if !blocked { + kept.push(change); + } + } + merged = app.ui.keymap.clone(); + if !merged.apply_preferences(&serde_json::to_string(&kept).map_err(|e| e.to_string())?) { + return Err(tl!("Shortcut file contains invalid or reserved bindings.").into()); + } if merged.preferences(&Keymap::new(&app.session.registry)).is_none() { return Err(tl!("Too many shortcut changes to save.").into()); } let mut assigned = std::collections::HashSet::new(); - for change in &doc.bindings { + for change in &kept { let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?; if !change.remove { assigned.insert(chord); @@ -130,7 +152,7 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value), String> { .is_some_and(|new| app.ui.keymap.command_for(chord).is_some_and(|old| !old.runs(&new.command, &new.params))) }) .count(); - Ok((merged, json!({"bindings":doc.bindings.len(), "conflicts":conflicts, "unknown_commands":unknown}))) + Ok((merged, json!({"bindings":kept.len(), "conflicts":conflicts, "unknown_commands":unknown}), skipped)) } /// Include UI actions outside Command Search when recognizing portable command ids. @@ -182,7 +204,7 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result { return Ok(Value::Null); } let text = input(p)?; - let (merged, summary) = merge(app, &text)?; + let (merged, summary, skipped) = merge(app, &text)?; if p.get("confirm").and_then(Value::as_bool).unwrap_or(false) { if app.ui.shortcut_preferences_blocked { return Err(tl!("Reset unreadable saved shortcuts before importing.").into()); @@ -190,6 +212,7 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result { app.ui.keymap = merged; shortcutui::save(app); app.ui.shortcut_editor.import = None; + shortcutui::report_skipped(app, &skipped); } else { app.ui.shortcut_editor.import = Some(Preview { text, summary: summary.clone() }); app.ui.shortcut_editor.open = true; @@ -245,6 +268,9 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result { } } } + if next.bindings.iter().any(|b| shortcutui::reserved(app, b.chord, &b.command)) { + return Err(tl!("Invalid or reserved shortcut key.").into()); + } if next.preferences(&defaults).is_none() { return Err(tl!("Too many shortcut changes to save.").into()); } diff --git a/crates/ui-egui/src/shortcutui.rs b/crates/ui-egui/src/shortcutui.rs index c798a5c4a6..74b8e8341a 100644 --- a/crates/ui-egui/src/shortcutui.rs +++ b/crates/ui-egui/src/shortcutui.rs @@ -54,25 +54,48 @@ pub fn load(app: &mut RustGisApp) { if let Some(changes) = app.services.load_pref.as_ref().and_then(|load| load(PREF)) { app.ui.shortcut_preferences_blocked = !app.ui.keymap.apply_preferences(&changes); } - // A stored shortcut on a key the menu bar keeps would never run. - let kept: Vec = app.ui.keymap.bindings.iter().map(|b| b.chord).filter(|c| reserved(app, *c)).collect(); + // A forwarded menu key reaches its own command; other bindings on menu keys cannot run. + let kept: Vec = app.ui.keymap.bindings.iter().filter(|b| reserved(app, b.chord, &b.command)).map(|b| b.chord).collect(); app.ui.keymap.bindings.retain(|b| !kept.contains(&b.chord)); + report_skipped(app, &kept); } -/// Whether the native menu bar keeps a key combination for itself. -fn reserved(app: &RustGisApp, chord: Chord) -> bool { - app.ui.reserved_shortcuts.iter().any(|k| { +/// One notice for menu conflicts left out of loaded preferences or a confirmed portable import. +/// The total counts every skipped binding; the short key list says when more are left out. +pub(crate) fn report_skipped(app: &mut RustGisApp, skipped: &[Chord]) { + if !skipped.is_empty() { + let mut keys = skipped.iter().take(5).map(|c| c.text(cfg!(target_os = "macos"))).collect::>().join(", "); + if skipped.len() > 5 { + keys.push_str(", …"); + } + let message = if skipped.len() == 1 { + "{count} shortcut binding was not loaded because its key is kept by the native menu: {keys}" + } else { + "{count} shortcut bindings were not loaded because their keys are kept by the native menu: {keys}" + }; + app.session.notify(crate::i18n::fmt(message, &[("count", &skipped.len().to_string()), ("keys", &keys)]), false); + } +} + +/// Whether the native menu bar prevents this command from using a chord. A menu that forwards +/// the chord to its own command keeps it from every other command, including imported bindings. +pub(crate) fn reserved(app: &RustGisApp, chord: Chord, command: &str) -> bool { + let same = |k: &egui::KeyboardShortcut| { (k.modifiers.command || k.modifiers.mac_cmd) == chord.command && k.modifiers.alt == chord.alt && k.modifiers.shift == chord.shift && k.logical_key == chord.key - }) + }; + if let Some((_, own)) = app.ui.forwarded_shortcuts.iter().find(|(k, _)| same(k)) { + return *own != command; + } + app.ui.reserved_shortcuts.iter().any(same) } fn assign(app: &mut RustGisApp, editor: &mut Editor, chord: Chord, target: Target) { if keymap::is_clipboard(chord) { editor.notice_clipboard = true; - } else if reserved(app, chord) { + } else if reserved(app, chord, &target.command) { editor.notice_reserved = true; } else if app.ui.keymap.command_for(chord).is_some_and(|b| !b.runs(&target.command, &target.params)) { editor.pending = Some((chord, target)); @@ -383,6 +406,17 @@ mod tests { load(&mut app); assert!(app.ui.keymap.command_for(quit).is_none()); assert!(app.ui.keymap.command_for(Chord::parse("Mod+J").unwrap()).is_some()); + // Select All's menu item forwards its key: its own command may be restored, not another. + let all = Chord::parse("Mod+A").unwrap(); + app.ui.forwarded_shortcuts = vec![(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A), "select.all")]; + app.ui.keymap.remove(all); + editor.notice_reserved = false; + assign(&mut app, &mut editor, all, Target { command: "select.all".into(), params: Value::Null }); + assert!(!editor.notice_reserved); + assert_eq!(app.ui.keymap.command_for(all).unwrap().command, "select.all"); + assign(&mut app, &mut editor, all, Target { command: "select.clear".into(), params: Value::Null }); + assert!(editor.notice_reserved); + assert_eq!(app.ui.keymap.command_for(all).unwrap().command, "select.all"); // ⌃T (Ctrl without ⌘) isn't the bare T. assert!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::CTRL, egui::Key::T)).is_none()); } diff --git a/crates/ui-egui/tests/integration/shortcut_customization.rs b/crates/ui-egui/tests/integration/shortcut_customization.rs index 47aa1e8ba1..761c83c626 100644 --- a/crates/ui-egui/tests/integration/shortcut_customization.rs +++ b/crates/ui-egui/tests/integration/shortcut_customization.rs @@ -29,6 +29,121 @@ fn harness(prefs: Arc>>) -> egui_kittest::Harness< ) } +/// A two-point layer and the macOS menu policy, installed before saved shortcuts load. +fn native_select_all_app(changes: Option<&str>) -> RustGisApp { + use rustgis_engine::data::{Coord, Dataset, Geometry, GeometryType}; + let mut session = Session::new(Project::default()); + let mut data = Dataset::new("Points", GeometryType::Point, vec![]); + for x in [0.0, 1.0] { + data.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); + } + let layer = session.map_mut().add_dataset(data); + session.active_layer = Some(layer); + let chord = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A); + let mut app = RustGisApp::new(session); + app.ui.reserved_shortcuts = vec![chord]; + app.ui.forwarded_shortcuts = vec![(chord, "select.all")]; + let mut services = Services::default(); + if let Some(changes) = changes { + let changes = changes.to_owned(); + services.load_pref = Some(Box::new(move |key| (key == "shortcut_changes").then(|| changes.clone()))); + } + app.with_services(services) +} + +/// The macOS shell reserves its menu keys before loading preferences. A forwarded Select All +/// must survive that startup and reach the real shortcut loop, while a text field keeps the key. +#[test] +fn native_select_all_survives_startup_and_respects_text_focus() { + let app = native_select_all_app(None); + let layer = app.session.active_layer.unwrap(); + let chord = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(3); + assert_eq!(h.state().session.map().layer(layer).unwrap().selection, [0, 1]); + h.state_mut().run("select.clear", Value::Null).unwrap(); + h.get_by(|node| node.placeholder() == Some("Filter layers")).focus(); + h.event(egui::Event::Text("Poi".into())); + h.run_steps(3); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("Points".into())); + h.run_steps(3); + assert_eq!(h.state().ui.layer_filter, "Points"); + assert!(h.state().session.map().layer(layer).unwrap().selection.is_empty()); +} + +/// Startup, direct assignment and file import share the native menu's command ownership. An +/// explicit removal/rebinding remains removed, and a skipped stored conflict is reported. +#[test] +fn native_forwarded_keys_preserve_preferences_and_refuse_other_commands() { + use serde_json::json; + let chord = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A); + let own = r#"[{"keys":"Mod+A","command":"select.all"}]"#; + let other = r#"[{"keys":"Mod+A","command":"select.clear"}]"#; + let mut app = native_select_all_app(Some(own)); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); + assert!(app.session.notices_since(0).is_empty()); + assert!(app.run("ui.shortcuts.set", json!({"keys":"Mod+A","command":"select.clear"})).is_err()); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); + let file = |bindings: &str| format!(r#"{{"rustgis_shortcuts":1,"bindings":{bindings}}}"#); + // Export on a shell without native reservations: a rebind includes the default's removal + // as well as its replacement, so importing must leave out both halves of a rejected rebind. + let mut source = RustGisApp::new(Session::new(Project::default())); + source.run("ui.shortcuts.set", json!({"keys":"Mod+A","command":"select.clear"})).unwrap(); + source.run("ui.shortcuts.set", json!({"keys":"Mod+J","command":"select.clear"})).unwrap(); + let mixed = source.run("ui.shortcuts.export", json!({"text":true})).unwrap()["text"].as_str().unwrap().to_owned(); + let mark = app.session.notice_mark(); + let summary = app.run("ui.shortcuts.import", json!({"text":mixed})).unwrap(); + assert_eq!(summary["bindings"], 1); + assert_eq!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::J)), None); + assert!(app.session.notices_since(mark).is_empty(), "preview changes nothing"); + app.run("ui.shortcuts.import", json!({"text":mixed,"confirm":true})).unwrap(); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); + assert_eq!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::J)).as_deref(), Some("select.clear")); + let notices = app.session.notices_since(mark); + assert_eq!(notices.len(), 1); + assert!(!notices[0].error); + let key = if cfg!(target_os = "macos") { "⌘A" } else { "Ctrl+A" }; + let skipped = format!("1 shortcut binding was not loaded because its key is kept by the native menu: {key}"); + assert_eq!(notices[0].text, skipped); + let malformed = r#"[{"keys":"Mod+L","command":"ui.theme"},{"keys":"not a key","command":"ui.theme"}]"#; + assert_eq!( + app.run("ui.shortcuts.import", json!({"text":file(malformed),"confirm":true})).unwrap_err(), + "Shortcut file contains invalid or reserved bindings." + ); + assert_eq!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::L)), None); + app.run("ui.shortcuts.set", json!({"keys":"Mod+A","command":"select.all","remove":true})).unwrap(); + assert_eq!(app.shortcut_command(chord), None); + let mark = app.session.notice_mark(); + app.run("ui.shortcuts.import", json!({"text":file(own),"confirm":true})).unwrap(); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); + assert!(app.session.notices_since(mark).is_empty(), "a clean import has no skipped bindings"); + let removal = r#"[{"keys":"Mod+A","command":"select.all","remove":true}]"#; + app.run("ui.shortcuts.import", json!({"text":file(removal),"confirm":true})).unwrap(); + assert_eq!(app.shortcut_command(chord), None, "an explicit removal without a rejected replacement still applies"); + assert!(app.session.notices_since(mark).is_empty()); + let app = native_select_all_app(Some(other)); + assert_eq!(app.shortcut_command(chord), None); + let notices = app.session.notices_since(0); + assert_eq!(notices.len(), 1); + assert!(!notices[0].error); + assert_eq!(notices[0].text, skipped); + let app = + native_select_all_app(Some(r#"[{"keys":"Mod+A","command":"select.all","remove":true},{"keys":"Mod+J","command":"select.all"}]"#)); + assert_eq!(app.shortcut_command(chord), None); + assert_eq!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::J)).as_deref(), Some("select.all")); +} + #[test] fn assigns_a_key_confirms_conflicts_and_restores_saved_preferences() { let prefs = Arc::new(Mutex::new(HashMap::new())); diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 6de9246dd8..e8d27aeff2 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -528,12 +528,16 @@ to open it in the editor. If saved preferences are unreadable or exceed the supp original value is preserved and edits apply only to the current session. **Reset All** explicitly replaces the saved shortcuts with the defaults. +The macOS native menu keeps some keys, such as ⌘Q. Its forwarded ⌘A remains available for +Select All, but cannot be assigned to another command. + Use **Import…** and **Export…** in the editor to back up shortcuts or share them between desktop, macOS and browser sessions. Export writes `rustgis-shortcuts.json`, containing only differences from the current defaults. `Mod` means Ctrl, or ⌘ on macOS, so the same file works across platforms. Import merges with your current shortcuts: review the counts of bindings, conflicts and unknown -commands, then choose **Import** or **Cancel**. The file wins on conflicting keys; unrelated -bindings stay unchanged. Unknown command ids are retained and become usable when their plugin is +commands, then choose **Import** or **Cancel**. Bindings that conflict with native menu keys are +left out, preserving current bindings on those keys; confirmation reports their count and keys. +The file wins on other conflicting keys; unrelated bindings stay unchanged. Unknown command ids are retained and become usable when their plugin is installed. Import only files you trust: pressing an imported key runs its command with the supplied parameters, which can include file writes or preference changes. Inspect shared JSON before importing. Invalid files are rejected without changing shortcuts. Files are limited to 100,100 From ab2937937ff15eb715fe120f9c9bd5c5b17bcd65 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 29 Nov 2026 17:41:31 -0600 Subject: [PATCH 3/3] fix(ui): retain native shortcut defaults and disclose skipped imports --- crates/ui-egui/src/shortcutfile.rs | 35 +++++++----- crates/ui-egui/src/shortcutui.rs | 43 +++++++++++--- .../integration/shortcut_customization.rs | 57 ++++++++++++++++++- docs/user-guide/workspace.md | 22 +++---- 4 files changed, 122 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/shortcutfile.rs b/crates/ui-egui/src/shortcutfile.rs index 90777db62d..04d100cda8 100644 --- a/crates/ui-egui/src/shortcutfile.rs +++ b/crates/ui-egui/src/shortcutfile.rs @@ -35,6 +35,7 @@ fn import_bindings<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result< pub(crate) struct Preview { pub text: String, pub summary: Value, + pub skipped: Vec, } /// Route picker and dropped shortcut bytes without allocating a base64 copy of oversized input. @@ -102,9 +103,11 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value, Vec), St return Err(tl!("Unsupported shortcut file version.").into()); } let changes = serde_json::to_string(&doc.bindings).map_err(|e| e.to_string())?; - let mut merged = app.ui.keymap.clone(); - if !merged.apply_preferences(&changes) { - return Err(tl!("Shortcut file contains invalid or reserved bindings.").into()); + { + let mut checked = app.ui.keymap.clone(); + if !checked.apply_preferences(&changes) { + return Err(tl!("Shortcut file contains invalid or reserved bindings.").into()); + } } // Validation above includes every record, even those this platform will leave out. let mut skipped = Vec::new(); @@ -115,28 +118,30 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value, Vec), St } } let mut kept = Vec::new(); + let mut assigned = std::collections::HashSet::new(); for change in &doc.bindings { let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?; - // A rejected rebind must not apply the removal of the default it replaces. - let blocked = if change.remove { skipped.contains(&chord) } else { shortcutui::reserved(app, chord, &change.command) }; + // A rejected rebind must not remove its displaced default. After an accepted assignment, + // a removal is explicit and stays in the file's order. + let blocked = if change.remove { + skipped.contains(&chord) && !assigned.contains(&chord) + } else { + shortcutui::reserved(app, chord, &change.command) + }; if !blocked { + if !change.remove { + assigned.insert(chord); + } kept.push(change); } } - merged = app.ui.keymap.clone(); + let mut merged = app.ui.keymap.clone(); if !merged.apply_preferences(&serde_json::to_string(&kept).map_err(|e| e.to_string())?) { return Err(tl!("Shortcut file contains invalid or reserved bindings.").into()); } if merged.preferences(&Keymap::new(&app.session.registry)).is_none() { return Err(tl!("Too many shortcut changes to save.").into()); } - let mut assigned = std::collections::HashSet::new(); - for change in &kept { - let chord = Chord::parse(&change.keys).ok_or(tl!("Invalid shortcut key."))?; - if !change.remove { - assigned.insert(chord); - } - } let unknown = assigned .iter() .filter_map(|&chord| merged.command_for(chord)) @@ -152,7 +157,7 @@ fn merge(app: &RustGisApp, text: &str) -> Result<(Keymap, Value, Vec), St .is_some_and(|new| app.ui.keymap.command_for(chord).is_some_and(|old| !old.runs(&new.command, &new.params))) }) .count(); - Ok((merged, json!({"bindings":kept.len(), "conflicts":conflicts, "unknown_commands":unknown}), skipped)) + Ok((merged, json!({"bindings":kept.len(), "conflicts":conflicts, "unknown_commands":unknown, "skipped":skipped.len()}), skipped)) } /// Include UI actions outside Command Search when recognizing portable command ids. @@ -214,7 +219,7 @@ pub fn run(app: &mut RustGisApp, id: &str, p: &Value) -> Result { app.ui.shortcut_editor.import = None; shortcutui::report_skipped(app, &skipped); } else { - app.ui.shortcut_editor.import = Some(Preview { text, summary: summary.clone() }); + app.ui.shortcut_editor.import = Some(Preview { text, summary: summary.clone(), skipped }); app.ui.shortcut_editor.open = true; } Ok(summary) diff --git a/crates/ui-egui/src/shortcutui.rs b/crates/ui-egui/src/shortcutui.rs index 74b8e8341a..e8b6361dd1 100644 --- a/crates/ui-egui/src/shortcutui.rs +++ b/crates/ui-egui/src/shortcutui.rs @@ -50,24 +50,42 @@ pub(crate) fn save(app: &mut RustGisApp) { } } +/// Load saved overrides, leaving native menu conflicts out while retaining permitted defaults. +/// Explicit removals still apply; only a rejected assignment restores its displaced default. pub fn load(app: &mut RustGisApp) { if let Some(changes) = app.services.load_pref.as_ref().and_then(|load| load(PREF)) { app.ui.shortcut_preferences_blocked = !app.ui.keymap.apply_preferences(&changes); } // A forwarded menu key reaches its own command; other bindings on menu keys cannot run. - let kept: Vec = app.ui.keymap.bindings.iter().filter(|b| reserved(app, b.chord, &b.command)).map(|b| b.chord).collect(); - app.ui.keymap.bindings.retain(|b| !kept.contains(&b.chord)); - report_skipped(app, &kept); + let skipped: Vec = app.ui.keymap.bindings.iter().filter(|b| reserved(app, b.chord, &b.command)).map(|b| b.chord).collect(); + app.ui.keymap.bindings.retain(|b| !skipped.contains(&b.chord)); + if !skipped.is_empty() { + let defaults = Keymap::new(&app.session.registry); + for &chord in &skipped { + if let Some(binding) = defaults.command_for(chord) + && !reserved(app, chord, &binding.command) + { + app.ui.keymap.assign(chord, &binding.command, binding.params.clone()); + } + } + } + report_skipped(app, &skipped); +} + +/// A bounded native key list shared by the import preview and the completion notice. +pub(crate) fn skipped_keys(skipped: &[Chord]) -> String { + let mut keys = skipped.iter().take(5).map(|c| c.text(cfg!(target_os = "macos"))).collect::>().join(", "); + if skipped.len() > 5 { + keys.push_str(", …"); + } + keys } /// One notice for menu conflicts left out of loaded preferences or a confirmed portable import. /// The total counts every skipped binding; the short key list says when more are left out. pub(crate) fn report_skipped(app: &mut RustGisApp, skipped: &[Chord]) { if !skipped.is_empty() { - let mut keys = skipped.iter().take(5).map(|c| c.text(cfg!(target_os = "macos"))).collect::>().join(", "); - if skipped.len() > 5 { - keys.push_str(", …"); - } + let keys = skipped_keys(skipped); let message = if skipped.len() == 1 { "{count} shortcut binding was not loaded because its key is kept by the native menu: {keys}" } else { @@ -332,6 +350,17 @@ pub fn show(app: &mut RustGisApp, ctx: &Context) { ("unknown", &preview.summary.get("unknown_commands").unwrap_or(&Value::Null).to_string()), ], )); + if !preview.skipped.is_empty() { + let message = if preview.skipped.len() == 1 { + "Will skip {count} shortcut binding kept by the native menu: {keys}" + } else { + "Will skip {count} shortcut bindings kept by the native menu: {keys}" + }; + ui.label(crate::i18n::fmt( + message, + &[("count", &preview.skipped.len().to_string()), ("keys", &skipped_keys(&preview.skipped))], + )); + } ui.label(tl!("Imported bindings replace conflicting keys. Unknown commands are kept for later use.")); if app.ui.shortcut_preferences_blocked { ui.label(tl!("Reset unreadable saved shortcuts before importing.")); diff --git a/crates/ui-egui/tests/integration/shortcut_customization.rs b/crates/ui-egui/tests/integration/shortcut_customization.rs index 761c83c626..fd30523ef2 100644 --- a/crates/ui-egui/tests/integration/shortcut_customization.rs +++ b/crates/ui-egui/tests/integration/shortcut_customization.rs @@ -133,7 +133,7 @@ fn native_forwarded_keys_preserve_preferences_and_refuse_other_commands() { assert_eq!(app.shortcut_command(chord), None, "an explicit removal without a rejected replacement still applies"); assert!(app.session.notices_since(mark).is_empty()); let app = native_select_all_app(Some(other)); - assert_eq!(app.shortcut_command(chord), None); + assert_eq!(app.shortcut_command(chord).as_deref(), Some("select.all")); let notices = app.session.notices_since(0); assert_eq!(notices.len(), 1); assert!(!notices[0].error); @@ -144,6 +144,57 @@ fn native_forwarded_keys_preserve_preferences_and_refuse_other_commands() { assert_eq!(app.shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::J)).as_deref(), Some("select.all")); } +/// Before confirmation, the real import modal names the native key it will leave out; Cancel +/// keeps every current binding and emits no completion notice. +#[test] +fn native_import_preview_names_skipped_bindings_before_confirmation() { + use serde_json::json; + let mut app = native_select_all_app(None); + let text = + r#"{"rustgis_shortcuts":1,"bindings":[{"keys":"Mod+A","command":"select.clear"},{"keys":"Mod+J","command":"select.clear"}]}"#; + let summary = app.run("ui.shortcuts.import", json!({"text":text})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + let key = if cfg!(target_os = "macos") { "⌘A" } else { "Ctrl+A" }; + let message = format!("Will skip 1 shortcut binding kept by the native menu: {key}"); + assert!(h.query_by_label(&message).is_some()); + assert_eq!(summary["skipped"], 1); + assert_eq!(summary["bindings"], 1); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Cancel").click(); + h.run_steps(3); + assert!(h.query_by_label("Import Keyboard Shortcuts").is_none()); + let chord = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A); + assert_eq!(h.state().shortcut_command(chord).as_deref(), Some("select.all")); + assert_eq!(h.state().shortcut_command(egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::J)), None); + assert!(h.state().session.notices_since(0).is_empty()); +} + +/// An accepted assignment makes a later removal explicit, even when an earlier assignment +/// on that chord was rejected by the native menu policy. +#[test] +fn native_import_keeps_a_removal_after_an_accepted_assignment() { + use serde_json::json; + let mut app = native_select_all_app(None); + let text = r#"{"rustgis_shortcuts":1,"bindings":[{"keys":"Mod+A","command":"select.clear"},{"keys":"Mod+A","command":"select.all"},{"keys":"Mod+A","command":"select.all","remove":true}]}"#; + let summary = app.run("ui.shortcuts.import", json!({"text":text,"confirm":true})).unwrap(); + let chord = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::A); + assert_eq!(app.shortcut_command(chord), None); + assert_eq!(summary["bindings"], 2); + assert_eq!(summary["skipped"], 1); + let notices = app.session.notices_since(0); + assert_eq!(notices.len(), 1); + assert!(!notices[0].error); + let key = if cfg!(target_os = "macos") { "⌘A" } else { "Ctrl+A" }; + assert_eq!(notices[0].text, format!("1 shortcut binding was not loaded because its key is kept by the native menu: {key}")); +} + #[test] fn assigns_a_key_confirms_conflicts_and_restores_saved_preferences() { let prefs = Arc::new(Mutex::new(HashMap::new())); @@ -290,7 +341,7 @@ fn import_preview_cancel_confirm_and_export_round_trip() { .to_string(); let before = h.state().ui.keymap.clone(); let summary = h.state_mut().run("ui.shortcuts.import", json!({"text":text})).unwrap(); - assert_eq!(summary, json!({"bindings":3,"conflicts":1,"unknown_commands":1})); + assert_eq!(summary, json!({"bindings":3,"conflicts":1,"unknown_commands":1,"skipped":0})); assert_eq!(h.state().ui.keymap, before); h.run_steps(3); h.get_by_role_and_label(egui::accesskit::Role::Button, "Cancel").click(); @@ -390,7 +441,7 @@ fn import_counts_final_conflicting_keys_and_recognizes_help() { ]}) .to_string(); let summary = app.run("ui.shortcuts.import", json!({"text":text})).unwrap(); - assert_eq!(summary, json!({"bindings":9,"conflicts":1,"unknown_commands":0})); + assert_eq!(summary, json!({"bindings":9,"conflicts":1,"unknown_commands":0,"skipped":0})); } #[test] diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index e8d27aeff2..a9e433dc5d 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -532,17 +532,19 @@ The macOS native menu keeps some keys, such as ⌘Q. Its forwarded ⌘A remains Select All, but cannot be assigned to another command. Use **Import…** and **Export…** in the editor to back up shortcuts or share them between desktop, -macOS and browser sessions. Export writes `rustgis-shortcuts.json`, containing only differences -from the current defaults. `Mod` means Ctrl, or ⌘ on macOS, so the same file works across platforms. +macOS and browser sessions. Export writes `rustgis-shortcuts.json`, containing only differences from +the current defaults. `Mod` means Ctrl, or ⌘ on macOS, so the same file works across platforms. Import merges with your current shortcuts: review the counts of bindings, conflicts and unknown -commands, then choose **Import** or **Cancel**. Bindings that conflict with native menu keys are -left out, preserving current bindings on those keys; confirmation reports their count and keys. -The file wins on other conflicting keys; unrelated bindings stay unchanged. Unknown command ids are retained and become usable when their plugin is -installed. Import only files you trust: pressing an imported key runs its command with the supplied -parameters, which can include file writes or preference changes. Inspect shared JSON before importing. -Invalid files are rejected without changing shortcuts. Files are limited to 100,100 -bytes (including version metadata) and 1,000 records. Merged preference data must fit 100,000 bytes. If saved preferences -are unreadable, use **Reset All** before importing so they are not silently overwritten. +commands, plus any skipped native menu bindings and their keys, then choose **Import** or +**Cancel**. Bindings that conflict with native menu keys are left out, preserving current bindings +on those keys; the preview and confirmation report their count and keys. The file wins on other +conflicting keys; unrelated bindings stay unchanged. Unknown command ids are retained and become +usable when their plugin is installed. Import only files you trust: pressing an imported key runs +its command with the supplied parameters, which can include file writes or preference changes. +Inspect shared JSON before importing. Invalid files are rejected without changing shortcuts. Files +are limited to 100,100 bytes (including version metadata) and 1,000 records. Merged preference data +must fit 100,000 bytes. If saved preferences are unreadable, use **Reset All** before importing so +they are not silently overwritten. The version 1 file format is: