DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
keymap: dispatch_filtered, panel twins and import aliases on craft-keymap 66f2202
aiongg506c429c6525
diff --git a/Cargo.lock b/Cargo.lockindex 91e7a6b89..863e963d9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -827,7 +827,7 @@ dependencies = [[[package]]name = "craft-keymap"version = "0.1.0"-source = "git+https://github.com/aiongg/craft-libs?rev=d6c7b45350f7a4352b845c9fdd2e63913d1af27d#d6c7b45350f7a4352b845c9fdd2e63913d1af27d"+source = "git+https://github.com/aiongg/craft-libs?rev=66f22029ba71dad29dcda156f01f680763aa6659#66f22029ba71dad29dcda156f01f680763aa6659"dependencies = ["egui","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 4767c4ee5..0936e75a1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/designcraft"# Shared writer; the immutable revision must be published before this consumer.craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.1.0", default-features = false }# Shared keyboard bindings: chords, overrides, conflicts, egui dispatch.-craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "d6c7b45350f7a4352b845c9fdd2e63913d1af27d", version = "=0.1.0", features = ["egui"] }+craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "66f22029ba71dad29dcda156f01f680763aa6659", version = "=0.1.0", features = ["egui"] }# internaldesigncraft-geom = { path = "crates/geom" }designcraft-color = { path = "crates/color" }diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rsindex 8e3c16452..ee85a0400 100644--- a/crates/ui-egui/src/keys.rs+++ b/crates/ui-egui/src/keys.rs@@ -33,6 +33,39 @@ const PANEL_KEYS: &[(&str, &str)] = &[("align", "Shift+F7"),];+/// Other names shortcut sets use for a command (InDesign's feature names), by command id.+const IMPORT_ALIASES: &[(&str, &str)] = &[+ ("app.quit", "Exit"),+ ("app.preferences", "General"),+ ("app.insertTableDialog", "Insert Table"),+ ("view.togglePresentation", "Presentation"),+ ("color.defaultFillStroke", "Apply Default Fill and Stroke Colors"),+ ("color.swapFillStroke", "Swap Fill and Stroke Colors"),+ ("view.togglePreview", "Toggle View Setting Between Default and Preview"),+ ("type.bold", "Apply Bold"),+ ("type.italic", "Apply Italic"),+ ("window.hidePanels", "Show/Hide All Panels"),+ ("window.hidePanelsExceptTools", "Show/Hide All Panels Except Toolbox"),+ ("window.nextDocument", "Next Window"),+ ("window.previousDocument", "Previous Window"),+];++/// Extra menu paths for import, where an alias would leave two commands on one name: InDesign's+/// Tools area has Apply Color, which is also `object.color`'s label.+const IMPORT_PATHS: &[(&str, &[&str])] = &[("color.applyColor", &["Tools", "Apply Color"])];++/// Commands that open a panel, by panel id. The panel's binding gets the command's default key+/// too, so the two are twins: a shortcut set that gives either one the key leaves both with it.+const PANEL_TWINS: &[(&str, &str)] = &[+ ("character", "app.characterPanel"),+ ("paragraph", "app.paragraphPanel"),+ ("glyphs", "app.glyphsPanel"),+ ("characterStyles", "app.characterStylesPanel"),+ ("paragraphStyles", "app.paragraphStylesPanel"),+ ("table", "app.tablePanel"),+ ("textWrap", "object.textWrap"),+];+pub fn panel(id: &str) -> CommandRef {CommandRef::with_params(PANEL_COMMAND, json!({ "panel": id }))}@@ -72,23 +105,23 @@ fn build_catalogue() -> Vec<Bindable> {let rows: HashSet<Vec<String>> = paths.values().flatten().map(|p| normalized(p)).collect();let app = Scope::app();let mut out = Vec::new();- let mut add = |command: CommandRef, label: &str, default: Option<&str>, fallback_path: Option<Vec<String>>, kind: Kind| {+ let mut add = |command: CommandRef, label: &str, defaults: &[&str], fallback_path: Option<Vec<String>>, kind: Kind| {let mut b = Bindable::new(command, label, app.clone()).with_kind(kind);match paths.get(&b.command.key()) {Some(found) => b.paths.extend(found.iter().cloned()),None => b.paths.extend(fallback_path.filter(|p| !rows.contains(&normalized(p)))),}- if let Some(binding) = default.and_then(|d| Binding::parse(d).ok()) {+ for binding in defaults.iter().filter_map(|d| Binding::parse(d).ok()) {b = b.with_default(binding);}out.push(b);};for (id, label, _, _) in menus::UI_COMMANDS {- add(CommandRef::new(*id), label, menus::default_shortcut(id), None, Kind::Command);+ add(CommandRef::new(*id), label, menus::default_shortcut(id).as_slice(), None, Kind::Command);}for c in designcraft_engine::command_specs() {let path = (!c.menu.is_empty()).then(|| c.menu.iter().map(|s| s.to_string()).chain([c.label.to_string()]).collect());- add(CommandRef::new(c.id), c.label, c.shortcut, path, Kind::Command);+ add(CommandRef::new(c.id), c.label, c.shortcut.as_slice(), path, Kind::Command);}let mut seen = Vec::new();for (id, label, _) in crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS) {@@ -96,16 +129,26 @@ fn build_catalogue() -> Vec<Bindable> {continue;}seen.push(id);- let default = PANEL_KEYS.iter().find(|(p, _)| p == id).map(|(_, k)| *k);- add(panel(id), label, default, Some(vec!["Window".into(), (*label).into()]), Kind::Command);+ let own = PANEL_KEYS.iter().find(|(p, _)| p == id).map(|(_, k)| *k);+ let twin = PANEL_TWINS.iter().find(|(p, _)| p == id).and_then(|(_, c)| menus::default_shortcut(c));+ let defaults: Vec<&str> = own.into_iter().chain(twin).collect();+ add(panel(id), label, &defaults, Some(vec!["Window".into(), (*label).into()]), Kind::Command);}for group in designcraft_tools::TOOL_GROUPS {let Some(first) = group.first() else { continue };for t in group.iter() {let kind = Kind::Tool { group: Some(first.id.to_string()) };- add(tool(t.id), t.label, t.shortcut, Some(vec!["Tools".into(), t.label.into()]), kind);+ add(tool(t.id), t.label, t.shortcut.as_slice(), Some(vec!["Tools".into(), t.label.into()]), kind);}}+ for b in &mut out {+ if !b.command.params.is_null() {+ continue;+ }+ let id = b.command.id.as_str();+ b.aliases.extend(IMPORT_ALIASES.iter().filter(|(c, _)| *c == id).map(|(_, a)| a.to_string()));+ b.paths.extend(IMPORT_PATHS.iter().filter(|(c, _)| *c == id).map(|(_, p)| p.iter().map(|s| s.to_string()).collect()));+ }out}@@ -197,15 +240,8 @@ pub fn set(app: &mut DesignApp, cmd: &CommandRef, shortcut: Option<&str>, policy/// Other commands on the keys `cmd` holds, by command key.pub fn conflicts(keymap: &Keymap, cmd: &CommandRef) -> Vec<String> {let mut out: Vec<String> = Vec::new();- for c in keymap.conflicts() {- let other = if c.a.0 == *cmd {- &c.b.0- } else if c.b.0 == *cmd {- &c.a.0- } else {- continue;- };- let key = other.key();+ for c in keymap.conflicts_with(cmd) {+ let key = c.b.0.key();if !out.contains(&key) {out.push(key);}diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex fb61be02e..74571bf4f 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -3005,38 +3005,21 @@ pub fn shortcuts(app: &mut DesignApp, ctx: &egui::Context) {let contexts: &[&str] = if typing { &[crate::keys::TEXT_CONTEXT] } else { &[] };let active = craft_keymap::Active { panel: None, contexts, typing };let hits = ctx.input_mut(|i| {- let platform = app.keymap.platform();- // Presses the dispatcher must not take: the clipboard events the canvas and text tools- // handle themselves (Paste carries the text), Clear (the active tool deletes), and the- // keys the native menu's accelerators already handled. They go back afterwards.- let mut held = Vec::new();- i.events.retain(|e| {- let keep = match e {- egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) => false,- egui::Event::Key { key, pressed: true, modifiers, .. } => {- let exact =- craft_keymap::Key::from_egui(*key).map(|k| craft_keymap::Chord::new(craft_keymap::Mods::from_egui(modifiers, platform), k));- let run = match exact.map(|c| app.keymap.lookup(&c, false, &active)) {- Some(craft_keymap::Lookup::Run(c)) => Some(c),- _ => None,- };- // The native menu's accelerator holds the command's default keys and fires- // only for them exactly: the Plus key standing in for = never reaches it.- !run.is_some_and(|c| {- c.id == "edit.clear"- || (c.params.is_null() && app.native_shortcuts.contains(&c.id) && app.keymap.overrides().get(&c.id).is_none())- })- }- _ => true,- };- if !keep {- held.push(e.clone());- }- keep- });- let hits = app.key_dispatcher.dispatch(i, &app.keymap, &active);- i.events.extend(held);- hits+ let native = &app.native_shortcuts;+ let overrides = app.keymap.overrides();+ // Presses the dispatcher leaves alone: Clear (the active tool deletes) and the keys the+ // native menu's accelerators already handled. An accelerator holds the command's default+ // keys and fires only for them exactly: the Plus key standing in for = never reaches it.+ // Copy, Cut and Paste stay too (the dispatcher's default): the canvas and text tools+ // handle them, and Paste carries the text.+ let accept = |hit: &craft_keymap::egui::Hit| {+ let c = &hit.command;+ let leave = hit.exact+ && hit.cycle.is_empty()+ && (c.id == "edit.clear" || (c.params.is_null() && native.contains(&c.id) && overrides.get(&c.id).is_none()));+ !leave+ };+ app.key_dispatcher.dispatch_filtered(i, &app.keymap, &active, accept)});for hit in hits {if !hit.cycle.is_empty() {@@ -3513,9 +3496,12 @@ mod tests {assert_eq!(shortcut_of(&app, "app.palette"), None, "a removed default stays removed");assert_eq!(shortcut_of(&app, "file.close"), None);assert_eq!(shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S"));- // Saved again in the current form, it reads back the same.+ // Saved again it reads back the same, and with one key per command it keeps the map form+ // an older version reads.let resaved = serde_json::to_vec(&app.ui).unwrap();assert_eq!(crate::UiState::from_preferences_json(&resaved).unwrap().shortcuts, app.ui.shortcuts);+ let saved: Value = serde_json::from_slice(&resaved).unwrap();+ assert_eq!(saved["shortcuts"], json!({"app.preferences": "Cmd+Alt+Shift+9", "app.palette": "", "file.close": ""}));}#[test]diff --git a/crates/ui-egui/src/shortcut_import.rs b/crates/ui-egui/src/shortcut_import.rsindex 0d62a535a..e413369d6 100644--- a/crates/ui-egui/src/shortcut_import.rs+++ b/crates/ui-egui/src/shortcut_import.rs@@ -351,6 +351,16 @@ mod tests {assert_eq!(menus::shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Enter"));}+ #[test]+ fn a_panel_item_shares_its_key_with_the_command_that_opens_the_panel() {+ let mut app = app();+ let set = "Shortcut Set : Panels\r\nProduct area : Window Menu\r\n\tType & Tables: Character --- Default: Ctrl+T\r\n";+ let r = menus::run_ui(&mut app, "window.importShortcuts", &json!({"text": set})).unwrap().unwrap();+ assert_eq!(crate::keys::shortcut(&app.keymap, &crate::keys::panel("character")).as_deref(), Some("Cmd+T"));+ assert_eq!(menus::shortcut_of(&app, "app.characterPanel").as_deref(), Some("Cmd+T"));+ assert!(!r["conflictsCleared"].as_array().into_iter().flatten().any(|c| c["id"] == "app.characterPanel"), "{r}");+ }+#[test]fn hostile_input_returns_a_report_or_an_error() {let mut app = app();