From 37949e4a76d202ceaaf9f23773d3a6cd4fa8e29c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 00:14:32 -0800 Subject: [PATCH 01/29] Command Palette: results for different commands that share a name show distinct names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Results whose names would match take the panel, menu or command they belong to as their path (Brushes and Symbols for Select All Unused, View › Rulers and View › Perspective Grid for Show Rulers, Layers and Navigator for Panel Options…, Tools for a tool that shares a command's name). Results that still match show their id after the name, as two filter plug-ins with one name now do. Names are made distinct in English and in the UI language, and a query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as the UI command that runs the engine command, and Place… and Print…, which were listed twice under one id, are listed once. The Catalan rows for Saved View 10 to 18 and Saved Selection 2 to 25 carry their own numbers instead of another saved view's or selection's. --- crates/ui-egui/src/i18n/ca.tsv | 66 ++--- crates/ui-egui/src/i18n/tests.rs | 20 ++ crates/ui-egui/src/palette.rs | 397 +++++++++++++++++++++++--- crates/ui-egui/src/shortcut_editor.rs | 2 +- docs/target-app-parity.md | 1 + 5 files changed, 408 insertions(+), 78 deletions(-) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a6d12d4f80..193ca8a7d1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3919,42 +3919,42 @@ digits Malayalam Malaiàlam Saved Desat Saved recovery data for {title} S’han desat les dades de recuperació de {title} Saved Selection 1 Selecció desada 1 - Saved Selection 10 Selecció desada 2 - Saved Selection 11 Selecció desada 3 - Saved Selection 12 Selecció desada 4 - Saved Selection 13 Selecció desada 5 - Saved Selection 14 Selecció desada 6 - Saved Selection 15 Selecció desada 7 - Saved Selection 16 Selecció desada 8 - Saved Selection 17 Selecció desada 9 - Saved Selection 18 Selecció desada 10 - Saved Selection 19 Selecció desada 11 - Saved Selection 2 Selecció desada 12 - Saved Selection 20 Selecció desada 13 - Saved Selection 21 Selecció desada 14 - Saved Selection 22 Selecció desada 15 - Saved Selection 23 Selecció desada 16 - Saved Selection 24 Selecció desada 17 - Saved Selection 25 Selecció desada 18 - Saved Selection 3 Selecció desada 19 - Saved Selection 4 Selecció desada 20 - Saved Selection 5 Selecció desada 21 - Saved Selection 6 Selecció desada 22 - Saved Selection 7 Selecció desada 23 - Saved Selection 8 Selecció desada 24 - Saved Selection 9 Selecció desada 25 + Saved Selection 10 Selecció desada 10 + Saved Selection 11 Selecció desada 11 + Saved Selection 12 Selecció desada 12 + Saved Selection 13 Selecció desada 13 + Saved Selection 14 Selecció desada 14 + Saved Selection 15 Selecció desada 15 + Saved Selection 16 Selecció desada 16 + Saved Selection 17 Selecció desada 17 + Saved Selection 18 Selecció desada 18 + Saved Selection 19 Selecció desada 19 + Saved Selection 2 Selecció desada 2 + Saved Selection 20 Selecció desada 20 + Saved Selection 21 Selecció desada 21 + Saved Selection 22 Selecció desada 22 + Saved Selection 23 Selecció desada 23 + Saved Selection 24 Selecció desada 24 + Saved Selection 25 Selecció desada 25 + Saved Selection 3 Selecció desada 3 + Saved Selection 4 Selecció desada 4 + Saved Selection 5 Selecció desada 5 + Saved Selection 6 Selecció desada 6 + Saved Selection 7 Selecció desada 7 + Saved Selection 8 Selecció desada 8 + Saved Selection 9 Selecció desada 9 Saved Selections Seleccions desades Saved to User Defined: {} Desat a Definit per l’usuari: {} Saved View 1 Vista desada 1 - Saved View 10 Vista desada 2 - Saved View 11 Vista desada 3 - Saved View 12 Vista desada 4 - Saved View 13 Vista desada 5 - Saved View 14 Vista desada 6 - Saved View 15 Vista desada 7 - Saved View 16 Vista desada 8 - Saved View 17 Vista desada 9 - Saved View 18 Vista desada 10 + Saved View 10 Vista desada 10 + Saved View 11 Vista desada 11 + Saved View 12 Vista desada 12 + Saved View 13 Vista desada 13 + Saved View 14 Vista desada 14 + Saved View 15 Vista desada 15 + Saved View 16 Vista desada 16 + Saved View 17 Vista desada 17 + Saved View 18 Vista desada 18 Saved View 19 Vista desada 19 Saved View 2 Vista desada 2 Saved View 20 Vista desada 20 diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 44db5d3dfd..45ab8fb25b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -434,6 +434,26 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// Each catalog's Saved View N and Saved Selection N rows carry the number N, so no two saved views +/// or saved selections show one name. +#[test] +fn numbered_saved_views_and_selections_keep_their_number() { + let mut bad = vec![]; + for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) { + for kind in ["Saved View", "Saved Selection"] { + for n in 1..=25 { + let source = format!("{kind} {n}"); + let Some(row) = lang.catalog().plain(&source) else { continue }; + let numbers: Vec<&str> = row.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).collect(); + if !numbers.is_empty() && numbers != [n.to_string().as_str()] { + bad.push(format!("{}: {source} -> {row}", lang.code)); + } + } + } + } + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// The Objects on Path Options section's Detach button, its undo step and the message for a /// Detach with no object chosen. #[test] diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 3e7fb53316..0bb8f6f955 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -10,7 +10,9 @@ use crate::{VectorcraftApp, menus}; /// Engine commands the palette leaves out, each with the UI command of the same name that runs it /// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete /// Selection asks before deleting a layer that holds art, and the other UI commands open the -/// command's dialog or file chooser. Scripts and the control channel still run the engine ids. +/// command's dialog or file chooser (the four Other Library… commands ask for the library file). +/// Batch… and Flattener Preview open the dialog or panel that runs the engine command. Scripts and +/// the control channel still run the engine ids. const WRAPPED: &[(&str, &str)] = &[ ("layer.delete", "ui.layerDelete"), ("brush.new", "ui.newBrush"), @@ -18,34 +20,185 @@ const WRAPPED: &[(&str, &str)] = &[ ("symbol.options", "ui.symbolOptions"), ("svgFilter.import", "ui.importSvgFilter"), ("text.convertListToText", "type.convertListToText"), + ("action.batch", "ui.batchDialog"), + ("flattener.preview", "ui.flattenerPreview"), + ("swatch.library.load", "window.swatchLibrary.other"), + ("graphicStyle.loadLibrary", "window.graphicStyleLibrary.other"), + ("symbol.loadLibrary", "window.symbolLibrary.other"), + ("brush.loadLibrary", "window.brushLibrary.other"), ]; -/// Everything the palette searches: (label, command id or `tool:`, shortcut). -pub fn items() -> Vec<(String, String, String)> { - let mut items = vec![]; - // Aliases kept for older scripts run a command that is listed already, and a wrapped engine - // command is listed as its UI command. +/// The menu path ([`context`]) a result takes when another result has its name: (id, English +/// path), for commands that no item of the menu bar runs and whose id names no parent command. +const CONTEXTS: &[(&str, &str)] = &[ + ("addon.pen.close", "Pen"), + ("addon.pen.reshape", "Pen"), + ("addon.pen.togglePoint", "Pen"), + ("brush.library", "Brushes"), + ("brush.unused", "Brushes"), + ("charStyle.setAttrs", "Character Styles"), + ("file.exportInBackground", "Export"), + ("file.openInBackground", "Open"), + ("graphicStyle.library", "Graphic Styles"), + ("help.links", "Help"), + ("imageTrace.hideRuns", "Image Trace"), + ("links.reveal", "Links"), + ("livePaint.fill", "Live Paint"), + ("object.blend.spine.convertAnchor", "Blend"), + ("paraStyle.setAttrs", "Paragraph Styles"), + ("path.close", "Path"), + ("path.convertAnchor", "Path"), + ("path.knife", "Path"), + ("path.reshapeSegment", "Path"), + ("plugin.hideRuns", "Plug-ins"), + ("swatch.library.get", "Swatches"), + ("symbol.library", "Symbols"), + ("symbol.unused", "Symbols"), + ("text.editRange", "Text"), + ("ui.layersPanelOptions", "Layers"), + ("ui.navigatorPanelOptions", "Navigator"), +]; + +/// A palette result before its name is made distinct ([`distinct_names`]). +struct Draft { + /// The English menu path, `›`-separated; each segment translates. + path: String, + /// The English label. + label: String, + /// Does the label translate? An installed filter plug-in's name does not. + translates: bool, + id: String, + shortcut: String, + /// Has [`distinct_names`] given the result its [`context`]? + in_context: bool, + /// Does the result show its id after its name? + keyed: bool, +} + +impl Draft { + fn new(path: &str, label: &str, id: String, shortcut: &str) -> Draft { + Draft { + path: path.to_string(), + label: label.to_string(), + translates: true, + id, + shortcut: shortcut.to_string(), + in_context: false, + keyed: false, + } + } + + /// The name in `lang`: the path's segments and the label translate on their own, and the id + /// follows in parentheses when the result shows it. + fn name(&self, lang: crate::i18n::Lang) -> String { + let label = if self.translates { crate::i18n::tr(lang, &self.label) } else { self.label.as_str() }; + let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) }; + if self.keyed { format!("{name} ({})", self.id) } else { name } + } +} + +/// The palette's results before their names are made distinct: every listed engine command and +/// plug-in command, UI command and tool. +fn drafts() -> Vec { + let mut out = vec![]; + // Aliases kept for older scripts run a command that is listed already, a wrapped engine + // command is listed as its UI command, and an engine command with a UI command of the same id + // (Place…, Print…) is listed once, as the UI command. let plugin_commands = vectorcraft_engine::cmd::plugin::command_specs(); - let listed = |id: &str| !vectorcraft_engine::cmd::is_alias(id) && !WRAPPED.iter().any(|(engine, _)| *engine == id); - let labeled = |menu: &[&str], label: &str| { - let path = menu.join(" › "); - if path.is_empty() { label.to_string() } else { format!("{path} › {label}") } - }; + let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); + let listed = |id: &str| !vectorcraft_engine::cmd::is_alias(id) && !WRAPPED.iter().any(|(engine, _)| *engine == id) && !ui_ids.contains(id); for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c.id)).chain(plugin_commands) { - items.push((labeled(c.menu, c.label), c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("").to_string())); + out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or(""))); } // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of // the Scripts folder runs from File › Scripts, by its path. A UI command that wraps an engine - // command takes that command's menu path, so a search for the path still finds it. + // command, or has an engine command's id, takes that command's menu path, so a search for the + // path still finds it. for c in menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND) { - let engine = WRAPPED.iter().find(|(_, ui)| *ui == c.0).and_then(|(engine, _)| vectorcraft_engine::find_command(engine)); - let label = engine.map_or_else(|| c.1.to_string(), |e| labeled(e.menu, c.1)); - items.push((label, c.0.to_string(), menus::shortcut_of(c.0).unwrap_or("").to_string())); + let engine = WRAPPED.iter().find(|(_, ui)| *ui == c.0).map_or(c.0, |(engine, _)| *engine); + let engine = vectorcraft_engine::find_command(engine); + let path = engine.map(|e| e.menu.join(" › ")).unwrap_or_default(); + out.push(Draft::new(&path, c.1, c.0.to_string(), menus::shortcut_of(c.0).unwrap_or(""))); } for tool in vectorcraft_tools::catalog::all_tools() { - items.push((tool.label.to_string(), format!("tool:{}", tool.id), crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or("").to_string())); + out.push(Draft::new("", tool.label, format!("tool:{}", tool.id), crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or(""))); + } + out +} + +/// Everything the palette searches: (label, command id or `tool:`, shortcut). Labels are the +/// English names before [`build`] makes them distinct. +pub fn items() -> Vec<(String, String, String)> { + drafts().into_iter().map(|d| (d.name(crate::i18n::Lang::EN), d.id, d.shortcut)).collect() +} + +/// The menu path a result shows when its name is another result's: its [`CONTEXTS`] path, Tools +/// for a tool, the menu path of the item of the menu bar that runs it (the four Other Library… +/// commands go under Window › Swatch Libraries, Brush Libraries, Graphic Style Libraries and Symbol +/// Libraries), or the label of the command whose id is its id without the last part (Reset Panel +/// goes under Character Style Options and Paragraph Style Options). +fn context(id: &str) -> Option { + if let Some((_, path)) = CONTEXTS.iter().find(|(c, _)| *c == id) { + return Some(path.to_string()); + } + if id.starts_with("tool:") { + return Some("Tools".to_string()); + } + if id.starts_with("plugin:") { + return None; + } + if let Some(path) = crate::shortcut_editor::menu_bar_path(id) { + return Some(path.to_string()); + } + let (parent, _) = id.rsplit_once('.')?; + let label = + vectorcraft_engine::find_command(parent).map(|c| c.label).or_else(|| menus::UI_COMMANDS.iter().find(|c| c.0 == parent).map(|c| c.1))?; + Some(label.trim_end_matches('…').to_string()) +} + +/// Gives results for different ids different names in each of `langs`. Results that share a name +/// in one of them take their [`context`], when they have one, as their menu path; results that +/// still share one show their id after it. An installed plug-in whose name is another +/// result's name with its id ("Blur (plugin:a)") shows its id too. +fn distinct_names(drafts: &mut [Draft], langs: &[crate::i18n::Lang]) { + // The results whose name, in one of `langs`, a result with another id has. + let shared = |drafts: &[Draft]| -> Vec { + let mut out = std::collections::BTreeSet::new(); + for &lang in langs { + let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); + for (i, d) in drafts.iter().enumerate() { + by_name.entry(d.name(lang)).or_default().push(i); + } + let differ = |list: &Vec| { + let ids: Vec<&str> = list.iter().filter_map(|&i| drafts.get(i)).map(|d| d.id.as_str()).collect(); + ids.iter().any(|id| Some(id) != ids.first()) + }; + out.extend(by_name.into_values().filter(differ).flatten()); + } + out.into_iter().collect() + }; + for i in shared(drafts) { + if let Some(d) = drafts.get_mut(i).filter(|d| !d.in_context) + && let Some(path) = context(&d.id) + { + d.path = path; + d.in_context = true; + } + } + // A pass gives every result of a shared name its id, so a name is shared again only by a result + // whose label ends with another result's id; one pass per result is enough. + for _ in 0..drafts.len() { + let mut changed = false; + for i in shared(drafts) { + if let Some(d) = drafts.get_mut(i).filter(|d| !d.keyed) { + d.keyed = true; + changed = true; + } + } + if !changed { + break; + } } - items } /// A palette label in `lang`: each `›`-separated menu segment and the command label translate on @@ -60,9 +213,9 @@ pub(crate) struct Entry { shortcut: String, /// The label in the UI language. shown: String, - /// The English label (what agents document), the shown label and the id (and the id of the - /// engine command a UI command wraps), lowercased, one per line: a query word (which has no - /// line break) matches within one of them. + /// The English label before and after [`distinct_names`] (what agents document), the shown + /// label and the id (and the id of the engine command a UI command wraps), lowercased, one per + /// line: a query word (which has no line break) matches within one of them. haystack: String, } @@ -89,31 +242,31 @@ fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc> { } /// The palette's entries in `lang`: [`items`], then one per filter plug-in's Object › Plug-ins -/// item (`plugin:`), whose name is not translated. +/// item (`plugin:`), whose name is not translated, each with a name no result for another id +/// shows, in English and in `lang` ([`distinct_names`]). A query still matches the name before +/// it was made distinct. fn build(lang: crate::i18n::Lang) -> Vec { - let entry = |label: String, shown: String, id: String, shortcut: String| { - let mut haystack = format!("{}\n{}\n{}", label.to_lowercase(), shown.to_lowercase(), id.to_lowercase()); - // A UI command that wraps an engine command is also found by the engine command's id. - if let Some((engine, _)) = WRAPPED.iter().find(|(_, ui)| *ui == id) { - haystack.push('\n'); - haystack.push_str(&engine.to_lowercase()); - } - Entry { id, shortcut, shown, haystack } - }; - let mut out: Vec = items() - .into_iter() - .map(|(label, id, shortcut)| { - let shown = shown_label(lang, &label); - entry(label, shown, id, shortcut) - }) - .collect(); - out.extend(crate::shortcut_editor::filter_items().iter().map(|f| { - let shortcut = crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("").to_string(); - let label = format!("{} › {}", f.group, f.label); - let shown = format!("{} › {}", shown_label(lang, &f.group), f.label); - entry(label, shown, format!("plugin:{}", f.id), shortcut) + let mut drafts = drafts(); + drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft { + translates: false, + ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id), crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) })); - out + let plain: Vec = drafts.iter().map(|d| d.name(crate::i18n::Lang::EN)).collect(); + distinct_names(&mut drafts, &[crate::i18n::Lang::EN, lang]); + drafts + .into_iter() + .zip(plain) + .map(|(d, plain)| { + let (label, shown) = (d.name(crate::i18n::Lang::EN), d.name(lang)); + let mut haystack = [plain, label, shown.clone(), d.id.clone()].map(|s| s.to_lowercase()).join("\n"); + // A UI command that wraps an engine command is also found by the engine command's id. + if let Some((engine, _)) = WRAPPED.iter().find(|(_, ui)| *ui == d.id) { + haystack.push('\n'); + haystack.push_str(&engine.to_lowercase()); + } + Entry { id: d.id, shortcut: d.shortcut, shown, haystack } + }) + .collect() } /// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry @@ -534,6 +687,133 @@ mod tests { assert_eq!(frame(&mut app, vec![]), 0); } + /// Each command, tool and plug-in is one result: Place… and Print…, which are engine commands + /// and UI commands of one id, are listed once, under their engine menu path. + #[test] + fn each_id_is_one_result() { + let entries = build(Lang::EN); + let mut seen = std::collections::HashSet::new(); + let twice: Vec<&str> = entries.iter().filter(|e| !seen.insert(e.id.as_str())).map(|e| e.id.as_str()).collect(); + assert!(twice.is_empty(), "{twice:?}"); + let shown = |id: &str| entries.iter().find(|e| e.id == id).map(|e| e.shown.as_str()); + assert_eq!((shown("file.place"), shown("file.print")), (Some("File › Place…"), Some("Print…"))); + } + + /// No two results for different commands, tools or plug-ins show the same name, in English or + /// in any language with a complete menu catalog. + #[test] + fn different_results_show_different_names() { + let langs = std::iter::once(Lang::EN).chain(Lang::all().filter(|l| l.complete_menus())); + let mut shared = vec![]; + for lang in langs { + let mut by_name: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for e in build(lang) { + let ids = by_name.entry(e.shown).or_default(); + if !ids.contains(&e.id) { + ids.push(e.id); + } + } + shared.extend(by_name.into_iter().filter(|(_, ids)| ids.len() > 1).map(|(name, ids)| format!("{}: {name}: {ids:?}", lang.code()))); + } + assert!(shared.is_empty(), "{} shared names:\n{}", shared.len(), shared.join("\n")); + } + + /// Results that would share a name show the panel, menu or command they belong to, or their id + /// when nothing else tells them apart. A query still finds them + /// by the plain name, the new path in English or in the UI language, and the id. + #[test] + fn results_that_share_a_name_show_where_they_belong() { + let entries = build(Lang::EN); + let shown = |id: &str| entries.iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap_or_else(|| panic!("{id} is a result")); + for (id, want) in [ + ("brush.unused", "Brushes › Select All Unused"), + ("symbol.unused", "Symbols › Select All Unused"), + ("ui.layersPanelOptions", "Layers › Panel Options…"), + ("ui.navigatorPanelOptions", "Navigator › Panel Options…"), + ("ui.charStyleOptions.resetPanel", "Character Style Options › Reset Panel"), + ("ui.paraStyleOptions.resetPanel", "Paragraph Style Options › Reset Panel"), + ("window.swatchLibrary.other", "Window › Swatch Libraries › Other Library…"), + ("window.brushLibrary.other", "Window › Brush Libraries › Other Library…"), + ("tool:knife", "Tools › Knife"), + ("path.knife", "Path › Knife"), + ("addon.pen.close", "Pen › Close Path"), + ("path.close", "Path › Close Path"), + ("type.fitHeadline", "Type › Fit Headline (type.fitHeadline)"), + ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), + ("shape.ellipse", "Ellipse (shape.ellipse)"), + ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), + ("help.links", "Help › Links"), + ("perspective.editText", "Object › Perspective › Edit Text"), + ("ui.batchDialog", "Batch…"), + ("ui.flattenerPreview", "Flattener Preview"), + ] { + assert_eq!(shown(id), want, "{id}"); + } + assert!(shown("perspective.grid.rulers").contains("Perspective Grid"), "{}", shown("perspective.grid.rulers")); + assert_ne!(shown("perspective.grid.rulers"), shown("view.rulers")); + assert!(entries.iter().all(|e| e.id != "action.batch" && e.id != "flattener.preview"), "the engine commands are listed as their UI commands"); + // A name nobody else has stays as it was. + assert_eq!(shown("object.group"), "Object › Group"); + let found = |entries: &[Entry], query: &str| -> Vec { + entries.iter().filter(|e| query.split_whitespace().all(|w| e.haystack.contains(&w.to_lowercase()))).map(|e| e.id.clone()).collect() + }; + for query in ["select all unused", "brushes select all unused", "brush.unused"] { + assert!(found(&entries, query).contains(&"brush.unused".to_string()), "{query}"); + } + assert!(!found(&entries, "symbols select all unused").contains(&"brush.unused".to_string())); + let zh = Lang::from_code("zh-hant").unwrap(); + let zh_entries = build(zh); + let brushes = crate::i18n::tr(zh, "Brushes"); + let unused = zh_entries.iter().find(|e| e.id == "brush.unused").unwrap(); + assert_eq!(unused.shown, format!("{brushes} › {}", crate::i18n::tr(zh, "Select All Unused"))); + assert!(found(&zh_entries, &format!("{brushes} select all unused")).contains(&"brush.unused".to_string())); + } + + /// Every menu path a result can take when it shares a name has a row in each catalog with + /// complete menus. + #[test] + fn the_paths_of_results_that_share_a_name_translate() { + let mut paths: Vec = CONTEXTS.iter().map(|(_, path)| path.to_string()).collect(); + paths.push("Tools".into()); + let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); + for d in drafts() { + by_name.entry(d.name(Lang::EN)).or_default().push(d.id); + } + paths.extend(by_name.into_values().filter(|ids| ids.len() > 1).flatten().filter_map(|id| context(&id))); + let mut missing = vec![]; + for lang in Lang::all().filter(|l| l.complete_menus()) { + for segment in paths.iter().flat_map(|p| p.split(" › ")) { + let row = format!("{}: {segment}", lang.code()); + if !crate::i18n::has(lang, segment) && !missing.contains(&row) { + missing.push(row); + } + } + } + assert!(missing.is_empty(), "{}", missing.join("\n")); + } + + /// A pick of each of two results that shared a name runs its own command: Show Rulers under View + /// › Rulers toggles the document rulers, and the one under the perspective grid toggles the + /// grid's rulers. + #[test] + fn a_pick_of_a_renamed_result_runs_its_own_command() { + let entries = build(Lang::EN); + let picks: Vec<(String, String)> = + entries.iter().filter(|e| e.haystack.lines().next() == Some("show rulers")).map(|e| (e.id.clone(), e.shown.clone())).collect(); + assert_eq!(picks.len(), 2, "{picks:?}"); + assert!(picks.iter().all(|(_, name)| name != "Show Rulers") && picks[0].1 != picks[1].1, "{picks:?}"); + for (id, name) in &picks { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let label = |app: &VectorcraftApp, id: &str| crate::menus::dynamic_label(app, id, ""); + let before: Vec = picks.iter().map(|(other, _)| label(&app, other)).collect(); + run_pick(&mut app, id); + for ((other, _), before) in picks.iter().zip(before) { + assert_eq!(label(&app, other) != before, other == id, "{name}: {other}"); + } + } + } + /// Each filter plug-in has one result, also when two share a name: its menu path translates, /// the plug-in's name does not, and a pick runs that filter (a dialog for one with parameters, /// nothing with no document open). @@ -568,4 +848,33 @@ mod tests { vectorcraft_plugins::registry::remove(one); vectorcraft_plugins::registry::remove(two); } + + /// Two filter plug-ins with one name show their ids after it, the name untranslated, and each + /// pick runs its own filter. + #[test] + fn filter_plugins_with_one_name_show_their_ids() { + use vectorcraft_plugins::wat as tpl; + let (one, two) = ("test.UI.palette_same-one", "test.UI.palette_same-two"); + for id in [one, two] { + let manifest = format!(r#"{{"id":"{id}","name":"Same Name","version":"1","kind":"filter","params":{{"wiggle":{{"type":"bool"}}}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + } + let zh = Lang::from_code("zh-hant").unwrap(); + let built = build(zh); + let path = format!("{} › {}", crate::i18n::tr(zh, "Object"), crate::i18n::tr(zh, "Plug-ins")); + for id in [one, two] { + let key = format!("plugin:{id}"); + let shown: Vec<&str> = built.iter().filter(|e| e.id == key).map(|e| e.shown.as_str()).collect(); + assert_eq!(shown, [format!("{path} › Same Name… ({key})")], "{id}"); + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + for id in [one, two] { + run_pick(&mut app, &format!("plugin:{id}")); + let d = app.ui.dialog.take().expect("the filter's dialog opens"); + assert_eq!(d.str("__plugin"), id.to_string()); + } + vectorcraft_plugins::registry::remove(one); + vectorcraft_plugins::registry::remove(two); + } } diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 88a97206c7..60b382714c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -753,7 +753,7 @@ fn menu_bar_paths() -> &'static HashMap<&'static str, Vec<(String, Value)>> { /// The menu path of the item of the menu bar that runs command `id` as a key press runs it /// ([`a_menu_bar_item_runs`]): the first item that runs it with no params, or else the first item, /// whose params all its items give. -fn menu_bar_path(id: &str) -> Option<&'static str> { +pub(crate) fn menu_bar_path(id: &str) -> Option<&'static str> { let (_, params) = command_doc(id)?; let items = menu_bar_paths().get(id).filter(|_| a_menu_bar_item_runs(id, params))?; chosen_path(items) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4b3c1ec869..310dbb0d62 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1252,6 +1252,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The panel menu's Save Selection submenu has Save Selection…, Update Selection and Edit Selection…, enabled and run as in the Select menu, and lists the document's saved selections: choosing one selects its objects again (`select.recall`). Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`). The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`). + No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Brushes › Select All Unused and Symbols › Select All Unused, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 44f75df965ca5b57561175c7de6390e795042b5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:22:38 -0800 Subject: [PATCH 02/29] Command Palette: lists commands that run from a pick, plus panels and effects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value (`needs_a_value`): a query with no default key and no menu bar item, whose answer a pick drops (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (`transparency.set`, Document Setup's units). Of those commands, the ones whose pick does something without params stay listed: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the three Asset Export commands that open the Asset Export panel, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. That leaves out 296 of the 1,006 engine commands it listed. The UI commands it listed stay as they were. Each panel is a result under Window › Show Panel: a pick shows the panel and leaves one already showing as it is. Each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel among the 14 results. The search hint and the app bar's search tooltip say "Search commands, tools, panels and effects", in every catalog. --- crates/ui-egui/src/chrome.rs | 4 +- crates/ui-egui/src/i18n/bg.tsv | 4 +- crates/ui-egui/src/i18n/bs.tsv | 4 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/gu.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/palette.rs | 384 +++++++++++++++++++++-- crates/ui-egui/src/panels/learn/tests.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 16 +- crates/ui-egui/src/tests/save.rs | 6 +- crates/ui-egui/src/titlebar.rs | 2 +- docs/target-app-parity.md | 3 +- 35 files changed, 432 insertions(+), 97 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index a6b7b11714..b31228b682 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -133,8 +133,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { - Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::shown_shortcut(sc)), - None => tl!("Search commands and tools").to_string(), + Some(sc) => format!("{} ({})", tl!("Search commands, tools, panels and effects"), menus::shown_shortcut(sc)), + None => tl!("Search commands, tools, panels and effects").to_string(), }; if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() { app.ui.palette_open = !app.ui.palette_open; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 7812216da8..bf6da4e273 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3144,8 +3144,8 @@ digits Malayalam Малаялам Scripts Скриптове Search Търсене Search All Търсене във всички - Search commands and tools Търсене на команди и инструменти - Search commands and tools… Търсене на команди и инструменти… + Search commands, tools, panels and effects Търсене на команди, инструменти, панели и ефекти + Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… Search Commands… Търсене на команди… Secondary Вторичен Section Symbol Символ за раздел diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2fb70385ff..5759e754c8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1283,7 +1283,7 @@ lighting Light Svjetlo Name* @ 66.67% (RGB/Preview) Naziv* @ 66,67% (RGB/pregled) No Document Nema dokumenta Press Pritisnite - Search commands and tools Pretraži naredbe i alate + Search commands, tools, panels and effects Pretraži naredbe, alate, panele i efekte Style: Stil: Switch workspace Promijeni radni prostor Show all open documents Prikaži sve otvorene dokumente @@ -4333,7 +4333,7 @@ font-technology Variable Varijabilni Saved {path} Sačuvano: {path} Saving Čuvanje Saving {} Čuvanje {} - Search commands and tools… Pretraži naredbe i alate… + Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… Dashed Line Isprekidana linija Panel menu Meni panela Unembed… Poništi ugrađivanje… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 193ca8a7d1..8a0a0537e5 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4053,8 +4053,8 @@ digits Malayalam Malaiàlam Scrub Numeric Fields by Dragging Canvia els camps numèrics arrossegant Search Cerca Search All Cerca a tot - Search commands and tools Cerca ordres i eines - Search commands and tools… Cerca ordres i eines… + Search commands, tools, panels and effects Cerca ordres, eines, panells i efectes + Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… Search Commands… Cerca ordres… Search Fonts Folder Cerca a la carpeta de tipus de lletra Searching… Cercant… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 75f527f782..16219dd4ae 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1307,7 +1307,7 @@ lighting Light Světlo Name* @ 66.67% (RGB/Preview) Název* @ 66,67 % (RGB/náhled) No Document Žádný dokument Press Klávesou - Search commands and tools Hledat příkazy a nástroje + Search commands, tools, panels and effects Hledat příkazy, nástroje, panely a efekty Style: Styl: Switch workspace Přepnout pracovní prostor Show all open documents Zobrazit všechny otevřené dokumenty @@ -4431,7 +4431,7 @@ font-technology Variable Variabilní Saved {path} Uloženo: {path} Saving Ukládání Saving {} Ukládání {} - Search commands and tools… Hledat příkazy a nástroje… + Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… Dashed Line Čárkovaná čára Panel menu Nabídka panelu Unembed… Zrušit vložení… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e13c1f9ae7..b585dafc5b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1828,7 +1828,7 @@ lighting Light Lys Name* @ 66.67% (RGB/Preview) Navn* @ 66.67% (RGB/forhåndsvisning) No Document Intet dokument Press Tryk på - Search commands and tools Søg i kommandoer og værktøjer + Search commands, tools, panels and effects Søg i kommandoer, værktøjer, paneler og effekter Style: Typografi: Switch workspace Skift arbejdsområde Show all open documents Vis alle åbne dokumenter @@ -4749,7 +4749,7 @@ font-technology Variable Variable Saved {path} Gemte {path} Saving Gemmer Saving {} Gemmer {} - Search commands and tools… Søg i kommandoer og værktøjer… + Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… Dashed Line Stiplet linje Panel menu Panelmenu Unembed… Ophæv integrering… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 68da6f84ba..4c854815c5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3203,8 +3203,8 @@ digits Malayalam Malayalam Filter Layers Panel Rows Zeilen im Ebenenbedienfeld filtern @msg `Custom` stands for changed settings: save the preset under another name `Custom` steht für geänderte Einstellungen: Speichern Sie die Vorgabe unter einem anderen Namen @msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1} - Search commands and tools Befehle und Werkzeuge suchen - Search commands and tools… Befehle und Werkzeuge suchen… + Search commands, tools, panels and effects Befehle, Werkzeuge, Bedienfelder und Effekte suchen + Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… Search Commands… Befehle suchen… Secondary Sekundär Section Symbol Paragrafenzeichen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 551130c700..84724a9030 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3827,8 +3827,8 @@ digits Malayalam Μαλαγιάλαμ Scribble… Μουτζούρωμα… Script / Brush Σενάριο / Πινέλο Search All Αναζήτηση όλων - Search commands and tools Αναζήτηση εντολών και εργαλείων - Search commands and tools… Αναζήτηση εντολών και εργαλείων… + Search commands, tools, panels and effects Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ + Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον Section Symbol Σύμβολο ενότητας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ddbbfce02e..50f8986525 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3235,8 +3235,8 @@ digits Malayalam Malayálam Filter Layers Panel Rows Filtrar filas del panel Capas @msg `Custom` stands for changed settings: save the preset under another name `Custom` representa ajustes modificados: guarda el preajuste con otro nombre @msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1} - Search commands and tools Buscar comandos y herramientas - Search commands and tools… Buscar comandos y herramientas… + Search commands, tools, panels and effects Buscar comandos, herramientas, paneles y efectos + Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… Search Commands… Buscar comandos… Secondary Secundario Section Symbol Símbolo de sección diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 5915b6a69e..76fcb80388 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1285,7 +1285,7 @@ lighting Light Valo Name* @ 66.67% (RGB/Preview) Nimi* @ 66.67% (RGB/esikatselu) No Document Ei asiakirjaa Press Paina - Search commands and tools Hae komentoja ja työkaluja + Search commands, tools, panels and effects Hae komentoja, työkaluja, paneeleita ja tehosteita Style: Tyyli: Switch workspace Vaihda työtilaa Show all open documents Näytä kaikki avoimet asiakirjat @@ -4350,7 +4350,7 @@ font-technology Variable Muuttuvat Saved {path} Tallennettu {path} Saving Tallennetaan Saving {} Tallennetaan {} - Search commands and tools… Hae komentoja ja työkaluja… + Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… Dashed Line Katkoviiva Panel menu Paneelivalikko Unembed… Poista upotus… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 5778a21665..b32d1971d0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3227,8 +3227,8 @@ digits Malayalam Malayalam Filter Layers Panel Rows Filtrer les lignes du panneau Calques @msg `Custom` stands for changed settings: save the preset under another name `Custom` désigne des réglages modifiés : enregistrez le paramètre prédéfini sous un autre nom @msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1} - Search commands and tools Chercher commandes et outils - Search commands and tools… Chercher commandes et outils… + Search commands, tools, panels and effects Chercher commandes, outils, panneaux et effets + Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… Search Commands… Rechercher des commandes… Secondary Secondaire Section Symbol Symbole de section diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 31548e1933..4ba32d4079 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3330,8 +3330,8 @@ Search Commands… આદેશો શોધો… Search Fonts Folder ફોન્ટ ફોલ્ડર શોધો Search Preferences પસંદગીઓ શોધો - Search commands and tools આદેશો અને ટૂલ્સ શોધો - Search commands and tools… આદેશો અને ટૂલ્સ શોધો… + Search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો + Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… Secondary ગૌણ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index bcaa573d47..e7795f6357 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4409,8 +4409,8 @@ antiAlias Sharp शार्प Search खोजें Search All सभी खोजें Search artboards खोज आर्टबोर्ड - Search commands and tools खोज आदेश और टूल - Search commands and tools… आदेश और टूल खोजें… + Search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें + Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… Search Commands… कमांड खोजें… Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर Search images इमेज खोजना diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8a2e0b3b9a..a66040d716 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3847,8 +3847,8 @@ mark-style Japanese Japán Filter Layers Panel Rows Rétegek panel sorainak szűrése @msg `Custom` stands for changed settings: save the preset under another name a `Custom` a módosított beállításokat jelöli: mentsd az előbeállítást más néven @msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1} - Search commands and tools Parancsok és eszközök keresése - Search commands and tools… Parancsok és eszközök keresése… + Search commands, tools, panels and effects Parancsok, eszközök, panelek és effektusok keresése + Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… Search Commands… Parancsok keresése… Search Fonts Folder Keresés betűtípusmappában Searching… Keresés… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 712148180d..b645dee4f4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1218,7 +1218,7 @@ lighting Light Cahaya Name* @ 66.67% (RGB/Preview) Nama* @ 66.67% (RGB/Pratinjau) No Document Tidak ada dokumen Press Tekan - Search commands and tools Cari perintah dan alat + Search commands, tools, panels and effects Cari perintah, alat, panel, dan efek Style: Gaya: Switch workspace Ganti ruang kerja Show all open documents Tampilkan semua dokumen terbuka @@ -4097,7 +4097,7 @@ font-technology Variable Variabel Saved {path} Berhasil menyimpan {path} Saving Menyimpan Saving {} Menyimpan {} - Search commands and tools… Cari perintah dan alat… + Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… Dashed Line Garis putus-putus Panel menu Menu panel Unembed… Lepaskan sematan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1d2e05bfb0..a1868a196a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3280,8 +3280,8 @@ digits Malayalam Malayalam Filter Layers Panel Rows Filtra righe del pannello Livelli @msg `Custom` stands for changed settings: save the preset under another name `Custom` indica impostazioni modificate: salva il preset con un altro nome @msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1} - Search commands and tools Cerca comandi e strumenti - Search commands and tools… Cerca comandi e strumenti… + Search commands, tools, panels and effects Cerca comandi, strumenti, pannelli ed effetti + Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… Search Commands… Cerca comandi… Secondary Secondario Section Symbol Simbolo di sezione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cdf8b04d3c..85236cf789 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3158,8 +3158,8 @@ mark-style Japanese 日本式 Filter Layers Panel Rows レイヤーパネルの行をフィルター @msg `Custom` stands for changed settings: save the preset under another name `Custom` は変更した設定を表します: プリセットを別の名前で保存してください @msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください - Search commands and tools コマンドとツールを検索 - Search commands and tools… コマンドとツールを検索… + Search commands, tools, panels and effects コマンド、ツール、パネル、効果を検索 + Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… Secondary セカンダリ Select All Art on Layer レイヤー上のすべてのアートを選択 Select All Assets すべてのアセットを選択 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a7b771b8b5..c7c8545e6a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1175,7 +1175,7 @@ lighting Light სინათლე Name* @ 66.67% (RGB/Preview) სახელი* @ 66.67% (RGB/წინასწარი ნახვა) No Document დოკუმენტი არ არის Press დააჭირეთ - Search commands and tools ბრძანებებისა და ხელსაწყოების ძიება + Search commands, tools, panels and effects ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება Style: სტილი: Switch workspace სამუშაო სივრცის გადართვა Show all open documents ყველა ღია დოკუმენტის ჩვენება @@ -3957,7 +3957,7 @@ font-technology Variable ცვლადი Saved {path} შენახულია: {path} Saving შენახვა Saving {} ინახება: {} - Search commands and tools… ბრძანებებისა და ხელსაწყოების ძიება… + Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… Dashed Line ტირეებიანი ხაზი Panel menu პანელის მენიუ Unembed… ჩაშენების მოხსნა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 2751e06e14..a988b15a49 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3147,8 +3147,8 @@ mark-style Japanese 일본식 Filter Layers Panel Rows 레이어 패널 행 필터링 @msg `Custom` stands for changed settings: save the preset under another name `Custom`은 변경된 설정을 나타냅니다. 프리셋을 다른 이름으로 저장하세요 @msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1} - Search commands and tools 명령 및 도구 검색 - Search commands and tools… 명령 및 도구 검색… + Search commands, tools, panels and effects 명령, 도구, 패널 및 효과 검색 + Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… Secondary 보조 Select All Art on Layer 레이어의 모든 아트웍 선택 Select All Assets 모든 에셋 선택 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 51f87bb262..fe1110957f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1736,7 +1736,7 @@ lighting Light Licht Name* @ 66.67% (RGB/Preview) Naam* @ 66.67% (RGB/Voorbeeld) No Document Geen document Press Druk op - Search commands and tools Opdrachten en gereedschappen zoeken + Search commands, tools, panels and effects Opdrachten, gereedschappen, panelen en effecten zoeken Style: Stijl: Switch workspace Werkruimte wisselen Show all open documents Alle geopende documenten tonen @@ -4657,7 +4657,7 @@ font-technology Variable Variabel Saved {path} {path} opgeslagen Saving Bezig met opslaan Saving {} {} wordt opgeslagen - Search commands and tools… Opdrachten en gereedschappen zoeken… + Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… Dashed Line Streepjeslijn Panel menu Paneelmenu Unembed… Insluiten ongedaan maken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 93969d2bc3..ca1959dcd0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1237,7 +1237,7 @@ lighting Light Światło Name* @ 66.67% (RGB/Preview) Nazwa* @ 66,67% (RGB/Podgląd) No Document Brak dokumentu Press Naciśnij - Search commands and tools Szukaj poleceń i narzędzi + Search commands, tools, panels and effects Szukaj poleceń, narzędzi, paneli i efektów Style: Styl: Switch workspace Przełącz obszar roboczy Show all open documents Pokaż wszystkie otwarte dokumenty @@ -4272,7 +4272,7 @@ font-technology Variable Zmienne Saved {path} Zapisano {path} Saving Zapisywanie Saving {} Zapisywanie {} - Search commands and tools… Szukaj poleceń i narzędzi… + Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… Dashed Line Linia przerywana Panel menu Menu panelu Unembed… Wyodrębnij… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index ad9df40e5a..65257dd8f7 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2697,8 +2697,8 @@ digits Malayalam Malaiala @msg `Custom` stands for changed settings: save the preset under another name `Custom` representa configurações alteradas: salve a predefinição com outro nome @msg `{key}` must be an array of these names: {_1} `{key}` deve ser uma matriz destes nomes: {_1} Search Commands… Pesquisar Comandos… - Search commands and tools Pesquisar comandos e ferramentas - Search commands and tools… Pesquisar comandos e ferramentas… + Search commands, tools, panels and effects Pesquisar comandos, ferramentas, painéis e efeitos + Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… Secondary Secundária Section Symbol Símbolo de Seção Select Selecionar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 073b662e3f..523b90ce41 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3267,8 +3267,8 @@ digits Malayalam Малаялам Filter Layers Panel Rows Фильтровать строки панели «Слои» @msg `Custom` stands for changed settings: save the preset under another name `Custom` обозначает изменённые параметры: сохраните набор под другим именем @msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1} - Search commands and tools Поиск команд и инструментов - Search commands and tools… Поиск команд и инструментов… + Search commands, tools, panels and effects Поиск команд, инструментов, панелей и эффектов + Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… Search Commands… Поиск команд… Secondary Вторичный Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c2a7e589f2..df06cdaded 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3159,8 +3159,8 @@ digits Malayalam Malayalam Scripts Skript Search Sök Search All Sök i alla - Search commands and tools Sök kommandon och verktyg - Search commands and tools… Sök kommandon och verktyg… + Search commands, tools, panels and effects Sök kommandon, verktyg, paneler och effekter + Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… Search Commands… Sök kommandon… Secondary Sekundär Section Symbol Paragraftecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4ee1ba27c9..ffabf3cbe8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3036,8 +3036,8 @@ digits Malayalam Malayalam Redefine {name} “{name}” Stilini Yeniden Tanımla @msg `Custom` stands for changed settings: save the preset under another name `Custom` değiştirilmiş ayarları ifade eder: ön ayarı başka bir adla kaydedin @msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1} - Search commands and tools Komutları ve araçları arayın - Search commands and tools… Komutları ve araçları arayın… + Search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri arayın + Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… Search Commands… Arama Komutları… Secondary İkincil Section Symbol Bölüm Sembolü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 95a5066abb..4353c39f14 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3272,8 +3272,8 @@ digits Malayalam Малаялам Filter Layers Panel Rows Фільтрувати рядки панелі «Шари» @msg `Custom` stands for changed settings: save the preset under another name `Custom` позначає змінені параметри: збережіть набір під іншим ім’ям @msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1} - Search commands and tools Пошук команд та інструментів - Search commands and tools… Пошук команд та інструментів… + Search commands, tools, panels and effects Пошук команд, інструментів, панелей та ефектів + Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… Search Commands… Пошук команд… Secondary Вторинний Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 21d20f0157..3fe9e73c10 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3604,8 +3604,8 @@ mark-style Japanese Kiểu Nhật Filter Layers Panel Rows Lọc hàng bảng Lớp @msg `Custom` stands for changed settings: save the preset under another name `Custom` biểu thị các cài đặt đã thay đổi: hãy lưu thiết lập sẵn với tên khác @msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1} - Search commands and tools Tìm kiếm lệnh và công cụ - Search commands and tools… Tìm kiếm lệnh và công cụ… + Search commands, tools, panels and effects Tìm kiếm lệnh, công cụ, bảng và hiệu ứng + Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… Search Commands… Tìm kiếm lệnh… Search Fonts Folder Tìm kiếm thư mục phông chữ Searching… Đang tìm kiếm… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5c0570781d..1b7440e3f1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3099,8 +3099,8 @@ digits Malayalam 马拉雅拉姆数字 Locked 已锁定 Hidden 已隐藏 Filter Layers Panel Rows 筛选图层面板行 - Search commands and tools 搜索命令和工具 - Search commands and tools… 搜索命令和工具… + Search commands, tools, panels and effects 搜索命令、工具、面板和效果 + Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… Search Commands… 搜索命令… Secondary 次要 Section Symbol 章节符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5de2e008bd..9e0659105b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4355,8 +4355,8 @@ digits Malayalam 馬來亞拉姆數字 Locked 已鎖定 Hidden 已隱藏 Filter Layers Panel Rows 篩選圖層面板列 - Search commands and tools 搜尋指令與工具 - Search commands and tools… 搜尋指令與工具… + Search commands, tools, panels and effects 搜尋指令、工具、面板與效果 + Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… Search Commands… 搜尋指令… Secondary 次要 Section Symbol 章節符號 diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 0bb8f6f955..7c684a8026 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1,4 +1,5 @@ -//! The command palette: fuzzy search over every command and tool. +//! The command palette: fuzzy search over the commands a pick runs, the tools, the panels and the +//! Effect menu's items. use std::sync::Arc; @@ -28,19 +29,54 @@ const WRAPPED: &[(&str, &str)] = &[ ("brush.loadLibrary", "window.brushLibrary.other"), ]; +/// Engine commands that [`crate::shortcut_editor::needs_a_value`] marks and that a pick, which +/// gives no params, still runs: Stop Script stops the running script, Clear Script Console empties +/// the Script Console, Clear Plug-in Cache deletes every plug-in's cache, Reset Preferences resets +/// every preference, Forget Import Matches forgets every saved match, Begin Undo Group and End +/// Undo Group begin and end a group, the six Save … Preset commands save a new preset (Save +/// Gradient Preset the selection's gradient), Delete Gradient Preset deletes the saved preset the +/// selection's gradient matches, Pixel Snapping Options… +/// opens its dialog, the three Asset Export commands open the Asset Export panel (#4864), New +/// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default +/// gradient, Define Perspective Grid makes the document's grid, and Select Slice deselects the +/// slices. +const PICK_RUNS: &[&str] = &[ + "script.stop", + "script.console.clear", + "plugin.clearCache", + "prefs.reset", + "importMatches.reset", + "edit.undoGroup.begin", + "edit.undoGroup.end", + "imageTrace.presets.save", + "flattener.presets.save", + "pdf.preset.save", + "print.presets.save", + "perspective.presets.save", + "gradient.presets.save", + "gradient.presets.delete", + "view.snapToPixel.options", + "assets.export", + "assets.export3D", + "assets.settings.set", + "symbol.new", + "paint.setGradientGeom", + "perspective.grid.set", + "object.slice.select", +]; + +/// The menu path of a panel's result: a pick runs Show Panel (`window.panel`) for the panel. +const PANEL_PATH: &str = "Window › Show Panel"; + /// The menu path ([`context`]) a result takes when another result has its name: (id, English /// path), for commands that no item of the menu bar runs and whose id names no parent command. const CONTEXTS: &[(&str, &str)] = &[ ("addon.pen.close", "Pen"), ("addon.pen.reshape", "Pen"), ("addon.pen.togglePoint", "Pen"), - ("brush.library", "Brushes"), - ("brush.unused", "Brushes"), ("charStyle.setAttrs", "Character Styles"), ("file.exportInBackground", "Export"), ("file.openInBackground", "Open"), - ("graphicStyle.library", "Graphic Styles"), - ("help.links", "Help"), ("imageTrace.hideRuns", "Image Trace"), ("links.reveal", "Links"), ("livePaint.fill", "Live Paint"), @@ -51,9 +87,6 @@ const CONTEXTS: &[(&str, &str)] = &[ ("path.knife", "Path"), ("path.reshapeSegment", "Path"), ("plugin.hideRuns", "Plug-ins"), - ("swatch.library.get", "Swatches"), - ("symbol.library", "Symbols"), - ("symbol.unused", "Symbols"), ("text.editRange", "Text"), ("ui.layersPanelOptions", "Layers"), ("ui.navigatorPanelOptions", "Navigator"), @@ -91,23 +124,35 @@ impl Draft { /// The name in `lang`: the path's segments and the label translate on their own, and the id /// follows in parentheses when the result shows it. fn name(&self, lang: crate::i18n::Lang) -> String { - let label = if self.translates { crate::i18n::tr(lang, &self.label) } else { self.label.as_str() }; + // A built-in effect's label translates by its effect id first, as the Effect menu's does. + let label = match self.id.strip_prefix("effect:") { + _ if !self.translates => self.label.as_str(), + Some(effect) => crate::i18n::tr_id(lang, effect, &self.label), + None => crate::i18n::tr(lang, &self.label), + }; let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) }; if self.keyed { format!("{name} ({})", self.id) } else { name } } } /// The palette's results before their names are made distinct: every listed engine command and -/// plug-in command, UI command and tool. +/// plug-in command, UI command, tool, panel and Effect menu item. fn drafts() -> Vec { let mut out = vec![]; // Aliases kept for older scripts run a command that is listed already, a wrapped engine // command is listed as its UI command, and an engine command with a UI command of the same id - // (Place…, Print…) is listed once, as the UI command. + // (Place…, Print…) is listed once, as the UI command. An engine command that needs a value a + // pick doesn't give, or a query whose answer a pick drops ([`crate::shortcut_editor::needs_a_value`]), + // is left out unless it does something besides answering ([`PICK_RUNS`]). let plugin_commands = vectorcraft_engine::cmd::plugin::command_specs(); let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); - let listed = |id: &str| !vectorcraft_engine::cmd::is_alias(id) && !WRAPPED.iter().any(|(engine, _)| *engine == id) && !ui_ids.contains(id); - for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c.id)).chain(plugin_commands) { + let listed = |c: &vectorcraft_engine::CommandSpec| { + !vectorcraft_engine::cmd::is_alias(c.id) + && !WRAPPED.iter().any(|(engine, _)| *engine == c.id) + && !ui_ids.contains(c.id) + && (!crate::shortcut_editor::needs_a_value(c.id) || PICK_RUNS.contains(&c.id)) + }; + for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)).chain(plugin_commands) { out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or(""))); } // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of @@ -123,6 +168,18 @@ fn drafts() -> Vec { for tool in vectorcraft_tools::catalog::all_tools() { out.push(Draft::new("", tool.label, format!("tool:{}", tool.id), crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or(""))); } + // A panel's result shows the panel, as `window.panel` does without `toggle`, under Window › + // Show Panel. + for (id, label) in crate::state::all_panels() { + out.push(Draft::new(PANEL_PATH, label, format!("panel:{id}"), crate::shortcut_editor::panel_shortcut(id).unwrap_or(""))); + } + // An Effect menu item runs what its item runs; a live-effect plug-in's name does not translate. + for e in crate::shortcut_editor::effect_items().iter() { + out.push(Draft { + translates: vectorcraft_plugins::effect::plugin_id(&e.effect).is_none(), + ..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect), crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) + }); + } out } @@ -144,7 +201,8 @@ fn context(id: &str) -> Option { if id.starts_with("tool:") { return Some("Tools".to_string()); } - if id.starts_with("plugin:") { + // A plug-in's, panel's or effect's result already shows its menu path. + if ["plugin:", "panel:", "effect:"].iter().any(|p| id.starts_with(p)) { return None; } if let Some(path) = crate::shortcut_editor::menu_bar_path(id) { @@ -273,13 +331,28 @@ fn build(lang: crate::i18n::Lang) -> Vec { /// stands for. A command whose menu bar item gives params runs what a click on that item runs /// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their /// dialogs. While that item is dimmed, no dialog opens and the status line says why the command -/// can't run. +/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu +/// item runs ([`crate::keymap::command_of`]). pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { if let Some(tool) = id.strip_prefix("tool:") { app.select_tool(tool); - } else if id.starts_with("plugin:") { + } else if let Some(panel) = id.strip_prefix("panel:") { + // A panel that can be seen stays as it is, where `window.panel` would put an open flyout or + // a floating panel away. + if let Err(e) = crate::panel_docking::reveal_panel(app, panel) { + app.status(e); + } + } else if id.starts_with("plugin:") || id.starts_with("effect:") { let command = crate::keymap::command_of(id); - menus::invoke(app, &command.id, command.params); + // While the Effect menu dims the item (nothing selected), no dialog opens and the status + // line says why. + if id.starts_with("effect:") && !menus::enabled(app, &command.id) { + if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) { + app.status(why); + } + } else { + menus::invoke(app, &command.id, command.params); + } } else { match crate::shortcut_editor::menu_target_now(app, id) { Some(Ok((id, p))) => menus::invoke(app, &id, p), @@ -289,6 +362,22 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } +/// The results the palette shows for the lowercased query `q`: the first 14 entries that hold every +/// word of it, the ones whose name without its menu path is the query (the Layers panel for +/// "layers") first, each group in catalog order. +fn matching<'a>(entries: &'a [Entry], q: &str) -> Vec<&'a Entry> { + let words: Vec<&str> = q.split_whitespace().collect(); + let whole = words.join(" "); + // The plain, English and shown names are the haystack's first three lines. + let named = |e: &Entry| e.haystack.lines().take(3).any(|l| l.rsplit(" › ").next().is_some_and(|n| n.trim_end_matches('…') == whole)); + let mut found: Vec<&Entry> = entries.iter().filter(|e| words.iter().all(|w| e.haystack.contains(w))).collect(); + if !whole.is_empty() { + found.sort_by_key(|e| !named(e)); + } + found.truncate(14); + found +} + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !app.ui.palette_open { return; @@ -297,7 +386,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let t = Tokens::get(ctx); let q = app.ui.palette_query.to_lowercase(); let entries = entries(ctx, crate::i18n::current()); - let matches: Vec<&Entry> = entries.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).take(14).collect(); + let matches = matching(&entries, &q); let mut run: Option = None; // The highlighted result (#1757): Up and Down move it (wrapping), the pointer over a result // takes it, and a new query starts again from the first. @@ -324,7 +413,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let r = ui.add( egui::TextEdit::singleline(&mut app.ui.palette_query) .align(egui::Align2::LEFT_CENTER) - .hint_text(tl!("Search commands and tools…")) + .hint_text(tl!("Search commands, tools, panels and effects…")) .desired_width(500.0), ); r.request_focus(); @@ -396,7 +485,7 @@ mod tests { let ctx = egui::Context::default(); let query = "use precise cursors"; let entries = entries(&ctx, Lang::EN); - let matches: Vec<&Entry> = entries.iter().filter(|e| query.split_whitespace().all(|word| e.haystack.contains(word))).take(14).collect(); + let matches = matching(&entries, query); assert!(matches.iter().any(|e| e.id == "view.preciseCursors"), "preference toggle appears for its name"); assert!(entries.iter().filter(|e| e.id == "view.capsLock").all(|e| e.shown != "Use Precise Cursors")); @@ -726,8 +815,10 @@ mod tests { let entries = build(Lang::EN); let shown = |id: &str| entries.iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap_or_else(|| panic!("{id} is a result")); for (id, want) in [ - ("brush.unused", "Brushes › Select All Unused"), - ("symbol.unused", "Symbols › Select All Unused"), + ("file.exportInBackground", "Export › Continue in Background"), + ("file.openInBackground", "Open › Continue in Background"), + ("imageTrace.hideRuns", "Image Trace › Continue in Background"), + ("plugin.hideRuns", "Plug-ins › Continue in Background"), ("ui.layersPanelOptions", "Layers › Panel Options…"), ("ui.navigatorPanelOptions", "Navigator › Panel Options…"), ("ui.charStyleOptions.resetPanel", "Character Style Options › Reset Panel"), @@ -742,8 +833,9 @@ mod tests { ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), ("shape.ellipse", "Ellipse (shape.ellipse)"), ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), - ("help.links", "Help › Links"), ("perspective.editText", "Object › Perspective › Edit Text"), + ("ui.action.play", "Play Action (ui.action.play)"), + ("ui.action.playAt", "Play Action (ui.action.playAt)"), ("ui.batchDialog", "Batch…"), ("ui.flattenerPreview", "Flattener Preview"), ] { @@ -757,24 +849,30 @@ mod tests { let found = |entries: &[Entry], query: &str| -> Vec { entries.iter().filter(|e| query.split_whitespace().all(|w| e.haystack.contains(&w.to_lowercase()))).map(|e| e.id.clone()).collect() }; - for query in ["select all unused", "brushes select all unused", "brush.unused"] { - assert!(found(&entries, query).contains(&"brush.unused".to_string()), "{query}"); + let id = "file.exportInBackground".to_string(); + for query in ["continue in background", "export continue in background", "file.exportinbackground"] { + assert!(found(&entries, query).contains(&id), "{query}"); } - assert!(!found(&entries, "symbols select all unused").contains(&"brush.unused".to_string())); + assert!(!found(&entries, "open continue in background").contains(&id)); let zh = Lang::from_code("zh-hant").unwrap(); let zh_entries = build(zh); - let brushes = crate::i18n::tr(zh, "Brushes"); - let unused = zh_entries.iter().find(|e| e.id == "brush.unused").unwrap(); - assert_eq!(unused.shown, format!("{brushes} › {}", crate::i18n::tr(zh, "Select All Unused"))); - assert!(found(&zh_entries, &format!("{brushes} select all unused")).contains(&"brush.unused".to_string())); + let export = crate::i18n::tr(zh, "Export"); + let background = zh_entries.iter().find(|e| e.id == id).unwrap(); + assert_eq!(background.shown, format!("{export} › {}", crate::i18n::tr(zh, "Continue in Background"))); + assert!(found(&zh_entries, &format!("{export} continue in background")).contains(&id)); } - /// Every menu path a result can take when it shares a name has a row in each catalog with - /// complete menus. + /// Every menu path a result can take when it shares a name, and Window › Show Panel, has a row + /// in each catalog with complete menus. Each command [`CONTEXTS`] names is a result. #[test] fn the_paths_of_results_that_share_a_name_translate() { + let ids: Vec = items().into_iter().map(|(_, id, _)| id).collect(); + for (id, _) in CONTEXTS { + assert!(ids.iter().any(|i| i == id), "{id} is a result"); + } let mut paths: Vec = CONTEXTS.iter().map(|(_, path)| path.to_string()).collect(); paths.push("Tools".into()); + paths.push(PANEL_PATH.into()); let mut by_name: std::collections::HashMap> = std::collections::HashMap::new(); for d in drafts() { by_name.entry(d.name(Lang::EN)).or_default().push(d.id); @@ -849,6 +947,228 @@ mod tests { vectorcraft_plugins::registry::remove(two); } + /// Of the engine commands the palette listed before, it leaves out only the ones + /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of + /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves + /// out (with no document, one object selected or several) changes neither the document, its + /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still + /// listed. + #[test] + fn the_palette_leaves_out_the_commands_a_pick_cannot_run() { + use vectorcraft_testkit::fixtures::Fixture; + let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect(); + // The rule before: every engine command but the aliases, the wrapped commands and the ids of + // UI commands. + let before: Vec<&vectorcraft_engine::CommandSpec> = vectorcraft_engine::command_specs() + .iter() + .filter(|c| !vectorcraft_engine::cmd::is_alias(c.id) && !WRAPPED.iter().any(|(e, _)| *e == c.id) && !ui_ids.contains(c.id)) + .collect(); + let listed: std::collections::HashSet = items().into_iter().map(|(_, id, _)| id).collect(); + let dropped: Vec<&vectorcraft_engine::CommandSpec> = before.iter().copied().filter(|c| !listed.contains(c.id)).collect(); + let ids: Vec<&str> = dropped.iter().map(|c| c.id).collect(); + for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set"] { + assert!(ids.contains(&id), "{id} is left out: {ids:?}"); + } + // What a pick can change: the document with its selection, history, revision and layer + // state, the Script Console, and the interface's state (an open dialog or panel, the + // selected tool), the status line aside. + let look = |app: &VectorcraftApp| { + let mut ui = serde_json::to_value(&app.ui).unwrap_or_default(); + if let Some(o) = ui.as_object_mut() { + o.remove("status"); + } + let doc = app.session.active().map(|st| { + (st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone()) + }); + (doc, app.session.script_console().lines().len(), ui) + }; + let acts = |id: &str| { + [vectorcraft_engine::Session::new(), Fixture::Single.session(), Fixture::Multi.session()].into_iter().any(|session| { + let mut app = VectorcraftApp::new(session, crate::Services::default()); + let before = look(&app); + run_pick(&mut app, id); + look(&app) != before + }) + }; + // `layer.setProps {}` records an undo step that changes nothing. + let changed: Vec<&str> = ids.iter().copied().filter(|id| *id != "layer.setProps" && acts(id)).collect(); + assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); + for c in &dropped { + assert!(c.shortcut.is_none() && crate::shortcut_editor::menu_bar_path(c.id).is_none(), "{}", c.id); + } + // The others are still listed, and each of PICK_RUNS, which needs_a_value marks. A pick of + // each one changes what `look` sees, except the commands that act on the session alone: + // [`a_pick_of_a_session_command_runs_it`] covers those, or they need a running script, an + // installed plug-in or saved import matches. + for c in &before { + let marked = crate::shortcut_editor::needs_a_value(c.id); + assert_eq!(listed.contains(c.id), !marked || PICK_RUNS.contains(&c.id), "{}", c.id); + assert!(marked || !PICK_RUNS.contains(&c.id), "{} needs no entry in PICK_RUNS", c.id); + } + let session_only = [ + "script.stop", + "script.console.clear", + "plugin.clearCache", + "prefs.reset", + "importMatches.reset", + "edit.undoGroup.begin", + "edit.undoGroup.end", + "imageTrace.presets.save", + "flattener.presets.save", + "pdf.preset.save", + "print.presets.save", + "perspective.presets.save", + "gradient.presets.save", + "gradient.presets.delete", + ]; + for id in PICK_RUNS.iter().filter(|id| !session_only.contains(id)) { + assert!(acts(id), "a pick of {id} does something"); + } + for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors", "path.close"]) { + assert!(listed.contains(*id), "{id} stays"); + } + } + + /// A pick of a query that changes the session runs it: Clear Script Console empties the Script + /// Console, Reset Preferences resets a changed preference, each Save … Preset command adds a + /// preset, Delete Gradient Preset deletes the one saved from the selection, and the edits between Begin Undo Group and End Undo Group are one undo step. + #[test] + fn a_pick_of_a_session_command_runs_it() { + let ids: Vec = items().into_iter().map(|(_, id, _)| id).collect(); + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let pick = |app: &mut VectorcraftApp, id: &str| { + assert!(ids.iter().any(|i| i == id), "{id} is a result"); + run_pick(app, id); + }; + app.session.script_frames = true; + app.run("script.run", json!({"source": "$.writeln('line')", "name": "c.js"})).unwrap(); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(&mut app); + } + assert!(!app.session.script_running() && !app.session.script_console().lines().is_empty()); + pick(&mut app, "script.console.clear"); + assert!(app.session.script_console().lines().is_empty(), "{}", app.ui.status); + + let default = app.session.prefs.use_precise_cursors; + app.session.prefs.use_precise_cursors = !default; + pick(&mut app, "prefs.reset"); + assert_eq!(app.session.prefs.use_precise_cursors, default, "{}", app.ui.status); + + for (save, list) in [ + ("imageTrace.presets.save", "imageTrace.presets"), + ("flattener.presets.save", "flattener.presets.list"), + ("pdf.preset.save", "pdf.preset.list"), + ("print.presets.save", "print.presets.list"), + ("perspective.presets.save", "perspective.presets.list"), + ] { + let count = |app: &mut VectorcraftApp| app.run(list, json!({})).unwrap()["presets"].as_array().map_or(0, Vec::len); + let before = count(&mut app); + pick(&mut app, save); + assert_eq!(count(&mut app), before + 1, "{save}: {}", app.ui.status); + } + // Save Gradient Preset saves the selection's gradient, and Delete Gradient Preset deletes + // the saved preset it matches. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); + pick(&mut app, "gradient.presets.save"); + assert_eq!(app.session.prefs.gradient_presets.len(), 1, "{}", app.ui.status); + pick(&mut app, "gradient.presets.delete"); + assert!(app.session.prefs.gradient_presets.is_empty(), "{}", app.ui.status); + + let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |st| st.history.undo.len()); + let before = undo(&app); + pick(&mut app, "edit.undoGroup.begin"); + for x in [10, 200] { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap(); + } + pick(&mut app, "edit.undoGroup.end"); + assert_eq!(undo(&app), before + 1, "{}", app.ui.status); + } + + /// The UI commands that open an engine command's dialog or ask first are still listed, and the + /// engine commands they wrap are not. + #[test] + fn the_wrapping_ui_commands_stay_listed() { + let ids: std::collections::HashSet = items().into_iter().map(|(_, id, _)| id).collect(); + for (engine, ui) in WRAPPED { + assert!(ids.contains(*ui) && !ids.contains(*engine), "{ui} listed, {engine} not"); + } + assert!(menus::UI_COMMANDS.iter().filter(|c| c.0 != "plugin.dialog" && c.0 != crate::scripts_menu::COMMAND).all(|c| ids.contains(c.0))); + } + + /// Each panel is a result under Window › Show Panel. A pick shows the panel, and a second pick + /// leaves it showing rather than hiding it as the Window menu item does. + #[test] + fn a_panel_is_a_result_whose_pick_shows_it() { + let entries = build(Lang::EN); + let panels: Vec<&Entry> = entries.iter().filter(|e| e.id.starts_with("panel:")).collect(); + assert_eq!(panels.len(), crate::state::all_panels().count()); + // More than 14 results hold "layers" in their menu path; the panel, named Layers, is shown + // first, and "color guide" shows the Color Guide panel first too. + for (query, want) in [("layers", "panel:layers"), ("color guide", "panel:colorGuide"), ("Layers ", "panel:layers")] { + let all = entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).count(); + let shown: Vec<&str> = matching(&entries, &query.to_lowercase()).into_iter().map(|e| e.id.as_str()).collect(); + assert_eq!(shown.first(), Some(&want), "{query}: {shown:?}"); + assert_eq!(shown.len(), all.min(14), "{query}"); + } + let layers = entries.iter().find(|e| e.id == "panel:layers").unwrap(); + assert_eq!(layers.shown, "Window › Show Panel › Layers"); + assert_eq!(layers.shortcut, crate::shortcut_editor::panel_shortcut("layers").unwrap_or("")); + let zh = Lang::from_code("zh-hant").unwrap(); + let shown = build(zh).into_iter().find(|e| e.id == "panel:layers").map(|e| e.shown).unwrap(); + assert_eq!(shown, ["Window", "Show Panel", "Layers"].map(|s| crate::i18n::tr(zh, s)).join(" › ")); + for id in ["swatches", crate::panels::asset_export::ID] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(!crate::panel_docking::showing(&app.ui, id), "{id}"); + run_pick(&mut app, &format!("panel:{id}")); + assert!(crate::panel_docking::showing(&app.ui, id), "{id}: {}", app.ui.status); + run_pick(&mut app, &format!("panel:{id}")); + assert!(crate::panel_docking::showing(&app.ui, id), "{id}: picked twice, still showing"); + } + } + + /// Each Effect menu item is a result under its menu path, with its shortcut. With a document + /// open and an object selected, a pick of Drop Shadow… opens its dialog, as the menu item + /// does, and changes nothing until the dialog is confirmed. + #[test] + fn an_effect_is_a_result_whose_pick_runs_its_menu_item() { + let entries = build(Lang::EN); + let effects = crate::shortcut_editor::effect_items(); + for e in effects.iter() { + let key = format!("effect:{}", e.effect); + assert_eq!(entries.iter().filter(|r| r.id == key).count(), 1, "{key}"); + } + let found: Vec<&Entry> = entries.iter().filter(|e| "drop shadow".split_whitespace().all(|w| e.haystack.contains(w))).collect(); + let shadow = + found.iter().find(|e| e.id.starts_with("effect:")).unwrap_or_else(|| panic!("{:?}", found.iter().map(|e| &e.id).collect::>())); + let item = effects.iter().find(|e| format!("effect:{}", e.effect) == shadow.id).unwrap(); + assert_eq!(shadow.shown, format!("{} › {}", item.group, item.label)); + let mut picked = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let mut clicked = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + let before = outcome(&picked); + run_pick(&mut picked, &shadow.id); + menus::invoke(&mut clicked, item.command, json!({ "effect": item.effect })); + let after = outcome(&picked); + assert!(after.0.is_some(), "the dialog opens: {}", after.2); + assert_eq!(after.1, before.1, "nothing changes yet"); + assert_eq!(after, outcome(&clicked), "the pick runs what the menu item runs"); + // With nothing selected the menu item is dimmed: no dialog opens, and the status line says + // why. + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.status.clear(); + run_pick(&mut app, &shadow.id); + assert!(app.ui.dialog.is_none() && !app.ui.status.is_empty(), "{}", app.ui.status); + // A built-in effect's name translates by its id, as the Effect menu shows it. + let fr = Lang::from_code("fr").unwrap(); + let add = build(fr).into_iter().find(|e| e.id == "effect:pathfinder.add").map(|e| e.shown).unwrap(); + assert!(add.ends_with(crate::i18n::tr_id(fr, "pathfinder.add", "Add")), "{add}"); + assert_eq!(crate::i18n::tr_id(fr, "pathfinder.add", "Add"), "Réunion"); + } + /// Two filter plug-ins with one name show their ids after it, the name untranslated, and each /// pick runs its own filter. #[test] diff --git a/crates/ui-egui/src/panels/learn/tests.rs b/crates/ui-egui/src/panels/learn/tests.rs index 319ca1decf..bc58612701 100644 --- a/crates/ui-egui/src/panels/learn/tests.rs +++ b/crates/ui-egui/src/panels/learn/tests.rs @@ -104,7 +104,7 @@ fn explore_tutorials_on_the_app_bar_shows_and_hides_the_learn_panel() { let ctx = context(); assert!(!shown(&app)); let nodes = frame(&mut app, &ctx, vec![], app_bar); - let search = center_where(&nodes, |label| label.starts_with("Search commands and tools")); + let search = center_where(&nodes, |label| label.starts_with("Search commands, tools, panels and effects")); let learn = center(&nodes, "Explore tutorials"); let (search, learn) = (search.expect("the search icon shows"), learn.expect("the app bar has Explore tutorials")); assert!(learn.x < search.x && (learn.y - search.y).abs() < 1.0, "beside the search icon: {learn:?}, {search:?}"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 60b382714c..55d71ca3c2 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -924,7 +924,7 @@ pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option Result<(String, Value), String> { +pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else { return Err(format!("command `{id}` is not available right now")); }; @@ -936,7 +936,7 @@ fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { /// run without them (as the Variables panel's commands do), and it is a query, whose answer a key /// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params /// doc names a field a call must give (File › Document Setup › Units, `{units}`)? -fn needs_a_value(key: &str) -> bool { +pub(crate) fn needs_a_value(key: &str) -> bool { static KEYS: OnceLock> = OnceLock::new(); KEYS.get_or_init(|| { vectorcraft_engine::command_specs() @@ -2839,4 +2839,16 @@ mod tests { assert_eq!(r["shortcut"], "Cmd+Alt+Shift+F11"); assert!(app.run("shortcuts.preset", json!({"name": null})).unwrap_err().starts_with("unknown preset")); } + + /// A command that needs a value is listed in the editor once the user gives it a key, but the + /// command search still leaves it out: a pick gives it no value. + #[test] + fn a_command_given_a_key_that_needs_a_value_is_no_pick() { + let mut overrides = Overrides::default(); + crate::keymap::set_override(&mut overrides, "document.setUnits", "Cmd+Alt+Shift+F12"); + let entry = entries().iter().find(|e| e.key == "document.setUnits").cloned().expect("the editor has a row for it"); + assert!(!listed(&Overrides::default(), &entry) && listed(&overrides, &entry)); + assert!(needs_a_value("document.setUnits")); + assert!(crate::palette::items().iter().all(|(_, id, _)| id != "document.setUnits")); + } } diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index b9b4111516..95756262b8 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -205,11 +205,13 @@ fn show_in_folder_needs_a_saved_document_and_a_file_manager() { assert_eq!(*shown.borrow(), ["/art/a.vectorcraft"]); } +/// The palette lists neither the old alias nor `file.documentColorMode`, which a pick can't run +/// without a mode; the CMYK and RGB menu items run the one command. #[test] -fn the_palette_lists_document_color_mode_once() { +fn document_color_mode_is_one_command() { let items = palette::items(); let ids: Vec<&str> = items.iter().map(|(_, id, _)| id.as_str()).filter(|id| id.to_ascii_lowercase().contains("documentcolormode")).collect(); - assert_eq!(ids, ["file.documentColorMode"]); + assert!(ids.is_empty(), "{ids:?}"); let mut app = app(); app.run("file.new", json!({})).unwrap(); let entries = menus::menu_entries(&app); diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index cbbd216e75..dd4ce4e38e 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -327,7 +327,7 @@ mod tests { let has = |s: &str| texts.iter().any(|t| t == s); assert_eq!(has("Discord"), width > 1000.0, "{width}: {texts:?}"); // Search is an icon only (as in PhotoCraft): its label lives in the tooltip. - assert!(!has("Search commands and tools"), "{width}: {texts:?}"); + assert!(!has("Search commands, tools, panels and effects"), "{width}: {texts:?}"); } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 310dbb0d62..64b651c4af 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1252,7 +1252,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The panel menu's Save Selection submenu has Save Selection…, Update Selection and Edit Selection…, enabled and run as in the Select menu, and lists the document's saved selections: choosing one selects its objects again (`select.recall`). Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`). The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`). - No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Brushes › Select All Unused and Symbols › Select All Unused, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). + No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). + The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel among the 14 results. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 4d882334242013023578f4da1fa6b7259cc7a7bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:20:53 -0800 Subject: [PATCH 03/29] Command Palette: compact rows in a shorter list that scrolls and says how many matched Each result is a 20-point row with no gap between rows, in place of a 24-point button with a 5-point gap. The list shows 12 rows at a time and scrolls; a window too short for 12 shows fewer, and the popup stays inside it. A name too long for its row ends with "...". With 12 rows the popup is 322 points tall, where 14 results took 458. The list holds up to 50 results, every one of them reachable, and the line under it says how many matched: "14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match". Up and Down still wrap; Page Up and Page Down move the highlight by the rows shown and stop at the ends. The highlighted row scrolls into view, and after a scroll with the wheel the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field: its description names the highlighted result and its place among every match ("2 of 120: ..."). The rows are list items, the highlighted one selected, and the count is a label. When the palette closes, the keyboard focus goes back to the widget that had it, unless a pick opened a dialog. The new strings have rows in every catalog. --- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/palette.rs | 640 ++++++++++++++++++++++++++-- docs/target-app-parity.md | 3 +- 30 files changed, 716 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bf6da4e273..acf12ee6a6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3146,6 +3146,10 @@ digits Malayalam Малаялам Search All Търсене във всички Search commands, tools, panels and effects Търсене на команди, инструменти, панели и ефекти Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… + No commands match Няма съвпадащи команди + {pos} of {total}: {name} {pos} от {total}: {name} +@plural {n} result|{n} results {n} резултат|{n} резултата +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните. Search Commands… Търсене на команди… Secondary Вторичен Section Symbol Символ за раздел diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5759e754c8..27c7c87a63 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4334,6 +4334,10 @@ font-technology Variable Varijabilni Saving Čuvanje Saving {} Čuvanje {} Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… + No commands match Nijedna naredba se ne podudara + {pos} of {total}: {name} {pos} od {total}: {name} +@plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite. Dashed Line Isprekidana linija Panel menu Meni panela Unembed… Poništi ugrađivanje… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8a0a0537e5..1a05ae0a1d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4055,6 +4055,10 @@ digits Malayalam Malaiàlam Search All Cerca a tot Search commands, tools, panels and effects Cerca ordres, eines, panells i efectes Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… + No commands match Cap ordre coincideix + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultats +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los. Search Commands… Cerca ordres… Search Fonts Folder Cerca a la carpeta de tipus de lletra Searching… Cercant… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 16219dd4ae..693b4373a2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4432,6 +4432,10 @@ font-technology Variable Variabilní Saving Ukládání Saving {} Ukládání {} Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… + No commands match Žádný příkaz neodpovídá + {pos} of {total}: {name} {pos} z {total}: {name} +@plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží. Dashed Line Čárkovaná čára Panel menu Nabídka panelu Unembed… Zrušit vložení… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b585dafc5b..5175934f3c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4750,6 +4750,10 @@ font-technology Variable Variable Saving Gemmer Saving {} Gemmer {} Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… + No commands match Ingen kommandoer passer + {pos} of {total}: {name} {pos} af {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultater +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem. Dashed Line Stiplet linje Panel menu Panelmenu Unembed… Ophæv integrering… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4c854815c5..54648dbc62 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3205,6 +3205,10 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1} Search commands, tools, panels and effects Befehle, Werkzeuge, Bedienfelder und Effekte suchen Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… + No commands match Keine passenden Befehle + {pos} of {total}: {name} {pos} von {total}: {name} +@plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen. Search Commands… Befehle suchen… Secondary Sekundär Section Symbol Paragrafenzeichen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 84724a9030..79f6c7957a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3829,6 +3829,10 @@ digits Malayalam Μαλαγιάλαμ Search All Αναζήτηση όλων Search commands, tools, panels and effects Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… + No commands match Καμία εντολή δεν ταιριάζει + {pos} of {total}: {name} {pos} από {total}: {name} +@plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε. Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον Section Symbol Σύμβολο ενότητας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 50f8986525..a5b95ed4ab 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3237,6 +3237,10 @@ digits Malayalam Malayálam @msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1} Search commands, tools, panels and effects Buscar comandos, herramientas, paneles y efectos Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… + No commands match Ningún comando coincide + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultado|{n} resultados +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos. Search Commands… Buscar comandos… Secondary Secundario Section Symbol Símbolo de sección diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 76fcb80388..31c447c9c4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4351,6 +4351,10 @@ font-technology Variable Muuttuvat Saving Tallennetaan Saving {} Tallennetaan {} Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… + No commands match Mikään komento ei vastaa hakua + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} tulos|{n} tulosta +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia. Dashed Line Katkoviiva Panel menu Paneelivalikko Unembed… Poista upotus… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b32d1971d0..47b80d39d1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3229,6 +3229,10 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1} Search commands, tools, panels and effects Chercher commandes, outils, panneaux et effets Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… + No commands match Aucune commande ne correspond + {pos} of {total}: {name} {pos} sur {total} : {name} +@plural {n} result|{n} results {n} résultat|{n} résultats +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner. Search Commands… Rechercher des commandes… Secondary Secondaire Section Symbol Symbole de section diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4ba32d4079..fa93fb5301 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3332,6 +3332,10 @@ Search Preferences પસંદગીઓ શોધો Search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… + No commands match કોઈ આદેશ મેળ ખાતો નથી + {pos} of {total}: {name} {total} માંથી {pos}: {name} +@plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો. Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… Secondary ગૌણ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e7795f6357..cc4634e21e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4411,6 +4411,10 @@ antiAlias Sharp शार्प Search artboards खोज आर्टबोर्ड Search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… + No commands match कोई आदेश मेल नहीं खाता + {pos} of {total}: {name} {total} में से {pos}: {name} +@plural {n} result|{n} results {n} परिणाम|{n} परिणाम +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें। Search Commands… कमांड खोजें… Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर Search images इमेज खोजना diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a66040d716..35b3d7db31 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3849,6 +3849,10 @@ mark-style Japanese Japán @msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1} Search commands, tools, panels and effects Parancsok, eszközök, panelek és effektusok keresése Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… + No commands match Nincs egyező parancs + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} találat +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez. Search Commands… Parancsok keresése… Search Fonts Folder Keresés betűtípusmappában Searching… Keresés… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index b645dee4f4..b973403431 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4098,6 +4098,10 @@ font-technology Variable Variabel Saving Menyimpan Saving {} Menyimpan {} Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… + No commands match Tidak ada perintah yang cocok + {pos} of {total}: {name} {pos} dari {total}: {name} +@plural {n} result|{n} results {n} hasil +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya. Dashed Line Garis putus-putus Panel menu Menu panel Unembed… Lepaskan sematan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a1868a196a..6054dee0e6 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3282,6 +3282,10 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1} Search commands, tools, panels and effects Cerca comandi, strumenti, pannelli ed effetti Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… + No commands match Nessun comando corrisponde + {pos} of {total}: {name} {pos} di {total}: {name} +@plural {n} result|{n} results {n} risultato|{n} risultati +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli. Search Commands… Cerca comandi… Secondary Secondario Section Symbol Simbolo di sezione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 85236cf789..20d397d9a4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3160,6 +3160,10 @@ mark-style Japanese 日本式 @msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください Search commands, tools, panels and effects コマンド、ツール、パネル、効果を検索 Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… + No commands match 一致するコマンドはありません + {pos} of {total}: {name} {total} 件中 {pos} 件目: {name} +@plural {n} result|{n} results {n} 件 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。 Secondary セカンダリ Select All Art on Layer レイヤー上のすべてのアートを選択 Select All Assets すべてのアセットを選択 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c7c8545e6a..3065cf8057 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3958,6 +3958,10 @@ font-technology Variable ცვლადი Saving შენახვა Saving {} ინახება: {} Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… + No commands match შესაბამისი ბრძანება არ არის + {pos} of {total}: {name} {pos} / {total}: {name} +@plural {n} result|{n} results {n} შედეგი +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად. Dashed Line ტირეებიანი ხაზი Panel menu პანელის მენიუ Unembed… ჩაშენების მოხსნა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a988b15a49..528eaf366b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3149,6 +3149,10 @@ mark-style Japanese 일본식 @msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1} Search commands, tools, panels and effects 명령, 도구, 패널 및 효과 검색 Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… + No commands match 일치하는 명령이 없습니다 + {pos} of {total}: {name} {total}개 중 {pos}번째: {name} +@plural {n} result|{n} results 결과 {n}개 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요. Secondary 보조 Select All Art on Layer 레이어의 모든 아트웍 선택 Select All Assets 모든 에셋 선택 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index fe1110957f..20d4a9926e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4658,6 +4658,10 @@ font-technology Variable Variabel Saving Bezig met opslaan Saving {} {} wordt opgeslagen Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… + No commands match Geen opdrachten gevonden + {pos} of {total}: {name} {pos} van {total}: {name} +@plural {n} result|{n} results {n} resultaat|{n} resultaten +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken. Dashed Line Streepjeslijn Panel menu Paneelmenu Unembed… Insluiten ongedaan maken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ca1959dcd0..e739638880 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4273,6 +4273,10 @@ font-technology Variable Zmienne Saving Zapisywanie Saving {} Zapisywanie {} Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… + No commands match Żadne polecenie nie pasuje + {pos} of {total}: {name} {pos} z {total}: {name} +@plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić. Dashed Line Linia przerywana Panel menu Menu panelu Unembed… Wyodrębnij… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 65257dd8f7..0172ca11fc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2699,6 +2699,10 @@ digits Malayalam Malaiala Search Commands… Pesquisar Comandos… Search commands, tools, panels and effects Pesquisar comandos, ferramentas, painéis e efeitos Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… + No commands match Nenhum comando corresponde + {pos} of {total}: {name} {pos} de {total}: {name} +@plural {n} result|{n} results {n} resultado|{n} resultados +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los. Secondary Secundária Section Symbol Símbolo de Seção Select Selecionar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 523b90ce41..53ffb0f35a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3269,6 +3269,10 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1} Search commands, tools, panels and effects Поиск команд, инструментов, панелей и эффектов Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… + No commands match Нет подходящих команд + {pos} of {total}: {name} {pos} из {total}: {name} +@plural {n} result|{n} results {n} результат|{n} результата|{n} результатов +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их. Search Commands… Поиск команд… Secondary Вторичный Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index df06cdaded..5452940db9 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3161,6 +3161,10 @@ digits Malayalam Malayalam Search All Sök i alla Search commands, tools, panels and effects Sök kommandon, verktyg, paneler och effekter Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… + No commands match Inga kommandon matchar + {pos} of {total}: {name} {pos} av {total}: {name} +@plural {n} result|{n} results {n} resultat|{n} resultat +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem. Search Commands… Sök kommandon… Secondary Sekundär Section Symbol Paragraftecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ffabf3cbe8..372faa8831 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3038,6 +3038,10 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1} Search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri arayın Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… + No commands match Eşleşen komut yok + {pos} of {total}: {name} {pos}/{total}: {name} +@plural {n} result|{n} results {n} sonuç +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin. Search Commands… Arama Komutları… Secondary İkincil Section Symbol Bölüm Sembolü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4353c39f14..718a7ea5c0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3274,6 +3274,10 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1} Search commands, tools, panels and effects Пошук команд, інструментів, панелей та ефектів Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… + No commands match Немає відповідних команд + {pos} of {total}: {name} {pos} з {total}: {name} +@plural {n} result|{n} results {n} результат|{n} результати|{n} результатів +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх. Search Commands… Пошук команд… Secondary Вторинний Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3fe9e73c10..4009871043 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3606,6 +3606,10 @@ mark-style Japanese Kiểu Nhật @msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1} Search commands, tools, panels and effects Tìm kiếm lệnh, công cụ, bảng và hiệu ứng Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… + No commands match Không có lệnh nào khớp + {pos} of {total}: {name} {pos} trên {total}: {name} +@plural {n} result|{n} results {n} kết quả +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp. Search Commands… Tìm kiếm lệnh… Search Fonts Folder Tìm kiếm thư mục phông chữ Searching… Đang tìm kiếm… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1b7440e3f1..37c5eff416 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3101,6 +3101,10 @@ digits Malayalam 马拉雅拉姆数字 Filter Layers Panel Rows 筛选图层面板行 Search commands, tools, panels and effects 搜索命令、工具、面板和效果 Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… + No commands match 没有匹配的命令 + {pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name} +@plural {n} result|{n} results {n} 个结果 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。 Search Commands… 搜索命令… Secondary 次要 Section Symbol 章节符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9e0659105b..657251ade9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4357,6 +4357,10 @@ digits Malayalam 馬來亞拉姆數字 Filter Layers Panel Rows 篩選圖層面板列 Search commands, tools, panels and effects 搜尋指令、工具、面板與效果 Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… + No commands match 沒有符合的指令 + {pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name} +@plural {n} result|{n} results {n} 個結果 +@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。 Search Commands… 搜尋指令… Secondary 次要 Section Symbol 章節符號 diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 7c684a8026..d6cd8564d4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -362,9 +362,9 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } -/// The results the palette shows for the lowercased query `q`: the first 14 entries that hold every -/// word of it, the ones whose name without its menu path is the query (the Layers panel for -/// "layers") first, each group in catalog order. +/// Every entry that holds every word of the lowercased query `q`, the ones whose name without its +/// menu path is the query (the Layers panel for "layers") first, each group in catalog order. +/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest. fn matching<'a>(entries: &'a [Entry], q: &str) -> Vec<&'a Entry> { let words: Vec<&str> = q.split_whitespace().collect(); let whole = words.join(" "); @@ -374,41 +374,149 @@ fn matching<'a>(entries: &'a [Entry], q: &str) -> Vec<&'a Entry> { if !whole.is_empty() { found.sort_by_key(|e| !named(e)); } - found.truncate(14); found } +/// The height of a result row, in points: one line of 13-point body text. +const ROW_HEIGHT: f32 = 20.0; +/// The most result rows the list shows at once; the others scroll into view. +const VISIBLE_ROWS: usize = 12; +/// The most results the list holds. The footer says how many matched in all. +const MAX_RESULTS: usize = 50; +/// The popup's distance from the top of the window, in points. +const TOP: f32 = 90.0; +/// The space kept between the popup and the bottom of the window, in points. +const BOTTOM_GAP: f32 = 8.0; + +/// What a result row shows and screen readers read: its name, and its shortcut after a comma. +fn row_label(e: &Entry) -> String { + let shortcut = menus::shown_shortcut(&e.shortcut); + if shortcut.is_empty() { e.shown.clone() } else { format!("{}, {shortcut}", e.shown) } +} + +/// The line under the results: how many results matched, how many of them the list holds when it +/// can't hold them all, or that none matched. +fn footer(listed: usize, total: usize) -> String { + if total == 0 { + tl!("No commands match").to_string() + } else if listed < total { + let line = crate::i18n::tn( + total as u64, + "{shown} of {n} result. Keep typing to narrow them.", + "{shown} of {n} results. Keep typing to narrow them.", + ); + crate::i18n::fmt(&line, &[("shown", &listed.to_string())]) + } else { + crate::i18n::tn(total as u64, "{n} result", "{n} results") + } +} + +/// How many times each key that moves the highlighted result was pressed this frame. +#[derive(Default)] +struct Moves { + down: usize, + up: usize, + page_down: usize, + page_up: usize, +} + +impl Moves { + fn any(&self) -> bool { + self.down + self.up + self.page_down + self.page_up > 0 + } + + /// The highlighted result of `n` after these moves from `sel`, a page being `page` rows: Up and + /// Down wrap at the ends, Page Up and Page Down stop at them. + fn apply(&self, sel: usize, n: usize, page: usize) -> usize { + let Some(last) = n.checked_sub(1) else { return 0 }; + let sel = sel.min(last); + let sel = (sel + self.down % n) % n; + let sel = (sel + n - self.up % n) % n; + let sel = sel.saturating_add(page.saturating_mul(self.page_down)).min(last); + sel.saturating_sub(page.saturating_mul(self.page_up)) + } +} + +/// `name` laid out on one line at most `width` points wide; a longer name ends with "…". +fn name_galley(painter: &egui::Painter, name: &str, font: egui::FontId, color: egui::Color32, width: f32) -> Arc { + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), font, color); + job.wrap = egui::text::TextWrapping { max_width: width.max(0.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + painter.layout_job(job) +} + +/// The scroll offset that keeps row `sel` in a list `view` points tall that was scrolled to `offset`. +fn offset_showing(sel: usize, offset: f32, view: f32) -> f32 { + let top = sel as f32 * ROW_HEIGHT; + offset.min(top).max(top + ROW_HEIGHT - view).max(0.0) +} + +/// The row nearest to `sel` among the rows of `n` wholly in view of a list `view` points tall +/// scrolled to `offset`. +fn nearest_in_view(sel: usize, offset: f32, view: f32, n: usize) -> usize { + let Some(last_row) = n.checked_sub(1) else { return 0 }; + // Half a point of leeway takes in rounding of the offset. + let first = (((offset - 0.5) / ROW_HEIGHT).ceil().max(0.0) as usize).min(last_row); + let end = ((offset + view + 0.5) / ROW_HEIGHT).floor().max(0.0) as usize; + let last = end.saturating_sub(1).clamp(first, last_row); + sel.clamp(first, last) +} + +/// The highlighted result, the query it belongs to and the list's scroll offset. +type Highlight = (usize, String, f32); + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + // The widget that had the keyboard focus when the palette opened takes it back when the palette + // closes, unless a pick opened a dialog, which focuses its own first field. + let focus_id = egui::Id::unique("palette-focus-before"); if !app.ui.palette_open { + if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::>(focus_id)) + && app.ui.dialog.is_none() + { + ctx.memory_mut(|m| m.request_focus(before)); + } return; } + if ctx.data(|d| d.get_temp::>(focus_id)).is_none() { + let before = ctx.memory(|m| m.focused()); + ctx.data_mut(|d| d.insert_temp(focus_id, before)); + } crate::shortcuts::hold_back_keys(app, ctx); let t = Tokens::get(ctx); let q = app.ui.palette_query.to_lowercase(); let entries = entries(ctx, crate::i18n::current()); - let matches = matching(&entries, &q); + let mut matches = matching(&entries, &q); + let total = matches.len(); + matches.truncate(MAX_RESULTS); let mut run: Option = None; - // The highlighted result (#1757): Up and Down move it (wrapping), the pointer over a result - // takes it, and a new query starts again from the first. + // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it + // by a page, the pointer over a result takes it, and a new query starts again from the first. let sel_id = egui::Id::unique("palette-selected"); - let (mut sel, last_q) = ctx.data(|d| d.get_temp::<(usize, String)>(sel_id)).unwrap_or_default(); - if last_q != q { + let (mut sel, last_q, mut offset) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let new_query = last_q != q; + if new_query { sel = 0; } let n = matches.len(); + let mut moves = Moves::default(); if n > 0 { - let (down, up) = - ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); - if down { - sel = (sel + 1) % n; - } - if up { - sel = (sel + n - 1) % n; - } - sel = sel.min(n - 1); + ctx.input_mut(|i| { + let mut key = |k| i.count_and_consume_key(egui::Modifiers::NONE, k); + moves = Moves { + down: key(egui::Key::ArrowDown), + up: key(egui::Key::ArrowUp), + page_down: key(egui::Key::PageDown), + page_up: key(egui::Key::PageUp), + }; + }); } - egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 90.0]).show(ctx, |ui| { - egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(10)).show(ui, |ui| { + let screen = ctx.content_rect(); + // The highlighted result the rows and the field's description are drawn with. + let mut drawn = sel; + // The area keeps itself inside the window (egui's `Area::constrain` is on), so in a window too + // short for the field, one row and the footer below TOP, the popup moves up. + egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, TOP]).show(ctx, |ui| { + let margin: i8 = 10; + egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(margin)).show(ui, |ui| { ui.set_width(520.0); let r = ui.add( egui::TextEdit::singleline(&mut app.ui.palette_query) @@ -418,20 +526,72 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ); r.request_focus(); ui.add_space(6.0); - for (i, e) in matches.iter().enumerate() { - let resp = ui.add( - egui::Button::new(e.shown.as_str()) - .shortcut_text(menus::shown_shortcut(&e.shortcut)) - .min_size(egui::vec2(500.0, 24.0)) - .selected(i == sel), - ); - if resp.hovered() && ui.input(|i| i.pointer.delta() != egui::Vec2::ZERO) { - sel = i; - } - if resp.clicked() { - run = Some(e.id.clone()); - } + // The list shows as many rows as fit above the footer in the window, up to + // VISIBLE_ROWS; a page is that many rows. + let spacing = ui.spacing().item_spacing.y; + let footer_height = spacing + 6.0 + ui.text_style_height(&egui::TextStyle::Body) + f32::from(margin) + BOTTOM_GAP; + let room = screen.bottom() - footer_height - ui.cursor().top() - spacing; + let rows = ((room / ROW_HEIGHT).floor().max(1.0) as usize).min(VISIBLE_ROWS); + sel = moves.apply(sel, n, rows); + drawn = sel; + let view = rows.min(n) as f32 * ROW_HEIGHT; + // Screen readers stay on the field: its description names the highlighted result and + // its place among every match, as the footer counts them. + if let Some(e) = matches.get(sel) { + let pos = (sel + 1).to_string(); + let of = total.to_string(); + let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } + if n > 0 { + ui.scope(|ui| { + // `show_rows` adds the item spacing to each row, and rows touch. + ui.spacing_mut().item_spacing = egui::Vec2::ZERO; + let mut area = egui::ScrollArea::vertical().id_salt("palette-results").max_height(view).auto_shrink([false, true]); + if new_query || moves.any() { + offset = offset_showing(sel, if new_query { 0.0 } else { offset }, view); + area = area.vertical_scroll_offset(offset); + } + let out = area.show_rows(ui, ROW_HEIGHT, n, |ui, range| { + for i in range { + let Some(e) = matches.get(i) else { continue }; + let (rect, resp) = ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW_HEIGHT), egui::Sense::click()); + if resp.hovered() && ui.input(|inp| inp.pointer.delta() != egui::Vec2::ZERO) { + sel = i; + } + let on = i == sel; + if on { + ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill); + } + let font = egui::TextStyle::Body.resolve(ui.style()); + let shortcut = menus::shown_shortcut(&e.shortcut); + let p = ui.painter(); + let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); + let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); + let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; + let name_at = rect.left() + 8.0; + let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); + p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + // `WidgetInfo::selected` reaches screen readers as a toggled state, so the + // row sets the selected state on its node itself. + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); + if resp.clicked() { + run = Some(e.id.clone()); + } + } + }); + let before = offset; + offset = out.state.clamped_offset().y; + // After a scroll with the wheel or the scroll bar, the highlight moves to the + // nearest row in view, so Enter runs a result that can be seen. + if !new_query && !moves.any() && (offset - before).abs() > 0.5 { + sel = nearest_in_view(sel, offset, view, n); + } + }); + } + ui.add_space(6.0); + ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); if ui.input(|i| i.key_pressed(egui::Key::Enter)) && let Some(e) = matches.get(sel) { @@ -439,7 +599,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); }); - ctx.data_mut(|d| d.insert_temp(sel_id, (sel, q))); + // The pointer or a scroll moved the highlight after the rows were drawn: the next frame draws + // it where it now is. + if sel != drawn { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp::(sel_id, (sel, q, offset))); if let Some(id) = run { app.ui.palette_open = false; run_pick(app, &id); @@ -765,7 +930,7 @@ mod tests { let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; let frame = |app: &mut VectorcraftApp, events: Vec| { ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| show(app, ui.ctx())).textures_delta.clear(); - ctx.data(|d| d.get_temp::<(usize, String)>(egui::Id::unique("palette-selected"))).unwrap().0 + ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 }; assert_eq!(frame(&mut app, vec![]), 0); assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowDown)]), 1); @@ -774,6 +939,13 @@ mod tests { assert!(last > 1, "Up on the first result wraps to the last: {last}"); app.ui.palette_query = "zoom in".into(); assert_eq!(frame(&mut app, vec![]), 0); + // With more matches than the list holds, Up on the first wraps to the last one it holds, and + // Down there wraps to the first. + app.ui.palette_query = "select".into(); + assert!(matching(&entries(&ctx, Lang::EN), "select").len() > MAX_RESULTS); + assert_eq!(frame(&mut app, vec![]), 0); + assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowUp)]), MAX_RESULTS - 1); + assert_eq!(frame(&mut app, vec![key(egui::Key::ArrowDown)]), 0); } /// Each command, tool and plug-in is one result: Place… and Print…, which are engine commands @@ -1106,13 +1278,12 @@ mod tests { let entries = build(Lang::EN); let panels: Vec<&Entry> = entries.iter().filter(|e| e.id.starts_with("panel:")).collect(); assert_eq!(panels.len(), crate::state::all_panels().count()); - // More than 14 results hold "layers" in their menu path; the panel, named Layers, is shown - // first, and "color guide" shows the Color Guide panel first too. + // Many results hold "layers" in their menu path; the panel, named Layers, is shown first, and "color guide" shows the Color Guide panel first too. for (query, want) in [("layers", "panel:layers"), ("color guide", "panel:colorGuide"), ("Layers ", "panel:layers")] { let all = entries.iter().filter(|e| query.to_lowercase().split_whitespace().all(|w| e.haystack.contains(w))).count(); let shown: Vec<&str> = matching(&entries, &query.to_lowercase()).into_iter().map(|e| e.id.as_str()).collect(); assert_eq!(shown.first(), Some(&want), "{query}: {shown:?}"); - assert_eq!(shown.len(), all.min(14), "{query}"); + assert_eq!(shown.len(), all, "{query}"); } let layers = entries.iter().find(|e| e.id == "panel:layers").unwrap(); assert_eq!(layers.shown, "Window › Show Panel › Layers"); @@ -1197,4 +1368,397 @@ mod tests { vectorcraft_plugins::registry::remove(one); vectorcraft_plugins::registry::remove(two); } + + /// The open palette in a window, drawn a frame at a time with the app's theme, in English, with + /// screen readers on. + struct Open { + app: VectorcraftApp, + ctx: egui::Context, + size: egui::Vec2, + time: f64, + /// Whether the last frame asked for another one at once. + repaint: bool, + } + + impl Open { + /// The palette open on `query` in a window `size` points big. + fn new(query: &str, size: egui::Vec2) -> Open { + crate::i18n::set_current(Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.palette_open = true; + app.ui.palette_query = query.into(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let mut open = Open { app, ctx, size, time: 0.0, repaint: false }; + open.frame(vec![]); + open + } + + /// One frame with `events`: its screen-reader tree. + fn frame(&mut self, events: Vec) -> Vec { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let app = &mut self.app; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() + } + + /// A frame where `k` is pressed `times` times. + fn press(&mut self, k: egui::Key, times: usize) -> Vec { + let key = egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + self.frame(vec![key; times]) + } + + /// The highlighted result's index. + fn highlighted(&self) -> usize { + self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 + } + + /// The popup's rectangle. + fn popup(&self) -> egui::Rect { + self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() + } + + /// The results the palette lists for its query. + fn listed(&self) -> Vec { + let entries = entries(&self.ctx, Lang::EN); + matching(&entries, &self.app.ui.palette_query.to_lowercase()).iter().take(MAX_RESULTS).map(|e| e.id.clone()).collect() + } + } + + /// The result rows of a screen-reader tree, top to bottom: (label, highlighted, top, bottom). + fn rows(nodes: &[egui::accesskit::Node]) -> Vec<(String, bool, f64, f64)> { + let mut rows: Vec<(String, bool, f64, f64)> = nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::ListItem) + .map(|n| { + let b = n.bounds().unwrap(); + (n.label().unwrap_or_default().to_string(), n.is_selected() == Some(true), b.y0, b.y1) + }) + .collect(); + rows.sort_by(|a, b| a.2.total_cmp(&b.2)); + rows + } + + /// The text of the labels in a screen-reader tree. + fn labels(nodes: &[egui::accesskit::Node]) -> Vec { + nodes.iter().filter(|n| n.role() == egui::accesskit::Role::Label).filter_map(|n| n.label().or(n.value()).map(str::to_string)).collect() + } + + /// The search field's screen-reader description. + fn field_description(nodes: &[egui::accesskit::Node]) -> String { + let field = nodes.iter().find(|n| n.role() == egui::accesskit::Role::TextInput).expect("the search field is in the tree"); + field.description().unwrap_or_default().to_string() + } + + const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0); + + /// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than + /// the 14 24-point buttons it showed before. + #[test] + fn results_are_compact_rows_that_touch() { + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let rows = rows(&nodes); + let inside: Vec<_> = rows.iter().filter(|r| r.3 <= f64::from(open.popup().bottom())).collect(); + assert!(inside.len() >= VISIBLE_ROWS, "{rows:?}"); + for pair in inside.windows(2).take(VISIBLE_ROWS - 1) { + assert_eq!(pair[0].3 - pair[0].2, f64::from(ROW_HEIGHT), "{pair:?}"); + assert_eq!(pair[0].3, pair[1].2, "rows touch: {pair:?}"); + } + // 14 results took 458 points before the rows were made compact. + let height = open.popup().height(); + println!("popup height for {VISIBLE_ROWS} rows: {height}"); + assert!(height <= 330.0, "{height}"); + } + + /// The footer says how many results matched, how many of them the list holds when it holds + /// fewer, or that none matched. + #[test] + fn the_footer_counts_the_results() { + crate::i18n::set_current(Lang::EN); + assert_eq!(footer(50, 60), "50 of 60 results. Keep typing to narrow them."); + assert_eq!(footer(3, 3), "3 results"); + assert_eq!(footer(1, 1), "1 result"); + assert_eq!(footer(0, 0), "No commands match"); + // The count takes each language's form. + crate::i18n::set_current(Lang::from_code("ru").unwrap()); + let ru = [footer(50, 51), footer(50, 52), footer(2, 2)]; + crate::i18n::set_current(Lang::EN); + assert_eq!( + ru, + [ + "50 из 51 результата. Продолжайте вводить, чтобы сузить их.", + "50 из 52 результатов. Продолжайте вводить, чтобы сузить их.", + "2 результата" + ] + ); + let mut open = Open::new("select", WINDOW); + let total = matching(&entries(&open.ctx, Lang::EN), "select").len(); + assert!(total > MAX_RESULTS, "{total}"); + let nodes = open.frame(vec![]); + assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); + // Every result the list holds is reachable: End of the list by keyboard shows the 50th. + let nodes = open.press(egui::Key::ArrowUp, 1); + assert_eq!(open.highlighted(), MAX_RESULTS - 1); + assert!(rows(&nodes).iter().any(|r| r.1), "the 50th row is drawn and highlighted"); + } + + /// With no match, the footer says so and Enter runs nothing and leaves the palette open. + #[test] + fn with_no_match_enter_runs_nothing() { + let mut open = Open::new("qqzzxxnothing", WINDOW); + let nodes = open.frame(vec![]); + assert!(rows(&nodes).is_empty()); + assert!(labels(&nodes).contains(&"No commands match".to_string()), "{:?}", labels(&nodes)); + open.app.ui.status.clear(); + open.press(egui::Key::Enter, 1); + open.frame(vec![]); + assert!(open.app.ui.palette_open && open.app.ui.status.is_empty(), "{}", open.app.ui.status); + } + + /// Down 15 times from the first result highlights the 16th, scrolled into view, and Enter runs + /// it. + #[test] + fn the_sixteenth_result_is_reached_by_keyboard_and_runs() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > 16, "{listed:?}"); + let nodes = open.press(egui::Key::ArrowDown, 15); + assert_eq!(open.highlighted(), 15); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + let entries = entries(&open.ctx, Lang::EN); + let want = entries.iter().find(|e| e.id == listed[15]).map(row_label).unwrap(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert_eq!(lit[0].0, want); + let popup = open.popup(); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "scrolled into view: {lit:?} in {popup:?}"); + let panel = listed[15].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// Page Down and Page Up move the highlight by the rows shown, stopping at the ends; Up and + /// Down wrap. + #[test] + fn page_keys_move_by_a_page_without_wrapping() { + let moves = |down, up, page_down, page_up| Moves { down, up, page_down, page_up }; + assert_eq!(moves(0, 0, 1, 0).apply(0, 50, 12), 12); + assert_eq!(moves(0, 0, 1, 0).apply(45, 50, 12), 49); + assert_eq!(moves(0, 0, 0, 1).apply(5, 50, 12), 0); + assert_eq!(moves(1, 0, 0, 0).apply(49, 50, 12), 0); + assert_eq!(moves(0, 1, 0, 0).apply(0, 50, 12), 49); + assert_eq!(moves(3, 0, 0, 0).apply(48, 50, 12), 1); + assert_eq!(moves(1, 0, 0, 0).apply(0, 0, 12), 0); + let mut open = Open::new("select", WINDOW); + open.press(egui::Key::PageDown, 1); + assert_eq!(open.highlighted(), VISIBLE_ROWS); + open.press(egui::Key::PageDown, 5); + assert_eq!(open.highlighted(), MAX_RESULTS - 1, "stops at the last"); + open.press(egui::Key::PageUp, 1); + assert_eq!(open.highlighted(), MAX_RESULTS - 1 - VISIBLE_ROWS); + open.press(egui::Key::PageUp, 9); + assert_eq!(open.highlighted(), 0, "stops at the first"); + } + + /// After the list is scrolled with the wheel, the highlight is on a row in view, so Enter runs a + /// result that can be seen. + #[test] + fn a_wheel_scroll_keeps_the_highlight_in_view() { + assert_eq!(nearest_in_view(0, 100.0, 240.0, 50), 5); + assert_eq!(nearest_in_view(30, 100.0, 240.0, 50), 16); + assert_eq!(nearest_in_view(8, 100.0, 240.0, 50), 8); + assert_eq!(nearest_in_view(3, 0.0, 240.0, 3), 2); + assert_eq!(nearest_in_view(0, 0.0, 240.0, 0), 0); + let mut open = Open::new("select", WINDOW); + let nodes = open.frame(vec![]); + let first = rows(&nodes).into_iter().next().unwrap(); + let at = egui::pos2(open.popup().center().x, ((first.2 + first.3) / 2.0) as f32); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -200.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + open.frame(vec![egui::Event::PointerMoved(at)]); + let mut nodes = open.frame(vec![wheel]); + // The frames that follow, up to the last one the palette or the scroll asks for, which + // has to show the highlight where Enter runs it. + for _ in 0..120 { + if !open.repaint { + break; + } + nodes = open.frame(vec![]); + } + assert!(!open.repaint, "the scroll settles"); + let sel = open.highlighted(); + assert!(sel > 0, "the highlight left the row scrolled out of view"); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); + } + + /// The pointer moved onto a row highlights that row alone, and the field's description names + /// it, on the frame drawn straight after. + #[test] + fn the_row_under_the_pointer_is_the_one_highlighted() { + let mut open = Open::new("select", WINDOW); + let listed = open.listed(); + let entries = entries(&open.ctx, Lang::EN); + let nodes = open.frame(vec![]); + let all = rows(&nodes); + let middle = |r: &(String, bool, f64, f64)| egui::pos2(open.popup().center().x, ((r.2 + r.3) / 2.0) as f32); + let (first, fourth) = (middle(&all[0]), middle(&all[3])); + open.frame(vec![egui::Event::PointerMoved(first)]); + open.frame(vec![egui::Event::PointerMoved(fourth)]); + assert_eq!(open.highlighted(), 3); + assert!(open.repaint, "the frame that moved the highlight asks for another"); + let nodes = open.frame(vec![]); + let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); + let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); + assert_eq!(lit, std::slice::from_ref(&label)); + assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select").len())); + } + + /// A name too long for its row is cut short with "…" and stays inside the width it is given. + #[test] + fn a_long_name_ends_with_an_ellipsis() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let long = "Window › Show Panel › A Panel Name Long Enough Not To Fit In The Row (addon.panels.long)"; + let cut = name_galley(ui.painter(), long, font.clone(), egui::Color32::WHITE, 200.0); + assert!(cut.elided && cut.size().x <= 200.0, "{:?}", cut.size()); + assert_eq!(cut.rows.last().and_then(|r| r.glyphs.last()).map(|g| g.chr), Some('…')); + let short = name_galley(ui.painter(), "Edit › Copy", font, egui::Color32::WHITE, 200.0); + assert!(!short.elided); + }); + out.textures_delta.clear(); + } + + /// The popup stays inside a short window, showing fewer rows when 12 don't fit; a page is the + /// rows shown. + #[test] + fn the_popup_stays_inside_a_short_window() { + for size in [egui::vec2(1280.0, 600.0), egui::vec2(800.0, 300.0), egui::vec2(800.0, 160.0)] { + let mut open = Open::new("select", size); + open.frame(vec![]); + let popup = open.popup(); + assert!(popup.top() >= 0.0 && popup.bottom() <= size.y, "{size:?}: {popup:?}"); + open.press(egui::Key::PageDown, 1); + let page = open.highlighted(); + if size.y < 400.0 { + assert!((1..VISIBLE_ROWS).contains(&page), "a short window shows fewer than 12 rows: {size:?}: {page}"); + } else { + assert_eq!(page, VISIBLE_ROWS, "{size:?}"); + } + } + } + + /// A click anywhere on a row, its empty right end included, runs it. + #[test] + fn a_click_anywhere_on_a_row_runs_it() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + let nodes = open.frame(vec![]); + let hidden = |id: &String| id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&open.app.ui, p)); + let k = listed.iter().position(hidden).expect("a hidden panel's result"); + assert!(k < VISIBLE_ROWS, "{listed:?}"); + let row = rows(&nodes).into_iter().nth(k).unwrap(); + let popup = open.popup(); + let at = egui::pos2(popup.right() - 24.0, ((row.2 + row.3) / 2.0) as f32); + let panel = listed[k].strip_prefix("panel:").unwrap_or_default().to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::PointerMoved(at)]); + open.frame(vec![button(true)]); + open.frame(vec![button(false)]); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + + /// Screen readers stay on the field: its description names the highlighted result and its + /// place, and follows the highlight; the rows are list items, the highlighted one selected, and + /// the footer's count is a label. + #[test] + fn screen_readers_hear_the_highlighted_result_and_the_count() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + let entries = entries(&open.ctx, Lang::EN); + let label = |i: usize| entries.iter().find(|e| e.id == listed[i]).map(row_label).unwrap(); + let nodes = open.frame(vec![]); + // More results match than the list holds: the place counts every match, as the footer does. + let total = matching(&entries, "show panel").len(); + assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}"); + assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0))); + let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); + assert_eq!(lit, [label(0)]); + assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); + let nodes = open.press(egui::Key::ArrowDown, 1); + assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); + // Fewer results match than the list holds. + let mut open = Open::new("copy", WINDOW); + let n = open.listed().len(); + assert!((1..MAX_RESULTS).contains(&n), "{n}"); + let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); + let nodes = open.frame(vec![]); + assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); + assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); + } + + /// The widget that had the keyboard focus when the palette opened has it again once the + /// palette closes. + #[test] + fn closing_gives_the_focus_back() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut text = String::new(); + let field = egui::Id::unique("other field"); + let mut frame = |app: &mut VectorcraftApp, focus: bool| { + ctx.run_ui(egui::RawInput::default(), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true); + frame(&mut app, false); + assert_eq!(ctx.memory(|m| m.focused()), Some(field)); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the search field takes the focus"); + app.ui.palette_open = false; + frame(&mut app, false); + frame(&mut app, false); + assert_eq!(ctx.memory(|m| m.focused()), Some(field)); + // A pick that opens a dialog leaves the focus to the dialog. + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + frame(&mut app, true); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + app.ui.palette_open = false; + run_pick(&mut app, "object.path.cleanUp"); + assert!(app.ui.dialog.is_some(), "Clean Up… opens its dialog: {}", app.ui.status); + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the dialog keeps the focus"); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 64b651c4af..9b50129f41 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1253,7 +1253,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`). The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`). No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). - The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel among the 14 results. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). + The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). + The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 1f059f6e0116a36c9fd42efc0bf781804498a000 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:17:50 -0800 Subject: [PATCH 04/29] Command Palette: a shorter window scrolls the list to keep the highlight in view When the window shrinks so the list shows fewer rows, the list scrolls to the highlighted result instead of leaving it below the visible rows, so Enter runs a result that can be seen. --- crates/ui-egui/src/palette.rs | 39 +++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index d6cd8564d4..750e484b77 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -461,8 +461,8 @@ fn nearest_in_view(sel: usize, offset: f32, view: f32, n: usize) -> usize { sel.clamp(first, last) } -/// The highlighted result, the query it belongs to and the list's scroll offset. -type Highlight = (usize, String, f32); +/// The highlighted result, the query it belongs to, the list's scroll offset and the list's height. +type Highlight = (usize, String, f32, f32); pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette @@ -491,7 +491,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it // by a page, the pointer over a result takes it, and a new query starts again from the first. let sel_id = egui::Id::unique("palette-selected"); - let (mut sel, last_q, mut offset) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let (mut sel, last_q, mut offset, last_view) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let mut view = last_view; let new_query = last_q != q; if new_query { sel = 0; @@ -534,7 +535,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let rows = ((room / ROW_HEIGHT).floor().max(1.0) as usize).min(VISIBLE_ROWS); sel = moves.apply(sel, n, rows); drawn = sel; - let view = rows.min(n) as f32 * ROW_HEIGHT; + view = rows.min(n) as f32 * ROW_HEIGHT; + // When the list's height changes, as when the window is resized, the list scrolls to + // keep the highlighted result in view. + let resized = (view - last_view).abs() > 0.5; // Screen readers stay on the field: its description names the highlighted result and // its place among every match, as the footer counts them. if let Some(e) = matches.get(sel) { @@ -548,7 +552,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // `show_rows` adds the item spacing to each row, and rows touch. ui.spacing_mut().item_spacing = egui::Vec2::ZERO; let mut area = egui::ScrollArea::vertical().id_salt("palette-results").max_height(view).auto_shrink([false, true]); - if new_query || moves.any() { + if new_query || moves.any() || resized { offset = offset_showing(sel, if new_query { 0.0 } else { offset }, view); area = area.vertical_scroll_offset(offset); } @@ -604,7 +608,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if sel != drawn { ctx.request_repaint(); } - ctx.data_mut(|d| d.insert_temp::(sel_id, (sel, q, offset))); + ctx.data_mut(|d| d.insert_temp::(sel_id, (sel, q, offset, view))); if let Some(id) = run { app.ui.palette_open = false; run_pick(app, &id); @@ -1608,6 +1612,29 @@ mod tests { assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); } + /// When the window shrinks so the list shows fewer rows, the list scrolls to keep the + /// highlighted result in view, and Enter runs that result. + #[test] + fn a_shorter_window_keeps_the_highlight_in_view() { + let mut open = Open::new("show panel", WINDOW); + let listed = open.listed(); + assert!(listed.len() > VISIBLE_ROWS, "{listed:?}"); + open.press(egui::Key::ArrowDown, VISIBLE_ROWS - 1); + assert_eq!(open.highlighted(), VISIBLE_ROWS - 1); + open.size = egui::vec2(800.0, 300.0); + let nodes = open.frame(vec![]); + assert_eq!(open.highlighted(), VISIBLE_ROWS - 1); + let popup = open.popup(); + let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); + assert_eq!(lit.len(), 1, "{lit:?}"); + assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); + let panel = listed[VISIBLE_ROWS - 1].strip_prefix("panel:").expect("a panel's result").to_string(); + assert!(!crate::panel_docking::showing(&open.app.ui, &panel), "{panel}"); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open); + assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); + } + /// The pointer moved onto a row highlights that row alone, and the field's description names /// it, on the frame drawn straight after. #[test] From 7e2095fd28d3a656d2ccae051a031da609e2c60f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:05:07 -0800 Subject: [PATCH 05/29] Command Palette: a press outside the popup closes it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A press of any pointer button outside the open Command Palette closes it: a click, a right-click or the start of a drag. Before, the palette stayed open after such a press. It closed on a pick, on Escape, or when the app bar's search button or Help › Search Commands… was used again. While the palette is open, a backdrop under the popup covers the canvas, the toolbars, the docked panels and the app bar, in the same order as a modal dialog's backdrop. The press that closes the palette does not press a tool button or another control under it. Windows drawn above the backdrop, such as a progress window, still get their clicks, and such a click also closes the palette. Clicks in the search field and on a result work as before. --- crates/ui-egui/src/palette.rs | 239 ++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 2 files changed, 240 insertions(+) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 750e484b77..53bc91100b 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -513,6 +513,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let screen = ctx.content_rect(); // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; + // The backdrop covers the canvas, the toolbars, the docked panels and the app bar under the + // popup, in the order of a modal dialog's backdrop (`dialogs::modal::backdrop`), so the press + // that closes the palette does not press a control under it. Windows in the Foreground order + // stay above it. Not focusable (`Sense::click()` is): Tab stays in the popup. + egui::Area::new(egui::Id::unique("palette-backdrop")).order(egui::Order::Middle).fixed_pos(screen.min).show(ctx, |ui| { + ui.allocate_rect(screen, egui::Sense::CLICK); + }); // The area keeps itself inside the window (egui's `Area::constrain` is on), so in a window too // short for the field, one row and the footer below TOP, the popup moves up. egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, TOP]).show(ctx, |ui| { @@ -603,6 +610,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); }); + // A press of any pointer button that the popup's layer does not get closes it: a press on the + // backdrop, or on a window above it, which also gets the press, even where that window lies + // over the popup. + let presses: Vec = ctx.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::PointerButton { pos, pressed: true, .. } => Some(*pos), + _ => None, + }) + .collect() + }); + let popup = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("palette")); + let outside = presses.into_iter().any(|p| ctx.layer_id_at(p) != Some(popup)); // The pointer or a scroll moved the highlight after the rows were drawn: the next frame draws // it where it now is. if sel != drawn { @@ -612,6 +633,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if let Some(id) = run { app.ui.palette_open = false; run_pick(app, &id); + } else if outside { + app.ui.palette_open = false; } } @@ -1788,4 +1811,220 @@ mod tests { frame(&mut app, false); assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the dialog keeps the focus"); } + + /// The whole window, with a document whose rectangle is selected, drawn a frame at a time in + /// English with screen readers on. + struct Window { + app: VectorcraftApp, + ctx: egui::Context, + time: f64, + /// Draw a window with an "Above" button at this place, in the Foreground order after the + /// app, as a progress window is drawn, and count its clicks. + above: Option, + above_clicks: usize, + } + + impl Window { + fn new() -> Window { + crate::i18n::set_current(Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + assert!(!app.session.doc().unwrap().selection.is_empty()); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 }; + window.frame(vec![]); + window.frame(vec![]); + window + } + + /// One frame of the whole window with `events`: its screen-reader tree. + fn frame(&mut self, events: Vec) -> Vec { + self.time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let app = &mut self.app; + let (above, clicks) = (self.above, &mut self.above_clicks); + let mut out = self.ctx.run_ui(input, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + if let Some(at) = above { + let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at); + area.show(ui.ctx(), |ui| { + if ui.button("Above").clicked() { + *clicks += 1; + } + }); + } + }); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() + } + + /// A primary click at `at`, a frame for the move, the press and the release: the release + /// frame's screen-reader tree. + fn click(&mut self, at: egui::Pos2) -> Vec { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + self.frame(vec![egui::Event::PointerMoved(at)]); + self.frame(vec![button(true)]); + self.frame(vec![button(false)]) + } + + /// A press of `button` at `from`, a move to `to` and the release there, a frame each. + fn drag(&mut self, button: egui::PointerButton, from: egui::Pos2, to: egui::Pos2) { + let event = |pos, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }; + self.frame(vec![egui::Event::PointerMoved(from)]); + self.frame(vec![event(from, true)]); + self.frame(vec![egui::Event::PointerMoved(to)]); + self.frame(vec![event(to, false)]); + } + + fn selection(&self) -> String { + format!("{:?}", self.app.session.doc().unwrap().selection) + } + + fn popup(&self) -> egui::Rect { + self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() + } + } + + /// The middle of the button whose screen-reader name is `name`, alone or followed by its + /// shortcut in parentheses. + fn button_at(nodes: &[egui::accesskit::Node], name: &str) -> egui::Pos2 { + let names: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::Button).filter_map(|n| n.label()).collect(); + let named = |l: &str| l == name || l.strip_prefix(name).is_some_and(|rest| rest.starts_with(' ') && rest.trim_start().starts_with('(')); + let node = nodes + .iter() + .find(|n| n.role() == egui::accesskit::Role::Button && n.label().is_some_and(named)) + .unwrap_or_else(|| panic!("a button named {name}: {names:?}")); + let b = node.bounds().unwrap(); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + } + + /// A click on the canvas outside the popup closes it and leaves the selection as it was. + #[test] + fn a_click_on_the_canvas_closes_the_palette() { + let mut window = Window::new(); + let before = window.selection(); + window.app.ui.palette_open = true; + window.frame(vec![]); + let canvas = window.app.canvas_rect.expect("the canvas is drawn"); + let at = canvas.left_bottom() + egui::vec2(30.0, -30.0); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.click(at); + assert!(!window.app.ui.palette_open, "the click outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.selection(), before, "the click does not reach the canvas"); + } + + /// A click on another control outside the popup closes the popup and does not press the + /// control. + #[test] + fn a_click_on_another_control_closes_the_palette_without_pressing_it() { + let mut window = Window::new(); + let tool = window.app.session.tool_id(); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Pen Tool"); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.click(at); + assert!(!window.app.ui.palette_open, "the click outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.app.session.tool_id(), tool, "the click does not pick the tool"); + // With the palette closed, the same click picks it. + window.click(at); + assert_eq!(window.app.session.tool_id(), "pen"); + } + + /// A right-click outside the popup closes it, and so does a drag that starts outside it. + #[test] + fn a_right_click_or_a_drag_outside_closes_the_palette() { + let mut window = Window::new(); + let before = window.selection(); + let canvas = window.app.canvas_rect.expect("the canvas is drawn"); + let at = canvas.left_bottom() + egui::vec2(30.0, -30.0); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(!window.popup().contains(at), "{at:?} is outside {:?}", window.popup()); + window.drag(egui::PointerButton::Secondary, at, at); + assert!(!window.app.ui.palette_open, "the right-click outside closes the palette"); + window.app.ui.palette_open = true; + window.frame(vec![]); + window.drag(egui::PointerButton::Primary, at, at + egui::vec2(80.0, -60.0)); + assert!(!window.app.ui.palette_open, "the drag outside closes the palette"); + window.frame(vec![]); + assert_eq!(window.selection(), before, "the drag does not reach the canvas"); + } + + /// A click on a window drawn above the backdrop, as a progress window is, closes the palette + /// and presses that window's button, beside the popup and where the window lies over it. + #[test] + fn a_click_on_a_window_above_closes_the_palette_and_reaches_it() { + for over in [false, true] { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + let popup = window.popup(); + window.above = Some(if over { popup.center() } else { egui::pos2(40.0, 400.0) }); + window.frame(vec![]); + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Above"); + assert_eq!(popup.contains(at), over, "{at:?} and the popup {popup:?}"); + window.click(at); + assert!(!window.app.ui.palette_open, "over the popup: {over}; the click on the window closes the palette"); + assert_eq!(window.above_clicks, 1, "over the popup: {over}; the window gets the click"); + } + } + + /// The click on the app bar's search button that opens the palette leaves it open; the next + /// click on the button closes it. + #[test] + fn the_click_that_opens_the_palette_does_not_close_it() { + let mut window = Window::new(); + let nodes = window.frame(vec![]); + let at = button_at(&nodes, "Search commands, tools, panels and effects"); + window.click(at); + assert!(window.app.ui.palette_open, "the click opens the palette"); + window.frame(vec![]); + window.frame(vec![]); + assert!(window.app.ui.palette_open, "and it stays open"); + window.click(at); + assert!(!window.app.ui.palette_open, "a second click closes it"); + } + + /// Clicks inside the popup keep it open: one in the search field, and one on a result, which + /// runs that result. + #[test] + fn clicks_inside_the_palette_keep_it_or_run_a_result() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.app.ui.palette_query = "show panel".into(); + window.frame(vec![]); + let nodes = window.frame(vec![]); + let popup = window.popup(); + let middle = |b: egui::accesskit::Rect| egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let field = nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::TextInput) + .filter_map(|n| n.bounds().map(middle)) + .find(|p| popup.contains(*p)) + .expect("the search field"); + window.click(field); + window.frame(vec![]); + assert!(window.app.ui.palette_open, "a click in the field keeps the palette open"); + assert_eq!(window.app.ui.palette_query, "show panel"); + let nodes = window.frame(vec![]); + let entries = entries(&window.ctx, Lang::EN); + let listed: Vec<_> = matching(&entries, "show panel").into_iter().take(MAX_RESULTS).collect(); + let hidden = |e: &&&Entry| e.id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&window.app.ui, p)); + let e = listed.iter().find(hidden).expect("a hidden panel's result"); + let label = row_label(e); + let row = rows(&nodes).into_iter().find(|r| r.0 == label).expect("its row is drawn"); + let panel = e.id.strip_prefix("panel:").unwrap_or_default().to_string(); + window.click(egui::pos2(window.popup().center().x, ((row.2 + row.3) / 2.0) as f32)); + assert!(!window.app.ui.palette_open); + assert!(crate::panel_docking::showing(&window.app.ui, &panel), "{panel}: {}", window.app.ui.status); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9b50129f41..fbca583b89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1255,6 +1255,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). + A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 91052081430967b29f0b0410907226deb11eb77e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:48:23 -0800 Subject: [PATCH 06/29] Command Palette: a field clicked above the popup keeps the focus When a press on a field in a window above the backdrop closes the palette, the widget that had the focus before the palette opened no longer takes it back from that field. The earlier widget gets the focus again only when nothing has it or the palette's own field still has it. --- crates/ui-egui/src/palette.rs | 53 ++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 53bc91100b..4e388b3e9e 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -466,11 +466,20 @@ type Highlight = (usize, String, f32, f32); pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette - // closes, unless a pick opened a dialog, which focuses its own first field. + // closes, unless a pick opened a dialog, which focuses its own first field, or the press that + // closed it focused another widget, such as a field in a window above the backdrop. let focus_id = egui::Id::unique("palette-focus-before"); + let field_id = egui::Id::unique("palette-field"); if !app.ui.palette_open { + let field = ctx.data_mut(|d| { + let field = d.get_temp::(field_id); + d.remove::(field_id); + field + }); + let now = ctx.memory(|m| m.focused()); if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::>(focus_id)) && app.ui.dialog.is_none() + && (now.is_none() || now == field) { ctx.memory_mut(|m| m.request_focus(before)); } @@ -533,6 +542,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { .desired_width(500.0), ); r.request_focus(); + ui.ctx().data_mut(|d| d.insert_temp(field_id, r.id)); ui.add_space(6.0); // The list shows as many rows as fit above the footer in the window, up to // VISIBLE_ROWS; a page is that many rows. @@ -1810,6 +1820,47 @@ mod tests { frame(&mut app, false); frame(&mut app, false); assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the dialog keeps the focus"); + // A click on a field in a window above the backdrop closes the palette and leaves the + // focus in that field. + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (mut text, mut above_text) = (String::new(), String::new()); + let above = egui::Id::unique("field above"); + let corner = egui::pos2(40.0, 400.0); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp, focus: bool, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }; + ctx.run_ui(input, |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + // Drawn before the palette, so the palette's own focus requests come after the field's. + egui::Area::new(egui::Id::unique("window above")).order(egui::Order::Foreground).fixed_pos(corner).show(ui.ctx(), |ui| { + ui.add(egui::TextEdit::singleline(&mut above_text).id(above)); + }); + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true, vec![]); + frame(&mut app, false, vec![]); + app.ui.palette_open = true; + frame(&mut app, false, vec![]); + frame(&mut app, false, vec![]); + let at = corner + egui::vec2(20.0, 8.0); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, false, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, false, vec![button(true)]); + frame(&mut app, false, vec![button(false)]); + assert!(!app.ui.palette_open, "the click on the window above closes the palette"); + frame(&mut app, false, vec![]); + frame(&mut app, false, vec![]); + assert_eq!(ctx.memory(|m| m.focused()), Some(above), "the clicked field keeps the focus"); } /// The whole window, with a document whose rectangle is selected, drawn a frame at a time in From c7f5320c5acec971d162e5d69974cb94e9251994 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:12:54 -0800 Subject: [PATCH 07/29] Command Palette: a small search index ranks the best match first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Results are ordered by how well they match instead of by registration order. A query equal to a result's id lists it first; then come results whose name is the query, whose name starts with it, and whose initials it is ("ea" finds Export As…). Within those, a whole word of the name ranks above a word it starts, then a word of the menu that holds the result, of its id, and text inside a word. At equal grades a tool ranks above a menu command, panel, effect or filter plug-in, and a shorter name above a longer one. The words of the menu bar item that runs a result, its own label included, also find it, read from the native menu bar when the app uses it. The index is built when the palette first opens after the language, plug-ins, shortcuts or menu bar change, and the last query's ranking is kept. Every result the earlier search found is still found, an empty query keeps the old order, and the highlight stays on its result when the results change while the palette is open. --- crates/ui-egui/src/palette.rs | 174 +++++-- crates/ui-egui/src/palette/search.rs | 705 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 849 insertions(+), 31 deletions(-) create mode 100644 crates/ui-egui/src/palette/search.rs diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 4e388b3e9e..3386bc65d8 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -8,6 +8,8 @@ use serde_json::json; use crate::theme::Tokens; use crate::{VectorcraftApp, menus}; +mod search; + /// Engine commands the palette leaves out, each with the UI command of the same name that runs it /// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete /// Selection asks before deleting a layer that holds art, and the other UI commands open the @@ -275,35 +277,82 @@ pub(crate) struct Entry { /// label and the id (and the id of the engine command a UI command wraps), lowercased, one per /// line: a query word (which has no line break) matches within one of them. haystack: String, + /// The English menu path of the first item of the menu bar shown that runs the entry + /// ([`search::menu_homes`]), if one does. + home: Option, + /// The English label of that item of the menu bar, which may differ from the entry's (File › + /// Exit runs Quit VectorCraft), or empty. + menu_item: &'static str, + /// The entry's kind, in the order [`search::kind`] ranks kinds. + kind: u8, +} + +/// The palette's entries, the index a query is looked up in, and the last query's ranked results. +pub(crate) struct Catalog { + list: Vec, + index: search::Index, + ranked: std::sync::Mutex)>>, +} + +impl std::ops::Deref for Catalog { + type Target = [Entry]; + + fn deref(&self) -> &[Entry] { + &self.list + } } -/// The palette's entries in `lang`. They are built when the language, the installed plug-ins or -/// the keyboard shortcuts (shown beside each entry) change, not on every frame while a query is -/// typed. /// What the entries depend on: the language, the installed plug-ins and the shortcuts. fn cache_key(lang: crate::i18n::Lang) -> (&'static str, u64, u64) { (lang.code(), menus::plugin_revision(), crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed)) } -fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc> { - type Cached = ((&'static str, u64, u64), Arc>); +/// The palette's entries in `lang` with the in-window menu bar. +#[cfg(test)] +fn entries(ctx: &egui::Context, lang: crate::i18n::Lang) -> Arc { + entries_in(ctx, lang, false) +} + +/// The palette's entries in `lang`, with the native menu bar when `native`. They and their index +/// are built the first time the palette opens after the language, the installed plug-ins, the +/// keyboard shortcuts (shown beside each entry) or the menu bar change, not at start and not on +/// every frame while a query is typed. +fn entries_in(ctx: &egui::Context, lang: crate::i18n::Lang, native: bool) -> Arc { + type Cached = ((&'static str, u64, u64), bool, Arc); let key = cache_key(lang); let id = egui::Id::unique("palette-entries"); - if let Some((k, v)) = ctx.data(|d| d.get_temp::(id)) + if let Some((k, n, v)) = ctx.data(|d| d.get_temp::(id)) && k == key + && n == native { return v; } - let built: Arc> = Arc::new(build(lang)); - ctx.data_mut(|d| d.insert_temp::(id, (key, built.clone()))); + let built = Arc::new(catalog(lang, native)); + ctx.data_mut(|d| d.insert_temp::(id, (key, native, built.clone()))); built } +/// The entries of [`build_in`] and their index. +fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { + let list = build_in(lang, native); + let shown_homes: Vec> = + list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), crate::i18n::tr(lang, e.menu_item)))).collect(); + let index = search::Index::build(&list, &shown_homes); + Catalog { list, index, ranked: std::sync::Mutex::new(None) } +} + +/// The palette's entries in `lang` with the in-window menu bar. +#[cfg(test)] +fn build(lang: crate::i18n::Lang) -> Vec { + build_in(lang, false) +} + /// The palette's entries in `lang`: [`items`], then one per filter plug-in's Object › Plug-ins /// item (`plugin:`), whose name is not translated, each with a name no result for another id /// shows, in English and in `lang` ([`distinct_names`]). A query still matches the name before -/// it was made distinct. -fn build(lang: crate::i18n::Lang) -> Vec { +/// it was made distinct. Each entry's menu home is read from the native menu bar when `native`. +fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { + let homes = search::menu_homes(native); let mut drafts = drafts(); drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft { translates: false, @@ -322,7 +371,9 @@ fn build(lang: crate::i18n::Lang) -> Vec { haystack.push('\n'); haystack.push_str(&engine.to_lowercase()); } - Entry { id: d.id, shortcut: d.shortcut, shown, haystack } + let (home, menu_item) = homes.get(&d.id).map_or((None, ""), |(path, item)| (Some(path.clone()), *item)); + let kind = search::kind(&d.id, home.as_deref()); + Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind } }) .collect() } @@ -362,19 +413,21 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } -/// Every entry that holds every word of the lowercased query `q`, the ones whose name without its -/// menu path is the query (the Layers panel for "layers") first, each group in catalog order. -/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest. -fn matching<'a>(entries: &'a [Entry], q: &str) -> Vec<&'a Entry> { - let words: Vec<&str> = q.split_whitespace().collect(); - let whole = words.join(" "); - // The plain, English and shown names are the haystack's first three lines. - let named = |e: &Entry| e.haystack.lines().take(3).any(|l| l.rsplit(" › ").next().is_some_and(|n| n.trim_end_matches('…') == whole)); - let mut found: Vec<&Entry> = entries.iter().filter(|e| words.iter().all(|w| e.haystack.contains(w))).collect(); - if !whole.is_empty() { - found.sort_by_key(|e| !named(e)); - } - found +/// The entries the query `q` matches, best first ([`search::rank`]). The ranking of the last query +/// is kept, so a frame that draws the same query does not rank again. [`show`] lists the first +/// [`MAX_RESULTS`] and counts the rest. +fn matching<'a>(catalog: &'a Catalog, q: &str) -> Vec<&'a Entry> { + let q = search::normalize(q); + let kept = catalog.ranked.lock().ok().and_then(|last| last.as_ref().filter(|(k, _)| *k == q).map(|(_, r)| r.clone())); + let ranked = kept.unwrap_or_else(|| { + let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q).into(); + // A poisoned lock only loses the kept ranking: the next frame ranks again. + if let Ok(mut last) = catalog.ranked.lock() { + *last = Some((q, ranked.clone())); + } + ranked + }); + ranked.iter().filter_map(|&i| catalog.list.get(i as usize)).collect() } /// The height of a result row, in points: one line of 13-point body text. @@ -461,8 +514,9 @@ fn nearest_in_view(sel: usize, offset: f32, view: f32, n: usize) -> usize { sel.clamp(first, last) } -/// The highlighted result, the query it belongs to, the list's scroll offset and the list's height. -type Highlight = (usize, String, f32, f32); +/// The highlighted result, the query it belongs to, the list's scroll offset, the list's height +/// and the highlighted result's id. +type Highlight = (usize, String, f32, f32, String); pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette @@ -492,7 +546,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { crate::shortcuts::hold_back_keys(app, ctx); let t = Tokens::get(ctx); let q = app.ui.palette_query.to_lowercase(); - let entries = entries(ctx, crate::i18n::current()); + let entries = entries_in(ctx, crate::i18n::current(), app.services.native_menu.is_some()); let mut matches = matching(&entries, &q); let total = matches.len(); matches.truncate(MAX_RESULTS); @@ -500,12 +554,19 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it // by a page, the pointer over a result takes it, and a new query starts again from the first. let sel_id = egui::Id::unique("palette-selected"); - let (mut sel, last_q, mut offset, last_view) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let (mut sel, last_q, mut offset, last_view, last_id) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); let mut view = last_view; let new_query = last_q != q; + // The highlight stays on its result when the results change under the same query, as when a + // plug-in is installed, a shortcut changes or the language changes; it goes to the first + // result when its result is gone. + let held = sel; if new_query { sel = 0; + } else if matches.get(sel).is_none_or(|e| e.id != last_id) { + sel = matches.iter().position(|e| e.id == last_id).unwrap_or(0); } + let moved = sel != held; let n = matches.len(); let mut moves = Moves::default(); if n > 0 { @@ -569,7 +630,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // `show_rows` adds the item spacing to each row, and rows touch. ui.spacing_mut().item_spacing = egui::Vec2::ZERO; let mut area = egui::ScrollArea::vertical().id_salt("palette-results").max_height(view).auto_shrink([false, true]); - if new_query || moves.any() || resized { + if new_query || moves.any() || resized || moved { offset = offset_showing(sel, if new_query { 0.0 } else { offset }, view); area = area.vertical_scroll_offset(offset); } @@ -639,7 +700,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if sel != drawn { ctx.request_repaint(); } - ctx.data_mut(|d| d.insert_temp::(sel_id, (sel, q, offset, view))); + let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default(); + ctx.data_mut(|d| d.insert_temp::(sel_id, (sel, q, offset, view, sel_key))); if let Some(id) = run { app.ui.palette_open = false; run_pick(app, &id); @@ -1312,7 +1374,7 @@ mod tests { /// leaves it showing rather than hiding it as the Window menu item does. #[test] fn a_panel_is_a_result_whose_pick_shows_it() { - let entries = build(Lang::EN); + let entries = catalog(Lang::EN, false); let panels: Vec<&Entry> = entries.iter().filter(|e| e.id.starts_with("panel:")).collect(); assert_eq!(panels.len(), crate::state::all_panels().count()); // Many results hold "layers" in their menu path; the panel, named Layers, is shown first, and "color guide" shows the Color Guide panel first too. @@ -2078,4 +2140,54 @@ mod tests { assert!(!window.app.ui.palette_open); assert!(crate::panel_docking::showing(&window.app.ui, &panel), "{panel}: {}", window.app.ui.status); } + + /// The entries and their index are built when the palette first opens, not before. + #[test] + fn the_search_index_is_built_when_the_palette_opens() { + type Cached = ((&'static str, u64, u64), bool, Arc); + let built = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(egui::Id::unique("palette-entries"))).is_some(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui.ctx())).textures_delta.clear(); + }; + frame(&mut app); + assert!(!built(&ctx), "nothing is built while the palette is closed"); + app.ui.palette_open = true; + frame(&mut app); + assert!(built(&ctx)); + } + + /// The highlight stays on its result when the results change under the same query: when a + /// plug-in whose name ranks above it is installed, a shortcut changes, or the language + /// changes. + #[test] + fn the_highlight_stays_on_its_result_when_the_results_change() { + use vectorcraft_plugins::wat as tpl; + let mut open = Open::new("group", WINDOW); + open.press(egui::Key::ArrowDown, 3); + let held = |open: &Open| open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap(); + let id = held(&open).4; + assert_eq!(open.listed().get(3), Some(&id)); + let filter = "test.UI.palette_highlight-group"; + let manifest = format!(r#"{{"id":"{filter}","name":"Group","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + open.frame(vec![]); + let listed = open.listed(); + let plugin = listed.iter().position(|r| *r == format!("plugin:{filter}")); + vectorcraft_plugins::registry::remove(filter); + assert!(plugin.is_some_and(|p| p < 3), "the plug-in ranks above the highlight: {listed:?}"); + let (sel, .., now) = held(&open); + assert_eq!((listed.get(sel), &now), (Some(&id), &id), "after the plug-in was installed"); + crate::shortcut_editor::GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + open.frame(vec![]); + assert_eq!(held(&open).4, id, "after a shortcut changed"); + crate::i18n::set_current(Lang::from_code("de").unwrap()); + open.frame(vec![]); + let (sel, .., now) = held(&open); + let de = entries(&open.ctx, Lang::from_code("de").unwrap()); + let de_listed: Vec = matching(&de, "group").iter().map(|e| e.id.clone()).collect(); + crate::i18n::set_current(Lang::EN); + assert_eq!((de_listed.get(sel), &now), (Some(&id), &id), "after the language changed"); + } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs new file mode 100644 index 0000000000..6889b54992 --- /dev/null +++ b/crates/ui-egui/src/palette/search.rs @@ -0,0 +1,705 @@ +//! The command palette's search: a small index of the words in each result's label, menu path and +//! id, the menu bar's home of each result, and the ranking of the results a query matches. + +use std::collections::HashMap; + +use super::{Entry, WRAPPED}; +use crate::menus; + +/// The most characters of a query the index reads (VectorCraft's own limit). The substring rule +/// and the exact tiers read the whole query. +const INDEX_CHARS: usize = 200; + +/// The field of a result a word comes from, best first. +const LABEL: u8 = 0; +const PATH: u8 = 1; +const ID: u8 = 2; + +/// A word's grade in a result, best first: a whole word of the label, a word of the label it +/// starts, a word of the menu path it is or starts, a word of the id it is or starts, or text +/// inside a word of any field ([`super::matching`]'s substring rule). +const LABEL_WORD: u8 = 1; +const LABEL_PREFIX: u8 = 2; +const PATH_WORD: u8 = 3; +const ID_WORD: u8 = 4; +const SUBSTRING: u8 = 5; +const NONE: u8 = u8::MAX; + +/// How a whole query matches a result, best first: it is the result's id, it is a label, a label +/// starts with it, or it is the initials of a label. +const EXACT_ID: u8 = 0; +const EXACT_LABEL: u8 = 1; +const PREFIX: u8 = 2; +const INITIALS: u8 = 3; +const NO_PHRASE: u8 = 4; + +/// One result in the list of a term: the result's place in the catalog and the field the term is +/// a word of. +#[derive(Clone, Copy)] +struct Posting { + entry: u16, + field: u8, +} + +/// The words of every result, each distinct word stored once. +#[derive(Default)] +pub(crate) struct Index { + /// Every distinct word, one after another. + term_text: String, + /// Each word's offset and length in `term_text`, sorted by the word's text. + terms: Vec<(u32, u32)>, + /// Each word's first posting and number of postings in `postings`, in the order of `terms`. + spans: Vec<(u32, u32)>, + postings: Vec, + /// The initials of each result's labels, one line per label. + initials_text: String, + /// Each result's offset and length in `initials_text`. + initials: Vec<(u32, u16)>, +} + +/// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,` +/// and `:`. +fn words(text: &str) -> impl Iterator { + text.split(|c: char| c.is_whitespace() || matches!(c, '.' | '-' | '/' | '(' | ')' | '…' | '›' | ',' | ':')).filter(|w| !w.is_empty()) +} + +/// The first letter of each word of `label`, words split at whitespace and at `-`, `/`, `(` and +/// `›`, lowercased. +fn initials_of(label: &str) -> String { + label + .split(|c: char| c.is_whitespace() || matches!(c, '-' | '/' | '(' | '›')) + .filter_map(|w| w.chars().find(|c| c.is_alphanumeric())) + .flat_map(char::to_lowercase) + .collect() +} + +/// A name's last `›`-separated part (the label) and the parts before it (the menu path). +fn split_name(name: &str) -> (&str, &str) { + match name.rsplit_once(" › ") { + Some((path, label)) => (label, path), + None => (name, ""), + } +} + +/// `name` without the id that follows it when the result shows its id. +fn without_id<'a>(name: &'a str, id: &str) -> &'a str { + name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name) +} + +/// The lowercased names a result is found by: the plain English name, the English name and the +/// shown name ([`super::build`]'s haystack lines). +fn names(e: &Entry) -> impl Iterator { + e.haystack.lines().take(3) +} + +/// The lowercased ids a result is found by: its own, and the engine command's a UI command wraps. +fn ids(e: &Entry) -> impl Iterator { + e.haystack.lines().skip(3) +} + +impl Index { + /// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The + /// words of a result's menu home and of its menu item's label count as menu path words. A + /// catalog with more results than a posting can name gets an empty index, and queries match by + /// the substring rule alone. + pub(crate) fn build(entries: &[Entry], homes: &[Option]) -> Index { + if entries.len() > usize::from(u16::MAX) { + return Index::default(); + } + let mut found: Vec<(String, u16, u8)> = vec![]; + let mut initials_text = String::new(); + let mut initials = Vec::with_capacity(entries.len()); + for (i, e) in entries.iter().enumerate() { + let Ok(entry) = u16::try_from(i) else { break }; + let id = ids(e).next().unwrap_or_default(); + let start = initials_text.len(); + let mut seen_initials: Vec = vec![]; + for name in names(e) { + let (label, path) = split_name(without_id(name, id)); + found.extend(words(label).map(|w| (w.to_string(), entry, LABEL))); + found.extend(words(path).map(|w| (w.to_string(), entry, PATH))); + let ini = initials_of(label); + if ini.chars().count() >= 2 && !seen_initials.contains(&ini) { + if !seen_initials.is_empty() { + initials_text.push('\n'); + } + initials_text.push_str(&ini); + seen_initials.push(ini); + } + } + for home in [e.home.as_deref(), Some(e.menu_item), homes.get(i).and_then(Option::as_deref)].into_iter().flatten() { + found.extend(words(&home.to_lowercase()).map(|w| (w.to_string(), entry, PATH))); + } + for id in ids(e) { + found.extend(words(id).map(|w| (w.to_string(), entry, ID))); + } + let len = u16::try_from(initials_text.len() - start).unwrap_or(0); + initials.push((u32::try_from(start).unwrap_or(0), len)); + } + found.sort_unstable(); + found.dedup(); + let mut index = Index { initials_text, initials, ..Index::default() }; + let mut last: Option<&str> = None; + for (word, entry, field) in &found { + if last != Some(word.as_str()) { + let (Ok(offset), Ok(len), Ok(start)) = + (u32::try_from(index.term_text.len()), u32::try_from(word.len()), u32::try_from(index.postings.len())) + else { + return Index::default(); + }; + index.term_text.push_str(word); + index.terms.push((offset, len)); + index.spans.push((start, 0)); + last = Some(word.as_str()); + } + index.postings.push(Posting { entry: *entry, field: *field }); + if let Some(span) = index.spans.last_mut() { + span.1 += 1; + } + } + index.term_text.shrink_to_fit(); + index.terms.shrink_to_fit(); + index.spans.shrink_to_fit(); + index.postings.shrink_to_fit(); + index.initials_text.shrink_to_fit(); + index.initials.shrink_to_fit(); + index + } + + /// The bytes the index holds. + #[cfg(test)] + pub(crate) fn bytes(&self) -> usize { + self.term_text.capacity() + + self.terms.capacity() * std::mem::size_of::<(u32, u32)>() + + self.spans.capacity() * std::mem::size_of::<(u32, u32)>() + + self.postings.capacity() * std::mem::size_of::() + + self.initials_text.capacity() + + self.initials.capacity() * std::mem::size_of::<(u32, u16)>() + } + + /// The text of the word at `(offset, len)` in `term_text`. + fn text(&self, &(offset, len): &(u32, u32)) -> &str { + let offset = offset as usize; + self.term_text.get(offset..offset + len as usize).unwrap_or_default() + } + + /// The best grade (1 to 4) `word` gets in each result, [`NONE`] where it is no word and starts + /// no word of the result. The words it starts are found by a binary search of the sorted words. + fn grades(&self, word: &str, n: usize) -> Vec { + let mut out = vec![NONE; n]; + let start = self.terms.partition_point(|t| self.text(t) < word); + for (t, at) in self.terms.iter().enumerate().skip(start) { + let term = self.text(at); + if !term.starts_with(word) { + break; + } + let whole = term == word; + let Some(&(begin, len)) = self.spans.get(t) else { continue }; + let (begin, len) = (begin as usize, len as usize); + for p in self.postings.get(begin..begin + len).unwrap_or_default() { + let grade = match p.field { + LABEL if whole => LABEL_WORD, + LABEL => LABEL_PREFIX, + PATH => PATH_WORD, + _ => ID_WORD, + }; + if let Some(g) = out.get_mut(usize::from(p.entry)) { + *g = (*g).min(grade); + } + } + } + out + } + + /// Is `query` (no spaces) the initials of one of result `i`'s labels? + fn initials_are(&self, i: usize, query: &str) -> bool { + let Some(&(offset, len)) = self.initials.get(i) else { return false }; + let (offset, len) = (offset as usize, usize::from(len)); + self.initials_text.get(offset..offset + len).is_some_and(|text| text.lines().any(|l| l == query)) + } +} + +/// `query` trimmed, lowercased, with each run of whitespace made one space. +pub(crate) fn normalize(query: &str) -> String { + query.split_whitespace().collect::>().join(" ").to_lowercase() +} + +/// The order of a result's kind when everything else ties: a tool, a command of the menu bar, a +/// panel, an effect, a filter plug-in, then a command with no item in the menu bar. +pub(crate) fn kind(id: &str, home: Option<&str>) -> u8 { + match id.split_once(':').map(|(k, _)| k) { + Some("tool") => 0, + Some("panel") => 2, + Some("effect") => 3, + Some("plugin") => 4, + _ if home.is_some() => 1, + _ => 5, + } +} + +/// How the whole lowercased `query` matches result `e` ([`EXACT_ID`] to [`NO_PHRASE`]), where +/// `initials` says whether the query is the initials of one of its labels. +fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { + if ids(e).any(|id| id == query) { + return EXACT_ID; + } + let trimmed = query.trim_end_matches('…'); + let labels = || names(e).flat_map(|n| [n, split_name(n).0]); + if labels().any(|l| l == query || l.trim_end_matches('…') == trimmed) { + return EXACT_LABEL; + } + if labels().any(|l| l.starts_with(query)) { + return PREFIX; + } + if initials { + return INITIALS; + } + NO_PHRASE +} + +/// What results are ordered by, compared field by field: how the whole query matches, the worst +/// grade a word gets, the sum of the grades, the kind of result and the label's length. +type RankKey = (u8, u8, u32, u8, usize); + +/// The results of `entries` that the lowercased `query` matches, best first, as places in +/// `entries`. A result matches when every word of the query is text in one of its names or ids +/// (the rule the palette always had, so nothing it found is lost), when every word of the query is +/// or starts a word of its label, menu path or id, or when the query is the initials of a label +/// ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), then by +/// the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the label's +/// length and the catalog order. An empty query lists every result in catalog order. +pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { + let query = normalize(query); + if query.is_empty() { + return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect(); + } + let spaced: Vec<&str> = query.split(' ').collect(); + let head: String = query.chars().take(INDEX_CHARS).collect(); + let tokens: Vec<&str> = words(&head).collect(); + let n = entries.len(); + let indexed: Vec> = tokens.iter().map(|t| index.grades(t, n)).collect(); + // The index reads only the start of a longer query, so such a query matches by the substring + // rule, which reads all of it. + let fits = query.chars().count() <= INDEX_CHARS; + let packed: String = query.chars().filter(|c| !c.is_whitespace()).collect(); + let packed = Some(packed).filter(|p| (2..=6).contains(&p.chars().count()) && p.chars().all(char::is_alphabetic)); + let mut ranked: Vec<(RankKey, u32)> = vec![]; + for (i, e) in entries.iter().enumerate() { + let Ok(place) = u32::try_from(i) else { break }; + let substring = spaced.iter().all(|w| e.haystack.contains(w)); + let initials = packed.as_deref().is_some_and(|p| index.initials_are(i, p)); + // Each word's grade, the worst and their sum; with initials, every word counts as a word + // the label starts, as the initials stand for every word of the label. + let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32); + for (grades, token) in indexed.iter().zip(&tokens) { + let mut g = grades.get(i).copied().unwrap_or(NONE); + if g == NONE { + all_indexed = false; + if e.haystack.contains(token) { + g = SUBSTRING; + } + } + let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) }; + worst = worst.max(g); + sum += u32::from(g); + } + if !(substring || all_indexed || initials) { + continue; + } + let tier = phrase(e, &query, initials); + let length = split_name(&e.shown).0.chars().count(); + ranked.push(((tier, worst, sum, e.kind, length), place)); + } + ranked.sort_by_key(|&(key, place)| (key, place)); + ranked.into_iter().map(|(_, place)| place).collect() +} + +/// The first place in the menu bar of each item a result runs, as an English `›`-separated path +/// of the menus that hold it: by command id, `panel:` for a Window menu panel (Learn too), +/// `effect:` for an Effect menu item and `plugin:` for an Object › Plug-ins filter. With +/// the native Mac menu bar (`native`), About, Preferences (under Settings), Language, Appearance +/// and Quit are in the application menu, which comes first, as `native_menu::mac_layout` puts +/// them. The in-window menu bar shows no application menu. Each home comes with the English label +/// of its item (File › Exit for Quit VectorCraft), empty for the application menu's items. +pub(crate) fn menu_homes(native: bool) -> HashMap { + fn key(id: &str, p: &serde_json::Value) -> String { + let field = |k: &str| p.get(k).and_then(serde_json::Value::as_str); + match (id, field("panel"), field("effect"), field("id")) { + ("window.panel", Some(panel), ..) => format!("panel:{panel}"), + ("window.learn", ..) => format!("panel:{}", crate::panels::learn::ID), + ("effect.dialog" | "effect.apply", _, Some(effect), _) => format!("effect:{effect}"), + ("plugin.dialog", _, _, Some(filter)) => format!("plugin:{filter}"), + _ => WRAPPED.iter().find(|(engine, _)| *engine == id).map_or(id, |(_, ui)| ui).to_string(), + } + } + fn walk(items: &[menus::Item], path: &mut Vec<&'static str>, skip: &[&str], out: &mut HashMap) { + for it in items { + match it { + menus::Item::Cmd(label, id, p) if !skip.contains(id) => { + out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label)); + } + menus::Item::Sub(name, children) => { + path.push(name); + walk(children, path, skip, out); + path.pop(); + } + _ => {} + } + } + } + let mut out = HashMap::new(); + let app_menu: &[(&str, &str)] = + &[("help.about", ""), ("edit.preferences", "Settings"), ("app.language", "Language"), ("window.brightness", "Appearance"), ("app.quit", "")]; + let skip: Vec<&str> = if native { app_menu.iter().map(|(id, _)| *id).collect() } else { vec![] }; + if native { + for (id, sub) in app_menu { + let path = if sub.is_empty() { crate::native_menu::APP_NAME.to_string() } else { format!("{} › {sub}", crate::native_menu::APP_NAME) }; + out.insert((*id).to_string(), (path, "")); + } + } + // The tree's first menu is the application menu, which the in-window bar never shows and + // the native bar builds itself. + for (name, items) in menus::menu_tree().into_iter().skip(1) { + walk(&items, &mut vec![name], &skip, &mut out); + } + out +} + +#[cfg(test)] +mod tests { + use super::super::{Catalog, catalog}; + use super::*; + use crate::i18n::Lang; + + /// The ids of the results `query` lists, best first. + fn ranked(c: &Catalog, query: &str) -> Vec { + rank(&c.list, &c.index, query).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect() + } + + /// A result named `name` (`›`-separated, its last part the label) with id `id`. + fn entry(name: &str, id: &str) -> Entry { + let home = None; + Entry { + id: id.to_string(), + shortcut: String::new(), + shown: name.to_string(), + haystack: [name, name, name, id].map(str::to_lowercase).join("\n"), + kind: kind(id, home.as_deref()), + home, + menu_item: "", + } + } + + /// `entries` with their index. + fn synthetic(entries: Vec) -> Catalog { + let index = Index::build(&entries, &[]); + Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } + } + + /// Where `id` is among the results of `query`. + fn place(c: &Catalog, query: &str, id: &str) -> Option { + ranked(c, query).iter().position(|r| r == id) + } + + /// For each pair of adjacent word grades, a result where the word gets the better grade ranks + /// above one where it gets the worse, and both are listed. The second word of each query is a + /// whole word of every label, so no whole-query tier applies. + #[test] + fn a_better_word_grade_ranks_first() { + for (query, better, worse) in [ + // A whole word of the label, then a word of the label it starts. + ("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two")), + // A word of the label it starts, then a word of the menu path. + ("fill zz", entry("Zz Filling", "a.one"), entry("Fill › Zz Other", "b.two")), + // A word of the menu path, then a word of the id. + ("zap zz", entry("Zap › Zz One", "a.one"), entry("Zz Two", "zap.two")), + // A word of the id, then text inside a word. + ("zip zz", entry("Zz Three", "zip.three"), entry("Zz Unzipped", "b.two")), + ] { + let (b, w) = (better.id.clone(), worse.id.clone()); + // The worse one comes first in the catalog, so only the grade puts the better first. + let c = synthetic(vec![worse, better]); + assert_eq!(ranked(&c, query), [b, w], "{query}"); + } + } + + /// For each pair of adjacent whole-query tiers, a result in the better tier ranks above one in + /// the worse. + #[test] + fn a_better_whole_query_tier_ranks_first() { + for (query, better, worse) in [ + // The query is the result's id, then it is a label. + ("zz.one", entry("Alpha", "zz.one"), entry("zz.one", "b.two")), + // The query is a label, then a label starts with it. + ("snap", entry("Snap", "a.one"), entry("Snapshot", "b.two")), + // A label starts with the query, then the query is a label's initials. + ("ab", entry("Abacus", "a.one"), entry("Alpha Beta", "b.two")), + // The query is a label's initials, then a whole word of a label that it does not start. + ("gb", entry("Green Blue", "a.one"), entry("Zz Gb", "b.two")), + ] { + let (b, w) = (better.id.clone(), worse.id.clone()); + let c = synthetic(vec![worse, better]); + assert_eq!(ranked(&c, query), [b, w], "{query}"); + } + } + + /// The kind of result and the label's length order results only when the grades tie: a tool + /// with a short label stays below a command whose label holds the word whole. Ties keep the + /// catalog order, the same on every ranking. + #[test] + fn kind_and_length_never_lift_a_worse_grade() { + let c = synthetic(vec![entry("Zz Cutx", "tool:cutx"), entry("Zz Cut With a Much Longer Label", "a.one")]); + assert_eq!(ranked(&c, "cut zz"), ["a.one", "tool:cutx"]); + let c = synthetic(vec![entry("Zz Cut Long Label", "a.one"), entry("Zz Cut Long", "b.two"), entry("Zz Cut", "tool:cut")]); + assert_eq!(ranked(&c, "cut zz"), ["tool:cut", "b.two", "a.one"], "the tool first, then the shorter label"); + let c = synthetic(vec![entry("Zz Same", "a.one"), entry("Zz Same", "b.two"), entry("Zz Same", "c.three")]); + assert_eq!(ranked(&c, "same zz"), ["a.one", "b.two", "c.three"]); + assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz")); + } + + /// Queries from the list of things people type, on the English results. + #[test] + fn common_queries_list_the_command_first() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n); + assert_eq!(first("ea"), "file.exportAs", "the initials of Export As…"); + assert_eq!(first("save"), "file.save"); + assert!(within("export", "file.exportAs", 3)); + assert_eq!(first("rect"), "tool:rectangle"); + let (tool, effect) = (place(&c, "rect", "tool:rectangle"), place(&c, "rect", "effect:convertToShape.rectangle")); + assert!(effect.is_some() && tool < effect, "{tool:?} {effect:?}"); + assert!(within("type", "tool:type", 2)); + assert!(within("layers", "panel:layers", 3)); + assert!(first("drop shadow").starts_with("effect:"), "{}", first("drop shadow")); + assert_eq!(first("view.goto1"), "view.goto1", "the whole id, above Saved View 10"); + assert_eq!(first("bring front"), "object.arrange.bringToFront"); + assert!(within("ruler", "view.rulers", 4)); + assert!(place(&c, "ruler", "perspective.grid.rulers").is_some()); + assert_eq!(first("deselect"), "select.none"); + let mut blurs: Vec = ranked(&c, "blur").into_iter().take(3).collect(); + blurs.sort(); + assert_eq!(blurs, ["effect:blur.gaussian", "effect:blur.radial", "effect:blur.smart"]); + assert!(ranked(&c, "zzzz").is_empty()); + // English names are searched in every language. + let zh = catalog(Lang::from_code("zh-hant").unwrap(), false); + for q in ["save", "rect"] { + assert_eq!(ranked(&zh, q).first(), ranked(&c, q).first(), "{q}"); + } + } + + /// What the palette always matched: every word of the query is text in one of the result's + /// names or ids. + fn substring_rule<'a>(c: &'a Catalog, query: &str) -> Vec<&'a str> { + let q = normalize(query); + c.list.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).map(|e| e.id.as_str()).collect() + } + + /// Each result's English name, shown name (in English, German and Chinese, Traditional) and id + /// find it, first unless another result has that name; its id always lists it first. + #[test] + fn every_result_is_found_first_by_its_name_and_its_id() { + for code in ["en", "de", "zh-hant"] { + let c = catalog(Lang::from_code(code).unwrap(), false); + let label = |n: &str| split_name(n).0.trim_end_matches('…').to_string(); + for e in &c.list { + let english = e.haystack.lines().nth(1).unwrap_or_default(); + for query in [english, &e.shown] { + let results = ranked(&c, query); + assert!(results.contains(&e.id), "{code}: {query} finds {}", e.id); + let q = normalize(query); + let named = c.list.iter().filter(|o| names(o).any(|n| n == q || label(n) == label(&q))).count(); + if named <= 1 { + assert_eq!(results.first(), Some(&e.id), "{code}: {query}"); + } + } + assert_eq!(ranked(&c, &e.id).first(), Some(&e.id), "{code}: {}", e.id); + } + } + } + + /// The queries the palette's tests use and a list of things people type. + const QUERIES: &[&str] = &[ + "select", + "zoom", + "zoom in", + "show panel", + "group", + "layers", + "color guide", + "drop shadow", + "use precise cursors", + "continue in background", + "export continue in background", + "show rulers", + "delete selection", + "cancel key object", + "fit headline", + "batch", + "flattener preview", + "panel options", + "close path", + "knife", + "play action", + "reset panel", + "other library", + "ellipse", + "blur", + "save", + "export", + "rect", + "type", + "ea", + "bring front", + "ruler", + "deselect", + "view.goto1", + "zzzz", + "pen", + "outlines", + "join paths", + "rounded corners", + "scaling", + "rotated", + "eyedroper", + "rectange", + "elipse", + "gruop", + "remove bg", + "outline text", + "flip", + "combine", + "vectorize", + "colour", + "transparent background", + "png", + "object.group", + "file.exportinbackground", + "window", + "s", + "e", + "…", + "› ", + ]; + + /// For each query, every result the palette found before is still found, and when it found 50 + /// or fewer, each of them is among the first 50 results, so the list still shows it. + #[test] + fn every_result_found_before_is_still_found_and_shown() { + assert_eq!(QUERIES.len(), 60); + let c = catalog(Lang::EN, false); + for q in QUERIES { + let before = substring_rule(&c, q); + let now = ranked(&c, q); + for id in &before { + let at = now.iter().position(|r| r == id); + assert!(at.is_some(), "{q}: {id} is still found"); + if before.len() <= super::super::MAX_RESULTS { + assert!(at < Some(super::super::MAX_RESULTS), "{q}: {id} is shown at {at:?}"); + } + } + } + } + + /// A query longer than the index reads still has to match in full: two labels that share their + /// first 200 characters are told apart by the rest. + #[test] + fn a_long_query_matches_in_full() { + let shared = "a".repeat(200); + let c = synthetic(vec![entry(&format!("{shared}b tail"), "a.one"), entry(&format!("{shared}c tail"), "b.two")]); + let query = format!("{shared}b"); + assert_eq!(substring_rule(&c, &query), ["a.one"]); + assert_eq!(ranked(&c, &query), ["a.one"]); + } + + /// Text in scripts without spaces, right-to-left text, combining characters, a very long pasted + /// query, punctuation alone and names that differ only in the id they show. + #[test] + fn unusual_text_is_searched_safely() { + let c = synthetic(vec![entry("物件 › 群組", "a.one"), entry("مرحبا عالم", "b.two"), entry("Cafe\u{301} Tool", "c.three")]); + assert_eq!(ranked(&c, "群組"), ["a.one"]); + assert_eq!(ranked(&c, "عالم"), ["b.two"]); + assert_eq!(ranked(&c, "cafe\u{301}"), ["c.three"]); + assert!(ranked(&c, &"x".repeat(5000)).is_empty()); + assert!(ranked(&c, &"群".repeat(5000)).is_empty()); + assert_eq!(ranked(&c, "›"), ["a.one"]); + assert!(ranked(&c, "…,.-").is_empty()); + let en = catalog(Lang::EN, false); + let both = ranked(&en, "fit headline"); + assert!(both.contains(&"type.fitHeadline".to_string()) && both.contains(&"text.fitHeadline".to_string()), "{both:?}"); + for id in ["type.fitHeadline", "text.fitHeadline"] { + assert_eq!(ranked(&en, &format!("Type › Fit Headline ({id})")).first().map(String::as_str), Some(id)); + } + let zh = Lang::from_code("zh-hant").unwrap(); + let zh_catalog = catalog(zh, false); + let group = crate::i18n::tr(zh, "Group"); + assert!(place(&zh_catalog, group, "object.group").is_some_and(|p| p < 3), "{group}"); + } + + /// Each result's home is the first item of the menu bar that runs it: an Effect menu item's + /// submenu, the Window menu for a panel whose item shows and hides it, Learn's own item, and + /// with the native Mac menu bar Preferences under the application menu's Settings. + #[test] + fn results_know_their_place_in_the_menu_bar() { + let homes = menu_homes(false); + let home = |id: &str| homes.get(id).map(|(path, _)| path.as_str()); + assert_eq!(home("effect:stylize.roundCorners"), Some("Effect › Stylize")); + assert_eq!(home("panel:layers"), Some("Window"), "matched by the panel, although the item also asks to toggle it"); + assert_eq!(home("panel:learn"), Some("Window")); + assert_eq!(home("panel:character"), Some("Window › Type")); + assert_eq!(home("edit.preferences"), Some("Edit")); + assert_eq!(home("help.about"), Some("Help"), "the in-window bar shows no application menu"); + assert_eq!(home("ui.layersPanelOptions"), None); + assert_eq!(homes.get("app.quit"), Some(&("File".to_string(), "Exit")), "with its item's own label"); + let native = menu_homes(true); + let native_home = |id: &str| native.get(id).map(|(path, _)| path.as_str()); + assert_eq!(native_home("edit.preferences"), Some("VectorCraft › Settings")); + assert_eq!(native_home("help.about"), Some("VectorCraft")); + assert_eq!(native_home("help.discord"), Some("Help")); + let c = catalog(Lang::EN, false); + let of = |id: &str| c.list.iter().find(|e| e.id == id).and_then(|e| e.home.clone()); + assert_eq!(of("effect:stylize.roundCorners").as_deref(), Some("Effect › Stylize")); + assert_eq!(of("tool:pen"), None); + // The home's words find the result: Preferences… under the native bar's Settings. + let native_catalog = catalog(Lang::EN, true); + assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some()); + assert!(place(&c, "settings pref", "edit.preferences").is_none()); + // The menu item's own label finds the result too: File › Exit runs Quit VectorCraft. + assert!(place(&c, "exit", "app.quit").is_some()); + } + + /// The index of the real results takes at most 512 KiB, homes included. + #[test] + fn the_index_stays_small() { + let c = catalog(Lang::EN, false); + let homes: usize = c.list.iter().filter_map(|e| e.home.as_ref()).map(String::capacity).sum(); + let bytes = c.index.bytes() + homes; + println!("{} results, index {} bytes, homes {homes} bytes", c.list.len(), c.index.bytes()); + assert!(bytes <= 512 * 1024, "{bytes}"); + } + + #[test] + #[ignore = "times the index and sample queries; run in a release build"] + fn time_the_index_and_queries() { + let started = std::time::Instant::now(); + let c = catalog(Lang::EN, false); + let built = started.elapsed(); + let started = std::time::Instant::now(); + let index = Index::build(&c.list, &[]); + println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes()); + let long = "q".repeat(200); + for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] { + let started = std::time::Instant::now(); + let runs = 100; + for _ in 0..runs { + std::hint::black_box(rank(&c.list, &c.index, q)); + } + println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs); + } + let started = std::time::Instant::now(); + for _ in 0..100 { + std::hint::black_box(substring_rule(&c, "bring front")); + } + println!("substring rule alone: {:?} per query", started.elapsed() / 100); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fbca583b89..8f8c9611be 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1256,6 +1256,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). + The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, and a shorter name above a longer one, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs), read from the native menu bar when the app uses it. Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `common_queries_list_the_command_first`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From eacf48e1f78dd59a6fc63916d8c77dc42716852f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:51:25 -0800 Subject: [PATCH 08/29] Command Palette: a menu's title no longer lifts every item in that menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A query that is a menu's title ("object", "effect", "select") put every item of that menu in the starts-with tier, because the tier also read each name with its menu path. Such items now rank by the word grades like the rest, below results whose label holds the query as a word. A query that holds `›` still starts a name with its menu path. - A new test checks that the native Mac menu bar's application menu holds the items the palette places there, under the same submenus. - The Drop Shadow query checks the exact effect, and the test of common queries is renamed to say that some only need to be near the top. - docs/target-app-parity.md: the earlier palette line no longer states the old ranking rule, and the new line gives the kind of result as the reason "rect" lists the Rectangle Tool first. --- crates/ui-egui/src/palette/search.rs | 69 ++++++++++++++++++++++++++-- docs/target-app-parity.md | 4 +- 2 files changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 6889b54992..a2bc113d4a 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -238,7 +238,8 @@ pub(crate) fn kind(id: &str, home: Option<&str>) -> u8 { } /// How the whole lowercased `query` matches result `e` ([`EXACT_ID`] to [`NO_PHRASE`]), where -/// `initials` says whether the query is the initials of one of its labels. +/// `initials` says whether the query is the initials of one of its labels. A query starts a name +/// when it starts the name's label, or, for a query that holds `›`, the name with its menu path. fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { if ids(e).any(|id| id == query) { return EXACT_ID; @@ -248,7 +249,9 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { if labels().any(|l| l == query || l.trim_end_matches('…') == trimmed) { return EXACT_LABEL; } - if labels().any(|l| l.starts_with(query)) { + // A menu's title alone does not put the items of that menu in this tier. + let with_path = query.contains('›'); + if names(e).any(|n| split_name(n).0.starts_with(query) || (with_path && n.starts_with(query))) { return PREFIX; } if initials { @@ -457,9 +460,65 @@ mod tests { assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz")); } - /// Queries from the list of things people type, on the English results. + /// A query that is a menu's title ranks a result whose label holds it as a word above the items + /// of that menu, which match only by their menu path. A query that names the menu with `›` + /// still starts the item's name. #[test] - fn common_queries_list_the_command_first() { + fn a_menu_title_does_not_lift_its_items() { + let c = synthetic(vec![entry("Object › Paint", "a.one"), entry("Outline Object", "b.two")]); + assert_eq!(ranked(&c, "object"), ["b.two", "a.one"]); + assert_eq!(ranked(&c, "object › pa"), ["a.one"]); + let en = catalog(Lang::EN, false); + for q in ["object", "effect", "select", "view", "type", "edit"] { + let first = rank(&en.list, &en.index, q).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase()); + let label = first.as_deref().map(|n| split_name(n).0.to_string()).unwrap_or_default(); + assert!(words(&label).any(|w| w.starts_with(q)), "{q}: {first:?}"); + } + } + + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, + /// under the same submenus. + #[test] + fn native_homes_follow_the_native_application_menu() { + use crate::native_menu::{self, MenuRole, Node}; + fn walk(nodes: &[Node], path: &mut Vec, out: &mut HashMap) { + for n in nodes { + match n { + Node::Item(it) => { + if let Some(id) = it.command { + out.entry(id.to_string()).or_insert_with(|| path.join(" › ")); + } + } + Node::Submenu { label, children } => { + path.push(label.clone()); + walk(children, path, out); + path.pop(); + } + _ => {} + } + } + } + let app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let bar = native_menu::mac_layout(&app, &native_menu::from_tree(&app, &menus::menu_tree()), Lang::EN).bar; + let app_menu = bar.menus.iter().find(|m| m.role == MenuRole::App).unwrap(); + let mut found = HashMap::new(); + walk(&app_menu.children, &mut vec![app_menu.title.clone()], &mut found); + // The items the native bar runs itself (Hide, Hide Others, Minimize) are not palette results. + found.retain(|id, _| ![native_menu::HIDE, native_menu::HIDE_OTHERS, native_menu::MINIMIZE].contains(&id.as_str())); + let homes = menu_homes(true); + let expected: HashMap = homes + .iter() + .filter(|(_, (path, _))| path.split(" › ").next() == Some(native_menu::APP_NAME)) + .map(|(id, (path, _))| (id.clone(), path.clone())) + .collect(); + assert!(!expected.is_empty()); + assert_eq!(found, expected); + } + + /// Queries from the list of things people type, on the English results: some list their command + /// first, others within the first few results. + #[test] + fn common_queries_list_the_command_near_the_top() { let c = catalog(Lang::EN, false); let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n); @@ -471,7 +530,7 @@ mod tests { assert!(effect.is_some() && tool < effect, "{tool:?} {effect:?}"); assert!(within("type", "tool:type", 2)); assert!(within("layers", "panel:layers", 3)); - assert!(first("drop shadow").starts_with("effect:"), "{}", first("drop shadow")); + assert_eq!(first("drop shadow"), "effect:stylize.dropShadow"); assert_eq!(first("view.goto1"), "view.goto1", "the whole id, above Saved View 10"); assert_eq!(first("bring front"), "object.arrange.bringToFront"); assert!(within("ruler", "view.rulers", 4)); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8f8c9611be..25944ab8d9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1253,10 +1253,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`). The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`). No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`). - The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. Results whose name without its menu path is the whole query come first, so "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). + The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. A query of "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). - The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, and a shorter name above a longer one, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs), read from the native menu bar when the app uses it. Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `common_queries_list_the_command_first`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). + The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From fbed80b2f891785622ea72ae213011078877ac97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:59:22 -0800 Subject: [PATCH 09/29] Command Palette: the highlighted result stays shown when a new result ranks above it When the results change under the same query and a new result pushes the highlighted one past the 50 shown results, the highlighted result now takes the last shown row, so Enter still runs it. Screen readers hear its place among every match. The saved view and saved selection catalog check also rejects two rows of one language that show the same name, also when the name holds no ASCII digits. --- crates/ui-egui/src/i18n/tests.rs | 8 +++-- crates/ui-egui/src/palette.rs | 59 ++++++++++++++++++++++++++++---- 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 4311da82fd..834be07550 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -434,13 +434,14 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } -/// Each catalog's Saved View N and Saved Selection N rows carry the number N, so no two saved views -/// or saved selections show one name. +/// Each catalog's Saved View N and Saved Selection N rows carry the number N, and no two of a +/// catalog's saved views or saved selections show one name, whatever digits the language uses. #[test] fn numbered_saved_views_and_selections_keep_their_number() { let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) { for kind in ["Saved View", "Saved Selection"] { + let mut seen = std::collections::HashMap::new(); for n in 1..=25 { let source = format!("{kind} {n}"); let Some(row) = lang.catalog().plain(&source) else { continue }; @@ -448,6 +449,9 @@ fn numbered_saved_views_and_selections_keep_their_number() { if !numbers.is_empty() && numbers != [n.to_string().as_str()] { bad.push(format!("{}: {source} -> {row}", lang.code)); } + if let Some(earlier) = seen.insert(row, source.clone()) { + bad.push(format!("{}: {earlier} and {source} both show {row}", lang.code)); + } } } } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 67bd572f39..9928837ebf 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -588,6 +588,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let entries = entries_in(ctx, crate::i18n::current(), app.services.native_menu.is_some()); let mut matches = matching(&entries, &q); let total = matches.len(); + // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it + // by a page, the pointer over a result takes it, and a new query starts again from the first. + let sel_id = egui::Id::unique("palette-selected"); + let (mut sel, last_q, mut offset, last_view, last_id) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); + let mut view = last_view; + let new_query = last_q != q; + // A result that ranks above the highlighted one when the results change under the same query + // can push it past the last shown result; it then takes the last shown row instead, and + // `kept` holds its place among every match. + let mut kept = None; + if !new_query + && let Some(at) = matches.iter().position(|e| e.id == last_id) + && at >= MAX_RESULTS + { + let held_result = matches.remove(at); + matches.truncate(MAX_RESULTS - 1); + matches.push(held_result); + kept = Some(at); + } matches.truncate(MAX_RESULTS); let recent = recent(&entries.list, &app.ui.recent_commands); // While the Recent Commands list is open, the arrow keys and Enter go to its rows, and the @@ -595,12 +614,6 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let list_open = recent_list_open(ctx); let mut run: Option = None; let mut history_focused = false; - // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it - // by a page, the pointer over a result takes it, and a new query starts again from the first. - let sel_id = egui::Id::unique("palette-selected"); - let (mut sel, last_q, mut offset, last_view, last_id) = ctx.data(|d| d.get_temp::(sel_id)).unwrap_or_default(); - let mut view = last_view; - let new_query = last_q != q; // The highlight stays on its result when the results change under the same query, as when a // plug-in is installed, a shortcut changes or the language changes; it goes to the first // result when its result is gone. @@ -716,7 +729,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Screen readers stay on the field: its description names the highlighted result and // its place among every match, as the footer counts them. if let Some(e) = matches.get(sel) { - let pos = (sel + 1).to_string(); + let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; + let pos = (rank + 1).to_string(); let of = total.to_string(); let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); @@ -2558,4 +2572,35 @@ mod tests { crate::i18n::set_current(Lang::EN); assert_eq!((de_listed.get(sel), &now), (Some(&id), &id), "after the language changed"); } + + /// A highlighted last shown result that a new result pushes past the limit stays shown and + /// highlighted, in the last row, so Enter still runs it; screen readers hear its place among + /// every match. + #[test] + fn the_highlighted_last_result_stays_shown_when_a_result_ranks_above_it() { + use vectorcraft_plugins::wat as tpl; + // A query no other test searches for, so the plug-in below leaves their results alone. + let mut open = Open::new("path", WINDOW); + assert!(matching(&entries(&open.ctx, Lang::EN), "path").len() > MAX_RESULTS); + open.press(egui::Key::ArrowUp, 1); + let held = |open: &Open| open.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap(); + let (sel, .., id) = held(&open); + assert_eq!(sel, MAX_RESULTS - 1); + let filter = "test.UI.palette_last-highlight-path"; + let manifest = format!(r#"{{"id":"{filter}","name":"Path Last Highlight Probe","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + open.frame(vec![]); + let entries = entries(&open.ctx, Lang::EN); + let ranked: Vec<&Entry> = matching(&entries, "path"); + let nodes = open.frame(vec![]); + let (sel, .., now) = held(&open); + vectorcraft_plugins::registry::remove(filter); + let plugin = ranked.iter().position(|e| e.id == format!("plugin:{filter}")); + assert!(plugin.is_some_and(|p| p < MAX_RESULTS), "the plug-in is shown: {plugin:?}"); + assert_eq!(ranked.iter().position(|e| e.id == id), Some(MAX_RESULTS), "the plug-in pushed the highlight past the limit"); + assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); + let label = row_label(ranked[MAX_RESULTS]); + assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); + assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); + } } From 03cf79c56509127924805cf56792273612eccec9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 20:06:59 -0800 Subject: [PATCH 10/29] Command Palette: a press on a Recent Commands row runs it instead of closing the palette The Recent Commands list draws on its own layer, so a press on one of its rows counted as a press outside the popup and closed the palette before the click ran the row. Presses on the list's layer now count as inside. --- crates/ui-egui/src/palette.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6d822a645f..ede05a4f0b 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -718,9 +718,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); }); - // A press of any pointer button that the popup's layer does not get closes it: a press on the - // backdrop, or on a window above it, which also gets the press, even where that window lies - // over the popup. + // A press of any pointer button that neither the popup's layer nor its Recent Commands list's + // layer gets closes it: a press on the backdrop, or on a window above it, which also gets the + // press, even where that window lies over the popup. let presses: Vec = ctx.input(|i| { i.events .iter() @@ -731,7 +731,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { .collect() }); let popup = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("palette")); - let outside = presses.into_iter().any(|p| ctx.layer_id_at(p) != Some(popup)); + let list = egui::LayerId::new(egui::Order::Foreground, recent_list_id()); + let outside = presses.into_iter().any(|p| !ctx.layer_id_at(p).is_some_and(|l| l == popup || l == list)); // The pointer or a scroll moved the highlight after the rows were drawn: the next frame draws // it where it now is. if sel != drawn { From d1b8b3007bdf0b937502c0825dd0c622da16838d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 20:16:01 -0800 Subject: [PATCH 11/29] Command Palette: a panel pick in Presentation Mode changes nothing As `window.panel` does, a pick of a panel's result in Presentation Mode now leaves the panels as they are and the status line says panels can't be shown in that mode. Before, the pick moved the panel to the front of its group and showed the dock once the mode ended. --- crates/ui-egui/src/palette.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 9928837ebf..150c782f96 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -389,8 +389,11 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { app.select_tool(tool); } else if let Some(panel) = id.strip_prefix("panel:") { // A panel that can be seen stays as it is, where `window.panel` would put an open flyout or - // a floating panel away. - if let Err(e) = crate::panel_docking::reveal_panel(app, panel) { + // a floating panel away. In Presentation Mode the pick fails and changes nothing, as + // `window.panel` does. + if app.ui.screen_mode >= 3 { + app.status("panels can't be shown in Presentation Mode"); + } else if let Err(e) = crate::panel_docking::reveal_panel(app, panel) { app.status(e); } } else if id.starts_with("plugin:") || id.starts_with("effect:") { @@ -1778,6 +1781,20 @@ mod tests { } } + /// In Presentation Mode a panel's pick fails as `window.panel` does: the status line says why, + /// and the panel does not show when the mode ends. + #[test] + fn a_panel_pick_in_presentation_mode_changes_nothing() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (open_panel, dock) = (app.ui.open_panel.clone(), app.ui.dock); + app.ui.screen_mode = 3; + run_pick(&mut app, "panel:swatches"); + assert_eq!(app.ui.status, "panels can't be shown in Presentation Mode"); + assert_eq!((app.ui.open_panel.clone(), app.ui.dock), (open_panel, dock)); + app.ui.screen_mode = 0; + assert!(!crate::panel_docking::showing(&app.ui, "swatches"), "the pick did not place the panel"); + } + /// Each Effect menu item is a result under its menu path, with its shortcut. With a document /// open and an object selected, a pick of Drop Shadow… opens its dialog, as the menu item /// does, and changes nothing until the dialog is confirmed. From e0f880ab1a44742f16aa710619bec90d30f53a03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:45:07 -0800 Subject: [PATCH 12/29] =?UTF-8?q?Arc:=20arcs=20follow=20the=20axes=20Gener?= =?UTF-8?q?al=20=E2=80=BA=20Constrain=20Angle=20turns?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool or placed from the Arc Segment Tool Options click dialog is drawn along the turned x and y axes, with its bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or the click, and F, C and Up/Down keep the turn. At 0° and whole turns arcs are drawn as before. shape.arc takes an optional rotation (degrees clockwise, about x1, y1 or about the reference point x, y); a rotation that is not a number is an error and adds nothing. --- crates/engine/src/cmd/create.rs | 32 +++++-- crates/engine/src/tests/constrain_new.rs | 94 ++++++++++++++++++++ crates/tools/src/draw2/family.rs | 107 +++++++++++++++++------ docs/gaps.md | 4 +- docs/mcp.md | 7 ++ docs/target-app-parity.md | 4 +- docs/ui-parity.md | 2 +- 7 files changed, 212 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index c7c5204e5e..4fca34a3ef 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Arc", [], None, - "{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}", + "{x1, y1, x2, y2, closed?, slope?, rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright) → {id}", has_doc, arc ), @@ -299,7 +299,8 @@ fn path_kind(path: PathData, live: Option) -> NodeKind { /// (): /// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog /// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays -/// put; a polygon or star turns its base orientation about its centre. The params as they are at +/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog +/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at /// 0° or a whole turn, for other commands and when they already carry a `rotation`. pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value { let base = s.prefs.constrain_angle; @@ -318,6 +319,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) "shape.polygon" | "shape.star" => { o.insert("rotation".into(), json!(rotation)); } + "shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => { + o.insert("rotation".into(), json!(rotation)); + } _ => {} } params @@ -590,13 +594,18 @@ fn spiral(s: &mut Session, p: &Value) -> Result { } fn arc(s: &mut Session, p: &Value) -> Result { + let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 }; + if !rotation.is_finite() { + return Err(bad("shape.arc", "rotation must be finite")); + } let closed = switch_or(p, "closed", false, "shape.arc")?; let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?; let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y")); - let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() { + // The upright path, and the point `rotation` turns it about. + let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() { let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?); let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize; - shapes::arc_segment( + let path = shapes::arc_segment( anchor, reference, number_or(p, "lengthX", 100.0, "shape.arc")?, @@ -604,12 +613,21 @@ fn arc(s: &mut Session, p: &Value) -> Result { base_x, number_or(p, "slope", 50.0, "shape.arc")?, closed, - ) + ); + (path, anchor) } else { let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?); let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?); let slope = number_or(p, "slope", 100.0, "shape.arc")?; - shapes::arc(a, b, slope, closed, base_x) + (shapes::arc(a, b, slope, closed, base_x), a) + }; + // 0 and whole turns leave the path as it is; quarter turns are exact. + let bbox_angle = bbox_turn(rotation); + let path = if bbox_angle == 0.0 { + path + } else { + let c = pivot.to_vec2(); + path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c)) }; let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None }; let look = s.new_art_look( @@ -617,7 +635,7 @@ fn arc(s: &mut Session, p: &Value) -> Result { if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, s.paint.stroke_width.max(0.1), ); - add_look(s, "Arc", path_kind(path, None), look, None) + insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle) } /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index 50797e35e3..d78ceae054 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -412,3 +412,97 @@ fn constrain_angle_turns_a_click_made_grid_about_its_reference_point() { let b = bounds(&s, id); assert_eq!((b.x0, b.y0, b.x1, b.y1), (175.0, 150.0, 225.0, 250.0), "turned about the click: {b:?}"); } + +/// The anchor points of the path `id`. +fn path_points(s: &Session, id: NodeId) -> Vec { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(), + other => panic!("a path: {other:?}"), + } +} + +/// The direction (degrees, counter-clockwise on the page) of the arc `id`'s first handle. +fn first_handle_angle(s: &Session, id: NodeId) -> f64 { + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") }; + let a = &path.subpaths[0].anchors[0]; + let v = a.h_out - a.p; + (-v.y).atan2(v.x).to_degrees() +} + +fn near(p: Point, x: f64, y: f64) -> bool { + close(p.x, x) && close(p.y, y) +} + +/// An arc dragged out runs along the turned axes: at 30° it still runs from the drag's start to +/// its end, its base leaves the start along the turned x axis and its bounding box turns 30°; at +/// 0° it is as before. +#[test] +fn constrain_angle_draws_a_dragged_arc_along_the_turned_axes() { + let mut s = new_doc(); + for (deg, handle) in [(0.0, 0.0), (30.0, 30.0)] { + set_angle(&mut s, deg); + s.select_tool("arc", ViewInfo::default()).unwrap(); + gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]); + let id = last_id(&s); + let pts = path_points(&s, id); + assert!(near(pts[0], 100.0, 100.0) && near(pts[1], 160.0, 120.0), "{deg}°: {pts:?}"); + assert!(close(first_handle_angle(&s, id), handle), "{deg}°: {}", first_handle_angle(&s, id)); + if deg == 0.0 { + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits()); + } else { + assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id)); + } + } +} + +/// An arc placed by the click dialog keeps its reference point at the click and runs its lengths +/// along the turned axes: at 30° from the top-left reference point, and at 90° about the center +/// one; at 0° the dialog's params are unchanged. +#[test] +fn constrain_angle_turns_a_click_made_arc_about_its_reference_point() { + let mut s = new_doc(); + let params = |reference: u64, x: f64, y: f64| json!({"x": x, "y": y, "lengthX": 100, "lengthY": 50, "reference": reference, "baseAlong": "x", "slope": 50, "closed": false, "fillArc": false}); + let click = Point::new(200.0, 200.0); + let p = params(0, 200.0, 200.0); + assert_eq!(constrain_click(&s, "shape.arc", p.clone(), click), p, "0°"); + set_angle(&mut s, 30.0); + let turned = constrain_click(&s, "shape.arc", p, click); + assert_eq!(turned["rotation"], json!(-30.0)); + let id = NodeId(s.execute("shape.arc", &turned).unwrap()["id"].as_u64().unwrap()); + let pts = path_points(&s, id); + let r = 30f64.to_radians(); + let end = (200.0 + 100.0 * r.cos() + 50.0 * r.sin(), 200.0 - 100.0 * r.sin() + 50.0 * r.cos()); + assert!(near(pts[0], 200.0, 200.0) && near(pts[1], end.0, end.1), "{pts:?} vs {end:?}"); + assert!(close(bbox_angle(&s, id), 30.0)); + set_angle(&mut s, 90.0); + let p = constrain_click(&s, "shape.arc", params(4, 200.0, 200.0), click); + let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap()); + // The ends at opposite corners of the 100 × 50 box centered on the click, turned exactly. + assert_eq!(path_points(&s, id), vec![Point::new(175.0, 250.0), Point::new(225.0, 150.0)]); + let b = bounds(&s, id); + assert!(close(b.x0, 175.0) && close(b.y0, 150.0) && close(b.x1, 225.0) && close(b.y1, 250.0), "turned about the click: {b:?}"); + assert_eq!(bbox_angle(&s, id), 90.0); +} + +/// `shape.arc` turns by an explicit `rotation` (clockwise) about `x1`, `y1` or about its reference +/// point; a `rotation` that is not a number is refused and adds nothing. +#[test] +fn arc_rotation_turns_it_and_must_be_a_number() { + let mut s = new_doc(); + let id = NodeId(s.execute("shape.arc", &json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": 90})).unwrap()["id"].as_u64().unwrap()); + let pts = path_points(&s, id); + assert!(near(pts[0], 0.0, 0.0) && near(pts[1], -20.0, 10.0), "{pts:?}"); + assert_eq!(bbox_angle(&s, id), -90.0, "a quarter turn clockwise"); + let id = + NodeId(s.execute("shape.arc", &json!({"x": 50, "y": 50, "lengthX": 10, "lengthY": 20, "rotation": 360})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(path_points(&s, id), vec![Point::new(50.0, 50.0), Point::new(60.0, 70.0)], "a whole turn leaves it upright"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits()); + for bad in [json!("x"), Value::Null] { + for p in + [json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": bad}), json!({"x": 0, "y": 0, "lengthX": 10, "lengthY": 20, "rotation": bad})] + { + assert!(s.execute("shape.arc", &p).is_err(), "{p}"); + assert_eq!(last_id(&s), id, "nothing added for {p}"); + } + } +} diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 2e93888d02..8d7fc38df5 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::Point; use crate::guides::{DrawSnap, Leave}; -use crate::shape::{box_params, drag_rect, turned_box}; +use crate::shape::{box_params, turned_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// How much ↑ or ↓ changes the arc's slope while it is dragged out. @@ -155,17 +155,13 @@ impl FamilyTool { } /// How the dragged point keeps to the start: a spiral's radius goes anywhere, the arc's and - /// the grids' corner keeps to a diagonal with Shift (a grid's square is taken along the - /// Constrain Angle's axes instead when it turns them, [`Self::command_at`]). + /// the grids' corner keeps to a diagonal with Shift (an arc's or a grid's square is taken along + /// the Constrain Angle's axes instead when it turns them, [`Self::command_at`]). fn leave(&self, cx: &ToolContext, start: Point, m: Mods) -> Option { - let turned = self.is_grid() && vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some(); + let turned = vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some(); (self.id != "spiral").then(|| Leave::diagonal(start, m.shift && !turned)) } - fn is_grid(&self) -> bool { - matches!(self.id, "rectangularGrid" | "polarGrid") - } - /// The natural logarithm of the radius of the inner end of a spiral of outer radius `r` drawn /// with the tool's decay and segments (a logarithm, so that a low decay with many segments does /// not round to 0). The decay ratio is clamped to 0.05…0.9999 as `shapes::spiral` clamps it. @@ -245,7 +241,7 @@ impl FamilyTool { } /// [`Self::command`] with General › Constrain Angle `base` (degrees, counter-clockwise): the - /// grids are drawn along the x and y axes turned by it, as the rectangle is. + /// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is. pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { match self.id { "spiral" => { @@ -263,25 +259,30 @@ impl FamilyTool { } (format!("shape.{}", self.id), params) } + // The arc: its box along the Constrain Angle's axes, with the reference point taken in + // that box and turned out onto the page; the arc turns about it. _ => { - let r = drag_rect(start, p, m).abs(); + let (r, axes) = turned_box(start, p, m, base); + let r = r.abs(); let (w, h) = (r.width().max(1e-9), r.height().max(1e-9)); let rp = vectorcraft_geom::reference_point(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), self.reference.min(8)); - let anchor = Point::new(r.x0 + rp.x, r.y0 + rp.y); - ( - "shape.arc".into(), - json!({ - "x": anchor.x, - "y": anchor.y, - "lengthX": w, - "lengthY": h, - "reference": self.reference, - "baseAlong": self.base_along, - "slope": self.slope, - "closed": self.closed, - "fillArc": self.fill_arc, - }), - ) + let local = Point::new(r.x0 + rp.x, r.y0 + rp.y); + let anchor = axes.map_or(local, |a| a * local); + let mut params = json!({ + "x": anchor.x, + "y": anchor.y, + "lengthX": w, + "lengthY": h, + "reference": self.reference, + "baseAlong": self.base_along, + "slope": self.slope, + "closed": self.closed, + "fillArc": self.fill_arc, + }); + if let Some(rotation) = axes.and_then(|_| vectorcraft_geom::constrain_rotation(base)) { + params["rotation"] = json!(rotation); + } + ("shape.arc".into(), params) } } } @@ -433,8 +434,8 @@ impl Tool for FamilyTool { let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { // The size as drawn (from the centre with Alt, square with Shift). - // A grid's along the Constrain Angle's axes, as it is drawn. - let r = if self.is_grid() { turned_box(s, self.last, self.mods, cx.constrain_angle).0 } else { drag_rect(s, self.last, self.mods) }; + // An arc's or a grid's along the Constrain Angle's axes, as it is drawn. + let r = turned_box(s, self.last, self.mods, cx.constrain_angle).0; let (w, h) = if self.id == "spiral" { ((self.last - s).x.abs(), (self.last - s).y.abs()) } else { (r.width(), r.height()) }; o.push(Overlay::Measure { p: self.last, text: cx.size_label(w, h) }); } @@ -1080,6 +1081,58 @@ mod tests { assert_eq!(v["rotation"], json!(-30.0)); } + /// General › Constrain Angle: an arc is drawn along the turned axes, its reference point taken + /// in the turned box and the arc turned about it; Shift's equal lengths are taken along the + /// turned axes, and F, C and ↑ keep the turn and the reference point; at 0° and whole turns + /// the arc is as before. + #[test] + fn arcs_follow_the_constrain_angle() { + let t = FamilyTool::new("arc"); + let (a, b) = (Point::new(100.0, 100.0), Point::new(160.0, 120.0)); + let flat = t.command(a, b, Mods::default()); + assert!(flat.1.get("rotation").is_none(), "{flat:?}"); + assert_eq!(t.command_at(a, b, Mods::default(), 0.0), flat); + assert_eq!(t.command_at(a, b, Mods::default(), 360.0), flat); + // At 90° the drag runs 20 along the turned x axis and 60 along the turned y axis; the + // top-left reference point of that box is at (100, 120) on the page. + let (c, v) = t.command_at(a, b, Mods::default(), 90.0); + assert_eq!(c, "shape.arc"); + assert_eq!( + v, + json!({"x": 100.0, "y": 120.0, "lengthX": 20.0, "lengthY": 60.0, "reference": 0, "baseAlong": "x", "slope": 50.0, "closed": false, "fillArc": false, "rotation": -90.0}) + ); + let shift = Mods { shift: true, ..Mods::default() }; + let (_, v) = t.command_at(a, b, shift, 30.0); + assert!((v["lengthX"].as_f64().unwrap() - v["lengthY"].as_f64().unwrap()).abs() < 1e-9, "equal along the turned axes: {v}"); + assert_eq!(v["rotation"], json!(-30.0)); + + // A Shift drag at 30°: the pointer is not held to the page's diagonal. + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.constrain_angle = 30.0; + let mut t = FamilyTool::new("arc"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 30.0).with_mods(shift)); + let expected = t.command_at(Point::new(10.0, 10.0), Point::new(70.0, 30.0), shift, 30.0); + assert_eq!(out, vec![Action::Begin("Arc".into()), Action::Preview(expected.0, expected.1.clone())]); + let preview = |a: Vec| match &a[..] { + [Action::Preview(c, v)] if c == "shape.arc" => v.clone(), + _ => panic!("{a:?}"), + }; + let v = preview(t.key(&cx, ToolKey::Letter('f'), Mods::default())); + assert_eq!(v["baseAlong"], json!("y")); + let v = preview(t.key(&cx, ToolKey::Letter('c'), Mods::default())); + assert_eq!(v["closed"], json!(true)); + let v = preview(t.key(&cx, ToolKey::Up, Mods::default())); + assert_eq!(v["slope"], json!(60.0)); + for k in ["x", "y", "lengthX", "lengthY", "rotation"] { + assert_eq!(v[k], expected.1[k], "{k} stays"); + } + } + /// The start and the dragged corner snap to Smart Guides (#506), Shift sliding the corner of /// a square grid along its diagonal into line. #[test] diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..a85090ce5f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -488,8 +488,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Until a choice is made (`default`), the panels follow General › Transform Pattern Tiles as before, and the menu checks Transform Both while it is on and Transform Object Only while it is off; a choice overrides it. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Arcs, spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Arcs, spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (). Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (). Estimate unchanged. - **Done (2026-10-17):** Background Export shows its progress in a dialog with Cancel and Continue in Background (#2564), on the shared cancel token (#2546); a cancelled export writes no file. Save As, Export for Screens and Export Selection don't show it yet. Estimate unchanged. **2026-11-06:** opening a file that takes longer than 0.4 s shows a progress window too, with a moving bar, Cancel and Continue in Background (part of #5930); Save and Place still show only the status bar's spinner. Estimate unchanged. - **Done:** quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the controls with Threshold and Advanced (Paths, Corners, Noise), as the public documentation describes (). Other context-specific Properties gaps remain. - **Done (2026-10-31, #394):** Units › East Asian Type is read, and Q and Ha are units. 1 Q and 1 Ha are each a diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..123523b500 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -761,6 +761,13 @@ dragged, headless `press_key` `c` chooses the tool bound to C (headless has no b from the typed letter, so with nothing being dragged `c` and `f` do not run their shortcuts there. Use `select_tool` or `invoke_menu` instead. +With General › Constrain Angle (`prefs.set {key: "constrainAngle"}`) other than 0° or a whole turn, the Arc tool's drag +and its click dialog draw the arc along the turned x and y axes: the drag sends `shape.arc` with `lengthX` and `lengthY` +measured along those axes, the reference point `x`, `y` at the drag's corner or the click, and a `rotation` of the +Constrain Angle's negative. `shape.arc` takes `rotation` in degrees clockwise on the page, about `x1`, `y1` or about the +reference point `x`, `y`; the arc's bounding box turns with it. Without `rotation`, or at 0° or a whole turn, the arc is +upright, and a `rotation` that is not a number is an error that adds nothing. + While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..61a69f1b6f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -666,7 +666,9 @@ since 2026-10-01. - **PDF writes a warped image once:** with downsampling on, the pieces of an image bent by a Warp effect are resampled for the widest and the highest size any piece places the image at, so every piece paints one image XObject (a colorized image: one colorized image and its soft mask), instead of one image for each size a piece is placed at. Another placement of the same image is still resampled for its own size. Without downsampling, a colorized image and a CMYK image with a grayscale image mask on its grid are decoded and encoded once for all the sizes they are placed at (pdf `tests::compression::a_warped_image_is_written_once_for_all_its_pieces`, `tests::colorize::a_colorized_warped_image_is_written_once_for_all_its_pieces`, `export::images::tests::colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. -- **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged.- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. +- **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. +- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. +- **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..431f1e46fd 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -468,7 +468,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | -| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); arcs, spirals, flares and Pen paths are not turned | +| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); spirals, flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | From c367a8e9914d7555e288adfdcb02975e62b0ce26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:14:41 -0800 Subject: [PATCH 13/29] Arrange: a Selection drag released in another document's tiled pane drops the artwork there MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under Window › Arrange › Tile, a Selection move dragged from the current pane and released over another document's pane copies the artwork into that document with edit.dropSelection, with no tab hover first. The pane becomes the current window, and the grab point lands under the pointer in that pane's own zoom and rotation. A release over another view of the source document moves the artwork with object.move, and Alt copies it. The source move is rolled back before the canvas sees the release, also when the pointer enters the pane and the button goes up in one frame. Artwork carried to a document through its tab can also be released in a third document's pane. A release over a pane's rulers or scroll bars, or after Escape, changes neither document, and a press in another pane with no artwork carried still only makes its document current. Dragging into a floating document window and the tab overflow menu are not covered. Docs: development.md, target-app-parity.md, gaps.md, roadmap.md, ui-parity.md. --- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/drag.rs | 10 +- crates/ui-egui/src/canvas/panes.rs | 47 ++++- crates/ui-egui/src/canvas/panes/tests.rs | 216 +++++++++++++++++++++++ crates/ui-egui/src/document_drag.rs | 91 +++++++++- docs/development.md | 16 +- docs/gaps.md | 6 +- docs/roadmap.md | 6 +- docs/target-app-parity.md | 6 +- docs/ui-parity.md | 8 +- 10 files changed, 387 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 847b60fd87..b914d1f626 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -42,7 +42,7 @@ pub use cursor::{HOVER_STILL_SECS, STILL_SECS, ViewKey}; use cursor::{cursor_icon, hover_cursor, hover_wait, still_wait}; use drag::drag_id; pub use drag::{apply_requests, dispatch, mods}; -pub(crate) use drag::{end_document_drag, pose_on_page, release_art_in_window, release_over_panel}; +pub(crate) use drag::{art_out, end_art_move, end_document_drag, pose_on_page, release_art_in_window, release_over_panel}; #[cfg(test)] use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id}; pub use fill::Fill; diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index cb01cf71d4..38be9651c7 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -29,6 +29,11 @@ pub(crate) fn end_document_drag(ctx: &egui::Context) { }); } +/// Whether a Selection tool move has left the canvas ([`drag_art_out`]) and still waits there. +pub(crate) fn art_out(ctx: &egui::Context) -> bool { + matches!(ctx.data(|d| d.get_temp::(drag_id())), Some(Drag::Art)) +} + /// Temp-memory key for the active canvas drag state. pub(super) fn drag_id() -> egui::Id { egui::Id::unique("canvas-drag") @@ -355,8 +360,9 @@ pub(crate) fn release_art_in_window(app: &mut VectorcraftApp, ctx: &egui::Contex } } -/// Roll back the art move dragged off the canvas; a panel takes the art instead. -fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) { +/// Roll back the art move dragged off the canvas, and end the canvas's drag; a panel or another +/// window's tiled pane takes the art instead. +pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) { // With no document open there is nothing to roll back; the tool still gets its mouse-up. let _ = app.session.cancel_interaction(); let view = app.view_info(); diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index bf070af076..dd2fec382f 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,8 +1,9 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document //! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press -//! in it makes its document the current one. Each view Window › New Window opened has a pane of -//! its own ([`crate::doc_windows`]). +//! in it makes its document the current one. A Selection drag released in it drops the dragged +//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New +//! Window opened has a pane of its own ([`crate::doc_windows`]). use std::collections::HashMap; use std::sync::Arc; @@ -243,12 +244,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; + let (mut cursor, mut dropped) = (None, None); // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) // stays over them. - for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) { + for ((w, cell), (_, area)) in cells.iter().copied().zip(areas.iter().copied()).filter(|((w, _), _)| Some(*w) != active) { if pane(app, ui, w, cell) { activate = Some(w); } + match artwork_over(app, ui, w, area) { + Some(Over::Held(c)) => cursor = Some(c), + Some(Over::Released(at, carried)) => dropped = Some((w, at, carried)), + None => {} + } ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); } if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) { @@ -256,6 +263,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { super::show(app, &mut canvas); ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); } + // After the canvas, which sets the cursor of the drag it holds. + if let Some(c) = cursor { + ui.ctx().set_cursor_icon(c); + } // Note the fits this frame made, for `refit_resized`. for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { @@ -263,12 +274,40 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } } app.canvas.panes.last = cells; - if let Some(w) = activate { + if let Some((w, at, carried)) = dropped { + crate::document_drag::drop_on_pane(app, ui.ctx(), w, at, carried); + } else if let Some(w) = activate { crate::doc_windows::show_window(app, w); } true } +/// A Selection drag's artwork over another window's tiled pane. +enum Over { + /// Held there: the cursor that shows whether a release moves or copies it. + Held(egui::CursorIcon), + /// Released there, at a document point in the pane's own view. + Released(Point, crate::document_drag::Carried), +} + +/// A Selection drag's artwork over `area`, the part of window `w`'s pane inside its rulers and +/// scroll bars, where no panel or floating window is over the pointer. A release there takes the +/// artwork before the canvas sees the release ([`crate::document_drag::take_for_pane`]). +fn artwork_over(app: &mut VectorcraftApp, ui: &Ui, w: Win, area: egui::Rect) -> Option { + let (uid, _) = slot(app, w)?; + let p = ui.input(|i| i.pointer.interact_pos())?; + if !area.contains(p) || ui.ctx().layer_id_at(p).is_some_and(|l| l != ui.layer_id()) { + return None; + } + let cursor = crate::document_drag::pane_cursor(app, ui.ctx(), uid)?; + if !ui.input(|i| i.pointer.primary_released()) { + return Some(Over::Held(cursor)); + } + let v = crate::doc_windows::view(app, w).copied()?; + let at = Xf::at(area, &v, ui.ctx().zoom_factor()).to_doc(p); + Some(Over::Released(at, crate::document_drag::take_for_pane(app, ui.ctx())?)) +} + /// Window `w`'s [`Slot`]. fn slot(app: &VectorcraftApp, (i, n): Win) -> Option { app.session.documents().get(i).map(|d| (d.uid, n)) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 34611fd0d7..85301cd22b 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -165,6 +165,222 @@ fn a_press_in_another_pane_makes_its_document_current_without_drawing() { assert!(app.session.documents()[1..].iter().all(|d| d.doc.art_bounds().is_none())); } +/// One headless frame at `time` seconds as the app runs it: a Selection move released off the +/// canvas ends first ([`crate::canvas::release_over_panel`]), then the tabs and the panes draw. +fn timed_frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: Option, events: Vec) -> egui::FullOutput { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + time, + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| { + crate::canvas::release_over_panel(app, ui.ctx()); + app.canvas_area(ui); + }); + out.textures_delta.clear(); + out +} + +/// [`timed_frame`] without a time. → the cursor. +fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::CursorIcon { + timed_frame(app, ctx, None, events).platform_output.cursor_icon +} + +/// Two 400 × 300 pt documents tiled side by side: the first, current, holds a selected 100 pt +/// square at 50, 50 and the second a 50 pt square at 300, 230. The Selection tool is chosen. +fn tiled_pair() -> (VectorcraftApp, egui::Context) { + let mut app = app_with(0); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 300, "y": 230, "width": 50, "height": 50})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + app_frame(&mut app, &ctx, vec![]); + app_frame(&mut app, &ctx, vec![]); + (app, ctx) +} + +/// Press on document point `at` on the canvas and move the pointer 20 × 10 points, still on the +/// canvas: the Selection tool moves the art under it. +fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: Point) { + let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at); + app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]); + app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]); + assert!(app.session.in_interaction(), "the Selection tool moves the art"); +} + +/// Window `w`'s pane: the screen point that shows document point `at` in it, and the pane. +fn in_pane(app: &VectorcraftApp, ctx: &egui::Context, w: Win, at: Point) -> (Pos2, egui::Rect) { + let (_, cell) = app.canvas.panes.last.iter().copied().find(|(o, _)| *o == w).unwrap(); + let area = view_rects(app, cell, ctx.pixels_per_point()).1; + (Xf::at(area, crate::doc_windows::view(app, w).unwrap(), 1.0).to_screen(at), cell) +} + +/// How many objects document `i`'s first layer holds. +fn objects(app: &VectorcraftApp, i: usize) -> usize { + app.session.documents()[i].doc.layers[0].children().map_or(0, Vec::len) +} + +/// The bounds of the one object selected in the current document. +fn selected_bounds(app: &VectorcraftApp) -> Rect { + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), 1, "one object is selected"); + st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap() +} + +#[test] +fn a_selection_drag_released_in_another_documents_pane_copies_the_art_there() { + let (mut app, ctx) = tiled_pair(); + // The target's view differs from the source's: the grab point still lands under the pointer. + app.views[1].zoom *= 0.6; + app.views[1].rotation = 30.0; + app_frame(&mut app, &ctx, vec![]); + let source = app.session.documents()[0].doc.clone(); + let source_undo = app.session.documents()[0].history.undo.len(); + let target = app.session.documents()[1].doc.clone(); + let target_undo = app.session.documents()[1].history.undo.len(); + let clipboard = app.session.clipboard.clone(); + grab(&mut app, &ctx, Point::new(100.0, 100.0)); + let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(170.0, 120.0)); + // The release comes in the first frame the pointer is over the pane. + app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false)]); + app_frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one"); + let placed = selected_bounds(&app); + assert!((placed.center().x - 170.0).abs() < 0.01 && (placed.center().y - 120.0).abs() < 0.01, "{placed:?}"); + assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1, "one step to undo"); + assert_eq!(app.session.documents()[0].doc, source, "the source keeps its art where it was"); + assert_eq!(app.session.documents()[0].history.undo.len(), source_undo); + assert_eq!(app.session.clipboard, clipboard, "the drag leaves the clipboard alone"); + assert!(!app.session.tool_busy()); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.documents()[1].doc, target); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1); +} + +#[test] +fn art_held_over_another_pane_shows_a_copy_and_drags_back_the_other_way() { + let (mut app, ctx) = tiled_pair(); + grab(&mut app, &ctx, Point::new(100.0, 100.0)); + let (over, _) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0)); + let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]); + assert_eq!(cursor, egui::CursorIcon::Copy, "over another document's pane the art is copied"); + assert_eq!(app.session.active_index(), Some(0), "holding the art over a pane does not switch documents"); + let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(120.0, 90.0)); + app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]); + app_frame(&mut app, &ctx, vec![button(drop, false)]); + app_frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(1)); + assert_eq!(objects(&app, 1), 2, "the copy joins the target's square"); + // From the target, now the canvas, back into the first document's pane. + app_frame(&mut app, &ctx, vec![]); + grab(&mut app, &ctx, Point::new(325.0, 255.0)); + let (back, _) = in_pane(&app, &ctx, (0, 1), Point::new(300.0, 200.0)); + app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(back), button(back, false)]); + app_frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(0)); + let placed = selected_bounds(&app); + assert!((placed.center().x - 300.0).abs() < 0.01 && (placed.center().y - 200.0).abs() < 0.01, "{placed:?}"); + assert_eq!(objects(&app, 0), 2); +} + +#[test] +fn a_selection_drag_into_another_view_of_its_document_moves_the_art() { + let (mut app, ctx) = tiled_pair(); + app.run("window.newWindow", json!({})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + app_frame(&mut app, &ctx, vec![]); + app_frame(&mut app, &ctx, vec![]); + let current = crate::doc_windows::current(&app).unwrap(); + let other = app.canvas.panes.last.iter().map(|(w, _)| *w).find(|w| w.0 == 0 && *w != current).unwrap(); + let undo = app.session.documents()[0].history.undo.len(); + let target = app.session.documents()[1].doc.clone(); + grab(&mut app, &ctx, Point::new(100.0, 100.0)); + let (drop, _) = in_pane(&app, &ctx, other, Point::new(250.0, 200.0)); + let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]); + assert_eq!(cursor, egui::CursorIcon::Move, "another view of the same document moves the art"); + app_frame(&mut app, &ctx, vec![button(drop, false)]); + app_frame(&mut app, &ctx, vec![]); + assert_eq!(crate::doc_windows::current(&app), Some(other), "the pane's view is the current window"); + assert_eq!(objects(&app, 0), 1, "the square moved, not copied"); + let moved = selected_bounds(&app); + assert!((moved.center().x - 250.0).abs() < 0.01 && (moved.center().y - 200.0).abs() < 0.01, "{moved:?}"); + assert_eq!(app.session.documents()[0].history.undo.len(), undo + 1); + assert_eq!(app.session.documents()[1].doc, target, "the other document is untouched"); +} + +#[test] +fn art_carried_through_a_tab_drops_into_a_third_documents_pane() { + let (mut app, ctx) = tiled_pair(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let source = app.session.documents()[0].doc.clone(); + let third = app.session.documents()[2].doc.clone(); + let titles = |out: egui::FullOutput| -> Vec { + let mut t: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::Text(t) if t.galley.text().contains(" @ ") => Some(egui::Rect::from_min_size(t.pos, t.galley.size())), + _ => None, + }) + .collect(); + t.sort_by(|a, b| a.left().total_cmp(&b.left())); + t + }; + timed_frame(&mut app, &ctx, Some(0.0), vec![]); + let tabs = titles(timed_frame(&mut app, &ctx, Some(0.01), vec![])); + assert_eq!(tabs.len(), 3); + let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(Point::new(100.0, 100.0)); + timed_frame(&mut app, &ctx, Some(0.05), vec![egui::Event::PointerMoved(p), button(p, true)]); + timed_frame(&mut app, &ctx, Some(0.1), vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]); + timed_frame(&mut app, &ctx, Some(0.2), vec![egui::Event::PointerMoved(tabs[2].center())]); + timed_frame(&mut app, &ctx, Some(0.25), vec![]); + timed_frame(&mut app, &ctx, Some(0.8), vec![]); + assert_eq!(app.session.active_index(), Some(2), "holding the art over the third tab makes that document current"); + timed_frame(&mut app, &ctx, Some(0.85), vec![]); + let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(150.0, 100.0)); + timed_frame(&mut app, &ctx, Some(0.9), vec![egui::Event::PointerMoved(drop)]); + timed_frame(&mut app, &ctx, Some(1.0), vec![button(drop, false)]); + timed_frame(&mut app, &ctx, Some(1.1), vec![]); + assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one"); + assert_eq!(objects(&app, 1), 2, "the copy joins the second document's square"); + let placed = selected_bounds(&app); + assert!((placed.center().x - 150.0).abs() < 0.01 && (placed.center().y - 100.0).abs() < 0.01, "{placed:?}"); + assert_eq!(app.session.documents()[0].doc, source); + assert_eq!(app.session.documents()[2].doc, third, "the document the tab showed is untouched"); +} + +#[test] +fn a_drag_released_off_a_panes_art_area_or_after_escape_changes_nothing() { + for (case, escape) in [("scroll bar", false), ("art area after Escape", true)] { + let (mut app, ctx) = tiled_pair(); + let docs: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect(); + grab(&mut app, &ctx, Point::new(100.0, 100.0)); + let (inside, cell) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0)); + let at = if escape { inside } else { pos2(cell.right() - 2.0, cell.center().y) }; + app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + if escape { + let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + app_frame(&mut app, &ctx, vec![key]); + } + app_frame(&mut app, &ctx, vec![button(at, false)]); + app_frame(&mut app, &ctx, vec![]); + assert_eq!(app.session.active_index(), Some(0), "{case}: the source stays current"); + let after: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect(); + assert!(after == docs, "{case}: neither document changes"); + assert!(!app.session.in_interaction(), "{case}: the move ended"); + } +} + #[test] fn consolidate_all_windows_shows_one_document_again() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/document_drag.rs b/crates/ui-egui/src/document_drag.rs index b44d09b5c3..7be4cfa1c4 100644 --- a/crates/ui-egui/src/document_drag.rs +++ b/crates/ui-egui/src/document_drag.rs @@ -1,4 +1,5 @@ -//! A selection dragged across document tabs remains editable and leaves its source intact. +//! A selection dragged across document tabs, or into another document's tiled pane, remains +//! editable and leaves its source intact. use std::sync::Arc; @@ -90,13 +91,15 @@ pub(crate) fn cleanup(app: &VectorcraftApp, ctx: &Context) { || i.multi_touch().is_some() || i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::Cancel, .. })) }); - let outside_release = - ctx.input(|i| i.pointer.primary_released() && !app.canvas_rect.is_some_and(|r| i.pointer.interact_pos().is_some_and(|p| r.contains(p)))); + // The canvas and the other windows' tiled panes take a release ([`drop_on_pane`]). + let target = |p: egui::Pos2| app.canvas_rect.is_some_and(|r| r.contains(p)) || app.canvas.panes.last.iter().any(|(_, r)| r.contains(p)); + let outside_release = ctx.input(|i| i.pointer.primary_released() && !i.pointer.interact_pos().is_some_and(target)); if !valid || cancel || outside_release || app.ui.dialog.is_some() { egui::DragAndDrop::clear_payload(ctx); } } - if !ctx.input(|i| i.pointer.primary_down()) { + // The source and grab point last through the release, for the pane it is released over. + if !ctx.input(|i| i.pointer.primary_down() || i.pointer.primary_released()) { ctx.data_mut(|d| { d.remove::(origin_id()); d.remove::(hover_id()); @@ -210,3 +213,83 @@ pub(crate) fn drop_on_canvas(app: &mut VectorcraftApp, resp: &Response, xf: &can } } } + +/// The artwork a Selection drag carries out of its canvas, taken by another window's tiled pane +/// ([`take_for_pane`]): its source and grab point, and the objects that travel. +pub(crate) struct Carried { + origin: Origin, + ids: Vec, +} + +/// The artwork a Selection drag carries: the transfer a tab hover started, or a Selection move of +/// the current document that left its canvas. The canvas hands that move over as a panel drag +/// ([`widgets::PanelDrag::Art`]) the frame after the pointer leaves, and Escape drops that; until +/// then the move under way is the drag. Either way the objects the move started with travel, not +/// an Alt-drag's preview copies. +fn carried(app: &VectorcraftApp, ctx: &Context) -> Option { + if ctx.input(|i| !i.focused || i.multi_touch().is_some() || i.key_pressed(egui::Key::Escape)) || app.ui.dialog.is_some() { + return None; + } + if let Some(art) = egui::DragAndDrop::payload::(ctx) { + return Some(Carried { origin: art.origin.clone(), ids: art.ids.clone() }); + } + let origin = ctx.data(|d| d.get_temp::(origin_id()))?; + let st = app.session.active().filter(|d| d.uid == origin.uid)?; + let ids = match egui::DragAndDrop::payload::(ctx).as_deref() { + Some(widgets::PanelDrag::Art(ids)) => ids.clone(), + Some(_) => return None, + None if canvas::art_out(ctx) => return None, + None => st.interaction.as_ref().filter(|i| i.label == "Move" || i.label == "Copy")?.selection.objects.clone(), + }; + (!ids.is_empty()).then_some(Carried { origin, ids }) +} + +/// Over the tiled pane of a window of document `uid`, while a Selection drag carries artwork: the +/// cursor that shows a move for another view of the source document without Alt, and a copy +/// otherwise. None when no artwork is carried. +pub(crate) fn pane_cursor(app: &VectorcraftApp, ctx: &Context, uid: u64) -> Option { + let c = carried(app, ctx)?; + let copy = ctx.input(|i| i.modifiers.alt); + Some(if c.origin.uid == uid && !copy { egui::CursorIcon::Move } else { egui::CursorIcon::Copy }) +} + +/// A release over another window's tiled pane takes the carried artwork: the drag ends, and a +/// move still under way on the canvas goes back to where it started, before the canvas sees the +/// release ([`canvas::end_art_move`]). +pub(crate) fn take_for_pane(app: &mut VectorcraftApp, ctx: &Context) -> Option { + let c = carried(app, ctx)?; + let moving = !egui::DragAndDrop::has_payload_of_type::(ctx) && app.session.in_interaction(); + egui::DragAndDrop::clear_payload(ctx); + ctx.data_mut(|d| d.remove::(origin_id())); + if moving { + canvas::end_art_move(app, ctx); + } + Some(c) +} + +/// The artwork `c` taken over window `w`'s tiled pane ([`take_for_pane`]), released at document +/// point `at` in that pane's view: `w` becomes the current window, and the artwork lands with its +/// grab point at `at`. Into another document it is copied (`edit.dropSelection`), and the source +/// stays as it was; in another view of the source document it moves, and Alt copies it +/// (`object.move`). When the command fails, the window that was current stays current and the +/// status bar shows the error. +pub(crate) fn drop_on_pane(app: &mut VectorcraftApp, ctx: &Context, w: crate::doc_windows::Win, at: Point, c: Carried) { + let Carried { origin, ids } = c; + let Some(uid) = app.session.documents().get(w.0).map(|d| d.uid) else { return }; + let before = crate::doc_windows::current(app); + app.ui.home = None; + crate::doc_windows::show_window(app, w); + let result = if uid == origin.uid { + let copy = ctx.input(|i| i.modifiers.alt); + app.run("object.move", json!({"ids": ids, "dx": at.x - origin.grab.x, "dy": at.y - origin.grab.y, "copy": copy})) + } else { + app.run("edit.dropSelection", json!({"sourceDocument": origin.uid, "ids": ids, "grab": [origin.grab.x, origin.grab.y], "at": [at.x, at.y]})) + }; + if let Err(e) = result { + if let Some(b) = before { + crate::doc_windows::show_window(app, b); + } + app.status(e); + } + ctx.request_repaint(); +} diff --git a/docs/development.md b/docs/development.md index 64b66678b5..8cf61cb285 100644 --- a/docs/development.md +++ b/docs/development.md @@ -497,7 +497,21 @@ to the source tab resumes a move (Alt copies). Escape or release outside the can Changing the source revision or unexpectedly changing/closing the destination cancels a stale transfer; focus loss, touch cancellation and multitouch cancel too. Moving tabs under a stationary pointer does not activate further tabs until the pointer moves. The close icon does not activate a tab during a drag. Overflow-menu hover activation and -cross-window dragging remain outside this change. +dragging into a floating document window remain outside this change. + +Under Window › Arrange › Tile, a Selection move released over another document's pane copies the +artwork into that document through `edit.dropSelection`, with no tab hover first. The pane becomes +the current window, the grab point lands under the pointer in that pane's own zoom and rotation, and +the source move is rolled back, including when the pointer enters the pane and the button is released +in the same frame. A release over another view of the source document (Window › New Window) moves the +artwork there with `object.move`, and Alt copies it. While the artwork is held over a pane, the cursor +shows a copy or a move. A release over a pane's rulers or scroll bars, or after Escape, changes +neither document. A press in another pane with no artwork carried still only makes its document +current. Page 14 of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf) +describes documents arranged side by side, with items dragged from one document into another. +Evidence: the `canvas::panes` tests drive real pointer frames from the current pane into another +document's pane, back the other way, into another view, through a tab into a third document's pane, +and off a pane's art area. The cited regressions assert the internal clipboard; they do not exercise the native system-clipboard adapter. Tab activation resets the Selection tool through `Session::set_active`; gesture regressions verify it is idle after switching, dropping diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..e9b658dc89 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -875,8 +875,10 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel Selection drags activate another visible document tab after 400 ms, then copy editable artwork on canvas release with the original grab point. Source and clipboard preservation, resource rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression -coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain -separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). +coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over +another document's pane copies the artwork into that document as well, and a release over another +view of the source document moves it (`canvas::panes` tests). Overflow-menu drag and drag into a +floating document window remain separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). ## Pathfinder › Trap (2026-10-23) diff --git a/docs/roadmap.md b/docs/roadmap.md index fae091f647..bb78bbff9b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -201,8 +201,10 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel Selection drags activate another visible document tab after 400 ms, then copy editable artwork on canvas release with the original grab point. Source and clipboard preservation, resource rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression -coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain -separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). +coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over +another document's pane copies the artwork into that document as well, and a release over another +view of the source document moves it (`canvas::panes` tests). Overflow-menu drag and drag into a +floating document window remain separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). ## Revision history diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..79ac4cbc89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2266,8 +2266,10 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel Selection drags activate another visible document tab after 400 ms, then copy editable artwork on canvas release with the original grab point. Source and clipboard preservation, resource rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression -coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain -separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). +coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over +another document's pane copies the artwork into that document as well, and a release over another +view of the source document moves it (`canvas::panes` tests). Overflow-menu drag and drag into a +floating document window remain separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). ## Gradient dither (2026-10-22) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..50927bf211 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -384,7 +384,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Interaction | Status | Evidence | |---|---|---| | Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | -| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; overflow and cross-window drag remain separate | +| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests); overflow-menu and floating-window drag remain separate | | A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | @@ -541,8 +541,10 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel Selection drags activate another visible document tab after 400 ms, then copy editable artwork on canvas release with the original grab point. Source and clipboard preservation, resource rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression -coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain -separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). +coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over +another document's pane copies the artwork into that document as well, and a release over another +view of the source document moves it (`canvas::panes` tests). Overflow-menu drag and drag into a +floating document window remain separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22). ## Live Paint Bucket From 8c53f8ce8863fcd9ecf4df12d3644c8596fde061 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 12:23:10 +0100 Subject: [PATCH 14/29] Fix #8093: Pathfinder takes a clip group's members where its mask shows them Pathfinder collected a clip group's members as if it were a plain group, so Divide cut the hidden art too and the result lost the mask. Each member is now cut to the group's clipping region first (nested clip groups by each region in turn): its area is intersected with the region, and Divide's cutting lines keep only their parts inside it. A member the mask hides gives no piece, a group among other objects takes the style of its top member that shows, and a selection the masks hide altogether is refused with a reason. This applies to every object.pathfinder.* operation, which also covers Merge on masked art (#3367). --- crates/engine/src/cmd/pathops.rs | 143 ++++++++++-- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/pathfinder_clip.rs | 243 +++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 371 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/tests/pathfinder_clip.rs diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 5b7f22abd9..75bb06bd0e 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject}; -use vectorcraft_geom::{FillRule, PathData}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; @@ -352,6 +352,92 @@ pub(crate) fn pf_leaves(d: &Document, n: &Node, out: &mut Vec) { } } +/// The region a clip group's members show through: its clipping path's outline +/// ([`vectorcraft_render::effects::clip_outline`]), cut by the clip groups around it. +struct Clip { + path: PathData, + rule: FillRule, +} + +/// Does `path` have an anchor or handle that isn't a finite number? +fn has_invalid_coordinates(path: &PathData) -> bool { + path.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| [a.p, a.h_in, a.h_out].iter().any(|q| !(q.x.is_finite() && q.y.is_finite()))) +} + +/// A Pathfinder operation's leaf shape ([`pf_leaves`]) with the region its clip groups show it +/// through, `None` outside any clip group. +type ClippedLeaf = (Node, Option>); + +/// [`pf_leaves`], each with the region the clip groups it is in show it through (#8093). A clip +/// group's clipping path is not a leaf, and the members of one whose clipping path clips by nothing +/// are hidden, as on the canvas, and left out. +fn clipped_pf_leaves(d: &Document, n: &Node, clip: Option<&Arc>, precision: f64, out: &mut Vec) -> Result<()> { + let (NodeKind::Group { children, clip: clips } | NodeKind::Layer { children, clip: clips, .. }) = &n.kind else { + let mut lv = vec![]; + leaves(n, &mut lv); + out.extend(lv.into_iter().map(|l| (l, clip.cloned()))); + return Ok(()); + }; + let hook = |c: &Node| vectorcraft_render::effects::outline_object(Some(d), c); + if let Some(art) = vectorcraft_render::effects::compound_shape_art(Some(d), n, Some(&hook)) { + out.push((art, clip.cloned())); + return Ok(()); + } + if !*clips { + return children.iter().try_for_each(|c| clipped_pf_leaves(d, c, clip, precision, out)); + } + let Some((first, rest)) = children.split_first() else { return Ok(()) }; + let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(first) else { return Ok(()) }; + let mut region = Clip { path: PathData::from_bezpath(&outline), rule }; + if has_invalid_coordinates(®ion.path) { + return Err(EngineError::Other("paths contain invalid coordinates".into())); + } + if let Some(outer) = clip { + let path = po::try_boolean(®ion.path, region.rule, &outer.path, outer.rule, BoolOp::Intersect, precision) + .map_err(|e| EngineError::Other(e.to_string()))?; + region = Clip { path, rule: FillRule::NonZero }; + } + let region = Arc::new(region); + rest.iter().try_for_each(|c| clipped_pf_leaves(d, c, Some(®ion), precision, out)) +} + +/// `path`, filled by `rule`, where `clip` shows it: its area intersected with the region, filled +/// non-zero, and with `lines` (Divide, whose open contours cut) its open contours' parts inside the +/// region, so their hidden parts cut nothing. +fn clipped(path: PathData, rule: FillRule, clip: &Clip, lines: bool, precision: f64) -> Result<(PathData, FillRule)> { + if has_invalid_coordinates(&path) { + // Left as it is for the operation to refuse ("paths contain invalid coordinates"). + return Ok((path, rule)); + } + let (Some(within), Some(bounds)) = (clip.path.control_bounds(), path.control_bounds()) else { return Ok((PathData::default(), rule)) }; + if within.intersect(bounds).is_zero_area() && !bounds.is_zero_area() { + // Wholly outside the region (a line's bounds may be flat, so only an area's are trusted). + return Ok((PathData::default(), rule)); + } + let (open, closed): (Vec, Vec) = + if lines { path.subpaths.into_iter().partition(|sp| !sp.closed) } else { (vec![], path.subpaths) }; + let mut subs = vec![]; + if !closed.is_empty() { + let area = po::try_boolean(&PathData::new(closed), rule, &clip.path, clip.rule, BoolOp::Intersect, precision) + .map_err(|e| EngineError::Other(e.to_string()))?; + subs.extend(area.subpaths); + } + if !open.is_empty() { + let open = PathData::new(open); + // Each segment is sampled at least every 1/16 of the region's shorter side (and 24 times), + // and the crossings found are refined: a part of the region narrower than that, which a + // line crosses between two samples, can be missed. + let step = (within.width().min(within.height()) / 16.0).max(precision); + let outline = clip.path.to_bezpath(); + let outside = |q| !vectorcraft_geom::hit::fill_contains(&outline, clip.rule, q); + match super::draw2::erase_outline(&open, step, &outside) { + Some(pieces) => subs.extend(pieces.into_iter().flat_map(|p| p.subpaths)), + None => subs.extend(open.subpaths), + } + } + Ok((PathData::new(subs), FillRule::NonZero)) +} + /// How many shapes a Pathfinder operation takes from `n` selected alone: its leaf shapes, however /// deep its groups nest (an expanded stroke is a group inside the group, #1635). Inside a compound /// shape, a blend, an envelope or another live object and a symbol instance count as one shape @@ -598,9 +684,9 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result { let mut styles: Vec