DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
keymap: the InDesign set import runs on craft_keymap::import
aiongg8bb887a188d7
diff --git a/ROADMAP.md b/ROADMAP.mdindex 6ca512064..0ba1879fc 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.mNewest first.+- **2026-10-19** · Import InDesign Set… runs on craft-keymap's importer: a set's Window menu panel items (Layers F7, Pages F12, Swatches F5) and Tools items set the panel and tool shortcuts, all of an item's Default keys apply, and the report adds numeric keypad keys read as main keys and likely commands for unmatched items (`window.importShortcuts`). On InDesign's Windows defaults it matches 280 of 1,629 items (was 233) and changes 27 commands. No readiness percentage change.- **2026-10-19** · Keyboard shortcuts run on the shared craft-keymap crate. Panels take shortcuts, with InDesign's defaults where the key is free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tool keys are editable in Edit › Keyboard Shortcuts and `window.setShortcut`, and tools sharing a key take turns (B). Saved shortcuts load unchanged. No readiness percentage change.- **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change.- **2026-10-16** · Threading: the loaded text cursor threads into a text frame inside a group (it hit the group and showed it could not thread); a plain click still selects the group (#1075). Gap 27 closed. No readiness percentage change.diff --git a/crates/ui-egui/src/keys.rs b/crates/ui-egui/src/keys.rsindex bc3c53b54..8e3c16452 100644--- a/crates/ui-egui/src/keys.rs+++ b/crates/ui-egui/src/keys.rs@@ -2,7 +2,7 @@//! tools with their default keys and menu paths), shortcut text, and the edits that//! `window.setShortcut`, the Keyboard Shortcuts dialog and the shortcut-set importer make.-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::sync::OnceLock;use craft_keymap::{Bindable, Binding, Chord, CommandRef, Key, Keymap, Kind, Mods, Overrides, Platform, Policy, Scope, Scopes};@@ -65,13 +65,18 @@ pub fn catalogue() -> &'static [Bindable] {fn build_catalogue() -> Vec<Bindable> {let paths = menu_paths();+ // An engine command's own menu placement counts only where no menu row stands: a row there+ // runs a UI command in its place (File › Save is the Save dialog when needed), and two+ // commands on one path leave the importer unable to pick either.+ let normalized = |path: &[String]| path.iter().map(|s| craft_keymap::import::normalize_label(s)).collect::<Vec<_>>();+ 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 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),+ None => b.paths.extend(fallback_path.filter(|p| !rows.contains(&normalized(p)))),}if let Some(binding) = default.and_then(|d| Binding::parse(d).ok()) {b = b.with_default(binding);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 87bbfd4fa..fb61be02e 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -94,7 +94,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &["window.importShortcuts","Import InDesign Shortcut Set",None,- "{path | text} — a set saved by InDesign's Show Set (.txt): matched commands take its Default shortcuts (or none), other commands lose keys it takes → {set, imported, changed, conflictsCleared, skipped (an earlier item whose keys a later one took), unmatched, unmatchedWithoutShortcut, unreadable}",+ "{path | text} — a set saved by InDesign's Show Set (.txt): matched commands, panels (Window menu items) and tools (Tools items) take its Default shortcuts (an item without Default keys takes its Text keys), or none when every item matched to them has none; other commands lose keys it takes unless they share them as defaults → {set, imported, changed [{id, label, item, line, from, to}], conflictsCleared [{id, label, shortcut}], skipped [{id, item, line, shortcut, takenBy, reason}] (an earlier item whose keys a later one took, or a reserved key), failed [{id, label, change, shortcuts}], unmatched [{item, line, keys, reason: noMatch | ambiguous | tool | context}], unmatchedWithoutShortcut, unreadable [{item, line, keys, reason}], approximated [{item, line, keys, note}] (numeric keypad keys bound as the main keys), suggestions [{item, line, candidates}] (never applied), truncated}; ids are command keys (`window.panel {\"panel\":\"layers\"}`)",),("app.findChange", "Find/Change…", Some("Cmd+F"), "{}"),("app.insertTableDialog", "Create Table…", None, "{} — Insert Table dialog (body/header/footer rows, columns)"),@@ -2982,14 +2982,6 @@ pub fn all_menu_items() -> Vec<(String, String)> {out}-/// Reads shortcut text into egui's modifiers and key (`command` for Cmd, `ctrl` for the Mac-/// Control key).-pub(crate) fn parse_shortcut(sc: &str) -> Option<(egui::Modifiers, egui::Key)> {- let chord = craft_keymap::Chord::parse(sc).ok()?;- let s = chord.to_egui_shortcut();- Some((s.modifiers, s.logical_key))-}-/// Global keyboard shortcuts: menu commands, panels and tools, through the keymap.pub fn shortcuts(app: &mut DesignApp, ctx: &egui::Context) {app.sync_keymap();diff --git a/crates/ui-egui/src/shortcut_import.rs b/crates/ui-egui/src/shortcut_import.rsindex 8654bf553..0d62a535a 100644--- a/crates/ui-egui/src/shortcut_import.rs+++ b/crates/ui-egui/src/shortcut_import.rs@@ -3,15 +3,15 @@//!//! The file lists items under `Product area : <area>` headers, one per line://! `<name> --- [none defined]` or `<name> --- <context>: <keys>, <context>: <keys>`. Item names-//! use `: ` between submenu levels. Only the Default context applies (DesignCraft has no-//! shortcut contexts); a type command with no Default entry takes its Text entry.--use std::collections::{BTreeSet, HashMap};+//! use `: ` between submenu levels. This module reads the file into a+//! [`craft_keymap::ForeignSet`]; `craft_keymap::import` matches and applies it. Default keys bind+//! in the command's home scope; an item without Default keys takes its Text keys.+use craft_keymap::import::{MAX_IMPORT_ENTRIES, MAX_IMPORT_TEXT};+use craft_keymap::{ContextRule, Flavor, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportReport};use serde_json::{Value, json};use crate::DesignApp;-use crate::menus::{self, Item};/// Largest set file read. InDesign's full set is a few hundred kilobytes (twice that as UTF-16).pub const MAX_BYTES: usize = 8 << 20;@@ -25,14 +25,20 @@ struct Entry {}struct SetItem {- area: String,+ /// Index into [`ParsedSet::areas`]; `None` before the first `Product area` line.+ area: Option<usize>,name: String,entries: Vec<Entry>,+ /// 1-based line in the file.+ line: usize,}struct ParsedSet {name: String,+ areas: Vec<String>,items: Vec<SetItem>,+ /// Items past [`MAX_IMPORT_ENTRIES`], not read.+ dropped: usize,}/// Text from the bytes of a set file: UTF-8 (with or without a BOM) or UTF-16 (by its BOM, or@@ -68,26 +74,34 @@ fn header<'a>(line: &'a str, label: &str) -> Option<&'a str> {rest.trim_start().strip_prefix(':').map(str::trim)}+/// The first [`MAX_IMPORT_TEXT`] chars of `s`.+fn capped(s: &str) -> &str {+ s.char_indices().nth(MAX_IMPORT_TEXT).and_then(|(end, _)| s.get(..end)).unwrap_or(s)+}+fn parse(text: &str) -> Result<ParsedSet, String> {let text = text.strip_prefix('\u{feff}').unwrap_or(text);- let mut set = ParsedSet { name: String::new(), items: Vec::new() };- let mut area = String::new();+ let mut set = ParsedSet { name: String::new(), areas: Vec::new(), items: Vec::new(), dropped: 0 };let mut header_seen = false;- for line in text.lines() {- let line = line.trim_end_matches('\r');- let trimmed = line.trim();+ for (n, line) in text.lines().enumerate() {+ let trimmed = line.trim_end_matches('\r').trim();if let Some(name) = header(trimmed, "Shortcut Set") {- set.name = name.to_string();+ set.name = capped(name).to_string();header_seen = true;} else if let Some(a) = header(trimmed, "Product area") {- area = a.to_string();+ set.areas.push(capped(a).to_string());header_seen = true;} else if let Some((name, keys)) = trimmed.split_once(" --- ") {let name = name.trim();if name.is_empty() {continue;}- set.items.push(SetItem { area: area.clone(), name: name.to_string(), entries: entries(keys) });+ if set.items.len() >= MAX_IMPORT_ENTRIES {+ set.dropped += 1;+ continue;+ }+ let area = set.areas.len().checked_sub(1);+ set.items.push(SetItem { area, name: name.to_string(), entries: entries(keys), line: n.saturating_add(1) });}}if set.items.is_empty() && !header_seen {@@ -105,17 +119,18 @@ fn entries(keys: &str) -> Vec<Entry> {}let mut pieces: Vec<String> = Vec::new();for piece in keys.split(", ") {+ let full = pieces.len() >= MAX_ENTRIES;match pieces.last_mut() {Some(last) if !piece.contains(": ") => {last.push_str(", ");last.push_str(piece);}+ _ if full => break,_ => pieces.push(piece.to_string()),}}pieces.into_iter()- .take(MAX_ENTRIES).filter_map(|p| {let (context, keys) = p.split_once(": ")?;Some(Entry { context: context.trim().to_string(), keys: keys.trim().to_string() })@@ -123,398 +138,116 @@ fn entries(keys: &str) -> Vec<Entry> {.collect()}-/// Whether the keys use Mac modifier names, where Ctrl is the Control key rather than the-/// command modifier.-fn is_mac_set(set: &ParsedSet) -> bool {- set.items.iter().flat_map(|i| &i.entries).any(|e| {- let k = e.keys.to_lowercase();- k.contains("cmd") || k.contains("command") || k.contains('⌘') || k.contains("opt") || k.contains('⌥')- })+/// `s` without a trailing `suffix`, compared without ASCII case.+fn strip_suffix_ignore_case<'a>(s: &'a str, suffix: &str) -> Option<&'a str> {+ let at = s.len().checked_sub(suffix.len())?;+ s.get(at..).filter(|end| end.eq_ignore_ascii_case(suffix)).and_then(|_| s.get(..at))}-#[derive(Clone, Copy, PartialEq, Eq)]-enum Mod {- Command,- Alt,- Shift,- Control,-}--/// Keys as InDesign writes them (`Shift+Ctrl+S`, `Ctrl+Num 5`, `Page Down`, `⇧⌘S`) as a-/// DesignCraft shortcut string (`Cmd+Shift+S`). Ctrl is the command modifier in a Windows set.-fn read_keys(keys: &str, mac: bool) -> Result<String, &'static str> {- const SYMBOLS: &[(&str, Mod)] = &[("⌘", Mod::Command), ("⌥", Mod::Alt), ("⇧", Mod::Shift), ("⌃", Mod::Control)];- const WORDS: &[(&str, Mod)] = &[- ("command", Mod::Command),- ("cmd", Mod::Command),- ("option", Mod::Alt),- ("opt", Mod::Alt),- ("alt", Mod::Alt),- ("shift", Mod::Shift),- ("control", Mod::Control),- ("ctrl", Mod::Control),- ];- let mut m = egui::Modifiers::NONE;- let mut set = |md: Mod| match md {- Mod::Command => m.command = true,- Mod::Alt => m.alt = true,- Mod::Shift => m.shift = true,- Mod::Control if mac => m.ctrl = true,- Mod::Control => m.command = true,- };- let mut rest = keys.trim();- 'strip: loop {- for (sym, md) in SYMBOLS {- if let Some(r) = rest.strip_prefix(sym) {- set(*md);- rest = r.strip_prefix('+').unwrap_or(r).trim_start();- continue 'strip;- }- }- for (word, md) in WORDS {- let Some(head) = rest.get(..word.len()) else { continue };- let Some(after) = rest.get(word.len()..) else { continue };- // The word must be followed by a separator and a key: "Alt" alone, or "Altx", is a key name.- let mut chars = after.chars();- if head.eq_ignore_ascii_case(word) && matches!(chars.next(), Some('+' | ' ' | '-')) && !chars.as_str().is_empty() {- set(*md);- rest = chars.as_str().trim_start();- continue 'strip;+/// The set as `craft_keymap::import` reads it. An area named `<menu> Menu` is that menu; the+/// Tools area is the Tools menu, where items named `… Tool` select tools. Items of other areas+/// (panel menus, text and tables, views) have no menu, so they match only by a one-segment name.+/// The keys are read with Mac modifier names when any key in the set uses one.+fn foreign(set: &ParsedSet) -> ForeignSet {+ let flavor = Flavor::detect(set.items.iter().flat_map(|i| &i.entries).map(|e| e.keys.as_str()));+ let menus: Vec<(Option<&str>, bool)> = set+ .areas+ .iter()+ .map(|a| {+ let a = a.trim();+ if a.eq_ignore_ascii_case("tools") {+ (Some(a), true)+ } else {+ (strip_suffix_ignore_case(a, " menu").map(str::trim).filter(|m| !m.is_empty() && !m.contains(':')), false)}- }- break;- }- if m.ctrl {- return Err("Control-key shortcuts are not supported");- }- let key = key_named(rest.trim()).ok_or("unknown key")?;- let sc = menus::shortcut_string(m, key);- // Only a string the shortcut dispatcher reads back as these keys is imported.- match menus::parse_shortcut(&sc) {- Some((pm, pk)) if pk == key && same_mods(pm, m) => Ok(sc),- _ => Err("unknown key"),- }-}--fn same_mods(a: egui::Modifiers, b: egui::Modifiers) -> bool {- a.command == b.command && a.alt == b.alt && a.shift == b.shift && a.ctrl == b.ctrl+ })+ .collect();+ let entries = set+ .items+ .iter()+ .map(|item| {+ let (menu, tools) = item.area.and_then(|a| menus.get(a)).copied().unwrap_or((None, false));+ let mut entry = ForeignEntry::new(menu, item.name.split(": ").map(str::trim)).at_line(item.line);+ entry.is_tool = tools && strip_suffix_ignore_case(&item.name, " tool").is_some();+ entry.keys = item.entries.iter().map(|e| ForeignKey::read(Some(&e.context), &e.keys, flavor)).collect();+ entry+ })+ .collect();+ ForeignSet { name: Some(set.name.clone()), entries }}-/// A key by the name InDesign gives it (Windows words, Mac symbols), case- and space-insensitive.-fn key_named(name: &str) -> Option<egui::Key> {- use egui::Key;- if name.is_empty() {- return None;+/// Imports a set: every matched command takes the set's shortcuts (or none, when every item+/// matched to it has none), other commands lose keys it takes (unless they share them as+/// defaults), and the rest keep theirs. Returns the report.+pub fn import(app: &mut DesignApp, text: &str) -> Result<Value, String> {+ if text.len() > MAX_BYTES {+ return Err(format!("the set is larger than {} MB", MAX_BYTES >> 20));}- let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase();- // The numeric keypad: egui doesn't tell its keys apart from the main ones.- let n = squashed.strip_prefix("numpad").or_else(|| squashed.strip_prefix("num").filter(|r| !r.is_empty() && *r != "lock")).unwrap_or(&squashed);- let key = match n {- "up" | "uparrow" | "arrowup" | "↑" => Key::ArrowUp,- "down" | "downarrow" | "arrowdown" | "↓" => Key::ArrowDown,- "left" | "leftarrow" | "arrowleft" | "←" => Key::ArrowLeft,- "right" | "rightarrow" | "arrowright" | "→" => Key::ArrowRight,- "pageup" | "pgup" | "⇞" => Key::PageUp,- "pagedown" | "pgdn" | "⇟" => Key::PageDown,- "home" | "↖" => Key::Home,- "end" | "↘" => Key::End,- "esc" | "escape" | "⎋" => Key::Escape,- "tab" | "⇥" => Key::Tab,- "space" | "spacebar" => Key::Space,- "enter" | "return" | "↩" | "⏎" | "⌤" => Key::Enter,- "backspace" | "⌫" => Key::Backspace,- "delete" | "del" | "forwarddelete" | "⌦" => Key::Delete,- "insert" | "ins" | "help" => Key::Insert,- _ => return Key::from_name(n).or_else(|| Key::from_name(&n.to_uppercase())).or_else(|| Key::from_name(name)),+ let parsed = parse(text)?;+ let set = foreign(&parsed);+ let options = ImportOptions {+ contexts: vec![("Default".into(), ContextRule::Home), (crate::keys::TEXT_CONTEXT.into(), ContextRule::HomeWithoutHomeEntry)],+ suggest: true,+ ..ImportOptions::default()};- Some(key)-}--/// Matching form of a label or menu name: no ellipsis, no `&`, single spaces, lower case, and-/// no Show/Hide in front (InDesign names a toggle by what choosing it does now).-fn norm(s: &str) -> String {- let s = s.replace('…', "").replace("...", "").replace('&', "");- let s = s.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();- ["show/hide ", "show ", "hide "].iter().find_map(|p| s.strip_prefix(p).filter(|r| !r.is_empty())).map_or(s.clone(), str::to_string)-}--/// DesignCraft's commands by menu path and label.-#[derive(Default)]-struct Index {- /// `menu\nsubmenu\nlabel` → ids, in the menu bar.- path: HashMap<String, BTreeSet<String>>,- /// The same from the engine commands' own menu placement, which a UI command (the one with- /// the dialog) may stand in for in the menu bar.- engine_path: HashMap<String, BTreeSet<String>>,- /// (menu, label) → ids, at any depth of that menu.- in_menu: HashMap<(String, String), BTreeSet<String>>,- /// label → ids, anywhere.- label: HashMap<String, BTreeSet<String>>,-}--impl Index {- fn build() -> Self {- fn walk(ix: &mut Index, items: &[Item], path: &mut Vec<String>) {- for it in items {- match it {- Item::Sub(name, children) => {- path.push(norm(name));- walk(ix, children, path);- path.pop();- }- // A shortcut runs the command without parameters; a fixed-parameter variant can't hold one.- Item::Cmd { label, id, params, .. } if params.is_null() => {- let label = norm(label);- let top = path.first().cloned().unwrap_or_default();- add_path(&mut ix.path, path, &label, id);- ix.in_menu.entry((top, label.clone())).or_default().insert(id.clone());- ix.label.entry(label).or_default().insert(id.clone());- }- _ => {}- }- }- }- let mut ix = Index::default();- for (menu, entries) in menus::menu_tree() {- walk(&mut ix, &entries, &mut vec![norm(menu)]);- }- for c in designcraft_engine::command_specs() {- let label = norm(c.label);- if !c.menu.is_empty() {- let path: Vec<String> = c.menu.iter().map(|m| norm(m)).collect();- add_path(&mut ix.engine_path, &path, &label, c.id);- }- ix.label.entry(label).or_default().insert(c.id.to_string());- }- for (id, label, _, _) in menus::UI_COMMANDS {- ix.label.entry(norm(label)).or_default().insert((*id).to_string());- }- ix- }-- /// The command an item names, trying the most specific match first. Matches by label alone- /// only count when exactly one command has that label.- fn find(&self, area: &str, name: &str) -> Option<String> {- let one = |s: Option<&BTreeSet<String>>| s.filter(|s| s.len() == 1).and_then(|s| s.first().cloned());- let segments: Vec<String> = name.split(": ").map(norm).collect();- let last = segments.last().cloned().unwrap_or_default();- let area = norm(area);- if let Some(menu) = area.strip_suffix(" menu").filter(|m| !m.contains(':')) {- let mut key = menu.to_string();- for s in &segments {- key.push('\n');- key.push_str(s);- }- if let Some(id) = one(self.path.get(&key)) {- return Some(id);- }- if segments.len() > 1- && let Some(id) = one(self.in_menu.get(&(menu.to_string(), segments.join(" "))))- {- return Some(id);- }- if let Some(id) = one(self.engine_path.get(&key)) {- return Some(id);- }- if let Some(id) = one(self.in_menu.get(&(menu.to_string(), last.clone()))) {- return Some(id);- }- // Menus are arranged differently: the item's own label, if no other command has it.- return one(self.label.get(&last));- }- if segments.len() == 1 { one(self.label.get(&last)) } else { None }- }+ app.sync_keymap();+ let mut report = craft_keymap::plan(&set, &app.keymap, &options).apply(&mut app.keymap);+ report.truncated = report.truncated.saturating_add(parsed.dropped);+ crate::keys::store(app);+ Ok(report_json(&report))}-fn add_path(map: &mut HashMap<String, BTreeSet<String>>, path: &[String], label: &str, id: &str) {- let mut key = path.join("\n");- key.push('\n');- key.push_str(label);- map.entry(key).or_default().insert(id.to_string());+/// An enum of the report as its serde name (`noMatch`, `numpad`).+fn name_of<T: serde::Serialize>(v: &T) -> Value {+ serde_json::to_value(v).unwrap_or(Value::Null)}-/// What the set says about one DesignCraft command, over every item matched to it.-struct Decision {- id: String,- item: String,- /// The first readable shortcut.- shortcut: Option<String>,- /// Every matched item said `[none defined]`.- all_none: bool,-}--fn command_label(id: &str) -> String {- menus::ui_label(id)- .map(|(l, _)| l.to_string())- .or_else(|| designcraft_engine::find_command(id).map(|c| c.label.to_string()))- .unwrap_or_else(|| id.to_string())-}--/// Gives the command with this key the shortcut, none (`""`), or its default (`None`).-fn store(app: &mut DesignApp, key: &str, shortcut: Option<&str>) {- if let Some(cmd) = craft_keymap::CommandRef::parse_key(key) {- let _ = crate::keys::set(app, &cmd, shortcut, craft_keymap::Policy::Keep);- }-}--fn keys_of(sc: &str) -> Option<(bool, bool, bool, bool, egui::Key)> {- menus::parse_shortcut(sc).map(|(m, k)| (m.command, m.alt, m.shift, m.ctrl, k))-}--/// Imports a set: every matched command takes the set's shortcut (or none), another command-/// holding an imported shortcut loses it, and the rest keep theirs. Returns the report.-pub fn import(app: &mut DesignApp, text: &str) -> Result<Value, String> {- if text.len() > MAX_BYTES {- return Err(format!("the set is larger than {} MB", MAX_BYTES >> 20));- }- let set = parse(text)?;- let mac = is_mac_set(&set);- let ix = Index::build();- let mut decisions: Vec<Decision> = Vec::new();- let mut unmatched = Vec::new();- let mut unmatched_without_shortcut = 0usize;- let mut unreadable = Vec::new();- for item in &set.items {- let shown = if item.area.is_empty() { item.name.clone() } else { format!("{} › {}", item.area, item.name) };- let all_keys = item.entries.iter().map(|e| format!("{}: {}", e.context, e.keys)).collect::<Vec<_>>().join(", ");- let Some(id) = ix.find(&item.area, &item.name) else {- if item.entries.is_empty() {- unmatched_without_shortcut += 1;- } else {- let tool = norm(&item.area) == "tools"- && designcraft_tools::TOOL_GROUPS.iter().flat_map(|g| g.iter()).any(|t| norm(t.label) == norm(&item.name));- let mut row = json!({"item": shown, "keys": all_keys});- if tool {- row["reason"] = json!("tool keys are fixed");- }- unmatched.push(row);- }- continue;- };- let in_context = |ctx: &'static str| item.entries.iter().filter(move |e| e.context.eq_ignore_ascii_case(ctx)).collect::<Vec<&Entry>>();- let text_command = id.starts_with("type.") || id.starts_with("text.");- let mut considered = in_context("Default");- if considered.is_empty() && text_command {- considered = in_context("Text");- }- let mut read = None;- let mut why = "";- for e in &considered {- match read_keys(&e.keys, mac) {- Ok(sc) => {- read = Some(sc);- break;- }- Err(w) => why = w,- }- }- if read.is_none() && !considered.is_empty() {- unreadable.push(json!({"item": shown, "keys": all_keys, "reason": why}));- }- let pos = match decisions.iter().position(|d| d.id == id) {- Some(p) => p,- None => {- decisions.push(Decision { id: id.clone(), item: shown.clone(), shortcut: None, all_none: true });- decisions.len() - 1- }- };- let Some(d) = decisions.get_mut(pos) else { continue };- d.all_none &= item.entries.is_empty();- if d.shortcut.is_none()- && let Some(sc) = read- {- d.shortcut = Some(sc);- d.item = shown;- }- }-- let before: HashMap<String, Option<String>> = menus::effective_shortcuts(app).into_iter().map(|(id, sc)| (id, Some(sc))).collect();- let mut imported = 0usize;- let mut taken: Vec<((bool, bool, bool, bool, egui::Key), String)> = Vec::new();- let mut skipped = Vec::new();- let mut decided: BTreeSet<String> = BTreeSet::new();- // When two items in the set want the same keys, the later one takes them (the rule shared by- // the Craft apps' importers).- let mut winner: HashMap<(bool, bool, bool, bool, egui::Key), usize> = HashMap::new();- for (i, d) in decisions.iter().enumerate() {- if let Some(keys) = d.shortcut.as_deref().and_then(keys_of) {- winner.insert(keys, i);- }- }- for (i, d) in decisions.iter().enumerate() {- match &d.shortcut {- Some(sc) => {- let Some(keys) = keys_of(sc) else { continue };- if let Some(w) = winner.get(&keys).filter(|&&w| w != i).and_then(|&w| decisions.get(w)) {- skipped.push(json!({"id": d.id, "item": d.item, "shortcut": sc, "takenBy": w.id}));- continue;- }- taken.push((keys, d.id.clone()));- if menus::default_shortcut(&d.id).and_then(keys_of) == Some(keys) {- store(app, &d.id, None);- } else {- store(app, &d.id, Some(sc.as_str()));- }- }- None if d.all_none => {- if menus::default_shortcut(&d.id).is_none() {- store(app, &d.id, None);- } else {- store(app, &d.id, Some(""));- }- }- None => continue,- }- imported += 1;- decided.insert(d.id.clone());- }- let mut conflicts = Vec::new();- for (id, sc) in menus::effective_shortcuts(app) {- if decided.contains(&id) {- continue;- }- // A command sharing its default keys with the one taking them (file.new and the New- // Document dialog) keeps them: the dispatcher already prefers the other.- let twin = |by: &str| {- let default = |id: &str| menus::default_shortcut(id).and_then(keys_of);- default(&id).is_some() && default(&id) == default(by)- };- if let Some(keys) = keys_of(&sc)- && taken.iter().any(|(k, by)| *k == keys && !twin(by))- {- store(app, &id, Some(""));- conflicts.push(json!({"id": id, "label": command_label(&id), "shortcut": sc}));- }- }- let changed: Vec<Value> = decisions- .iter()- .filter(|d| decided.contains(&d.id))- .filter_map(|d| {- let from = before.get(&d.id).cloned().flatten();- let to = menus::shortcut_of(app, &d.id);- (from != to).then(|| json!({"id": d.id, "label": command_label(&d.id), "item": d.item, "from": from, "to": to}))- })- .collect();- Ok(json!({- "set": set.name,- "imported": imported,- "changed": changed,- "conflictsCleared": conflicts,- "skipped": skipped,- "unmatched": unmatched,- "unmatchedWithoutShortcut": unmatched_without_shortcut,- "unreadable": unreadable,- }))+/// The report as `window.importShortcuts` returns it. Commands are command keys (`file.save`,+/// `window.panel {"panel":"layers"}`) under `id`.+fn report_json(r: &ImportReport) -> Value {+ json!({+ "set": r.set,+ "imported": r.imported,+ "changed": Value::Array(r.changed.iter().map(|c| json!({+ "id": c.command.key(), "label": c.label, "item": c.item, "line": c.line, "from": c.from, "to": c.to,+ })).collect()),+ "conflictsCleared": Value::Array(r.conflicts_cleared.iter().map(|c| json!({+ "id": c.command.key(), "label": c.label, "shortcut": c.shortcut,+ })).collect()),+ "skipped": Value::Array(r.skipped.iter().map(|s| json!({+ "id": s.command.key(), "item": s.item, "line": s.line, "shortcut": s.shortcut,+ "takenBy": s.kept_by.as_ref().map(|c| c.key()), "reason": name_of(&s.reason),+ })).collect()),+ "failed": Value::Array(r.failed.iter().map(|f| json!({+ "id": f.command.key(), "label": f.label, "change": name_of(&f.change), "shortcuts": f.shortcuts,+ })).collect()),+ "unmatched": Value::Array(r.unmatched.iter().map(|u| json!({+ "item": u.item, "line": u.line, "keys": u.keys, "reason": name_of(&u.reason),+ })).collect()),+ "unmatchedWithoutShortcut": r.unmatched_without_shortcut,+ "unreadable": Value::Array(r.unreadable.iter().map(|u| json!({+ "item": u.item, "line": u.line, "keys": u.keys, "reason": u.reason.to_string(),+ })).collect()),+ "approximated": Value::Array(r.approximated.iter().map(|a| json!({+ "item": a.item, "line": a.line, "keys": a.keys, "note": name_of(&a.note),+ })).collect()),+ "suggestions": Value::Array(r.suggestions.iter().map(|s| json!({+ "item": s.item, "line": s.line, "candidates": s.candidates.iter().map(|c| c.key()).collect::<Vec<_>>(),+ })).collect()),+ "truncated": r.truncated,+ })}/// One line for the Keyboard Shortcuts dialog about an import's report.pub fn summary(lang: &str, report: &Value) -> String {let n = |k: &str| report[k].as_u64().unwrap_or_default().to_string();let len = |k: &str| report[k].as_array().map_or(0, Vec::len).to_string();+ // Rows for keys in contexts DesignCraft lacks belong to items that did match.+ let unmatched = report["unmatched"].as_array().map_or(0, |rows| rows.iter().filter(|r| r["reason"] != "context").count());crate::i18n::tr(lang, "Imported {count} shortcuts from “{set}”; {unmatched} items not matched, {unreadable} unreadable.").replace("{count}", &n("imported")).replace("{set}", report["set"].as_str().unwrap_or_default())- .replace("{unmatched}", &len("unmatched"))+ .replace("{unmatched}", &unmatched.to_string()).replace("{unreadable}", &len("unreadable"))}@@ -553,6 +286,7 @@ pub fn import_delivered(app: &mut DesignApp, bytes: &[u8]) {#[cfg(test)]mod tests {use super::*;+ use crate::menus;fn app() -> DesignApp {DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())@@ -571,10 +305,14 @@ mod tests {\tFrobnicate Everything --- Default: Ctrl+F12\r\n\\tNever Heard Of It --- [none defined]\r\n\Product area : File Menu\r\n\- \tClose --- Default: Shift+Ctrl+Num 5, Default: Ctrl+F4\r\n\+ \tClose --- Default: Shift+Ctrl+Num 5, Default: Ctrl+F4, Tables: Ctrl+3\r\n\\tSave --- Default: Ctrl+Hyperspace\r\n\\tRevert --- Default: Shift+Ctrl+F9\r\n\\tSave As... --- Default: Shift+Ctrl+F9\r\n\+ Product area : Window Menu\r\n\+ \tColor: Swatches --- Default: Shift+Ctrl+F2\r\n\+ Product area : Tools\r\n\+ \tPen Tool --- Default: Shift+Ctrl+F3\r\n\garbage line without a separator\r\n";let r = menus::run_ui(&mut app, "window.importShortcuts", &json!({"text": set})).unwrap().unwrap();assert_eq!(r["set"], "My Set");@@ -587,14 +325,27 @@ mod tests {assert_eq!(menus::shortcut_of(&app, "app.palette"), None);assert!(r["conflictsCleared"].as_array().unwrap().iter().any(|c| c["id"] == "app.palette"), "{r}");// Unknown items with shortcuts and unreadable keys are reported; Save keeps its shortcut.- assert_eq!(r["unmatched"], json!([{"item": "Edit Menu › Frobnicate Everything", "keys": "Default: Ctrl+F12"}]));+ assert_eq!(+ r["unmatched"],+ json!([+ {"item": "Edit > Frobnicate Everything", "line": 7, "keys": "Default: Ctrl+F12", "reason": "noMatch"},+ {"item": "File > Close", "line": 10, "keys": "Tables: Ctrl+3", "reason": "context"},+ ])+ );+ // Keys in a context DesignCraft lacks don't make their matched item count as unmatched.+ assert!(summary("en", &r).contains("; 1 items not matched"), "{}", summary("en", &r));assert_eq!(r["unmatchedWithoutShortcut"], 1);- assert_eq!(r["unreadable"][0]["item"], "File Menu › Save");+ assert_eq!(r["unreadable"][0]["item"], "File > Save");assert_eq!(menus::shortcut_of(&app, "app.save").as_deref(), Some("Cmd+S"));// Two items want the same keys: the later one takes them.assert_eq!(menus::shortcut_of(&app, "app.saveDialog").as_deref(), Some("Cmd+Shift+F9"));assert_eq!(r["skipped"][0]["takenBy"], "app.saveDialog", "{r}");- assert_eq!(r["imported"], 4);+ // A Window menu panel item and a Tools item apply to the panel and the tool.+ assert_eq!(crate::keys::shortcut(&app.keymap, &crate::keys::panel("swatches")).as_deref(), Some("Cmd+Shift+F2"));+ assert_eq!(crate::keys::shortcut(&app.keymap, &crate::keys::tool("pen")).as_deref(), Some("Cmd+Shift+F3"));+ // The numeric keypad key is bound as the main key of the same name, and reported.+ assert_eq!(r["approximated"][0]["item"], "File > Close", "{r}");+ assert_eq!(r["imported"], 6, "{r}");// Reset Shortcuts is the way back.menus::run_ui(&mut app, "window.resetShortcuts", &json!({})).unwrap().unwrap();assert_eq!(menus::shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+Enter"));diff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex c38b86d59..daeb1eadd 100644--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@ -416,7 +416,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level- Spring-loaded Zoom: hold Cmd+Space (Ctrl+Space on Windows/Linux) for the Zoom cursor and click/scrubby zoom; Alt-click zooms out. Release returns to the previous tool without changing the document or undo history. Text-frame and text-field typing suppress the shortcut; Space remains Hand.- Guides belong to the active layer: hidden with it (or with its Show Guides off) and locked with it.- Pencil tool (N): freehand strokes, shown as you draw in the layer's colour, simplified to smooth paths (Alt closes); Smooth and Erase tools re-fit or remove the stretch you drag along (`path.smooth`, `path.erase`).-- Edit › Keyboard Shortcuts: every command, panel and tool, click and press the new keys (they move from the commands that held them, which the dialog lists), per-command and global reset; `window.setShortcut` (panels as `window.panel` with `{panel}`, tools by id). Panels open with InDesign's keys where DesignCraft leaves them free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tools sharing a key take turns (B: Content Collector, Content Placer). Shortcuts run on the shared craft-keymap crate. Import InDesign Set… reads a set saved by InDesign's Show Set (.txt) and reports what it changed and what it could not match; `window.importShortcuts`.+- Edit › Keyboard Shortcuts: every command, panel and tool, click and press the new keys (they move from the commands that held them, which the dialog lists), per-command and global reset; `window.setShortcut` (panels as `window.panel` with `{panel}`, tools by id). Panels open with InDesign's keys where DesignCraft leaves them free (Swatches F5, Color F6, Layers F7, Info F8, Stroke F10, Paragraph Styles F11, Character Styles Shift+F11, Pages F12, Align Shift+F7); tools sharing a key take turns (B: Content Collector, Content Placer). Shortcuts run on the shared craft-keymap crate. Import InDesign Set… reads a set saved by InDesign's Show Set (.txt), including its Window menu panel items and Tools items, and reports what it changed and what it could not match, with likely commands for unmatched items; `window.importShortcuts`.- Primary Text Frame (New Document) and Smart Text Reflow: pages are added while the primary story oversets and empty ones at the end removed, in the same undo step (Preferences › Type).- Glyphs panel: every character of any font (rendered by our renderer), search by character or U+code, click to insert, recently used.- UI scaling (Preferences › Interface, 50–200%; `window.uiScale`); the window title steps aside when the bar is crowded.