From 37949e4a76d202ceaaf9f23773d3a6cd4fa8e29c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 00:14:32 -0800 Subject: [PATCH 01/62] 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/62] 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/62] 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/62] 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/62] 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 c49d45c8266308eb92273a40c8da8599a7940f0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:01:23 -0800 Subject: [PATCH 06/62] Path Precision Tools: Common Tangents measures each line near where it touches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each tangent measured every segment of both paths to find where it touches them, so two paths of thousands of segments with thousands of tangents took segments × tangents work. Each line now starts from the segment found for the nearest sampled direction and walks outward only as far as the stretch that lies along it. On two 2,000-sided polygons with 4,000 tangents, the segment measurements drop from about 33.5 million to 1.6 million. A turned or scaled ellipse is measured exactly however thin it is. A map is refused only when its determinant is within the rounding of its entries; before, an ellipse more than about 1e12 times longer than wide was refused as having no area. --- .../pathops/src/addons/pathtools/tangents.rs | 132 +++++++++++++++--- 1 file changed, 113 insertions(+), 19 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 2059932aa2..c01c80957e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -77,7 +77,9 @@ impl Outline { pub fn ellipse(unit: Affine) -> Result { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); - if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may + // belong to a map with no area. Any thinner ellipse is measured exactly. + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) @@ -270,11 +272,13 @@ impl Outline { } } - /// The points of the outline on the line `p · n = h`, its support value: the point where - /// `p · n` is largest, and the ends of any straight side along the line. Another point counts - /// when it lies within `tol` of the line plus `slope` times its distance from that largest - /// point, where `slope` is how far off the normal's angle may be. - fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + /// The points of the outline on the line `p · n = h`, its support value, which is reached on + /// segment `at`: the point where `p · n` is largest, and the ends of any straight side along + /// the line. Another point counts when it lies within `tol` of the line plus `slope` times its + /// distance from that largest point, where `slope` is how far off the normal's angle may be. + /// On a convex outline the points that count form one run around the largest one, so the + /// segments are measured from `at` outward both ways until a segment's end does not count. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec { match self { Outline::Ellipse { center, m: [a, b, c, d] } => { let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); @@ -282,9 +286,25 @@ impl Outline { vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] } Outline::Convex { segments, .. } => { + let len = segments.len(); let mut all = vec![]; - for s in segments { - each_extreme(s, n, |p, v| all.push((p, v))); + let Some(first) = segments.get(at % len.max(1)) else { return vec![] }; + each_extreme(first, n, |p, v| all.push((p, v))); + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot(); + let mut ahead = 0; + for j in 1..len { + match segments.get((at + j) % len) { + Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } + ahead = j; + } + for j in 1..len - ahead { + match segments.get((at + len - j) % len) { + Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } } let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() @@ -322,6 +342,8 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { } fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + #[cfg(test)] + tests::EXTREMES.with(|c| c.set(c.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -396,10 +418,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincid let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); let mut out = Vec::with_capacity(external.len() + internal.len()); for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { for root in list { - let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + let t = tangent_at(&a, &b, kind, root.angle, root.double, size); out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); } } @@ -414,21 +437,47 @@ struct Root { double: bool, } -/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, -/// and `b` on the same side (external) or the other side (internal). `double` when the outlines -/// touch there. -fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { +/// An outline with the segment it is touched on at each sampled normal angle. +struct Hinted<'a> { + o: &'a Outline, + at: &'a [f64], + hints: &'a [usize], +} + +impl Hinted<'_> { + /// The support value at the normal angle `angle` and the segment it is reached on, walking on + /// from the segment of the sample at or before `angle`. + fn support(&self, angle: f64) -> (f64, usize) { + let angle = angle.rem_euclid(TAU); + // Before the first sample, the last one (taken 2π back) comes before `angle`. + let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1)); + self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0)) + } +} + +/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's +/// value, and `b` on the same side (external) or the other side (internal). `double` when the +/// outlines touch there. +fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent { + let n = dir(angle); // The rounding allowed in `p · n` grows with each outline's own size and its distance from the // origin. let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); - let (tol_a, tol_b) = (rounding(a), rounding(b)); + let (tol_a, tol_b) = (rounding(a.o), rounding(b.o)); // Bisection finds a simple root's angle to about the rounding of the support values; the // golden-section search finds a double root's to about 1e-8 radians. let slope = if double { 1e-7 } else { 1e-10 }; - let ha = a.support(n); - let (on_a, on_b) = match kind { - TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), - TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + let (ha, sa) = a.support(angle); + let on_a = a.o.touching(n, ha, tol_a, slope, sa); + let on_b = match kind { + TangentKind::External => { + let (hb, sb) = b.support(angle); + b.o.touching(n, hb, tol_b, slope, sb) + } + TangentKind::Internal => { + let (hb, sb) = b.support(angle + TAU / 2.0); + b.o.touching(-n, hb, tol_b, slope, sb) + } }; // Positions along the line, which runs square to `n` through `n * ha`. let t = Vec2::new(-n.y, n.x); @@ -441,7 +490,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool // stand a little apart. let (from, to) = if double && hi - lo <= 1e-6 * size { // Touching at one point: the narrower outline's width along the line, centered there. - let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); let mid = (lo + hi) / 2.0; (mid - width / 2.0, mid + width / 2.0) } else if mean(&on_a) <= mean(&on_b) { @@ -575,11 +624,18 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { #[cfg(test)] mod tests { + use std::cell::Cell; + use kurbo::Rect; use vectorcraft_geom::shapes; use super::*; + thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread. + pub(super) static EXTREMES: Cell = const { Cell::new(0) }; + } + fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -850,6 +906,44 @@ mod tests { assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); } + #[test] + fn each_tangent_measures_only_the_segments_near_where_it_touches() { + // Two regular 2,000-gons about one center, one turned half a step: 4,000 external + // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // measurements per tangent. + let sides = 2_000; + let gon = |turn: f64| { + let pts: Vec = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap()); + EXTREMES.with(|c| c.set(0)); + let all = common_tangents(&a, &b).unwrap(); + let calls = EXTREMES.with(Cell::get); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides); + assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len()); + let r = 100.0 * (TAU / (4 * sides) as f64).sin(); + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_very_thin_ellipse_is_measured_exactly() { + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the + // ellipse's tips to the circle. + let thin = Affine::scale_non_uniform(1e6, 1e-7); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + } + // A map whose determinant is lost in the rounding of its entries is still refused. + assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + } + #[test] fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is From 7e1d76ae7d4e8ebd70b48589dfb9b4fdbe9bd775 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:31:26 -0800 Subject: [PATCH 07/62] Path Precision Tools: Common Tangents tests a turned thin ellipse and the area limit The thin-ellipse test now also turns the figure 30 degrees and checks that each line still ends at the ellipse's tip. A determinant four times its rounding is accepted and one equal to its rounding is refused, so the limit is tested on both sides. The comment on the limit said the opposite of the rule: an ellipse is measured exactly when its determinant is larger than the rounding of its entries. The segment counter used by the tests is declared next to the function it counts, and the estimate in the work test is corrected to about 8,000 measurements per tangent. --- .../pathops/src/addons/pathtools/tangents.rs | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index c01c80957e..9e198229fd 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -78,7 +78,8 @@ impl Outline { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may - // belong to a map with no area. Any thinner ellipse is measured exactly. + // belong to a map with no area. An ellipse whose determinant is larger is measured + // exactly. if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } @@ -313,8 +314,6 @@ impl Outline { } } -/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where -/// the curve runs square to `n`) and the value there. /// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product /// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared /// with the segment's control polygon length squared. @@ -341,9 +340,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { low < -1e-9 * scale } +#[cfg(test)] +thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread, for the tests. + static EXTREMES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { #[cfg(test)] - tests::EXTREMES.with(|c| c.set(c.get() + 1)); + EXTREMES.with(|n| n.set(n.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -631,11 +638,6 @@ mod tests { use super::*; - thread_local! { - /// How many times [`each_extreme`] has measured a segment on this thread. - pub(super) static EXTREMES: Cell = const { Cell::new(0) }; - } - fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -909,7 +911,7 @@ mod tests { #[test] fn each_tangent_measures_only_the_segments_near_where_it_touches() { // Two regular 2,000-gons about one center, one turned half a step: 4,000 external - // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // tangents. Measuring every segment of both outlines for every tangent takes about 8,000 // measurements per tangent. let sides = 2_000; let gon = |turn: f64| { @@ -928,19 +930,28 @@ mod tests { #[test] fn a_very_thin_ellipse_is_measured_exactly() { - // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the - // ellipse's tips to the circle. - let thin = Affine::scale_non_uniform(1e6, 1e-7); - let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); - let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); - for t in &all { - check_against_samples(t, &sa, &sb, 1e-3); - let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; - assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned + // 30 degrees: the tangents run from the ellipse's tips to the circle. + for deg in [0.0, 30.0] { + let turn = Affine::rotate(f64::to_radians(deg)); + let thin = turn * Affine::scale_non_uniform(1e6, 1e-7); + let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + // The end on the ellipse, taken back to the unturned figure. + let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to); + let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}"); + } } - // A map whose determinant is lost in the rounding of its entries is still refused. + // A determinant a few times its rounding is taken; one lost in the rounding of the map's + // entries is still refused. + assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok()); + assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); } From 91052081430967b29f0b0410907226deb11eb77e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:48:23 -0800 Subject: [PATCH 08/62] 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 09/62] 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 10/62] 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 d487dae5b3d31bfab978332f92080b75c98eece1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:19:45 -0800 Subject: [PATCH 11/62] Path Precision Tools: Common Tangents refuses a path that turns inward at a join The convexity check compared points sampled along each segment and the curvature inside each segment, but not the corner where one segment meets the next. A segment that leaves its start a little the wrong way could make an inward corner that neither check saw. Each join is now checked by the directions the two segments meet it in, skipping segments of no length. --- .../pathops/src/addons/pathtools/tangents.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 9e198229fd..b8a7ce6b6e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -156,6 +156,16 @@ impl Outline { if segments.iter().any(|s| bends_against(s, sign)) { return Err(OutlineError::NotConvex); } + // A corner can also turn inward between two of the points: each join is checked by the + // directions the segments leave and reach it in. Segments of no length are passed over. + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot()); + let ends: Vec<(Vec2, Vec2)> = segments + .iter() + .filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0]))) + .collect(); + if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) { + return Err(OutlineError::NotConvex); + } let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); if !center.x.is_finite() || !center.y.is_finite() { return Err(OutlineError::Empty); @@ -982,6 +992,15 @@ mod tests { bp.close_path(); let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); + // A triangle whose first side is a cubic that leaves its start a little the wrong way: the + // corner there turns inward, though the checked points and the curve itself turn one way. + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0)); + bp.line_to((50.0, 100.0)); + bp.close_path(); + let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(¬ch).err(), Some(OutlineError::NotConvex)); // A square traced twice around winds around twice. let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); From 83f21f44965f725989bff6276f0b1ece48e8c3bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:36:17 -0800 Subject: [PATCH 12/62] Path Precision Tools: Common Tangents adds the centerline between tiny paths The centerline was left out whenever the two centers were less than 1e-9 points apart, so two separate paths a billionth of a point wide got their tangents but no centerline. Centers now count as one point only when they are closer than a billionth of the larger path's size. --- crates/engine/src/cmd/addons/pathtools/tangents.rs | 3 ++- .../src/cmd/addons/pathtools/tangents/tests.rs | 13 +++++++++++++ crates/pathops/src/addons/pathtools/tangents.rs | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 4376cbe791..8102777687 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { }; return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); } - let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + // Centers closer than a billionth of the larger path's size count as one point: no line. + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center())); let fill = Paint::None; let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 5ed6e2b0d6..aef694bbdd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() { } } +#[test] +fn tiny_paths_close_together_still_get_the_centerline() { + // Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four + // tangents, and centers apart by far more than their sizes' rounding. + let mut s = session(); + let a = circle(&mut s, 1.0, 1.0, 1e-10); + let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}"); + assert_eq!(r["centerline"], r["ids"][4]); +} + #[test] fn the_lines_take_the_current_stroke_and_no_fill() { let mut s = session(); diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index b8a7ce6b6e..a42e628cad 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -259,7 +259,7 @@ impl Outline { } /// The diagonal of the bounds (an ellipse's: of the box its axes span). - fn size(&self) -> f64 { + pub fn size(&self) -> f64 { match self { Outline::Ellipse { m, .. } => { let [a, b, c, d] = *m; From fbed80b2f891785622ea72ae213011078877ac97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:59:22 -0800 Subject: [PATCH 13/62] 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 14/62] 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 15/62] 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 0f4cc60018a33c3678833b44e9938ad56d32b966 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:30:25 -0800 Subject: [PATCH 16/62] Actions: Reset Actions restores the default set The Actions panel menu has Reset Actions. It asks first: OK replaces every set in the panel with the built-in Default Actions set, which becomes current and selected, and Append adds the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2). Cancel changes nothing. The item is off while an action records or plays, and the reset records no undo step. - ui.actionSet.reset {mode?: "replace" | "append"} runs it; omitted params count as {}, and another type, key or mode is an error. - Replace clears the panel's selected action and step, expanded actions and a dragged step, and closes an open dialog that holds a set index. On the built-in set already shown that way it changes nothing. - New strings have rows in every catalog. Three French messages about tangents get the no-break space before the colon that fr.tsv uses. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/confirm.rs | 22 ++ crates/ui-egui/src/dialogs/tests.rs | 33 +++ 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 | 10 +- 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/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/actions.rs | 243 +++++++++++++++++++++ crates/ui-egui/src/panels/actions/files.rs | 2 +- docs/mcp.md | 11 + docs/target-app-parity.md | 1 + docs/ui-parity.md | 3 +- 39 files changed, 442 insertions(+), 5 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0e3d6df203..f81ea2f7f9 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1647,6 +1647,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), + ( + "ui.actionSet.reset", + "Reset Actions", + "", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index da1062838f..30b02e4380 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -339,6 +339,7 @@ registry! { Replace: [confirm::REPLACE] => confirm::REPLACE_SPEC, ReplaceFiles: [confirm::REPLACE_FILES] => confirm::REPLACE_FILES_SPEC, ResetPreferences: [confirm::RESET_PREFS] => confirm::RESET_PREFS_SPEC, + ResetActions: [confirm::RESET_ACTIONS] => confirm::RESET_ACTIONS_SPEC, NewSwatch: [new_swatch::KIND] => new_swatch::SPEC, NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 6f51be44d9..15b28c2d27 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -134,6 +134,28 @@ fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { Ok(Value::Null) } +/// The dialog kind of the question Reset Actions asks in the Actions panel menu +/// ([`ask_reset_actions`]). Fields: `message`, `detail`, `append` (set by Append). +pub const RESET_ACTIONS: &str = "resetActions"; + +pub(super) const RESET_ACTIONS_SPEC: DialogSpec = DialogSpec { confirm: reset_actions, alternate: Some(("Append", "append")), ..SPEC }; + +/// Ask whether to replace the Actions panel's sets with the built-in set. OK replaces them, Append +/// adds the built-in set after them ([`crate::panels::actions::reset`]), and Cancel or Escape +/// changes nothing. +pub(crate) fn ask_reset_actions(app: &mut VectorcraftApp) { + let message = tl!("Replace the current actions with the default set?"); + let detail = tl!("Append adds the default set after the current sets instead."); + app.ui.dialog = Some(Dialog::new(RESET_ACTIONS, json!({"message": message, "detail": detail, "append": false}))); +} + +/// OK or Append on [`ask_reset_actions`]: closes, then resets the action sets. +fn reset_actions(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mode = if d.fields.get("append").and_then(Value::as_bool) == Some(true) { "append" } else { "replace" }; + app.ui.dialog = None; + app.run(crate::panels::actions::RESET, json!({ "mode": mode })) +} + /// Most messages kept for later while a dialog is open ([`tell`]). const MAX_WAITING: usize = 16; diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 3ce5455437..201b34171d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2524,6 +2524,39 @@ fn flare_options_alt_turns_cancel_into_reset() { ); } +/// Reset Actions' question: OK replaces the action sets with the built-in set, Append adds the +/// built-in set after them, and Cancel or Escape (`cancel`) leaves them as they are. +#[test] +fn reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets() { + use crate::panels::actions::{ActionSet, default_sets}; + let names = |app: &VectorcraftApp| app.ui.action_sets.iter().map(|s| s.name.clone()).collect::>(); + let mut app = app(); + app.ui.action_sets.push(ActionSet::new("Mine", vec![])); + app.ui.action_set = Some(1); + let mut f = Frames::new(); + for (answer, want, current) in [ + (Some("Cancel"), vec!["Default Actions", "Mine"], Some(1)), + (None, vec!["Default Actions", "Mine"], Some(1)), + (Some("Append"), vec!["Default Actions", "Mine", "Default Actions 2"], Some(1)), + (Some("OK"), vec!["Default Actions"], Some(0)), + ] { + crate::dialogs::confirm::ask_reset_actions(&mut app); + match answer { + Some(label) => { + let at = f.button(&mut app, label); + f.press(&mut app, at, true); + f.press(&mut app, at, false); + } + None => cancel(&mut app), + } + assert!(app.ui.dialog.is_none(), "{answer:?} closes the question"); + assert_eq!(names(&app), want, "{answer:?}"); + assert_eq!(app.ui.action_set, current, "{answer:?}"); + } + let saved = |sets: &[ActionSet]| serde_json::to_value(sets).unwrap(); + assert_eq!(saved(&app.ui.action_sets), saved(&default_sets()), "OK leaves the built-in set as it comes"); +} + /// The slider that screen readers name `label` in `out`'s tree: its node id, number and text. fn slider_node(out: &egui::FullOutput, label: &str) -> (egui::accesskit::NodeId, Option, Option) { let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..994edf40ff 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2571,6 +2571,10 @@ font-technology Variable Променливи Play Current Selection Изпълнение на текущия избор Save Actions… Запазване на действия… Load Actions… Зареждане на действия… + Reset Actions Нулиране на действия + Replace the current actions with the default set? Да се заменят ли текущите действия с набора по подразбиране? + Append adds the default set after the current sets instead. С „Добавяне“ наборът по подразбиране се добавя след текущите набори. + Append Добавяне Plug-in Info Информация за приставката Plug-ins Приставки Plug-in… Приставка… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..8c0e37094a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1502,6 +1502,10 @@ lighting Light Svjetlo Play Current Selection Reprodukuj trenutni odabir Save Actions… Sačuvaj akcije… Load Actions… Učitaj akcije… + Reset Actions Vrati akcije na početno + Replace the current actions with the default set? Zamijeniti trenutne akcije zadanim skupom? + Append adds the default set after the current sets instead. Dugme Dodaj umjesto toga dodaje zadani skup iza trenutnih skupova. + Append Dodaj Reflect Horizontal Odrazi vodoravno Rotate 90° CW Rotiraj za 90° u smjeru kazaljke Set 1 Skup 1 diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..e5b3ac903b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3329,6 +3329,10 @@ digits Malayalam Malaiàlam Play Current Selection Reprodueix la selecció actual Save Actions… Desa les accions… Load Actions… Carrega accions… + Reset Actions Restableix les accions + Replace the current actions with the default set? Voleu reemplaçar les accions actuals pel conjunt predeterminat? + Append adds the default set after the current sets instead. Amb Afegeix, el conjunt predeterminat s’afegeix després dels conjunts actuals. + Append Afegeix Play: Reprodueix: Plug-in Info Informació del complement Plug-ins Complements diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..03d2d0903e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1530,6 +1530,10 @@ lighting Light Světlo Play Current Selection Přehrát aktuální výběr Save Actions… Uložit akce… Load Actions… Načíst akce… + Reset Actions Obnovit akce + Replace the current actions with the default set? Nahradit aktuální akce výchozí sadou? + Append adds the default set after the current sets instead. Tlačítko Připojit místo toho přidá výchozí sadu za aktuální sady. + Append Připojit Reflect Horizontal Zrcadlit vodorovně Rotate 90° CW Otočit o 90° po směru hodin Set 1 Sada 1 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..29db307e85 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4103,6 +4103,10 @@ lighting Light Lys Play Current Selection Afspil aktuel markering Save Actions… Gem handlinger… Load Actions… Indlæs handlinger… + Reset Actions Nulstil handlinger + Replace the current actions with the default set? Vil du erstatte de aktuelle handlinger med standardsættet? + Append adds the default set after the current sets instead. Tilføj tilføjer i stedet standardsættet efter de aktuelle sæt. + Append Tilføj Reflect Horizontal Spejl vandret Rotate 90° CW Rotér 90° med uret Set 1 Sæt 1 diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..9206418420 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2617,6 +2617,10 @@ diagnostics ui Oberfläche Play Current Selection Aktuelle Auswahl abspielen Save Actions… Aktionen speichern… Load Actions… Aktionen laden… + Reset Actions Aktionen zurücksetzen + Replace the current actions with the default set? Aktuelle Aktionen durch den Standardsatz ersetzen? + Append adds the default set after the current sets instead. Mit „Anhängen“ wird der Standardsatz stattdessen nach den aktuellen Sätzen hinzugefügt. + Append Anhängen Plug-in Info Plug-in-Informationen Plug-ins Plug-ins Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..76d5a30fba 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3525,6 +3525,10 @@ theme Appearance Εμφάνιση Play Current Selection Αναπαραγωγή τρέχουσας επιλογής Save Actions… Αποθήκευση ενεργειών… Load Actions… Φόρτωση ενεργειών… + Reset Actions Επαναφορά ενεργειών + Replace the current actions with the default set? Να αντικατασταθούν οι τρέχουσες ενέργειες με το προεπιλεγμένο σύνολο; + Append adds the default set after the current sets instead. Η Προσάρτηση προσθέτει αντί γι’ αυτό το προεπιλεγμένο σύνολο μετά τα τρέχοντα σύνολα. + Append Προσάρτηση Plug-in Info Πληροφορίες προσθέτου Plug-in… Πρόσθετο… Point Text Objects Αντικείμενα κειμένου σημείου diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..7653ca26ef 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2660,6 +2660,10 @@ font-technology Variable Variables Play Current Selection Reproducir la selección actual Save Actions… Guardar acciones… Load Actions… Cargar acciones… + Reset Actions Restablecer acciones + Replace the current actions with the default set? ¿Reemplazar las acciones actuales por el conjunto predeterminado? + Append adds the default set after the current sets instead. Añadir agrega en su lugar el conjunto predeterminado después de los conjuntos actuales. + Append Añadir Plug-in Info Información del plugin Plug-ins Plugins Plug-in… Plugin… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..5d9baaf716 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1504,6 +1504,10 @@ lighting Light Valo Play Current Selection Toista nykyinen valinta Save Actions… Tallenna toiminnot… Load Actions… Lataa toiminnot… + Reset Actions Palauta toiminnot + Replace the current actions with the default set? Korvataanko nykyiset toiminnot oletussarjalla? + Append adds the default set after the current sets instead. Lisää-painike lisää sen sijaan oletussarjan nykyisten sarjojen perään. + Append Lisää Reflect Horizontal Peilaa vaakasuunnassa Rotate 90° CW Kierrä 90° myötäpäivään Set 1 Sarja 1 diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..34482ccebc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2648,6 +2648,10 @@ font-technology Variable Variables Play Current Selection Exécuter la sélection actuelle Save Actions… Enregistrer les scripts… Load Actions… Charger des scripts… + Reset Actions Réinitialiser les scripts + Replace the current actions with the default set? Remplacer les scripts actuels par le jeu par défaut ? + Append adds the default set after the current sets instead. Le bouton Ajouter ajoute plutôt le jeu par défaut après les jeux actuels. + Append Ajouter Plug-in Info Informations sur le module externe Plug-ins Modules externes Plug-in… Module externe… @@ -7464,9 +7468,9 @@ breakText Glyphs Glyphes @msg a selected path has no area un tracé sélectionné n’a pas de surface @msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments @msg the two paths have the same outline les deux tracés ont le même contour -@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune -@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne -@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..b2909ced84 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2051,6 +2051,10 @@ Live curve fitting લાઇવ કર્વ ફિટિંગ Live preview લાઇવ પૂર્વાવલોકન Load Actions… ઍક્શન લોડ કરો… + Reset Actions ઍક્શન રીસેટ કરો + Replace the current actions with the default set? વર્તમાન ઍક્શનને ડિફૉલ્ટ સેટથી બદલવા છે? + Append adds the default set after the current sets instead. ઉમેરો તેના બદલે ડિફૉલ્ટ સેટને વર્તમાન સેટ પછી ઉમેરે છે. + Append ઉમેરો Load All Styles બધી સ્ટાઇલ લોડ કરો Load All Styles… બધી સ્ટાઇલ લોડ કરો… Load Character Styles કેરેક્ટર સ્ટાઇલ લોડ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..3db6e28401 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2756,6 +2756,10 @@ antiAlias Sharp शार्प Live Shape लाइव आकार Live Shape Properties लाइव शेप प्रॉपर्टीज़ Load Actions… एक्शन्स लोड करें… + Reset Actions एक्शन्स रीसेट करें + Replace the current actions with the default set? मौजूदा एक्शन्स को डिफ़ॉल्ट सेट से बदलें? + Append adds the default set after the current sets instead. जोड़ें इसके बजाय डिफ़ॉल्ट सेट को मौजूदा सेट के बाद जोड़ता है। + Append जोड़ें Load Color Profile… लोड कलर प्रोफ़ाइल… Load EPS into Clipboard ईपीएस को क्लिपबोर्ड में लोड करें Load Image into Clipboard क्लिपबोर्ड में इमेज लोड करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..b94721a1a0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3206,6 +3206,10 @@ diagnostics ui felület Play Current Selection Kijelölt művelet lejátszása Save Actions… Műveletek mentése… Load Actions… Műveletek betöltése… + Reset Actions Műveletek visszaállítása + Replace the current actions with the default set? Lecseréled az aktuális műveleteket az alapértelmezett készletre? + Append adds the default set after the current sets instead. A Hozzáfűzés ehelyett az aktuális készletek után adja hozzá az alapértelmezett készletet. + Append Hozzáfűzés Plug-in Info Bővítmény adatai Plug-ins Bővítmények Plug-in… Bővítmény… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..3c111424a3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1429,6 +1429,10 @@ lighting Light Cahaya Play Current Selection Putar seleksi saat ini Save Actions… Simpan tindakan… Load Actions… Muat tindakan… + Reset Actions Atur ulang tindakan + Replace the current actions with the default set? Ganti tindakan saat ini dengan set default? + Append adds the default set after the current sets instead. Tambahkan justru menambahkan set default setelah set saat ini. + Append Tambahkan Reflect Horizontal Pencerminan horizontal Rotate 90° CW Putar 90° searah jarum jam Set 1 Set 1 diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..8754acf7e0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2698,6 +2698,10 @@ diagnostics ui interfaccia Play Current Selection Esegui selezione corrente Save Actions… Salva azioni… Load Actions… Carica azioni… + Reset Actions Ripristina azioni + Replace the current actions with the default set? Sostituire le azioni correnti con il set predefinito? + Append adds the default set after the current sets instead. Aggiungi aggiunge invece il set predefinito dopo i set correnti. + Append Aggiungi Plug-in Info Informazioni plug-in Plug-ins Plug-in Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..d0b04c7878 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2784,6 +2784,10 @@ diagnostics ui UI Play Current Selection 選択項目を再生 Save Actions… アクションを保存… Load Actions… アクションを読み込み… + Reset Actions アクションをリセット + Replace the current actions with the default set? 現在のアクションを初期設定のセットで置き換えますか? + Append adds the default set after the current sets instead. 「追加」を選ぶと、初期設定のセットを現在のセットの後に追加します。 + Append 追加 Plug-in Info プラグイン情報 Plug-in… プラグイン… Points ポイント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..6de2e02ead 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3453,6 +3453,10 @@ lighting Light სინათლე Play Current Selection მიმდინარე მონიშნულის შესრულება Save Actions… მოქმედებების შენახვა… Load Actions… მოქმედებების ჩატვირთვა… + Reset Actions მოქმედებების ჩამოყრა + Replace the current actions with the default set? ჩანაცვლდეს მიმდინარე მოქმედებები ნაგულისხმევი ნაკრებით? + Append adds the default set after the current sets instead. დამატება ამის ნაცვლად ნაგულისხმევ ნაკრებს მიმდინარე ნაკრებების შემდეგ ამატებს. + Append დამატება Reflect Horizontal ჰორიზონტალურად არეკვლა Rotate 90° CW 90°-ით შემობრუნება საათის ისრის მიმართულებით Set 1 ნაკრები 1 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..7650d7ffe0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2774,6 +2774,10 @@ diagnostics ui UI Play Current Selection 현재 선택 항목 재생 Save Actions… 액션 저장… Load Actions… 액션 불러오기… + Reset Actions 액션 재설정 + Replace the current actions with the default set? 현재 액션을 기본 세트로 바꾸시겠습니까? + Append adds the default set after the current sets instead. 추가를 누르면 대신 기본 세트를 현재 세트 뒤에 추가합니다. + Append 추가 Plug-in Info 플러그인 정보 Plug-in… 플러그인… Points 포인트 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..e405ea5eca 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1997,6 +1997,10 @@ lighting Light Licht Play Current Selection Huidige selectie afspelen Save Actions… Acties opslaan… Load Actions… Acties laden… + Reset Actions Acties opnieuw instellen + Replace the current actions with the default set? De huidige acties vervangen door de standaardset? + Append adds the default set after the current sets instead. Toevoegen voegt in plaats daarvan de standaardset toe na de huidige sets. + Append Toevoegen Reflect Horizontal Horizontaal spiegelen Rotate 90° CW 90° met de klok mee draaien Set 1 Set 1 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..c00b790dc4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1443,6 +1443,10 @@ lighting Light Światło Play Current Selection Odtwórz bieżące zaznaczenie Save Actions… Zapisz operacje… Load Actions… Wczytaj operacje… + Reset Actions Resetuj operacje + Replace the current actions with the default set? Zastąpić bieżące operacje zestawem domyślnym? + Append adds the default set after the current sets instead. Dołącz dodaje zamiast tego zestaw domyślny po bieżących zestawach. + Append Dołącz Reflect Horizontal Odbij w poziomie Rotate 90° CW Obróć o 90° w prawo Set 1 Zestaw 1 diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..7aa71576ca 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2194,6 +2194,10 @@ antiAlias Sharp Nítido Play Current Selection Reproduzir Seleção Atual Save Actions… Salvar Ações… Load Actions… Carregar Ações… + Reset Actions Redefinir Ações + Replace the current actions with the default set? Substituir as ações atuais pelo conjunto padrão? + Append adds the default set after the current sets instead. Anexar adiciona o conjunto padrão depois dos conjuntos atuais. + Append Anexar Plug-in Info Informações do Plug-in Plug-ins Plug-ins Plug-in… Plug-in… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..942cb3b44c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2687,6 +2687,10 @@ diagnostics ui интерфейс Play Current Selection Воспроизвести текущее выделение Save Actions… Сохранить действия… Load Actions… Загрузить действия… + Reset Actions Сбросить действия + Replace the current actions with the default set? Заменить текущие действия набором по умолчанию? + Append adds the default set after the current sets instead. Кнопка «Добавить» вместо этого добавляет набор по умолчанию после текущих наборов. + Append Добавить Plug-in Info Сведения о модуле Plug-ins Модули Plug-in… Модуль… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..58b4194a69 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2591,6 +2591,10 @@ font-technology Variable Variabla Play Current Selection Spela upp aktuell markering Save Actions… Spara åtgärder… Load Actions… Läs in åtgärder… + Reset Actions Återställ åtgärder + Replace the current actions with the default set? Vill du ersätta de aktuella åtgärderna med standarduppsättningen? + Append adds the default set after the current sets instead. Lägg till lägger i stället till standarduppsättningen efter de aktuella uppsättningarna. + Append Lägg till Plug-in Info Information om plugin Plug-ins Plugins Plug-in… Plugin… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..eed24053b8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2432,6 +2432,10 @@ shape Open Açık Play Current Selection Geçerli Seçimi Oynat Save Actions… Eylemleri Kaydet… Load Actions… Eylemleri Yükle… + Reset Actions Eylemleri Sıfırla + Replace the current actions with the default set? Geçerli eylemler varsayılan setle değiştirilsin mi? + Append adds the default set after the current sets instead. Ekle bunun yerine varsayılan seti geçerli setlerin sonuna ekler. + Append Ekle Plug-in Info Eklenti Bilgisi Plug-ins Eklentiler Plug-in… Eklenti… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..648ff247eb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2690,6 +2690,10 @@ diagnostics ui інтерфейс Play Current Selection Відтворити поточне виділення Save Actions… Зберегти дії… Load Actions… Завантажити дії… + Reset Actions Скинути дії + Replace the current actions with the default set? Замінити поточні дії набором за умовчанням? + Append adds the default set after the current sets instead. Кнопка «Додати» натомість додає набір за умовчанням після поточних наборів. + Append Додати Plug-in Info Відомості про модуль Plug-ins Модулі Plug-in… Модуль… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..ca7e0ed76e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3006,6 +3006,10 @@ diagnostics ui giao diện Play Current Selection Phát vùng chọn hiện tại Save Actions… Lưu hành động… Load Actions… Tải hành động… + Reset Actions Đặt lại hành động + Replace the current actions with the default set? Thay thế các hành động hiện tại bằng bộ mặc định? + Append adds the default set after the current sets instead. Nối thêm sẽ thêm bộ mặc định vào sau các bộ hiện tại. + Append Nối thêm Plug-in Info Thông tin plug-in Plug-ins Plug-in Plug-in… Phần bổ trợ… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..e69508653b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2551,6 +2551,10 @@ diagnostics ui 界面 Play Current Selection 播放当前选择项目 Save Actions… 存储动作… Load Actions… 载入动作… + Reset Actions 重置动作 + Replace the current actions with the default set? 要用默认动作组替换当前动作吗? + Append adds the default set after the current sets instead. “追加”会改为将默认动作组添加到当前动作组之后。 + Append 追加 Plug-in Info 插件信息 Plug-ins 增效工具 Plug-in… 增效工具… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..11b0b8b9c8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3822,6 +3822,10 @@ diagnostics ui 介面 Play Current Selection 播放目前選取項目 Save Actions… 儲存動作… Load Actions… 載入動作… + Reset Actions 重設動作 + Replace the current actions with the default set? 要用預設動作組取代目前的動作嗎? + Append adds the default set after the current sets instead. 「附加」會改為將預設動作組加到目前動作組之後。 + Append 附加 Plug-in Info 增效模組資訊 Plug-ins 增效模組 Plug-in… 增效模組… diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 495e606d6c..b4e1c668ac 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1004,6 +1004,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::load_set(app, p), crate::panels::actions::DELETE_SETS => crate::panels::actions::delete_sets(app, p), crate::panels::actions::DUPLICATE => crate::panels::actions::duplicate(app, p), + crate::panels::actions::RESET => crate::panels::actions::reset(app, p), "ui.shortcutImportDialog" => crate::dialogs::shortcut_import::command(app, p), _ => return None, }; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index ced961e32c..2b285c704b 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1648,6 +1648,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{set?: index, action?: index} copy the Actions panel's action at action in set (0 is the top set) to right after it in the same set; without action, copy set with all its actions to right after it (default: the current set). The copy is named after the original with \" copy\" added, a copied set gets an id of its own, and the copy is selected. The panel menu's Duplicate runs this for the selected action, else the current set. An index past the last set or action, or a copy that would give its set more than 1,000 actions or an action set file larger than 8 MiB, is an error and copies nothing → {set, action?}", ), + ( + crate::panels::actions::RESET, + "Reset Actions", + "", + "{mode?: \"replace\" | \"append\"} Reset Actions. replace (the default) replaces every set in the Actions panel with a new copy of the built-in Default Actions set, makes it current and selected, clears the panel's selected action and step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their ids and changed is false. append adds a new copy of the built-in set after the sets there are, with the next free number when its name is in use (Default Actions 2), and keeps the current set and the selection. Omitted params count as {}. Params of another type, another key, another mode, or a reset while an action records or plays (also while it waits at a stop) is an error and changes nothing. No undo step is recorded. The panel menu's Reset Actions asks first (dialog `resetActions`): OK runs this with replace, Append with append → {changed, mode, set: the first built-in set's index}", + ), ("file.showPackage", "Show Package", "", "{folder} show a package folder (file.package's folder) in the file manager → {folder}"), ( "docInfo.save", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 1c5509e9ae..8786b477f3 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -2145,6 +2145,81 @@ pub fn duplicate(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(result) } +/// The command that puts the built-in action set back ([`reset`]). +pub const RESET: &str = "ui.actionSet.reset"; + +/// `ui.actionSet.reset {mode?: "replace" | "append"}`: Reset Actions. `replace` (the default) +/// replaces every set in the panel with a new copy of the built-in sets ([`default_sets`]), makes +/// the first one current and selected, clears the panel's selected action and step, its expanded +/// actions and a step being dragged, and closes an open Set Options, New Action, Batch or step +/// dialog that names a set. When the panel already shows the built-in sets that way, nothing +/// changes and the sets keep their ids. `append` adds a new copy of the built-in sets after the +/// sets there are, a name already in use getting the next free number (`Default Actions 2`), and +/// keeps the current set and the selection. Omitted params (`null`) count as `{}`. Params of another +/// type, another key, or another `mode` is an error, and so is a reset while an action records or +/// plays (also while it waits at a stop); then nothing changes. No undo step is recorded. +/// → {changed, mode, set: the index of the first built-in set} +pub fn reset(app: &mut VectorcraftApp, p: &Value) -> Result { + const SELECTED: &str = "actions-selected"; + const EXPANDED: &str = "actions-expanded"; + let append = match p { + Value::Null => false, + Value::Object(m) => { + if let Some(key) = m.keys().find(|k| *k != "mode") { + let keys = "mode"; + return Err(format!("unknown parameter `{key}`; the command takes: {keys}")); + } + match m.get("mode").map(Value::as_str) { + None | Some(Some("replace")) => false, + Some(Some("append")) => true, + Some(_) => return Err("mode must be replace or append".into()), + } + } + got => return Err(format!("the params must be an object, not {got}")), + }; + if app.ui.recording.is_some() { + return Err("an action is already recording".into()); + } + if app.ui.action_playing.is_some() { + return Err("an action is already playing".into()); + } + let sets = default_sets(); + if append { + let first = app.ui.action_sets.len(); + for mut set in sets { + set.name = files::free_set_name(&app.ui.action_sets, &set.name); + app.ui.action_sets.push(set); + } + return Ok(json!({ "changed": true, "mode": "append", "set": first })); + } + let ctx = app.ui_ctx.clone(); + let panel_clear = ctx.as_ref().is_none_or(|ctx| { + pstate::>(ctx, SELECTED).is_none() + && pstate::>(ctx, SELECTED_STEP).is_none() + && pstate::>(ctx, DRAGGED_STEP).is_none() + && pstate::>(ctx, EXPANDED).is_empty() + }); + // The ids are not saved, so two lists that save alike hold the same sets. + let built_in = serde_json::to_value(&app.ui.action_sets).is_ok_and(|now| serde_json::to_value(&sets).is_ok_and(|new| new == now)); + let shown_as_reset = app.ui.action_set == Some(0) && app.ui.action_sets_selected == [0] && !app.ui.dialog.as_ref().is_some_and(holds_set); + if built_in && shown_as_reset && panel_clear { + return Ok(json!({ "changed": false, "mode": "replace", "set": 0 })); + } + app.ui.action_sets = sets; + app.ui.action_set = Some(0); + app.ui.action_sets_selected = vec![0]; + if app.ui.dialog.as_ref().is_some_and(holds_set) { + app.ui.dialog = None; + } + if let Some(ctx) = ctx { + set_pstate::>(&ctx, SELECTED, None); + set_pstate::>(&ctx, SELECTED_STEP, None); + set_pstate::>(&ctx, DRAGGED_STEP, None); + set_pstate(&ctx, EXPANDED, BTreeSet::::new()); + } + Ok(json!({ "changed": true, "mode": "replace", "set": 0 })) +} + /// The panel's (≡) menu. pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Button Mode is off while an action records, so the Stop button the list shows stays in reach. @@ -2239,6 +2314,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { app.status(e); } } + // Asks first: OK replaces the sets with the built-in set, Append adds it after them. + if widgets::menu_item(ui, tl!("Reset Actions"), !recording && app.ui.action_playing.is_none(), false) { + crate::dialogs::confirm::ask_reset_actions(app); + } } fn inclusion_box( @@ -3744,6 +3823,170 @@ mod tests { assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["set"].clone()), Some(json!(3)), "Set Options still on Other"); } + /// The sets as Save Actions… writes them, without the ids. + fn saved_sets(sets: &[ActionSet]) -> Value { + serde_json::to_value(sets).unwrap() + } + + /// A click on the panel menu's Reset Actions. + fn menu_reset(ctx: &egui::Context, app: &mut VectorcraftApp) { + use super::super::tests_appearance::{click, frame_events}; + let texts = frame_events(ctx, app, vec![], menu); + let item = texts.iter().find(|(s, _)| s.trim() == "Reset Actions").map(|(_, r)| *r).expect("Reset Actions in the menu"); + click(ctx, app, item.center(), menu); + } + + /// The panel menu's Reset Actions asks before it changes anything, also with no current set, + /// and does nothing while an action records or plays, waiting at a stop included. + #[test] + fn the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs() { + let mut app = app_with_sets(); + let ctx = egui::Context::default(); + let before = saved_sets(&app.ui.action_sets); + menu_reset(&ctx, &mut app); + let d = app.ui.dialog.as_ref().expect("Reset Actions asks first, with no current set too"); + assert_eq!((d.kind.as_str(), d.bool("append")), (crate::dialogs::confirm::RESET_ACTIONS, false)); + assert_eq!(saved_sets(&app.ui.action_sets), before, "asking changes no set"); + app.ui.dialog = None; + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + menu_reset(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "off while an action records"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + app.ui.dialog = None; + menu_reset(&ctx, &mut app); + assert!(app.ui.dialog.is_none(), "off while playback waits at a stop"); + } + + /// `ui.actionSet.reset` replaces every set, edited ones included, with the built-in set, makes it + /// current and selected, clears the panel's selected action and step, expanded actions and a + /// dragged step, closes a dialog that holds a set index, and records no undo step. + #[test] + fn reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones() { + let mut app = app_with_sets(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + app.ui.action_sets[0].name = "Renamed".into(); + app.ui.action_sets[0].actions.pop(); + app.ui.action_set = Some(2); + app.ui.action_sets_selected = vec![1, 2]; + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let nudge = app.ui.action_sets[1].actions[1].id; + set_pstate::>(&ctx, "actions-selected", Some((1, 1))); + set_pstate::>(&ctx, SELECTED_STEP, Some((nudge, 0))); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([nudge])); + let dragged: DraggedStep = (nudge, 0, std::sync::Arc::new((vec![], BTreeSet::new()))); + set_pstate::>(&ctx, DRAGGED_STEP, Some(dragged)); + crate::dialogs::action_batch::open(&mut app, 1, 1).unwrap(); + + assert_eq!(app.run(RESET, json!({})).unwrap(), json!({"changed": true, "mode": "replace", "set": 0})); + assert_eq!(saved_sets(&app.ui.action_sets), saved_sets(&default_sets()), "only the built-in set, as it comes"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0]), "it is current and selected"); + assert_eq!(pstate::>(&ctx, "actions-selected"), None); + assert_eq!(pstate::>(&ctx, SELECTED_STEP), None); + assert!(pstate::>(&ctx, "actions-expanded").is_empty()); + assert!(pstate::>(&ctx, DRAGGED_STEP).is_none()); + assert!(app.ui.dialog.is_none(), "the Batch dialog of a replaced set closes"); + assert_eq!(undo_steps(&app), undo, "no undo step"); + + app.ui.action_sets.clear(); + app.ui.action_set = None; + assert_eq!(app.run(RESET, Value::Null).unwrap(), json!({"changed": true, "mode": "replace", "set": 0}), "from no sets"); + assert_eq!(saved_sets(&app.ui.action_sets), saved_sets(&default_sets())); + assert_eq!(app.ui.action_set, Some(0)); + } + + /// Reset Actions on the built-in set as it comes still makes it current when no set is, and + /// changes nothing, ids included, once the panel shows it as a reset leaves it. + #[test] + fn reset_on_the_built_in_set_makes_it_current_then_changes_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.ui.action_set, None, "a new app has no current set"); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + assert_eq!(app.run(RESET, json!({"mode": "replace"})).unwrap()["changed"], true, "the set becomes current"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(0), vec![0])); + let ids = (app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect::>()); + assert_eq!(app.run(RESET, json!({})).unwrap(), json!({"changed": false, "mode": "replace", "set": 0})); + assert_eq!((app.ui.action_sets[0].id, app.ui.action_sets[0].actions.iter().map(|a| a.id).collect()), ids, "the ids stay"); + set_pstate(&ctx, "actions-expanded", BTreeSet::from([ids.1[0]])); + assert_eq!(app.run(RESET, json!({})).unwrap()["changed"], true, "an expanded action is collapsed"); + crate::dialogs::action_set_options::open(&mut app, 0); + assert_eq!(app.run(RESET, json!({})).unwrap()["changed"], true, "Set Options for the set closes"); + assert!(app.ui.dialog.is_none()); + } + + /// Append adds a copy of the built-in set after the sets there are, with the first free number, + /// and keeps every set, the current set, the selection and an open dialog as they are. + #[test] + fn reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest() { + let mut app = app_with_sets(); + app.ui.action_sets[0].actions.pop(); + app.ui.action_sets[2].name = "Default Actions 3".into(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + set_pstate::>(&ctx, "actions-selected", Some((1, 1))); + let before = saved_sets(&app.ui.action_sets); + assert_eq!(app.run(RESET, json!({"mode": "append"})).unwrap(), json!({"changed": true, "mode": "append", "set": 3})); + assert_eq!(set_names(&app), ["Default Actions", "Mine", "Default Actions 3", "Default Actions 2"]); + assert_eq!(saved_sets(&app.ui.action_sets[..3]), before, "the sets there were stay as they were"); + assert_eq!(saved_sets(&app.ui.action_sets[3..])[0]["actions"], saved_sets(&default_sets())[0]["actions"], "the built-in actions"); + assert_eq!(app.ui.action_set, None, "still no current set"); + assert_eq!(pstate::>(&ctx, "actions-selected"), Some((1, 1)), "the selection stays"); + app.ui.action_set = Some(1); + app.ui.action_sets_selected = vec![1]; + crate::dialogs::action_batch::open(&mut app, 1, 0).unwrap(); + assert_eq!(app.run(RESET, json!({"mode": "append"})).unwrap()["set"], 4); + assert_eq!(set_names(&app)[4], "Default Actions 4"); + assert_eq!((app.ui.action_set, app.ui.action_sets_selected.clone()), (Some(1), vec![1]), "the current set stays"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::action_batch::KIND), "the Batch dialog stays open"); + } + + /// `ui.actionSet.reset` refuses params that are not an object, another key or mode, and a reset + /// while an action records or plays, waiting at a stop included, and then changes nothing. + #[test] + fn reset_refuses_bad_params_and_a_running_action_and_changes_nothing() { + let mut app = app_with_sets(); + let before = saved_sets(&app.ui.action_sets); + for (p, error) in [ + (json!(1), "the params must be an object, not 1"), + (json!("append"), "the params must be an object, not \"append\""), + (json!([]), "the params must be an object, not []"), + (json!({"mode": null}), "mode must be replace or append"), + (json!({"mode": 1}), "mode must be replace or append"), + (json!({"mode": "clear"}), "mode must be replace or append"), + (json!({"mode": "append", "set": 0}), "unknown parameter `set`; the command takes: mode"), + ] { + assert_eq!(app.run(RESET, p.clone()).unwrap_err(), error, "{p}"); + assert_eq!(saved_sets(&app.ui.action_sets), before, "{p} changes nothing"); + assert_eq!(app.ui.action_set, None); + } + + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run(START_RECORDING, json!({})).unwrap(); + for mode in ["replace", "append"] { + assert_eq!(app.run(RESET, json!({ "mode": mode })).unwrap_err(), "an action is already recording"); + } + assert_eq!(saved_sets(&app.ui.action_sets), before, "a recording keeps its set"); + app.run(STOP_RECORDING, json!({})).unwrap(); + + let (mut app, _) = app_with_a_stop(true); + let before = saved_sets(&app.ui.action_sets); + play(&mut app, 0, 0).unwrap(); + assert!(waiting_at_stop(&app)); + for mode in ["replace", "append"] { + assert_eq!(app.run(RESET, json!({ "mode": mode })).unwrap_err(), "an action is already playing"); + } + assert_eq!(saved_sets(&app.ui.action_sets), before, "the playing set stays"); + } + /// A recording keeps its steps when a canceled undo group drops journal entries made before the /// recording began. #[test] diff --git a/crates/ui-egui/src/panels/actions/files.rs b/crates/ui-egui/src/panels/actions/files.rs index 5bdd0b9a98..d6ca465275 100644 --- a/crates/ui-egui/src/panels/actions/files.rs +++ b/crates/ui-egui/src/panels/actions/files.rs @@ -275,7 +275,7 @@ pub fn read_set(text: &str, name: &str) -> Result { } /// `name`, else `name 2`, `name 3` … : the first that no set in `sets` has. -fn free_set_name(sets: &[ActionSet], name: &str) -> String { +pub(super) fn free_set_name(sets: &[ActionSet], name: &str) -> String { let taken = |n: &str| sets.iter().any(|s| s.name == n); if !taken(name) { return name.to_string(); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..cad6802efa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3957,6 +3957,17 @@ already walks Image Trace. Short agent entry points: " copy" added, a copied set gets an id of its own, and the copy is selected. An index past the last set or action is an error, and so is a copy that would give its set more than 1,000 actions or a file larger than 8 MiB; then nothing is copied. The panel menu's Duplicate runs this for the selected action, else the current set. + `ui.actionSet.reset {mode?: "replace" | "append"}` is Reset Actions, and returns `{changed, mode, set}` (`set` is + the index of the first built-in set). `replace`, the default, replaces every set in the panel with a new copy of + VectorCraft's built-in Default Actions set, makes it current and selected, clears the panel's selected action and + step and its expanded actions, and closes an open Set Options, New Action, Batch or step dialog that names a set; + when the panel already shows only the built-in set as it comes in that state, nothing changes, the sets keep their + ids and `changed` is false. `append` adds a new copy of the built-in set after the sets there are, with the + next free number when its name is in use (`Default Actions 2`), and keeps the current set and the selection. + Omitted params count as `{}`. Params of another type, another key, another `mode`, or a reset while an action + records or plays (also while it waits at a stop) is an error and changes nothing. Reset records no undo step. The panel menu's Reset + Actions is disabled while an action records or plays; it opens a `resetActions` question (fields `message`, + `detail`, `append`): OK runs this with `replace`, Append with `append`, and `ui.dialog.cancel` changes nothing. - Image Trace: `imageTrace.presets`, `imageTrace.make {id?, preset?, params?, view?}` (or `imageTrace.makeAndExpand`), `imageTrace.setView`, `imageTrace.expand`, `imageTrace.release`. A key inside `params` that is not one of the trace settings, such as `colours`, is an error that names it and the nearest setting (`colors`), as for a command's own keys. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..54c6d5a3e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -845,6 +845,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Select Object… opens Set Selection, where the note typed names the objects to select, and adds a step to the recording in progress, after the selected step, or at the end of the selected action; playback selects the objects whose Attributes note matches it, and the steps after it act on them ([Insert non-recordable tasks into actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/insert-non-recordable-tasks-into-actions.html); `ui.action.insertSelectObject`, `select.byNote`). VectorCraft's own rules, which the page does not cover: the note matches anywhere and in any letter case unless Case Sensitive or Whole Word is checked, hidden and locked objects are left out, the objects found replace the selection, a step that finds none stops the playback with an error, and the note is at most 1,024 bytes. Action sets with the step save as version 4. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. + - Actions panel: the panel menu's Reset Actions asks first; OK replaces the sets in the panel with the default set, and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.reset`). VectorCraft's own rules, which the page does not cover: the default set is VectorCraft's own Default Actions set; after OK it is current and selected, and no action or step is selected; Append names its copy with the next free number (`Default Actions 2`) and keeps the current set; Cancel changes nothing; the item is off while an action records or plays, waiting at a stop included; Undo does not bring the old sets back. Tests `panels::actions::tests::{the_panel_menus_reset_actions_asks_first_and_is_off_while_an_action_runs, reset_replaces_every_set_with_the_built_in_set_and_clears_what_named_the_old_ones, reset_on_the_built_in_set_makes_it_current_then_changes_nothing, reset_append_adds_the_built_in_set_with_a_free_number_and_keeps_the_rest, reset_refuses_bad_params_and_a_running_action_and_changes_nothing}`, `dialogs::tests::reset_actions_ok_replaces_append_adds_and_cancel_keeps_the_sets`. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..c499df1e1a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -418,7 +418,8 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | -| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Reset, Clear and Replace Actions remain | +| Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; Clear and Replace Actions remain | +| Actions panel: ≡ › Reset Actions asks first; OK replaces the sets in the panel with the default set and Append adds the default set after them ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | done | `ui.actionSet.reset`; `panels/actions.rs` and `dialogs/tests.rs` tests. The default set is VectorCraft's own Default Actions set | | Actions panel: ≡ › Load Actions… also reads action sets saved as `.aia` files ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `actionSet.read`, `ui.actionSet.load`; `tests/actionset.rs`, `panels/actions.rs` tests, `import_fuzz`. Steps with a label and no recorded values come in as menu commands that run with no values and open no dialog, matched by label, and Set Selection steps come in as Select Object steps; the other steps, recorded menu items included, are left out and counted | | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). Button Mode shows the color | | Actions panel: ≡ › Button Mode shows each action by name as a button in its Action Options color, without sets or steps; a click on a button plays the action, and choosing Button Mode again shows the list ([the help page](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | done | `ui.action.buttonMode`, `ui.action.playAt`; `panels/actions.rs` tests. VectorCraft's own rules: every set's actions show in set order, an action without a color is an ordinary button, the mode is kept with the UI preferences, and it cannot be turned on while an action records | From d738e7f0c0816fc3ce86f0f81cb11e082121d67e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:31:37 -0800 Subject: [PATCH 17/62] Image Trace: Flat Logo traces a disc on a gray panel without slivers of a paler ground When the colors of an image lie on one line, as a pale gray ground, a gray panel and a charcoal disc do, an edge pixel between the panel and the disc is also reproduced by a mix of the ground and the disc. Flat Logo switches such a pixel to the mix of the classes beside it only when its neighbors lie on both sides of the class it drops, which a class beyond both classes of the edge never satisfies. A charcoal disc on a gray panel on a paler ground traced with 28 slivers of the ground, of at most two pixels each, around it when its edges were sharp, and with one sliver when they were blurred by 0.7 pixel, with the colors found or named. A pixel now also takes the mix of the classes beside it when the class it drops lies beyond both of them on their line, the pixel's own neighbors lie on each side of it, no neighbor lies past the nearer of the two toward the dropped class, and a chain of neighbors, each nearer that class than the one before, leads from the pixel, in at most 6 steps, to that class's color or to a flat area of that class. A class named some levels off the color of its flat areas still counts. The pixels of a pale line on the disc, whether one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their mixes. An edge blurred by a pixel or more can still leave slivers of the ground. Docs: docs/image-trace-adjustments.md, docs/target-app-parity.md. --- crates/trace/src/logo/tests.rs | 32 ++++++ crates/trace/src/logo/unmix.rs | 175 +++++++++++++++++++++++++++++--- docs/image-trace-adjustments.md | 13 +++ docs/target-app-parity.md | 1 + 4 files changed, 205 insertions(+), 16 deletions(-) diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 33ab678a1f..2f346a80a1 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -1158,3 +1158,35 @@ fn a_noisy_hard_edged_gray_between_black_and_white_is_one_shape() { } } } + +#[test] +fn a_disc_on_a_gray_panel_on_a_paler_ground_has_no_slivers_of_the_ground() { + // The panel's gray lies on the line from the ground's gray to the disc's charcoal, so the disc's + // edge pixels are also a mix of the ground and the disc. + let (ground, panel, disc) = ([240, 240, 240], [200, 200, 200], [60, 60, 60]); + for blur in [0.0, 0.7] { + let grays = render(150, 150, blur, move |x, y| { + let (cx, cy) = (x.clamp(35.0, 115.0), y.clamp(35.0, 115.0)); + Some(if (x - 75.0).hypot(y - 75.0) < 30.0 { + disc + } else if (20.0..130.0).contains(&x) && (20.0..130.0).contains(&y) && (x - cx).hypot(y - cy) < 15.0 { + panel + } else { + ground + }) + }); + for named in [false, true] { + let logo_colors = if named { vec!["#F0F0F0".into(), "#C8C8C8".into(), "#3C3C3C".into()] } else { Vec::new() }; + let res = trace(&grays, &TraceParams { logo_colors, ..logo_params() }); + let paths: Vec<_> = res.paths.iter().map(|t| (t.color, t.pixels)).collect(); + assert_eq!(res.paths.len(), 3, "blur {blur}, named {named}: one path per color; {paths:?}"); + for k in 0..16 { + let a = f64::from(k) * std::f64::consts::TAU / 16.0; + let at = Point::new(75.0 + 31.0 * a.cos(), 75.0 + 31.0 * a.sin()); + assert_eq!(top_color(&res, at), Some(panel), "blur {blur}, named {named}: beside the disc at {at:?}"); + } + assert_eq!(top_color(&res, Point::new(8.0, 75.0)), Some(ground), "blur {blur}, named {named}: the ground"); + assert_eq!(top_color(&res, Point::new(75.0, 75.0)), Some(disc), "blur {blur}, named {named}: the disc"); + } + } +} diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 3268c9c20a..d148309d50 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -5,7 +5,8 @@ //! runs, so each pixel is instead explained as a mix of at most three classes, whichever mix //! reproduces the pixel best. When another mix also reproduces it (with a gray between black and //! white among the classes, a black-to-white edge pixel is a mix of black and gray as well as of -//! black and white), the pixel takes the mix whose classes lie nearest it in the flat areas around it, +//! black and white, and a gray-to-black edge pixel is a mix of white and black as well as of gray +//! and black), the pixel takes the mix whose classes lie nearest it in the flat areas around it, //! when its neighbors show an edge between those classes. use std::collections::{HashMap, HashSet}; @@ -217,7 +218,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] continue; } let Some(mixes) = mixed.get(&key) else { continue }; - let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, width, height, i, classes, &mixes.best, m)).collect(); + let edges: Vec<&Weights> = mixes.tied.iter().filter(|m| across_edge(pix, &flat, (width, height), i, classes, &mixes.best, m)).collect(); if edges.is_empty() { continue; } @@ -244,10 +245,24 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// Whether pixel `i` lies on an edge between the two classes of `other`, rather than in an area of /// a class of `best` that `other` leaves out: for each such class, the pixel has a neighbor beyond -/// it toward each class of `other`, along the line between them. (A black-to-white edge pixel as -/// light as a gray has a darker neighbor and a lighter one; a gray stroke on white has no neighbor -/// darker than the gray.) -fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f64; 4]], best: &Weights, other: &Weights) -> bool { +/// it toward each class of `other`, along the line between them, or, for a class that lies beyond +/// both classes of `other` on that line, a neighbor on each side of the pixel itself, none past +/// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that +/// nearer class or a flat area of it (`flat`), each nearer it than the one before. (A black-to-white +/// edge pixel as light as a gray has a darker neighbor and a lighter one; a gray stroke on white +/// has no neighbor darker than the gray; a gray-to-black edge pixel has a lighter neighbor and a +/// darker one, and lighter pixels lead to the flat gray; a pale line one pixel wide on black has +/// only darker neighbors; the pixels beside a blurred pale line's middle reach no flat gray; and a +/// white gap between black and gray has a neighbor lighter than the gray.) +fn across_edge( + pix: &[Px], + flat: &[Option], + (width, height): (usize, usize), + i: usize, + classes: &[[f64; 4]], + best: &Weights, + other: &Weights, +) -> bool { let [(a, _), (b, _)] = other.as_slice() else { return false }; let (Some(ca), Some(cb)) = (classes.get(*a), classes.get(*b)) else { return false }; let ab: [f64; 4] = std::array::from_fn(|j| cb[j] - ca[j]); @@ -262,21 +277,75 @@ fn across_edge(pix: &[Px], width: usize, height: usize, i: usize, classes: &[[f6 let off = (0..4).map(|j| (v[j] - ca[j] - t * ab[j]).powi(2)).sum::().sqrt(); (t, off) }; - let (x, y) = (i % width.max(1), i / width.max(1)); - let neighbors: Vec = (y.saturating_sub(1)..(y + 2).min(height)) - .flat_map(|yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx)) - .filter(|&j| j != i) - .filter_map(|j| pix.get(j)) - .map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])])) - .filter(|&(_, off)| off <= 2.0 * PURE) - .map(|(t, _)| t) - .collect(); + // Where pixel `j` lies along the line, when it lies within `2 * PURE` of it. + let at = |j: usize| { + pix.get(j) + .map(|q| place([f64::from(q[0]), f64::from(q[1]), f64::from(q[2]), f64::from(q[3])])) + .filter(|&(_, off)| off <= 2.0 * PURE) + .map(|(t, _)| t) + }; + // The pixels around pixel `j`. + let around = |j: usize| { + let (x, y) = (j % width.max(1), j / width.max(1)); + (y.saturating_sub(1)..(y + 2).min(height)) + .flat_map(move |yy| (x.saturating_sub(1)..(x + 2).min(width)).map(move |xx| yy * width + xx)) + .filter(move |&n| n != j) + }; + let neighbors: Vec = around(i).filter_map(at).collect(); let left_out: Vec = best.iter().filter(|&&(c, w)| w > 0.0 && c != *a && c != *b).map(|&(c, _)| c).collect(); + // Whether the pixel has a neighbor on each side of place `t` along the line. + let straddled = |t: f64| neighbors.iter().any(|&tn| (t - tn) * len > PURE) && neighbors.iter().any(|&tn| (tn - t) * len > PURE); + // Whether pixel `j`, at place `t`, lies within `PURE` of class `c` (at place `to`), or in a flat + // area of class `c` ([`flat_classes`]), or beside one and within `PURE` of its color along the + // line (as when `c` is named some levels off the area's color). + let touches = |j: usize, t: f64, c: usize, to: f64| { + let in_c = |n: usize| flat.get(n).copied().flatten() == Some(c); + (t - to).abs() * len <= PURE || in_c(j) || around(j).any(|n| in_c(n) && at(n).is_some_and(|tn| (tn - t).abs() * len <= PURE)) + }; + // Whether a chain of neighbors from the pixel, each nearer place `to` than the one before and + // none past it (`past`), comes to class `c` ([`touches`]) in at most `NEARBY` steps. (From a + // pixel beside a pale line's middle, the middle is the only neighbor nearer the gray, and it has + // none, and it is far from the gray.) + let reaches = |to: f64, c: usize, past: &dyn Fn(f64) -> bool| { + let Some(t) = at(i) else { return false }; + let mut front = vec![(i, t)]; + let mut seen = HashSet::from([i]); + for step in 0..=NEARBY { + let mut next = Vec::new(); + for &(j, t) in &front { + if touches(j, t, c, to) { + return true; + } + if step < NEARBY { + for n in around(j) { + if let Some(tn) = at(n).filter(|&tn| !past(tn) && (tn - to).abs() < (t - to).abs()) + && seen.insert(n) + { + next.push((n, tn)); + } + } + } + } + if next.is_empty() { + return false; + } + front = next; + } + false + }; !left_out.is_empty() && left_out.iter().all(|&c| { let Some(&cv) = classes.get(c) else { return false }; let (tc, _) = place(cv); - neighbors.iter().any(|&t| (tc - t) * len > PURE) && neighbors.iter().any(|&t| (t - tc) * len > PURE) + if straddled(tc) { + return true; + } + if (0.0..=1.0).contains(&tc) { + return false; + } + let beyond = |tn: f64| if tc < 0.0 { -tn * len > PURE } else { (tn - 1.0) * len > PURE }; + let (to, near) = if tc < 0.0 { (0.0, *a) } else { (1.0, *b) }; + !neighbors.iter().any(|&tn| beyond(tn)) && at(i).is_some_and(straddled) && reaches(to, near, &beyond) }) } @@ -670,6 +739,80 @@ mod tests { } } + #[test] + fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() { + // A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway + // to charcoal, flat charcoal. The edge pixel is a mix of the gray and the charcoal, with none + // of the ground in it. + let g = |v: f64| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let classes = vec![g(240.0), g(200.0), g(60.0), [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + let px = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let mut pix = vec![px(200.0); 5]; + pix.push(px(130.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix, 11, 1, &classes); + assert_eq!(pl[0][5], 0.0, "ground in the edge pixel"); + assert!((pl[1][5] - 0.5).abs() < 0.02 && (pl[2][5] - 0.5).abs() < 0.02, "gray {} charcoal {}", pl[1][5], pl[2][5]); + // The cases below are vertical lines: three rows alike, read in the middle row. + // The same edge with the panel's pixels three levels darker than the named gray. + let mut pix = vec![px(197.0); 5]; + pix.push(px(130.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes); + assert_eq!(pl[0][11 + 5], 0.0, "ground in the edge pixel beside a gray three levels off"); + // An edge pixel whose lightest neighbor leads nowhere, with another chain of lighter pixels + // to the gray. + let outer = [vec![px(200.0); 5], vec![px(170.0)], vec![px(60.0); 7]].concat(); + let middle = [vec![px(200.0); 5], vec![px(170.0), px(130.0), px(180.0)], vec![px(60.0); 5]].concat(); + let (pl, _, _) = unmix(&[outer.clone(), middle, outer].concat(), 13, 3, &classes); + assert_eq!(pl[0][13 + 6], 0.0, "ground in the edge pixel beside a dead end"); + // A pixel half ground and half charcoal between charcoal pixels, flat gray three pixels off: + // a thin pale line on the charcoal, kept. + let mut pix = vec![px(200.0); 3]; + pix.extend([px(60.0); 2]); + pix.push(px(150.0)); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 11, 3, &classes); + assert!((pl[0][11 + 5] - 0.5).abs() < 0.02, "the line: ground {}", pl[0][11 + 5]); + // A gap of the ground's color one pixel wide between flat charcoal and flat gray: the pixel + // half charcoal and half ground beside it keeps its ground. + let mut pix = vec![px(60.0); 5]; + pix.extend([px(150.0), px(236.0)]); + pix.extend([px(200.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 12, 3, &classes); + assert!((pl[0][12 + 5] - 0.5).abs() < 0.02, "the gap: ground {}", pl[0][12 + 5]); + // A pale line blurred over three pixels on the charcoal, flat gray five pixels off: the pixels + // beside its middle have a lighter neighbor and a darker one, and keep their ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(60.0); 3]); + pix.extend([px(103.0), px(154.0), px(103.0)]); + pix.extend([px(60.0); 9]); + let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes); + for j in [20 + 8, 20 + 10] { + assert!((pl[0][j] - 43.0 / 180.0).abs() < 0.02 && pl[1][j] == 0.0, "the blurred line at {j}: ground {} gray {}", pl[0][j], pl[1][j]); + } + // A pale line one pixel wide that falls between two pixels, covering half of one and three + // quarters of the other: both pixels keep their ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(60.0); 3]); + pix.extend([px(150.0), px(195.0)]); + pix.extend([px(60.0); 10]); + let (pl, _, _) = unmix(&pix.repeat(3), 20, 3, &classes); + for (j, want) in [(20 + 8, 0.5), (20 + 9, 0.75)] { + let (ground, gray) = (pl[0][j], pl[1][j]); + assert!((ground - want).abs() < 0.02 && gray == 0.0, "the line between pixels at {j}: ground {ground} gray {gray}"); + } + // An edge from the gray to the charcoal blurred by 0.7 pixel: the pixels between take no + // ground. + let mut pix = vec![px(200.0); 5]; + pix.extend([px(199.97), px(197.8), px(166.7), px(93.3), px(62.2)]); + pix.extend([px(60.0); 5]); + let (pl, _, _) = unmix(&pix.repeat(3), 15, 3, &classes); + for j in [15 + 7, 15 + 8] { + assert_eq!(pl[0][j], 0.0, "the blurred edge at {j}: ground"); + } + } + #[test] fn row_distances_match_a_scan_of_the_window_around_each_pixel() { // Three classes scattered over 23 x 17 pixels, some pixels holding two, most none. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 2bd58e4df4..4d96ec6299 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -134,6 +134,19 @@ between pixels or is blurred traces as black and white. A flat area whose color some levels off, counts as holding the named colors it is a blend of, and so do the pixels of exactly its color that touch it. +The same holds when the left-out color lies beyond both colors of the edge, as a pale gray ground lies +beyond a gray panel and a charcoal disc: an edge pixel between the panel and the disc is also a blend of +the ground and the disc. Flat Logo reads it as a blend of the panel and the disc when, along the line +through the three colors, the pixel has a neighbor on each side of it, no neighbor lies past the panel +toward the ground, and a chain of neighbors, each nearer the panel's color than the one before, leads +from the pixel, in at most 6 steps, to the panel's color or to a flat area of the panel. The same rule +applies to a left-out color darker than both colors of the edge, and to colors that are not grays. A +charcoal disc on a gray panel on a paler ground then traces with no slivers of the ground around it when +its edges are sharp or blurred by 0.7 pixel. An edge blurred by a pixel or more can still leave slivers +of the ground. The pixels of a pale line on the disc, whether one pixel wide, blurred over three pixels +or falling between two pixels, and the edge of a gap of the ground's color between the disc and the +panel keep the ground in their blends. + **Large images.** An image of more than 1500 pixels on a side is traced as any other, only more slowly, and the trace says so: `imageTrace.make` returns the note in `warnings` and the status bar shows it (the [results optimization](https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cc4082ad68..cb7677aa70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1591,6 +1591,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly (an edge blurred by a pixel or more, or pixel noise of a level or more, can still leave gray slivers); gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide that touches black traces as black and white, and a short one about three pixels wide can lose most or all of its gray), and a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. +- **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. From 42001569145960e05374e2d4422afd0dfb905517 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:18:17 -0800 Subject: [PATCH 18/62] Repeat: a selected Radial Repeat has handles for its instances and radius With one radial repeat selected, the Selection tool shows a handle below it and a handle on its circle between the first two instances. Dragging the first one down adds an instance for every 16 px and dragging it up removes them (1 to 1,000). Dragging the second one outward or inward makes the radius larger or smaller (0 or more); only the part of the drag along the line from the center counts. Each drag previews and commits object.repeat.options as one undo step, Escape cancels it, and a drag that ends where it began leaves no undo step. The handles hide with the edges or the bounding box and for a locked or hidden repeat, and bounding-box handles keep priority where they meet, as with Grid Repeat. --- crates/tools/src/lib.rs | 1 + crates/tools/src/repeat_radial.rs | 436 +++++++++++++++++++++ crates/tools/src/select.rs | 40 +- crates/ui-egui/src/canvas.rs | 3 +- crates/ui-egui/src/canvas/tests.rs | 96 +++++ crates/ui-egui/src/canvas/tool_overlays.rs | 26 ++ docs/gaps.md | 2 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 9 files changed, 602 insertions(+), 5 deletions(-) create mode 100644 crates/tools/src/repeat_radial.rs diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index a168c28396..07579cd456 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -34,6 +34,7 @@ pub mod pie; pub mod place; pub mod printtiling; pub mod repeat_grid; +pub mod repeat_radial; pub mod rulerguide; pub mod select; pub mod settings; diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs new file mode 100644 index 0000000000..05eafc8d1b --- /dev/null +++ b/crates/tools/src/repeat_radial.rs @@ -0,0 +1,436 @@ +//! Radial Repeat's on-canvas handles: a handle below the repeat adds or removes instances, and a +//! handle on the circle the instances sit on sets its radius, as the public "Create radial +//! repeats" page describes. Drawing and hit testing share the document-space geometry of +//! [`RadialHandles::of`]; a drag previews the existing Repeat Options command and commits as one +//! undo step. +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; + +use crate::bbox::Handle; +use crate::{Action, Cursor, Mods, ToolContext}; + +/// The radius of the instances and radius handles (screen points). +pub const HANDLE_RADIUS: f32 = 5.0; + +/// How far (screen points) the instances handle sits below the bounding box, clear of its own +/// handles and rotate zones. +pub const HANDLE_GAP: f64 = 22.0; + +/// How far (screen points) the instances handle is dragged for each instance it adds or removes. +pub const INSTANCE_STEP: f64 = 16.0; + +/// How near (screen points) a press must come to a handle to take it. +const REACH: f64 = 8.0; + +/// The most instances a radial repeat has (as `object.repeat.options` accepts them). +const MAX_INSTANCES: f64 = 1000.0; + +/// A control of [`RadialHandles`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RadialPart { + /// Below the repeat: drag down for more instances, up for fewer. + Instances, + /// On the circle, between the first two instances: drag outward for a larger radius, inward + /// for a smaller one. + Radius, +} + +/// The controls of a selected radial repeat, in document space. +#[derive(Clone, Copy, Debug)] +pub struct RadialHandles { + pub id: NodeId, + instances: u32, + /// The circle the instances' centers sit on. + pub center: Point, + pub radius: f64, + /// The unit direction from the center to the radius handle. + out: Vec2, + /// Document points of drag for each instance. + step: f64, + pub instances_at: Point, + pub radius_at: Point, +} + +impl RadialHandles { + /// The controls of a single editable radial repeat selected whole, the instances handle placed + /// below `frame` (the bounding box the Selection tool shows; its geometric bounds without one) + /// at `zoom`. + pub fn of(doc: &Document, selection: &Selection, frame: Option, zoom: f64) -> Option { + let [id] = selection.objects.as_slice() else { return None }; + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let n = doc.node(*id)?; + let NodeKind::Repeat(spec) = &n.kind else { return None }; + let RepeatKind::Radial { instances, radius, center, start_angle, end_angle, .. } = spec.kind else { return None }; + if ![radius, center.x, center.y, start_angle, end_angle].iter().all(|v| v.is_finite()) { + return None; + } + let source = spec.source_bounds()?; + if !finite(source.center()) { + return None; + } + // As `repeat_transforms` lays the instances out: the first one at `start_angle` from the + // source's own direction, the rest a step apart. + let instances = instances.clamp(1, 1000); + let mut d = source.center() - center; + if d.hypot() < 1e-9 { + d = Vec2::new(0.0, -1.0); + } + let sweep = end_angle - start_angle; + let full = (sweep.abs() - 360.0).abs() < 1e-9; + let step = if full || instances == 1 { sweep / f64::from(instances) } else { sweep / f64::from(instances - 1) }; + // Halfway between the first two instances (opposite the only one of a full turn). + let out = (Affine::rotate((start_angle + step / 2.0).to_radians()) * d.normalize().to_point()).to_vec2(); + let radius = radius.max(0.0); + let frame = match frame { + Some(f) => aabb(f.corners())?, + None => n.geometric_bounds_with(&doc.symbol_boxes())?, + }; + let h = Self { + id: *id, + instances, + center, + radius, + out, + step: INSTANCE_STEP / zoom, + instances_at: Point::new(frame.center().x, frame.y1 + HANDLE_GAP / zoom), + radius_at: center + out * radius, + }; + (finite(h.instances_at) && finite(h.radius_at) && h.step.is_finite() && h.step > 0.0).then_some(h) + } + + /// Both controls with where they are. + pub fn parts(&self) -> [(RadialPart, Point); 2] { + [(RadialPart::Instances, self.instances_at), (RadialPart::Radius, self.radius_at)] + } + + /// The control under `p` (the nearer within reach) and the repeat's controls, unless a + /// bounding-box handle is there, which keeps its scaling. + fn hit(cx: &ToolContext, p: Point) -> Option<(Self, RadialPart)> { + if !cx.show_bbox || !finite(p) { + return None; + } + let h = Self::of(cx.doc, cx.selection, crate::select::selection_box(cx), cx.zoom)?; + let reach = cx.tol(REACH); + let (part, _) = + h.parts().into_iter().map(|(part, q)| (part, q.distance(p))).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1))?; + (!crate::select::bbox_handle_at(cx, p)).then_some((h, part)) + } + + /// The Repeat Options that dragging `part` by `d` (document points) from the press gives; + /// none when the drag is too far to measure. + fn options(&self, part: RadialPart, d: Vec2) -> Option { + match part { + RadialPart::Instances => { + let n = f64::from(self.instances) + (d.y / self.step).round(); + // NaN only comes from an infinite drag; the clamp keeps a huge one at the limit. + (!n.is_nan()).then(|| json!({ "instances": n.clamp(1.0, MAX_INSTANCES) as u32 })) + } + RadialPart::Radius => { + // Only the part of the drag along the line from the center moves the circle. + let r = ((self.radius + d.dot(self.out)).max(0.0) * 100.0).round() / 100.0; + r.is_finite().then(|| json!({ "radius": r })) + } + } + } + + /// The direction (counter-clockwise degrees) in which the radius handle moves the circle out. + fn out_angle(&self) -> f64 { + (-self.out.y).atan2(self.out.x).to_degrees() + } +} + +/// The page-square bounds of `corners`. +fn aabb(corners: [Point; 4]) -> Option { + let r = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |r, p| r.union_pt(*p)); + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r) +} + +fn finite(p: Point) -> bool { + p.x.is_finite() && p.y.is_finite() +} + +/// The resize cursor of `part`, turned with the view: up and down for the instances handle, along +/// the line from the center for the radius handle. +fn part_cursor(cx: &ToolContext, h: &RadialHandles, part: RadialPart) -> Cursor { + match part { + RadialPart::Instances => crate::select::handle_cursor(Handle::Bottom, -cx.view_angle()), + RadialPart::Radius => crate::select::handle_cursor(Handle::Right, h.out_angle() - cx.view_angle()), + } +} + +/// The cursor over a radial repeat's control at `p`, if one is there. +pub fn cursor(cx: &ToolContext, p: Point) -> Option { + let (h, part) = RadialHandles::hit(cx, p)?; + Some(part_cursor(cx, &h, part)) +} + +/// A drag of one of a radial repeat's controls. +#[derive(Clone, Debug)] +pub struct RadialDrag { + handles: RadialHandles, + part: RadialPart, + start: Point, + /// The options the press found, and the last ones previewed. + from: Value, + last: Option, +} + +impl RadialDrag { + pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option { + if mods.cmd || mods.ctrl || mods.alt { + return None; + } + let (handles, part) = RadialHandles::hit(cx, p)?; + let from = handles.options(part, Vec2::ZERO)?; + Some(Self { handles, part, start: p, from, last: None }) + } + + /// Whether the drag has changed the repeat (and so previews it). + pub fn adjusting(&self) -> bool { + self.last.is_some() + } + + pub fn cursor(&self, cx: &ToolContext) -> Cursor { + part_cursor(cx, &self.handles, self.part) + } + + /// Preview the options the pointer at `p` gives, when they change; the first change opens + /// the undo step. + pub fn drag(&mut self, p: Point) -> Vec { + if !finite(p) { + return vec![]; + } + let Some(v) = self.handles.options(self.part, p - self.start) else { return vec![] }; + if self.last.as_ref().unwrap_or(&self.from) == &v { + return vec![]; + } + let mut out = vec![]; + if self.last.is_none() { + out.push(Action::Begin("Repeat Options".into())); + } + out.push(Action::Preview("object.repeat.options".into(), v.clone())); + self.last = Some(v); + out + } + + /// Commit the drag; one that ends where it began leaves no undo step. + pub fn finish(self) -> Vec { + match self.last { + Some(v) if v == self.from => vec![Action::Cancel], + Some(_) => vec![Action::Commit], + None => vec![], + } + } + + pub fn cancel(self) -> Vec { + if self.last.is_some() { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{cx, doc_with_rect, paint}; + use std::sync::Arc; + use vectorcraft_doc::pattern::RepeatSpec; + + /// [`doc_with_rect`]'s 100 × 100 square at (100, 100) as a radial repeat of eight instances + /// with a radius of 100 pt about (150, 250), selected. The instances span (0, 100)–(300, 400). + fn radial() -> (Document, Selection) { + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::radial(vec![Arc::new(source)], 8, Some(100.0))); + let mut selection = Selection::default(); + selection.set([id]); + (doc, selection) + } + + fn set(doc: &mut Document, selection: &Selection, f: impl FnOnce(&mut u32, &mut f64, &mut f64, &mut f64)) { + let NodeKind::Repeat(spec) = &mut doc.node_mut(selection.objects[0]).unwrap().kind else { panic!("a repeat") }; + let RepeatKind::Radial { instances, radius, start_angle, end_angle, .. } = &mut spec.kind else { panic!("a radial repeat") }; + f(instances, radius, start_angle, end_angle); + } + + fn near(a: Point, b: Point) -> bool { + a.distance(b) < 1e-6 + } + + fn preview(out: &[Action]) -> Option<&Value> { + out.iter().find_map(|a| match a { + Action::Preview(cmd, v) if cmd == "object.repeat.options" => Some(v), + _ => None, + }) + } + + #[test] + fn the_handles_sit_below_the_repeat_and_on_its_circle_at_every_zoom() { + let (doc, selection) = radial(); + // Halfway between the first instance (straight up from the center) and the second, 45° + // clockwise from it. + let half = 22.5_f64.to_radians(); + let on_circle = Point::new(150.0 + 100.0 * half.sin(), 250.0 - 100.0 * half.cos()); + for zoom in [0.02, 1.0, 4.0] { + let h = RadialHandles::of(&doc, &selection, None, zoom).unwrap(); + assert!(near(h.instances_at, Point::new(150.0, 400.0 + HANDLE_GAP / zoom)), "{zoom}: {:?}", h.instances_at); + assert!(near(h.radius_at, on_circle), "{zoom}: {:?}", h.radius_at); + assert_eq!((h.center, h.radius), (Point::new(150.0, 250.0), 100.0)); + } + // Placed below the bounding box the Selection tool shows. + let frame = OrientedBox::aligned(Rect::new(-10.0, 90.0, 310.0, 410.0)); + let h = RadialHandles::of(&doc, &selection, Some(frame), 1.0).unwrap(); + assert!(near(h.instances_at, Point::new(150.0, 410.0 + HANDLE_GAP))); + } + + #[test] + fn the_radius_handle_follows_the_instances_angles() { + let (mut doc, selection) = radial(); + // One instance: opposite it. + set(&mut doc, &selection, |n, _, _, _| *n = 1); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.radius_at, Point::new(150.0, 350.0)), "{:?}", h.radius_at); + // Three instances over a quarter turn from 90°: between those at 90° and 135°. + set(&mut doc, &selection, |n, _, a, b| (*n, *a, *b) = (3, 90.0, 180.0)); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + let a = 112.5_f64.to_radians(); + assert!(near(h.radius_at, Point::new(150.0 + 100.0 * a.sin(), 250.0 - 100.0 * a.cos())), "{:?}", h.radius_at); + // A radius of 0: at the center, still apart from the instances handle. + set(&mut doc, &selection, |_, r, _, _| *r = 0.0); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + assert!(near(h.radius_at, Point::new(150.0, 250.0))); + assert!(h.radius_at.distance(h.instances_at) > 2.0 * REACH); + } + + #[test] + fn no_handles_without_a_single_valid_radial_repeat() { + let (mut doc, mut selection) = radial(); + for zoom in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(RadialHandles::of(&doc, &selection, None, zoom).is_none(), "{zoom}"); + } + let paint = paint(); + let h = RadialHandles::of(&doc, &selection, None, 1.0).unwrap(); + { + let mut c = cx(&doc, &selection, &paint); + assert!(cursor(&c, h.instances_at).is_some()); + c.show_bbox = false; + assert!(cursor(&c, h.instances_at).is_none(), "the bounding box is hidden"); + } + let id = selection.objects[0]; + doc.node_mut(id).unwrap().locked = true; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a locked repeat"); + doc.node_mut(id).unwrap().locked = false; + doc.node_mut(id).unwrap().visible = false; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a hidden repeat"); + doc.node_mut(id).unwrap().visible = true; + for bad in [f64::NAN, f64::INFINITY] { + set(&mut doc, &selection, |_, r, _, _| *r = bad); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "radius {bad}"); + set(&mut doc, &selection, |_, r, a, _| (*r, *a) = (100.0, bad)); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "start angle {bad}"); + set(&mut doc, &selection, |_, _, a, _| *a = 0.0); + } + let other = doc.alloc_id(); + let mut second = doc.node(id).unwrap().clone(); + second.id = other; + let layer = doc.layers[0].id; + doc.insert(Some(layer), 1, second).unwrap(); + selection.set([id, other]); + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "two objects selected"); + selection.set([id]); + let NodeKind::Repeat(spec) = &mut doc.node_mut(id).unwrap().kind else { panic!("a repeat") }; + spec.kind = RepeatKind::Grid { + h_spacing: 10.0, + v_spacing: 10.0, + rows: 3, + cols: 3, + grid_type: Default::default(), + flip_rows: false, + flip_cols: false, + }; + assert!(RadialHandles::of(&doc, &selection, None, 1.0).is_none(), "a grid repeat"); + } + + #[test] + fn dragging_the_instances_handle_steps_the_count() { + let (doc, selection) = radial(); + let paint = paint(); + let mut c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert!(d.drag(h.instances_at + Vec2::new(0.0, 7.0)).is_empty(), "less than half a step changes nothing"); + assert!(!d.adjusting()); + // Two steps down, a little sideways: ten instances, one undo step. + let out = d.drag(h.instances_at + Vec2::new(5.0, 32.0)); + assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}"); + assert_eq!(preview(&out), Some(&json!({"instances": 10}))); + assert!(d.drag(h.instances_at + Vec2::new(0.0, 36.0)).is_empty(), "the same count isn't previewed again"); + assert!(d.adjusting()); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + // Far up: one instance at least; far down: 1,000 at most. + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 900.0))), Some(&json!({"instances": 1}))); + assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 1e300))), Some(&json!({"instances": 1000}))); + assert!(d.drag(Point::new(f64::NAN, 0.0)).is_empty(), "a non-finite pointer"); + // Back where it began: no undo step. + assert_eq!(preview(&d.drag(h.instances_at)), Some(&json!({"instances": 8}))); + assert!(matches!(d.finish().as_slice(), [Action::Cancel])); + // The step is the same on screen at every zoom: 16 px is a quarter point at 64. + c.zoom = 64.0; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let mut d = RadialDrag::hit(&c, h.instances_at, Mods::default()).unwrap(); + assert_eq!(preview(&d.drag(h.instances_at - Vec2::new(0.0, 0.25))), Some(&json!({"instances": 7}))); + assert!(matches!(d.cancel().as_slice(), [Action::Cancel])); + // Alt, Cmd and Ctrl keep the Selection tool's own gestures. + assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none()); + } + + #[test] + fn dragging_the_radius_handle_moves_the_circle_in_and_out() { + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + let out = (h.radius_at - h.center) / 100.0; + let across = Vec2::new(-out.y, out.x); + let mut d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap(); + // 25 pt out and 40 pt across: only the outward part counts. + let o = d.drag(h.radius_at + out * 25.0 + across * 40.0); + assert!(matches!(o.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{o:?}"); + assert_eq!(preview(&o), Some(&json!({"radius": 125.0}))); + assert!(d.drag(h.radius_at + across * 30.0).iter().any(|a| matches!(a, Action::Preview(_, v) if v == &json!({"radius": 100.0})))); + // Past the center: a radius of 0. + assert_eq!(preview(&d.drag(h.radius_at - out * 250.0)), Some(&json!({"radius": 0.0}))); + // Too far to measure: nothing previewed. + assert!(d.drag(Point::new(f64::MAX, -f64::MAX)).is_empty()); + assert!(matches!(d.finish().as_slice(), [Action::Commit])); + // Escape before any change leaves nothing to undo. + let d = RadialDrag::hit(&c, h.radius_at, Mods::default()).unwrap(); + assert!(d.cancel().is_empty()); + } + + #[test] + fn a_bounding_box_handle_wins_where_they_overlap() { + let (doc, selection) = radial(); + let paint = paint(); + let mut c = cx(&doc, &selection, &paint); + // Zoomed far out (the 300 pt repeat 6 px across), the radius handle lies on a + // bounding-box handle, which keeps its scaling; the instances handle stays clear of the box. + c.zoom = 0.02; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + assert!(crate::select::bbox_handle_at(&c, h.radius_at)); + assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_none()); + assert!(cursor(&c, h.radius_at).is_none()); + assert!(!crate::select::bbox_handle_at(&c, h.instances_at)); + assert!(RadialDrag::hit(&c, h.instances_at, Mods::default()).is_some()); + // At full size both are the repeat's, with resize cursors along their drags. + c.zoom = 1.0; + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + assert!(RadialDrag::hit(&c, h.radius_at, Mods::default()).is_some()); + assert_eq!(cursor(&c, h.instances_at), Some(Cursor::ResizeV)); + // The radius handle points 22.5° clockwise from straight up: the up-and-down cursor. + assert_eq!(cursor(&c, h.radius_at), Some(Cursor::ResizeV)); + } +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8a755395dc..543f9c7bb1 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -147,6 +147,8 @@ enum State { Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. GridRepeat(crate::repeat_grid::GridDrag), + /// Drag a radial repeat's instances or radius handle. + RadialRepeat(crate::repeat_radial::RadialDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), /// Dragging a 9-slice guide of the symbol being edited. @@ -826,6 +828,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::RadialRepeat(_)) + && let State::RadialRepeat(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::NineSlice(_)) && let State::NineSlice(d) = std::mem::take(&mut self.state) @@ -875,7 +883,7 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, _ => false, } } @@ -917,6 +925,7 @@ impl Tool for SelectionTool { State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), + State::RadialRepeat(d) => d.adjusting(), _ => false, } } @@ -1228,6 +1237,9 @@ impl Tool for SelectionTool { if let State::GridRepeat(d) = &self.state { return d.cursor(cx); } + if let State::RadialRepeat(d) = &self.state { + return d.cursor(cx); + } if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { return Cursor::Move; } @@ -1235,7 +1247,8 @@ impl Tool for SelectionTool { && !m.cmd && !m.ctrl && !m.alt - && let Some(cursor) = crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)) + && let Some(cursor) = + crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p)) { return cursor; } @@ -1553,6 +1566,21 @@ impl SelectionTool { _ => return Some(vec![]), } } + if let State::RadialRepeat(mut d) = self.state.clone() { + match ev.kind { + PointerKind::Drag | PointerKind::Up => { + let mut out = d.drag(ev.pos); + if ev.kind == PointerKind::Up { + out.extend(d.finish()); + self.state = State::Idle; + } else { + self.state = State::RadialRepeat(d); + } + return Some(out); + } + _ => return Some(vec![]), + } + } if matches!(self.state, State::Idle) && ev.kind == PointerKind::Down && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) @@ -1569,6 +1597,14 @@ impl SelectionTool { self.hover = None; return Some(vec![]); } + if matches!(self.state, State::Idle) + && ev.kind == PointerKind::Down + && let Some(d) = crate::repeat_radial::RadialDrag::hit(cx, ev.pos, ev.mods) + { + self.state = State::RadialRepeat(d); + self.hover = None; + return Some(vec![]); + } None } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 847b60fd87..ba72946d38 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -78,7 +78,7 @@ use tool_overlays::{DIAL_RADIUS, HiddenMarks}; pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, - print_tiling_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, + print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, }; pub(crate) use view::animated_zoom; pub(crate) use view::drag_rotation; @@ -1347,6 +1347,7 @@ fn selection_visuals( draw_inside_overlay(app, painter, xf); mirror_axis_overlay(app, painter, xf); grid_repeat_overlay(app, painter, xf); + radial_repeat_overlay(app, painter, xf); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 9a5d7fc0b3..4f01911a26 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4722,6 +4722,102 @@ fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() { assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step"); } +/// A selected radial repeat draws its instances handle and its radius handle (none with the +/// bounding box hidden). In a zoomed view turned 30°, dragging the instances handle two steps down +/// adds two instances without scaling the source, and dragging the radius handle 20 pt outward +/// makes the circle 20 pt larger, as one undo step each; Escape puts a drag back. +#[test] +fn radial_repeat_handles_set_instances_and_radius_in_one_undo_step_each() { + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, INSTANCE_STEP, RadialHandles}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let ctx = egui::Context::default(); + // The first frame fits the artboard in the window; then zoom to 1.5 px a point and turn 30°. + frame(&mut app, &ctx, vec![]); + app.view_mut().unwrap().zoom = 1.5; + app.view_mut().unwrap().rotation = 30.0; + frame(&mut app, &ctx, vec![]); + // Instances, radius and the source's bounds. + let radial = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") }; + let vectorcraft_doc::RepeatKind::Radial { instances, radius, .. } = spec.kind else { panic!("a radial repeat") }; + (instances, radius, spec.source_bounds().unwrap()) + }; + let handles = |app: &mut VectorcraftApp| { + let frame = app.selection_box(); + let st = app.session.active().unwrap(); + RadialHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap() + }; + let before = radial(&app); + assert_eq!((before.0, before.1), (6, 60.0)); + let h = handles(&mut app); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let circle_at = + |drawn: &[Shape], at: Pos2| drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS)); + let drawn = shapes(&mut app, &ctx); + assert!(circle_at(&drawn, xf.to_screen(h.instances_at)), "the instances handle is drawn"); + assert!(circle_at(&drawn, xf.to_screen(h.radius_at)), "the radius handle is drawn"); + app.ui.view.bounding_box = false; + let drawn = shapes(&mut app, &ctx); + assert!(!circle_at(&drawn, xf.to_screen(h.instances_at)) && !circle_at(&drawn, xf.to_screen(h.radius_at)), "hidden with the bounding box"); + app.ui.view.bounding_box = true; + frame(&mut app, &ctx, vec![]); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let drag = |app: &mut VectorcraftApp, from: Pos2, to: Pos2| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + for k in 1..=4 { + frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * k as f32 / 4.0)]); + } + }; + let release = |app: &mut VectorcraftApp, at: Pos2| frame(app, &ctx, vec![button(at, false)]); + // 2.2 steps down the page (the screen's down turned 30°): two more instances. + let to = xf.to_screen(h.instances_at + vectorcraft_geom::Vec2::new(0.0, 2.2 * INSTANCE_STEP / 1.5)); + drag(&mut app, xf.to_screen(h.instances_at), to); + assert_eq!(radial(&app).0, 8, "the drag previews"); + release(&mut app, to); + let after = radial(&app); + assert_eq!((after.0, after.1), (8, 60.0)); + assert_eq!(after.2, before.2, "the source keeps its size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 6, "one undo step"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 8); + // 20 pt outward from the center. + frame(&mut app, &ctx, vec![]); + let h = handles(&mut app); + let out = (h.radius_at - h.center) / h.radius; + let to = xf.to_screen(h.radius_at + out * 20.0); + drag(&mut app, xf.to_screen(h.radius_at), to); + release(&mut app, to); + assert_eq!((radial(&app).0, radial(&app).1), (8, 80.0)); + assert_eq!(radial(&app).2, before.2, "the source keeps its size"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((radial(&app).0, radial(&app).1), (8, 60.0), "the radius's own undo step"); + // Escape during a drag puts the radius back and leaves no undo step. + frame(&mut app, &ctx, vec![]); + let h = handles(&mut app); + drag(&mut app, xf.to_screen(h.radius_at), xf.to_screen(h.radius_at + out * 30.0)); + assert_eq!(radial(&app).1, 90.0, "the drag previews"); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut full = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events: vec![escape], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + full.textures_delta.clear(); + assert_eq!(radial(&app).1, 60.0); + release(&mut app, xf.to_screen(h.radius_at + out * 30.0)); + assert_eq!(radial(&app).1, 60.0, "the release after Escape changes nothing"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial(&app).0, 6, "the instances step is the one before"); +} + /// While a symbol with 9-slice guides is edited, the canvas draws its four guides dotted across /// its art, with ruler guides hidden too, and none once the mode ends. Dragging the left guide in /// a zoomed view moves that guide alone, as one undo step. diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 67f6ac861a..b05259f8f6 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -535,6 +535,32 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x } } +/// A selected radial repeat's circle with its radius handle on it, and its instances handle below +/// it, at the places the Selection tool's hit testing finds them. +pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { + use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles}; + if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + return; + } + let frame = app.selection_box(); + let Some(st) = app.session.active() else { return }; + let Some(h) = RadialHandles::of(&st.doc, &st.selection, frame, xf.zoom) else { return }; + let t = Tokens::get(p.ctx()); + // The circle the instances' centers sit on, while it is a sensible size on screen. + let (c, r) = (xf.to_screen(h.center), (h.radius * xf.zoom) as f32); + if c.is_finite() && r.is_finite() && r > 0.5 && r < 20_000.0 { + p.circle_stroke(c, r, Stroke::new(3.0, t.measure_bg)); + p.circle_stroke(c, r, Stroke::new(1.0, t.selection)); + } + for (_, at) in h.parts() { + let c = xf.to_screen(at); + if c.is_finite() { + p.circle_filled(c, HANDLE_RADIUS, t.measure_bg); + p.circle_stroke(c, HANDLE_RADIUS, Stroke::new(2.0, t.selection)); + } + } +} + /// The radius of the Rotate View dial, in screen points. pub(super) const DIAL_RADIUS: f32 = 40.0; diff --git a/docs/gaps.md b/docs/gaps.md index eda7bb21dd..088912552d 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -139,7 +139,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done:** the selection tools take a clipping path (a clip group's or a layer's clipping mask) on its outline, within the selection tolerance, before the art it clips, so Direct Selection reshapes a mask where the art covers its edge; Select Behind lists the same, and the eyedropper and the tools that act on what is drawn are unchanged. Broader G1 estimates unchanged. - **Done:** one selected clip group's Properties panel has Edit Clipping Path and Edit Contents at its top, which select its clipping path or its clipped art for the selection tools (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. - **Done:** the Properties panel has the additional contextual controls of the public Properties panel overview: Blend Options in Quick Actions for one blend with the Blend tool, Merge Live Paint for a Live Paint group selected with more paths to merge (Live Paint Make and Merge refuse type, images and other objects that aren't paths, which used to vanish among the group's sources), the Width Profile list in Appearance with the Width tool or a variable-width stroke, an applied effect's Delete icon beside fx (with several effects it opens the Appearance panel), and Corner and Corner Radius for corners selected with Direct Selection (public doc cited in target-app-parity.md). Broader G1 estimates unchanged. -- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. Radial Repeat handles remain. Estimates unchanged. +- **Done (#2691):** a selected Grid Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)) shows a handle below the grid, one right of it and one past its bottom-right corner: dragging them adds or removes rows, columns or both (1 to 500). A slider between the first two columns and one between the first two rows set the horizontal and vertical spacing, staying halfway across the gap under the pointer. Each drag is one undo step through `object.repeat.options` and Escape cancels it; the controls hide with the edges or the bounding box, and bounding-box handles keep priority where they meet. A selected Radial Repeat ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)) shows a handle below it, dragged down for more instances and up for fewer (16 px each, 1 to 1,000), and a handle on its circle between the first two instances, dragged outward or inward for a larger or smaller radius (0 or more); the same undo, Escape, visibility and priority rules apply. The radial splitter remains. Estimates unchanged. - **Done (#2651):** Object › Repeat › Options… for a Grid Repeat has a Preview checkbox ([public page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html)): while it is on the repeat on the canvas follows the fields, Cancel puts the original back without a history step and OK keeps the previewed values as one undo step. Radial and Mirror Repeat Options have none, as their public pages list none. Estimate unchanged. - **Done (#2877):** a selected Mirror Repeat shows its axis: drag the line or the center handle to move it, an end handle to rotate it (Shift: 45°); each drag is one undo step and Escape cancels it. Bounding-box handles take priority over the axis line; the center and end handles keep their actions. Broader G1 estimates unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..3222960ef2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -641,6 +641,7 @@ since 2026-10-01. - **Graph legend swatches have their series' stroke:** a default legend swatch of a stacked column, stacked bar, area or pie series has the thin white stroke of the series' marks (VectorCraft's own rule), beside the plot or across the top, and a stroke kept on the series is on the swatch too. Each series' group then paints with one stroke, so a stacked column or area graph the graph tools draw is saved to `.ai` with its data and settings and opens again as a live graph; a stacked bar graph is still written as its art, as the reader has no type for it. Evidence: `cmd::graph::tests::a_legend_swatch_has_the_stroke_of_its_series_marks`, `cmd::graph::tests::a_drawn_stacked_column_graph_saved_as_ai_opens_as_a_graph_that_takes_new_data`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`. Scores unchanged. - **Graph section in the Properties panel:** with one graph selected, or series of one graph picked with Group Selection, the Properties panel shows a Graph section. Its Graph Type… button opens the dialog of Object › Graph › Type… ([Format pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html)). Its Graph Data… button opens the dialog of Object › Graph › Data…; this button is VectorCraft's own. Column… shows when every series it would change draws columns or bars, and Marker… when every one draws lines, scatter points or radar lines; this is VectorCraft's own rule. Regression tests in `crates/ui-egui/src/panels/properties/tests.rs`. Scores unchanged. - **Selected Grid Repeat handles (#2691):** `tools/src/repeat_grid.rs` tests place the handles outside the grid at zoom 0.5, 1 and 4, preview rows, columns and spacing, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression drags the row handle two tiles down in a zoomed view (3 → 5 rows, the source unchanged, one Undo back) and the column-spacing slider. Scores and hours unchanged. +- **Selected Radial Repeat handles:** `tools/src/repeat_radial.rs` tests place the instances handle below the repeat and the radius handle on its circle between the first two instances at zoom 0.02, 1 and 4 (opposite a single instance, at the center with a radius of 0), step the count by whole instances within 1 to 1,000, set the radius from the outward part of a drag and stop it at 0, hide the handles for a locked, hidden or invalid repeat, leave no undo step for a drag that ends where it began, and give bounding-box handles priority; a headless canvas regression in a zoomed view turned 30° drags the instances handle (6 → 8 instances, the source unchanged, one Undo back) and the radius handle (60 → 80 pt), and Escape puts a radius drag back. Scores and hours unchanged. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged. - **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8e06948b33..8c104ff5bc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -395,7 +395,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | | Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | -| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; Radial Repeat has no handles yet | +| Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)); its splitter has no handle yet | | Grid Repeat Options (Object › Repeat › Options…) has a Preview checkbox: the repeat on the canvas follows the fields while the dialog is open, Cancel puts the original back without a history step, OK keeps the previewed values as one undo step | done | #2651; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html) lists the Preview option for the grid options only, so Radial and Mirror Repeat Options have none; `dialogs/command.rs` tests | | Type on a Path Options (Type › Type on a Path › Type on a Path Options…, or a double-click on the Type on a Path tools) has a Preview checkbox, off when it opens: the selected type on a path follows Effect, Flip, Align to Path and Spacing while the dialog is open, Cancel puts it back without a history step, OK keeps the previewed values as one undo step | done | #5360; the [public page](https://helpx.adobe.com/illustrator/using/creating-type-path.html) lists the dialog's options, and public tutorials of the dialog show its Preview checkbox; `tests/pathtype.rs` | | Graph Type (Object › Graph › Type…, or a double-click on a graph tool) is a dialog of its own: a menu at the top shows Graph Options or the page of an axis; Graph Options has a button per graph type, Value Axis with Separate Scales, the Style checkboxes (Add Drop Shadow, Add Legend Across Top, First Row in Front, First Column in Front) and the options of the type picked (Column or Bar Width and Cluster Width; Mark Data Points, Connect Data Points, Edge-to-Edge Lines and Draw Filled Lines; a pie graph's Legend, Position and Sort); the Value Axis page (Left Axis and Right Axis with the value axis on both sides) has Tick Values with Override Calculated Values, Tick Marks and Add Labels, and the Category Axis page has Tick Marks with Draw Tick Marks Between Labels; with series picked by Group Selection the type and value axis go to those series | done | Public pages: [graph types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-types.html), [value axes](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/change-graph-value-axes.html), [columns, bars and lines](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-columns-bars-and-lines.html), [pie graphs](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/format-pie-graphs.html), [separate scales](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/assign-different-scales-to-value-axes.html), [combined types](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/visualize-data/combine-different-graph-types.html). The options dimmed for a type, the pages listed and the Legend checkbox are VectorCraft's own rules. Dialog `graphType`; `dialogs/graph_type.rs` and its tests | From e0f880ab1a44742f16aa710619bec90d30f53a03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:45:07 -0800 Subject: [PATCH 19/62] =?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 20/62] 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 532d2ea6d775538d08e3a65e8b08b0544c3870f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:04:30 -0800 Subject: [PATCH 21/62] Packaging Tools: Check Fold Lines finds the panels and hinges of a blank and lists what is wrong MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Packaging Tools › Check Fold Lines, and the Fold Lines panel's Check button, check the fold lines of the selection, or of the document while nothing is selected (`addon.packaging.check`). - Cut lines bound the material: each connected piece that encloses an area is one blank, its largest closed cut line is the outline, and a closed cut line inside it is a hole. A slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it, and an outline drawn as several open cut lines works too. - Creases, partial cuts and perforations divide a blank into panels; the pieces between the same two panels form one hinge. - 15 issue codes, errors and warnings, each naming its lines; cut line ends within a tolerance (0.1 pt, 0.01 to 10) are joined and reported as a gap. With `select`, the lines the issues name are selected. - The panel lists the issues in the interface language, with a summary line; clicking an issue or its Select button selects its lines. The list is kept until the document changes. `vectorcraft_pathops::adjacency` maps paths as live_paint does and keeps, for each edge, every input it lies on and the faces on both sides; the blank model is `vectorcraft_three_d::fold::blanks`. The engine now depends on vectorcraft-three-d directly. Docs: docs/mcp.md (Check Fold Lines), crates/pathops/README.md, ROADMAP. --- Cargo.lock | 2 + ROADMAP.md | 1 + crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/addons/packaging.rs | 8 +- .../engine/src/cmd/addons/packaging/check.rs | 176 +++ .../src/cmd/addons/packaging/check/tests.rs | 165 +++ .../engine/src/cmd/addons/packaging/roles.rs | 4 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 3 + crates/pathops/README.md | 8 + crates/pathops/src/lib.rs | 4 +- crates/pathops/src/planar.rs | 2 + crates/pathops/src/planar/adjacency.rs | 169 +++ crates/pathops/src/planar/adjacency/tests.rs | 200 +++ crates/pathops/src/planar/map.rs | 16 +- crates/three-d/Cargo.toml | 3 + crates/three-d/src/fold.rs | 1237 +++++++++++++++++ crates/three-d/src/fold/tests.rs | 740 ++++++++++ crates/three-d/src/lib.rs | 1 + crates/ui-egui/src/addons/packaging.rs | 144 +- crates/ui-egui/src/addons/packaging/tests.rs | 133 +- crates/ui-egui/src/i18n/bg.tsv | 19 + crates/ui-egui/src/i18n/bs.tsv | 19 + crates/ui-egui/src/i18n/ca.tsv | 19 + crates/ui-egui/src/i18n/cs.tsv | 19 + crates/ui-egui/src/i18n/da.tsv | 19 + crates/ui-egui/src/i18n/de.tsv | 19 + crates/ui-egui/src/i18n/el.tsv | 19 + crates/ui-egui/src/i18n/es.tsv | 19 + crates/ui-egui/src/i18n/fi.tsv | 19 + crates/ui-egui/src/i18n/fr.tsv | 19 + crates/ui-egui/src/i18n/gu.tsv | 19 + crates/ui-egui/src/i18n/hi.tsv | 19 + crates/ui-egui/src/i18n/hu.tsv | 19 + crates/ui-egui/src/i18n/id.tsv | 19 + crates/ui-egui/src/i18n/it.tsv | 19 + crates/ui-egui/src/i18n/ja.tsv | 19 + crates/ui-egui/src/i18n/ka.tsv | 19 + crates/ui-egui/src/i18n/ko.tsv | 19 + crates/ui-egui/src/i18n/nl.tsv | 19 + crates/ui-egui/src/i18n/pl.tsv | 19 + crates/ui-egui/src/i18n/pt-br.tsv | 19 + crates/ui-egui/src/i18n/ru.tsv | 19 + crates/ui-egui/src/i18n/sv.tsv | 19 + crates/ui-egui/src/i18n/tr.tsv | 19 + crates/ui-egui/src/i18n/uk.tsv | 19 + crates/ui-egui/src/i18n/vi.tsv | 19 + crates/ui-egui/src/i18n/zh-hans.tsv | 19 + crates/ui-egui/src/i18n/zh-hant.tsv | 19 + crates/ui-egui/src/menus/invoke.rs | 5 + docs/mcp.md | 56 +- 51 files changed, 3593 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/check.rs create mode 100644 crates/engine/src/cmd/addons/packaging/check/tests.rs create mode 100644 crates/pathops/src/planar/adjacency.rs create mode 100644 crates/pathops/src/planar/adjacency/tests.rs create mode 100644 crates/three-d/src/fold.rs create mode 100644 crates/three-d/src/fold/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 81946466b5..3b31ba9996 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6709,6 +6709,7 @@ dependencies = [ "vectorcraft-svg", "vectorcraft-testkit", "vectorcraft-text", + "vectorcraft-three-d", "vectorcraft-tools", "vectorcraft-trace", "wat", @@ -7017,6 +7018,7 @@ dependencies = [ name = "vectorcraft-three-d" version = "0.24.1" dependencies = [ + "proptest", "vectorcraft-geom 0.24.1", "vectorcraft-pathops 0.24.1", ] diff --git a/ROADMAP.md b/ROADMAP.md index 6471505555..f658cccb58 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..099f46c028 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -29,6 +29,8 @@ vectorcraft-tools = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-render = { workspace = true } vectorcraft-pathops = { workspace = true } +# The panels and hinges of a packaging blank (Packaging Tools' Check Fold Lines). +vectorcraft-three-d = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-trace = { workspace = true } vectorcraft-svg = { workspace = true } diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 7e262c3869..6099386b98 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -1,9 +1,11 @@ //! Packaging Tools (`addon.packaging.*`), a built-in add-on for the dielines of boxes and other //! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line //! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each -//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Its submenu +//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold +//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. +mod check; mod roles; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; @@ -11,7 +13,9 @@ pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; pub fn specs() -> Vec { - roles::specs() + let mut v = roles::specs(); + v.extend(check::specs()); + v } #[cfg(test)] diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs new file mode 100644 index 0000000000..59f195d4df --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -0,0 +1,176 @@ +//! Check Fold Lines (`addon.packaging.check`): the blanks the fold lines make, their panels and +//! hinges, and what is wrong with the lines, found by [`vectorcraft_three_d::fold::blanks`]. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; + +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; +use super::roles::{Role, RoleTable, can_carry, role_targets}; +use crate::{Result, Session}; + +const CHECK: &str = "addon.packaging.check"; + +/// How far apart the ends of two lines may be and still be joined, in points. +const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); + +pub fn specs() -> Vec { + vec![cmd!( + "addon.packaging.check", + "Check Fold Lines", + ["Object", "Plug-ins", "Packaging Tools"], + None, + "{ids?: [id…] (default: the selection), select?: bool (false), tolerance?: pt 0.01..10 (0.1)} check the fold lines (addon.packaging.roles) among the objects (through groups and clip groups), or, while nothing is selected and ids is left out, every fold line of the document that is shown. Cut lines bound the blanks: each connected piece of them that encloses material is one blank, its outline is its largest closed cut line, and a closed cut line inside it is a hole, so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in it; open cut lines that meet end to end count as one closed cut line. Crease, Partial Cut and Perforation lines divide a blank into panels; the pieces of them between two panels are that pair's hinge. A cut line end that comes within tolerance of another cut line is joined to it. Issues, in this order: noCut, open, looseEnd (errors), gap (a warning: the gap is closed), tooComplex (an error: more than 65,536 segments or 256 panels in a blank), cutOverCrease (an error), duplicate, danglingCrease, noSplit, outside, notStraight (it folds along the line through its longest piece), sliver, ambiguous, loosePanel (joined to the largest panel by no chain of hinges), nonPrinting (warnings). With select, the objects the issues name become the selection, unless no issue names one. Changes nothing in the document → {ok (no error), blanks, panels, hinges, holes, issues: [{severity: error|warning, code, message (English), ids, at?: [x, y]}], scope: ids|selection|document}", + has_doc, + check + )] +} + +/// The English message for an issue (the Fold Lines panel shows it in the interface language). +fn message(code: IssueCode, scope: &str) -> &'static str { + match code { + IssueCode::NoCut if scope == "document" => "No cut lines are in the document.", + IssueCode::NoCut => "No cut lines are in the selection.", + IssueCode::Open => "The cut lines do not enclose an area.", + IssueCode::LooseEnd => "A cut line ends without meeting another cut line.", + IssueCode::Gap => "A gap between cut lines was closed.", + IssueCode::TooComplex => "The fold lines are too complex to check.", + IssueCode::CutOverCrease => "A cut line and a crease lie on top of each other.", + IssueCode::Duplicate => "Two lines of the same role lie on top of each other.", + IssueCode::DanglingCrease => "A crease ends inside a panel.", + IssueCode::NoSplit => "A crease does not divide two panels.", + IssueCode::Outside => "A crease lies outside the cut outline.", + IssueCode::NotStraight => "A crease that is not straight is folded along one straight line.", + IssueCode::Sliver => "A gap between cut lines is too narrow to tell apart.", + IssueCode::Ambiguous => "A cut-out area holds other fold lines.", + IssueCode::LoosePanel => "A panel is not joined to the rest by a crease.", + IssueCode::NonPrinting => "A fold line is on a non-printing layer.", + } +} + +/// Every object of the document that can carry a role and is shown: on a shown layer, in shown +/// groups, and shown itself. +fn shown_targets(d: &Document) -> Vec { + fn walk(n: &Node, out: &mut Vec) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)), + _ if can_carry(n) => out.push(n.id), + _ => {} + } + } + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &mut out)); + out +} + +/// The path of object `n` in document coordinates: a path's own, or a compound path's members'. +fn path_of(n: &Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => Some(path.clone()), + NodeKind::Compound { children, .. } => Some(PathData::new( + children + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Path { path, .. } => Some(path.subpaths.iter().cloned()), + _ => None, + }) + .flatten() + .collect(), + )), + _ => None, + } +} + +/// Whether object `id` is on a layer, or a sublayer, that does not print. +fn on_non_printing_layer(d: &Document, id: NodeId) -> bool { + d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. })) +} + +fn kind(role: Role) -> LineKind { + match role { + Role::Cut => LineKind::Cut, + Role::Crease => LineKind::Crease, + Role::PartialCut => LineKind::PartialCut, + Role::Perforation => LineKind::Perforation, + } +} + +fn check(s: &mut Session, p: &Value) -> Result { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = match length_given(p, "tolerance", CHECK)? { + None => TOLERANCE.1, + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, + Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + }; + let given = p.get("ids").is_some_and(|v| !v.is_null()); + let roots = checked_ids_or_selection(s, p, CHECK)?; + let d = &s.doc()?.doc; + let (scope, targets) = match (given, roots.is_empty()) { + (true, _) => ("ids", role_targets(d, &roots, false).0), + (false, false) => ("selection", role_targets(d, &roots, false).0), + (false, true) => ("document", shown_targets(d)), + }; + let table = RoleTable::of(d); + let mut lines = vec![]; + let mut non_printing = vec![]; + let mut segments = 0usize; + for id in targets { + // Once the lines have more segments than the check takes, it reports them as too complex: + // the rest are not copied. + if segments > MAX_SEGMENTS { + break; + } + let Some(n) = d.node(id) else { continue }; + let (Some(role), Some(path)) = (table.role_of(n), path_of(n)) else { continue }; + if on_non_printing_layer(d, id) { + non_printing.push(id.0); + } + segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); + lines.push(FoldLine { path, kind: kind(role), angle: None, key: id.0 }); + } + let (found, mut issues) = blanks(&lines, tolerance); + if !non_printing.is_empty() { + issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + } + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows: Vec = issues + .iter() + .map(|i| { + let mut row = json!({ + "severity": if i.code.is_error() { "error" } else { "warning" }, + "code": i.code.id(), + "message": message(i.code, scope), + "ids": i.keys, + }); + if let (Some(at), Some(o)) = (i.at, row.as_object_mut()) { + o.insert("at".into(), json!([at.x, at.y])); + } + row + }) + .collect(); + if select { + let mut ids: Vec = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); + ids.sort_unstable_by_key(|id| id.0); + ids.dedup(); + if !ids.is_empty() { + s.select(|_, sel| sel.set(ids.iter().copied()))?; + } + } + Ok(json!({ + "ok": ok, + "blanks": found.len(), + "panels": found.iter().map(|b| b.panels.len()).sum::(), + "hinges": found.iter().map(|b| b.hinges.len()).sum::(), + "holes": found.iter().map(|b| b.holes.len()).sum::(), + "issues": rows, + "scope": scope, + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/check/tests.rs b/crates/engine/src/cmd/addons/packaging/check/tests.rs new file mode 100644 index 0000000000..427656fc29 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/check/tests.rs @@ -0,0 +1,165 @@ +//! Tests for Check Fold Lines: the blanks, panels, hinges and issues of fold lines drawn in a +//! document. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn check(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.check", &p).unwrap() +} + +fn codes(r: &Value) -> Vec<&str> { + r["issues"].as_array().unwrap().iter().map(|i| i["code"].as_str().unwrap()).collect() +} + +/// A tray blank: a 100 pt base with a 40 pt wall on each side, its outline a cut line and the +/// base's four sides creases → (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +#[test] +fn a_tray_checks_clean_with_five_panels_and_four_hinges() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!((r["blanks"].as_u64(), r["panels"].as_u64(), r["hinges"].as_u64(), r["holes"].as_u64()), (Some(1), Some(5), Some(4), Some(0)), "{r}"); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(r["scope"], "document"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a check records no undo step"); +} + +#[test] +fn the_selection_or_ids_limit_the_check_to_their_lines() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [creases[0]] })).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool()), (Some("selection"), Some(false))); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the selection."); + let r = check(&mut s, json!({ "ids": [outline] })); + assert_eq!((r["scope"].as_str(), r["ok"].as_bool(), r["panels"].as_u64()), (Some("ids"), Some(true), Some(1)), "{r}"); + // No fold lines at all in the document. + let mut s = session(); + let r = check(&mut s, json!({})); + assert_eq!(codes(&r), ["noCut"]); + assert_eq!(r["issues"][0]["message"], "No cut lines are in the document."); +} + +#[test] +fn issues_name_their_lines_and_select_selects_them() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A slit from the outline that stops in the middle of the base. + let slit = path(&mut s, "M190 100 L190 190"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], false); + let loose = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "looseEnd").cloned().unwrap(); + assert_eq!((loose["severity"].as_str(), loose["ids"].clone()), (Some("error"), json!([slit])), "{r}"); + assert_eq!(loose["at"], json!([190.0, 190.0])); + assert!(s.doc().unwrap().selection.objects.is_empty(), "without select, the selection stays"); + let r = check(&mut s, json!({ "select": true })); + let named: std::collections::BTreeSet = + r["issues"].as_array().unwrap().iter().flat_map(|i| i["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap())).collect(); + let selected: std::collections::BTreeSet = s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert!(selected.contains(&slit) && selected == named, "{selected:?} {named:?}"); + assert!(!selected.contains(&creases[1])); +} + +#[test] +fn a_clean_check_with_select_leaves_the_selection_alone() { + let mut s = session(); + let (outline, _) = tray(&mut s); + s.execute("select.set", &json!({ "ids": [outline] })).unwrap(); + let r = check(&mut s, json!({ "ids": [outline], "select": true })); + assert!(codes(&r).is_empty(), "{r}"); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [outline]); +} + +#[test] +fn tolerance_is_checked_and_joins_gaps_up_to_it() { + let mut s = session(); + tray(&mut s); + for bad in [json!(0.005), json!(10.5), json!("x"), json!(true)] { + let e = s.execute("addon.packaging.check", &json!({ "tolerance": bad })).unwrap_err().to_string(); + assert!(e.contains("tolerance"), "{e}"); + } + let e = s.execute("addon.packaging.check", &json!({ "select": 1 })).unwrap_err().to_string(); + assert!(e.contains("select"), "{e}"); + for edge in [json!(0.01), json!(10), json!("2 mm")] { + assert_eq!(check(&mut s, json!({ "tolerance": edge }))["ok"], true); + } + // A slit that stops 0.5 pt short of a crease: a gap at a tolerance of 1 pt, a loose end at 0.1 pt. + let mut s = session(); + tray(&mut s); + let slit = path(&mut s, "M190 100 L190 139.5"); + role(&mut s, "cut", &[slit]); + s.execute("select.none", &json!({})).unwrap(); + assert!(codes(&check(&mut s, json!({ "tolerance": 0.1 }))).contains(&"looseEnd")); + let near = check(&mut s, json!({ "tolerance": 1 })); + assert!(!codes(&near).contains(&"looseEnd"), "{near}"); +} + +#[test] +fn hidden_lines_are_left_out_and_lines_on_a_non_printing_layer_are_noted() { + let mut s = session(); + let (_, creases) = tray(&mut s); + // A hidden crease is not checked while nothing is selected: the tray has three hinges and a + // panel joined by none. + s.execute("layer.setProps", &json!({ "ids": [creases[0]], "visible": false })).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!((r["panels"].as_u64(), r["hinges"].as_u64()), (Some(4), Some(3)), "{r}"); + // A cut line on a layer that does not print. + let mut s = session(); + s.execute("layer.new", &json!({ "printable": false })).unwrap(); + let (outline, _) = tray(&mut s); + let r = check(&mut s, json!({})); + assert_eq!(r["ok"], true, "a warning only"); + let note = r["issues"].as_array().unwrap().iter().find(|i| i["code"] == "nonPrinting").cloned().unwrap(); + assert_eq!(note["severity"], "warning"); + assert!(note["ids"].as_array().unwrap().contains(&json!(outline)), "{note}"); + assert_eq!(note["message"], "A fold line is on a non-printing layer."); +} + +#[test] +fn a_compound_path_and_a_grouped_line_are_checked() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + // A window: a closed cut line in the base, made a compound path with nothing else. + let window = path(&mut s, "M170 170 L210 170 L210 210 L170 210 Z"); + s.execute("select.set", &json!({ "ids": [window] })).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64(); + let window = compound.unwrap_or(window); + role(&mut s, "cut", &[window]); + s.execute("select.set", &json!({ "ids": [outline, creases[0], creases[1], creases[2], creases[3], window] })).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let r = check(&mut s, json!({})); + assert_eq!(r["scope"], "selection"); + assert_eq!((r["ok"].as_bool(), r["panels"].as_u64(), r["holes"].as_u64()), (Some(true), Some(5), Some(1)), "{r}"); +} diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 010384c6c2..2b3c7696f3 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -186,7 +186,7 @@ fn free_role_name(d: &Document, table: &RoleTable, role: Role) -> String { /// Whether `n` can carry a role: a path (a live shape too) that is neither a clipping path nor a /// guide, or a compound path. -fn can_carry(n: &Node) -> bool { +pub(super) fn can_carry(n: &Node) -> bool { match &n.kind { NodeKind::Path { clipping, guide, .. } => !clipping && !guide, NodeKind::Compound { .. } => true, @@ -199,7 +199,7 @@ fn can_carry(n: &Node) -> bool { /// how many of `roots` and their members can't (text, images, symbol instances and other objects). /// With `editable`, objects that are locked or hidden, are in a locked or hidden group or layer, or /// are on a locked artboard are left out and counted as skipped. -fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { +pub(super) fn role_targets(d: &Document, roots: &[NodeId], editable: bool) -> (Vec, usize) { fn walk(n: &Node, out: &mut Vec, skipped: &mut usize) { match &n.kind { NodeKind::Group { children, .. } => { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 75313d4e4c..1338bb5776 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -40,6 +40,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.colorMask", "addon.image.removeBackground", "addon.image.removeColorMask", + "addon.packaging.check", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index a4c6c1af40..d8c01c6545 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1011,6 +1011,9 @@ fn structured_junk() { ("addon.packaging.roles", json!({"ids": [-1, 1e300]})), ("addon.packaging.setRoleSwatch", json!({"role": "perforation", "swatch": "[Registration]"})), ("addon.packaging.setRoleSwatch", json!({"role": "cut", "swatch": 5})), + ("addon.packaging.check", json!({"ids": [u64::MAX, -1], "select": "yes", "tolerance": 1e308})), + ("addon.packaging.check", json!({"tolerance": "-5 mm", "select": true})), + ("addon.packaging.check", json!({"ids": [], "tolerance": null})), // Smart Pen add-on. ("addon.pen.append", json!({"id": 2, "x": 1e308, "y": 0, "in": [1e308, -1e308]})), ("addon.pen.append", json!({"id": 2, "subpath": u64::MAX, "x": 0, "y": 0, "segment": "curved"})), diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 08380830b2..2397045a84 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -61,6 +61,14 @@ Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` t `shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +```rust +pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } +pub struct MapEdge { pub path: PathData, pub sources: Vec, pub left: Option, pub right: Option, pub piece: usize } +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option; +``` + +`adjacency` maps the paths as `live_paint` does and also reports, for each edge, every input it lies on and the faces on its left and right as it runs along its path (document coordinates, y down). A line drawn on top of another keeps both inputs on the edge, whatever the input order. A piece of line that ends inside a face has that face on both sides. Faces narrower than `precision` are listed as slivers, and `outlines` holds the outer boundary of each connected piece of the paths. It returns `None` for more than `SHAPE_BUILDER_MAX_SEGMENTS` segments, non-finite input or a `precision` that is not a positive number. + ## Offset / stroke ```rust diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 49b7c051f1..d35050f70c 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -30,8 +30,8 @@ pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; pub use planar::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point, - live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, + encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index 75234b3943..f702f993ed 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -26,12 +26,14 @@ use vectorcraft_geom::{FillRule, PathData, SubPath}; use crate::boolean::{DEFAULT_PRECISION, Seg, Tidy, eps_for, is_sliver, segs_to_subpath, snap_horizontals, tidy_segments, to_seg}; use crate::pathfinder::{Region, Shape}; +mod adjacency; mod graph; mod index; mod live_paint; mod map; mod shape_builder; +pub use adjacency::{Adjacency, MapEdge, MapFace, MapOutline, adjacency}; pub(crate) use graph::pin_ends; #[cfg(test)] use index::{Crossings, RectIndex, reference_budget, segment_footprint, work_done}; diff --git a/crates/pathops/src/planar/adjacency.rs b/crates/pathops/src/planar/adjacency.rs new file mode 100644 index 0000000000..52357a0d67 --- /dev/null +++ b/crates/pathops/src/planar/adjacency.rs @@ -0,0 +1,169 @@ +//! Which faces of a planar map each edge separates, and every input each edge lies on. +//! +//! [`live_paint`](super::live_paint) gives each edge under its front-most input only, and says +//! nothing about the faces on its sides. [`adjacency`] reads both from the same planar map, so a +//! caller can tell which faces a line divides and which lines lie on top of each other. + +use super::graph::{find, half_segs, twin, unshear}; +use super::index::RectIndex; +use super::map::{Map, map_with}; +use super::*; + +/// A planar map of some paths with each edge's sides and inputs ([`adjacency`]). +#[derive(Clone, Debug, Default)] +pub struct Adjacency { + pub faces: Vec, + pub edges: Vec, + /// Bounded areas left out as slivers: narrower than the precision on average, such as a thin + /// gap between two lines. + pub slivers: Vec, + /// The outer boundary of each connected piece of the paths. + pub outlines: Vec, +} + +/// A bounded face: its outline, then the outer boundaries of the pieces inside it (as holes), and +/// its area without them. +#[derive(Clone, Debug)] +pub struct MapFace { + pub path: PathData, + pub area: f64, + /// The connected piece of the paths whose edges bound it. + pub piece: usize, +} + +/// An edge: a piece of one or more inputs between two places where paths meet. +#[derive(Clone, Debug)] +pub struct MapEdge { + pub path: PathData, + /// Every input it lies on (indices into the inputs, ascending). + pub sources: Vec, + /// The faces on each side of it as it runs along `path`, seen on the page (document + /// coordinates, y down): `left` on the left. `None` outside every bounded face, or in a sliver. + /// A piece of line that ends loose inside a face has that face on both sides. + pub left: Option, + pub right: Option, + pub piece: usize, +} + +/// The outer boundary of a connected piece of the paths. +#[derive(Clone, Debug)] +pub struct MapOutline { + pub path: PathData, + pub piece: usize, +} + +/// The planar map of `shapes`, every path an edge as in [`live_paint`](super::live_paint), with +/// faces refit to `precision` and slivers narrower than it left out. `None` when the paths can't be +/// swept (non-finite, too degenerate, or more than [`SHAPE_BUILDER_MAX_SEGMENTS`] segments), when +/// `precision` is not a positive number, and when no path has two anchors. +pub fn adjacency(shapes: &[Shape], precision: f64) -> Option { + if !(precision.is_finite() && precision > 0.0) { + return None; + } + let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(SubPath::segment_count).sum(); + if segments > SHAPE_BUILDER_MAX_SEGMENTS { + return None; + } + let m = map_with(shapes, false, precision)?; + Some(read(&m)) +} + +fn read(m: &Map) -> Adjacency { + let path = |cycle: &[usize], closed: bool| { + let segs: Vec = cycle.iter().flat_map(|&h| half_segs(&m.edges, h)).collect(); + segs_to_subpath(&tidy_segments(segs, closed, &m.tidy), closed) + }; + let unsheared = |subpaths: Vec| unshear(PathData::new(subpaths), &m.anchors, m.snap); + + // Connected pieces, by the vertices the edges join, numbered in the order they are first met. + let vertices = m.edges.iter().flat_map(|e| e.ends).max().map_or(0, |v| v + 1); + let mut parent: Vec = (0..vertices).collect(); + for e in &m.edges { + let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1])); + if let Some(p) = parent.get_mut(a) { + *p = b; + } + } + let mut number: Vec> = vec![None; vertices]; + let mut pieces = 0; + let mut piece_of_vertex = |v: usize| { + let root = find(&mut parent, v); + match number.get_mut(root) { + Some(Some(n)) => *n, + Some(slot) => { + *slot = Some(pieces); + pieces += 1; + pieces - 1 + } + None => 0, + } + }; + let edge_pieces: Vec = m.edges.iter().map(|e| piece_of_vertex(e.ends[0])).collect(); + let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| edge_pieces.get(h / 2)).copied().unwrap_or(0); + + // The face on each half-edge's side: a face's own cycle, and the outer boundaries of the + // pieces inside it, bound it. + let mut face_of: Vec> = vec![None; 2 * m.edges.len()]; + let mut faces = Vec::with_capacity(m.faces.len()); + for (i, (cycle, _, area)) in m.faces.iter().enumerate() { + let holes: Vec<&(Vec, BezPath)> = m.face_holes.get(i).into_iter().flatten().filter_map(|&k| m.holes.get(k)).collect(); + for &h in cycle.iter().chain(holes.iter().flat_map(|(c, _)| c)) { + if let Some(f) = face_of.get_mut(h) { + *f = Some(i); + } + } + let mut subpaths: Vec = path(cycle, true).into_iter().collect(); + subpaths.extend(holes.iter().filter_map(|(c, _)| path(c, true))); + // A hole's outer boundary winds the other way: its area is negative. + let area = area + holes.iter().map(|(_, bp)| bp.area()).sum::(); + faces.push(MapFace { path: unsheared(subpaths), area, piece: piece_of(cycle) }); + } + + // A face walk leaves out the edges that end loose (spurs): such an edge lies inside the face + // around its middle, on both sides. + let mut on_cycle = vec![false; 2 * m.edges.len()]; + let cycles = m.faces.iter().map(|f| &f.0).chain(m.holes.iter().map(|h| &h.0)).chain(m.slivers.iter().map(|s| &s.0)); + for &h in cycles.flatten() { + if let Some(c) = on_cycle.get_mut(h) { + *c = true; + } + } + let spur = |e: usize| !on_cycle.get(2 * e).copied().unwrap_or(true) && !on_cycle.get(twin(2 * e)).copied().unwrap_or(true); + // The faces by their bounds, so that each spur tests only the faces whose bounds hold it; + // built only when there is a spur. + let bezpaths: Vec = if (0..m.edges.len()).any(spur) { faces.iter().map(|f| f.path.to_bezpath()).collect() } else { vec![] }; + let face_index = RectIndex::new(bezpaths.iter().enumerate().map(|(i, bp)| (bp.bounding_box(), i)).collect()); + let face_around = |p: Point| { + face_index + .at(p, 0.0) + .copied() + .filter(|&i| bezpaths.get(i).is_some_and(|bp| bp.winding(p) != 0)) + .min_by(|&a, &b| faces.get(a).map_or(f64::INFINITY, |f| f.area).total_cmp(&faces.get(b).map_or(f64::INFINITY, |f| f.area))) + }; + + // A face cycle winds so its face is on the side where the cross product of the half-edge's + // direction and the way to the face is positive: on the page, with y down, that is the right. + let edges = m + .edges + .iter() + .enumerate() + .filter_map(|(e, edge)| { + let sp = path(&[2 * e], false)?; + let path = unsheared(vec![sp]); + let (left, right) = if spur(e) { + let around = path.to_bezpath().segments().next().map(|s| s.eval(0.5)).and_then(face_around); + (around, around) + } else { + (face_of.get(twin(2 * e)).copied().flatten(), face_of.get(2 * e).copied().flatten()) + }; + Some(MapEdge { path, sources: edge.sources.clone(), left, right, piece: edge_pieces.get(e).copied().unwrap_or(0) }) + }) + .collect(); + let slivers = m.slivers.iter().filter_map(|(cycle, _)| path(cycle, true)).map(|sp| unsheared(vec![sp])).collect(); + let outlines = + m.holes.iter().filter_map(|(cycle, _)| Some(MapOutline { path: unsheared(vec![path(cycle, true)?]), piece: piece_of(cycle) })).collect(); + Adjacency { faces, edges, slivers, outlines } +} + +#[cfg(test)] +mod tests; diff --git a/crates/pathops/src/planar/adjacency/tests.rs b/crates/pathops/src/planar/adjacency/tests.rs new file mode 100644 index 0000000000..8677a7e11a --- /dev/null +++ b/crates/pathops/src/planar/adjacency/tests.rs @@ -0,0 +1,200 @@ +use super::*; +use kurbo::{ParamCurveNearest, Vec2}; +use proptest::prelude::*; +use vectorcraft_geom::{FillRule, Rect, shapes}; + +fn line(a: (f64, f64), b: (f64, f64)) -> Shape { + Shape::new(PathData::single(SubPath::polyline(&[Point::new(a.0, a.1), Point::new(b.0, b.1)], false)), FillRule::NonZero, 0) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Shape { + Shape::new(shapes::rectangle(Rect::new(x0, y0, x1, y1)), FillRule::NonZero, 0) +} + +fn inside(f: &MapFace, p: Point) -> bool { + f.path.to_bezpath().winding(p) != 0 +} + +/// The edges whose middle lies within 0.01 of `p`. +fn edges_at(a: &Adjacency, p: Point) -> Vec<&MapEdge> { + a.edges + .iter() + .filter(|e| { + let bp = e.path.to_bezpath(); + bp.segments().any(|s| { + let n = s.nearest(p, 1e-6); + n.distance_sq < 1e-4 + }) + }) + .collect() +} + +#[test] +fn a_line_across_a_rectangle_divides_two_faces_it_lies_between() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((40.0, -10.0), (40.0, 60.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2, "{:?}", a.faces); + let left_face = a.faces.iter().position(|f| inside(f, Point::new(20.0, 25.0))).unwrap(); + let right_face = a.faces.iter().position(|f| inside(f, Point::new(70.0, 25.0))).unwrap(); + assert_ne!(left_face, right_face); + assert!((a.faces[left_face].area - 2000.0).abs() < 1e-6 && (a.faces[right_face].area - 3000.0).abs() < 1e-6); + let shared = edges_at(&a, Point::new(40.0, 25.0)); + assert_eq!(shared.len(), 1, "{shared:?}"); + let e = shared[0]; + assert_eq!(e.sources, vec![1]); + let mut sides = [e.left.unwrap(), e.right.unwrap()]; + sides.sort_unstable(); + let mut want = [left_face, right_face]; + want.sort_unstable(); + assert_eq!(sides, want); + // The rectangle's own sides have a face on one side only; the line's ends stick out into no face. + let side = edges_at(&a, Point::new(70.0, 0.0)); + assert_eq!(side.len(), 1); + assert_eq!([side[0].left, side[0].right].iter().flatten().count(), 1); + let stub = edges_at(&a, Point::new(40.0, -5.0)); + assert_eq!((stub[0].left, stub[0].right), (None, None)); + assert!(a.faces.iter().all(|f| f.piece == 0) && a.edges.iter().all(|e| e.piece == 0)); +} + +#[test] +fn a_line_that_ends_inside_a_face_has_that_face_on_both_sides() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), line((50.0, 0.0), (50.0, 30.0)), line((20.0, 10.0), (30.0, 20.0))], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 1); + for at in [Point::new(50.0, 15.0), Point::new(25.0, 15.0)] { + let e = edges_at(&a, at); + assert_eq!(e.len(), 1, "{at:?}"); + assert_eq!((e[0].left, e[0].right), (Some(0), Some(0)), "{at:?}"); + } +} + +#[test] +fn loose_lines_in_many_faces_look_only_at_the_faces_near_them() { + // A 40 × 40 grid of separate squares, then the same with a loose line in each. + let squares: Vec = + (0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| rect(x, y, x + 10.0, y + 10.0)).collect(); + let started = super::super::index::work_done(); + assert_eq!(adjacency(&squares, DEFAULT_PRECISION).unwrap().faces.len(), 1600); + let plain = super::super::index::work_done() - started; + let mut all = squares.clone(); + all.extend((0..1600).map(|k| (f64::from(k % 40) * 20.0, f64::from(k / 40) * 20.0)).map(|(x, y)| line((x + 5.0, y), (x + 5.0, y + 5.0)))); + let started = super::super::index::work_done(); + let a = adjacency(&all, DEFAULT_PRECISION).unwrap(); + let work = super::super::index::work_done() - started - plain; + let loose: Vec<&MapEdge> = a.edges.iter().filter(|e| e.sources.len() == 1 && e.sources[0] >= 1600).collect(); + assert_eq!(loose.len(), 1600); + for e in loose { + let mid = e.path.to_bezpath().segments().next().unwrap().eval(0.5); + let face = a.faces.iter().position(|f| inside(f, mid)); + assert_eq!((e.left, e.right), (face, face)); + assert!(face.is_some()); + } + // Testing every face for each loose line would read 1,600 faces per line. + assert!(work <= 64 * 1600, "{work} reads"); +} + +#[test] +fn a_line_on_a_rectangle_side_keeps_both_inputs_in_either_order() { + for flip in [false, true] { + let (r, l) = (rect(0.0, 0.0, 100.0, 50.0), line((-10.0, 50.0), (110.0, 50.0))); + let shapes = if flip { vec![l, r] } else { vec![r, l] }; + let a = adjacency(&shapes, DEFAULT_PRECISION).unwrap(); + let on = edges_at(&a, Point::new(30.0, 50.0)); + assert_eq!(on.len(), 1, "flip {flip}: {on:?}"); + assert_eq!(on[0].sources, vec![0, 1], "flip {flip}"); + } +} + +#[test] +fn each_side_names_the_face_seen_on_that_side_of_the_edge() { + // A tray-like outline with a crease grid, edges drawn in every direction. + let a = adjacency( + &[ + rect(0.0, 0.0, 90.0, 60.0), + line((30.0, 0.0), (30.0, 60.0)), + line((60.0, 60.0), (60.0, 0.0)), + line((90.0, 20.0), (0.0, 20.0)), + line((0.0, 40.0), (90.0, 40.0)), + ], + DEFAULT_PRECISION, + ) + .unwrap(); + assert_eq!(a.faces.len(), 9); + let mut checked = 0; + for e in &a.edges { + let bp = e.path.to_bezpath(); + let Some(seg) = bp.segments().next() else { continue }; + let (p, d) = (seg.eval(0.5), seg.end() - seg.start()); + let n = d.normalize(); + // On the page (y down), the left of a direction (dx, dy) is (dy, -dx). + let (left_at, right_at) = (p + Vec2::new(n.y, -n.x) * 0.5, p + Vec2::new(-n.y, n.x) * 0.5); + for (side, at) in [(e.left, left_at), (e.right, right_at)] { + match side { + Some(f) => assert!(inside(&a.faces[f], at), "{e:?}"), + None => assert!(a.faces.iter().all(|f| !inside(f, at)), "{e:?}"), + } + checked += 1; + } + } + assert!(checked >= 24, "{checked}"); +} + +#[test] +fn a_slot_narrower_than_the_precision_is_a_sliver() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 50.004, 40.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.slivers.len(), 1, "{:?}", a.slivers); + assert_eq!(a.faces.len(), 1); + let b = adjacency(&[rect(0.0, 0.0, 100.0, 50.0), rect(50.0, 10.0, 51.0, 40.0)], DEFAULT_PRECISION).unwrap(); + assert!(b.slivers.is_empty()); + assert_eq!(b.faces.len(), 2, "the slot is a face of its own"); +} + +#[test] +fn a_ring_is_a_face_with_a_hole_and_two_pieces() { + let a = adjacency(&[rect(0.0, 0.0, 100.0, 100.0), rect(30.0, 30.0, 70.0, 70.0)], DEFAULT_PRECISION).unwrap(); + assert_eq!(a.faces.len(), 2); + let ring = a.faces.iter().find(|f| inside(f, Point::new(10.0, 10.0))).unwrap(); + assert!(!inside(ring, Point::new(50.0, 50.0)), "the inner square is a hole in the ring"); + assert!((ring.area - 8400.0).abs() < 1e-6, "{}", ring.area); + assert_eq!(a.outlines.len(), 2); + assert_ne!(a.outlines[0].piece, a.outlines[1].piece); + let inner = a.faces.iter().find(|f| inside(f, Point::new(50.0, 50.0))).unwrap(); + assert_ne!(inner.piece, ring.piece); + let inner_side = edges_at(&a, Point::new(50.0, 30.0)); + let mut sides = [inner_side[0].left, inner_side[0].right]; + sides.sort_unstable(); + assert!(sides.iter().all(Option::is_some), "a ring face on one side, the inner square on the other: {sides:?}"); +} + +#[test] +fn bad_input_gives_no_map() { + assert!(adjacency(&[], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[line((0.0, 0.0), (f64::NAN, 1.0))], DEFAULT_PRECISION).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], 0.0).is_none()); + assert!(adjacency(&[rect(0.0, 0.0, 10.0, 10.0)], f64::INFINITY).is_none()); + let mut points: Vec = (0..=SHAPE_BUILDER_MAX_SEGMENTS + 1).map(|i| Point::new(i as f64, (i % 2) as f64)).collect(); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_none(), "over the segment limit"); + points.truncate(64); + let open = Shape::new(PathData::single(SubPath::polyline(&points, false)), FillRule::NonZero, 0); + assert!(adjacency(&[open], DEFAULT_PRECISION).is_some()); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + /// Random lines and boxes never panic, and every side an edge names is a face. + #[test] + fn random_lines_give_a_consistent_map( + segs in proptest::collection::vec((-50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..12), + boxed in any::(), + ) { + let mut shapes: Vec = segs.iter().map(|&(a, b, c, d)| line((a, b), (c, d))).collect(); + if boxed { + shapes.push(rect(-40.0, -40.0, 40.0, 40.0)); + } + if let Some(a) = adjacency(&shapes, DEFAULT_PRECISION) { + for e in &a.edges { + prop_assert!(e.left.is_none_or(|f| f < a.faces.len()) && e.right.is_none_or(|f| f < a.faces.len())); + prop_assert!(e.sources.iter().all(|&s| s < shapes.len())); + } + } + } +} diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index aa853b2469..a9b25d24b5 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -15,23 +15,23 @@ pub(crate) struct Rest { /// The planar graph of `shapes` (in the sweep's frame) with its faces walked: what [`build`] makes /// Live Paint faces and edges from, and what [`Map::merge`] merges faces in. pub(crate) struct Map { - edges: Vec, + pub(super) edges: Vec, around: Vec>, slot_of: Vec, /// Bounded faces: their cycle of half-edges, path and area; and, by their bounds, which can /// hold a point, so finding the face around one tests only those. - faces: Vec<(Vec, BezPath, f64)>, + pub(super) faces: Vec<(Vec, BezPath, f64)>, face_index: RectIndex, /// Bounded faces left out as slivers ([`is_sliver`]): their cycle of half-edges and the inputs /// whose fill covers them (none for a gap, such as a thin cutout). pub(super) slivers: Vec<(Vec, Vec)>, /// Outer boundaries of connected pieces, and the face each one is a hole in. - holes: Vec<(Vec, BezPath)>, - face_holes: Vec>, - tidy: Tidy, + pub(super) holes: Vec<(Vec, BezPath)>, + pub(super) face_holes: Vec>, + pub(super) tidy: Tidy, /// The inputs' anchors (sorted by x) and how close results snap back onto them. - anchors: Vec, - snap: f64, + pub(super) anchors: Vec, + pub(super) snap: f64, } /// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads; @@ -41,7 +41,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { } /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. -fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { +pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); diff --git a/crates/three-d/Cargo.toml b/crates/three-d/Cargo.toml index f5eefa1c9b..48d2bfbf05 100644 --- a/crates/three-d/Cargo.toml +++ b/crates/three-d/Cargo.toml @@ -11,3 +11,6 @@ workspace = true [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-pathops = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs new file mode 100644 index 0000000000..c68f8aa6ca --- /dev/null +++ b/crates/three-d/src/fold.rs @@ -0,0 +1,1237 @@ +//! The panels and hinges of a packaging blank, from its fold lines. +//! +//! Cut lines bound the material. Each connected piece of Cut lines with material is one blank: its +//! outline is the largest closed Cut subpath of the piece when every other face of the piece lies +//! inside it or inside another closed Cut subpath, and the piece's outer boundary otherwise. A face +//! is material when it lies inside that outline and inside no other closed Cut subpath of the piece, +//! so a slot drawn as a rectangle across the outline leaves the same material as a notch drawn in +//! it. Crease, Partial Cut and Perforation lines divide the material into panels; the pieces of them +//! between two panels are that pair's hinge. [`blanks`] also lists what is wrong with the lines +//! ([`IssueCode`]). + +use std::collections::{HashMap, HashSet}; + +use vectorcraft_geom::kurbo::{Line, ParamCurveArclen, ParamCurveNearest, PathSeg}; +use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape as _, SubPath}; +use vectorcraft_pathops::{Adjacency, DEFAULT_PRECISION, SHAPE_BUILDER_MAX_SEGMENTS, Shape, adjacency, find_gaps, interior_point, unite_all}; + +/// Most panels one blank may have. Its hinges are the edges of a planar graph on its panels, so there +/// are at most 3 × 256 - 6 = 762 of them. +pub const MAX_PANELS: usize = 256; +/// Most segments the fold lines may have together. +pub const MAX_SEGMENTS: usize = SHAPE_BUILDER_MAX_SEGMENTS; + +/// What a fold line does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LineKind { + /// Separates the material. + Cut, + /// A fold. + Crease, + /// A fold cut part way through the board. + PartialCut, + /// A fold along a line of cuts. + Perforation, +} + +impl LineKind { + /// The angle a line of this kind folds at when it has none of its own, in degrees: Crease and + /// Perforation 90, Partial Cut -90 (VectorCraft's own values); a positive angle folds away from + /// the printed side. A Cut line does not fold: 0. + pub fn default_angle(self) -> f64 { + match self { + LineKind::Cut => 0.0, + LineKind::Crease | LineKind::Perforation => 90.0, + LineKind::PartialCut => -90.0, + } + } +} + +/// A fold line: the path (document coordinates), its kind, its own fold angle in degrees if it has +/// one, and a key the issues name it by. +#[derive(Clone, Debug)] +pub struct FoldLine { + pub path: PathData, + pub kind: LineKind, + pub angle: Option, + pub key: u64, +} + +/// One blank: its panels, the hinges between them, and its holes. +#[derive(Clone, Debug, Default)] +pub struct Blank { + pub panels: Vec, + pub hinges: Vec, + pub holes: Vec, +} + +/// A panel: an area of material between fold lines. +#[derive(Clone, Debug)] +pub struct Panel { + pub outline: PathData, + pub area: f64, +} + +/// The fold between panels `a` and `b` (indices into the blank's panels, `a` < `b`), about the +/// straight line from `from` to `to`, at `angle` degrees, made of the lines `keys`. `straight` is +/// false when its pieces are not on one straight line within the tolerance; it then folds about the +/// line through its longest piece. +#[derive(Clone, Debug)] +pub struct Hinge { + pub a: usize, + pub b: usize, + pub from: Point, + pub to: Point, + pub angle: f64, + pub keys: Vec, + pub straight: bool, +} + +/// What can be wrong with fold lines, in the order [`blanks`] lists them. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum IssueCode { + /// No Cut line. + NoCut, + /// The Cut lines enclose no area. + Open, + /// An end of a Cut line meets no other fold line within the tolerance (a slit that ends on a + /// crease is not loose). + LooseEnd, + /// An end of a Cut line comes within the tolerance of a Cut line without meeting it; the panels + /// are built with the gap closed. + Gap, + /// Over [`MAX_SEGMENTS`] segments or [`MAX_PANELS`] panels in a blank, or the lines can't be + /// mapped. + TooComplex, + /// A Cut line and a crease lie on top of each other. + CutOverCrease, + /// Two lines of the same kind lie on top of each other. + Duplicate, + /// A crease ends inside a panel. + DanglingCrease, + /// A crease divides no two panels. + NoSplit, + /// A crease lies outside every blank. + Outside, + /// A hinge's pieces are not on one straight line. + NotStraight, + /// A gap between lines is narrower than the planar map can tell apart. + Sliver, + /// A hole holds crease lines, or a blank lies inside a hole. + Ambiguous, + /// A panel is joined to the largest panel of its blank by no chain of hinges. + LoosePanel, + /// A fold line is on a layer that does not print (the caller reports it). + NonPrinting, +} + +impl IssueCode { + /// Every code, in order. + pub const ALL: [IssueCode; 15] = [ + IssueCode::NoCut, + IssueCode::Open, + IssueCode::LooseEnd, + IssueCode::Gap, + IssueCode::TooComplex, + IssueCode::CutOverCrease, + IssueCode::Duplicate, + IssueCode::DanglingCrease, + IssueCode::NoSplit, + IssueCode::Outside, + IssueCode::NotStraight, + IssueCode::Sliver, + IssueCode::Ambiguous, + IssueCode::LoosePanel, + IssueCode::NonPrinting, + ]; + + /// The code's stable id. + pub fn id(self) -> &'static str { + match self { + IssueCode::NoCut => "noCut", + IssueCode::Open => "open", + IssueCode::LooseEnd => "looseEnd", + IssueCode::Gap => "gap", + IssueCode::TooComplex => "tooComplex", + IssueCode::CutOverCrease => "cutOverCrease", + IssueCode::Duplicate => "duplicate", + IssueCode::DanglingCrease => "danglingCrease", + IssueCode::NoSplit => "noSplit", + IssueCode::Outside => "outside", + IssueCode::NotStraight => "notStraight", + IssueCode::Sliver => "sliver", + IssueCode::Ambiguous => "ambiguous", + IssueCode::LoosePanel => "loosePanel", + IssueCode::NonPrinting => "nonPrinting", + } + } + + /// Whether it is an error (the blank can't be made as drawn) rather than a warning. + pub fn is_error(self) -> bool { + matches!(self, IssueCode::NoCut | IssueCode::Open | IssueCode::LooseEnd | IssueCode::TooComplex | IssueCode::CutOverCrease) + } +} + +/// One issue: its code, the lines it is about, and the place it is at, when it has one. +#[derive(Clone, Debug, PartialEq)] +pub struct Issue { + pub code: IssueCode, + pub keys: Vec, + pub at: Option, +} + +impl Issue { + fn new(code: IssueCode, mut keys: Vec, at: Option) -> Self { + keys.sort_unstable(); + keys.dedup(); + Issue { code, keys, at } + } +} + +/// One subpath of a fold line. +struct Piece { + sp: SubPath, + line: usize, +} + +/// The blanks `lines` make, and their issues in [`IssueCode`] order. `tolerance` (points) is how +/// far apart a Cut line's end and another Cut line may be and still be joined, by a line [`blanks`] +/// adds, and how far a hinge's pieces may stray from one straight line. Nothing is built when there +/// is no Cut line, the lines are too complex, or the Cut lines enclose no area. +pub fn blanks(lines: &[FoldLine], tolerance: f64) -> (Vec, Vec) { + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { DEFAULT_PRECISION }; + // Counted before anything is copied. + let segments = lines.iter().flat_map(|l| &l.path.subpaths).filter(|sp| usable(sp)).try_fold(0usize, |n, sp| { + let n = n.saturating_add(sp.segment_count()); + (n <= MAX_SEGMENTS).then_some(n) + }); + if segments.is_none() { + return (vec![], vec![Issue::new(IssueCode::TooComplex, vec![], None)]); + } + let pieces: Vec = lines + .iter() + .enumerate() + .flat_map(|(line, l)| l.path.subpaths.iter().filter(|sp| usable(sp)).map(move |sp| Piece { sp: sp.clone(), line })) + .collect(); + let mut issues = vec![]; + let kind = |p: &Piece| lines.get(p.line).map_or(LineKind::Cut, |l| l.kind); + let key = |p: &Piece| lines.get(p.line).map_or(0, |l| l.key); + let cuts: Vec<&Piece> = pieces.iter().filter(|p| kind(p) == LineKind::Cut).collect(); + if cuts.is_empty() { + return (vec![], vec![Issue::new(IssueCode::NoCut, vec![], None)]); + } + let folds: Vec<&Piece> = pieces.iter().filter(|p| kind(p) != LineKind::Cut).collect(); + let cut_shapes: Vec = cuts.iter().map(|p| shape(p.sp.clone())).collect(); + let gaps = find_gaps(&cut_shapes, tolerance); + // `find_gaps` takes ends closer than 1/10,000 of the tolerance as joined, which the map may not + // join: those are bridged too, without an issue. + let joined = find_gaps(&cut_shapes, (tolerance * 1e-4).max(1e-6)); + // An end a gap starts or ends at is not loose. + let gap_ends = + Cells::new(gaps.iter().chain(&joined).flatten().map(|&e| (Rect::from_points(e, e), (e.x.to_bits(), e.y.to_bits()))).collect(), 0.0, 4096.0); + let bridged = |at: Point| gap_ends.near(at, 1e-6).into_iter().any(|(x, y)| Point::new(f64::from_bits(x), f64::from_bits(y)).distance(at) <= 1e-6); + issues.extend( + loose_ends(&cuts, &folds, tolerance) + .into_iter() + .filter(|&(_, at)| !bridged(at)) + .map(|(i, at)| Issue::new(IssueCode::LooseEnd, vec![cuts.get(i).map_or(0, |p| key(p))], Some(at))), + ); + if !gaps.is_empty() { + // The cut lines by their ends, to name the line each gap starts from. + let at_ends = cuts.iter().enumerate().flat_map(|(i, p)| ends(&p.sp).into_iter().map(move |e| (Rect::from_points(e, e), (i, e)))); + let by_end = Cells::new(at_ends.map(|(r, (i, e))| (r, (i, e.x.to_bits(), e.y.to_bits()))).collect(), 0.0, 4096.0); + for g in &gaps { + let of = by_end + .near(g[0], 1e-6) + .into_iter() + .find(|&(_, x, y)| Point::new(f64::from_bits(x), f64::from_bits(y)).distance(g[0]) <= 1e-6) + .and_then(|(i, _, _)| cuts.get(i)) + .map(|p| key(p)); + issues.push(Issue::new(IssueCode::Gap, of.into_iter().collect(), Some(g[0]))); + } + } + let gaps: Vec<[Point; 2]> = gaps.into_iter().chain(joined).collect(); + let gap_shape = shape_of_gaps(&gaps); + let Some(material) = Material::new(&cuts, &gaps, cut_shapes.into_iter().chain(gap_shape.clone()).collect()) else { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return (vec![], sorted(issues)); + }; + if material.blanks.is_empty() { + issues.push(Issue::new(IssueCode::Open, cuts.iter().map(|p| key(p)).collect(), None)); + return (vec![], sorted(issues)); + } + let all: Vec = pieces.iter().map(|p| shape(p.sp.clone())).chain(gap_shape).collect(); + let Some(full) = adjacency(&all, DEFAULT_PRECISION) else { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return (vec![], sorted(issues)); + }; + let cut_lines: Vec = cuts.iter().map(|p| p.line).collect(); + let ctx = Context { lines, pieces: &pieces, cut_lines: &cut_lines, material: &material, full: &full, tolerance }; + let built = ctx.build(&mut issues); + (built, sorted(issues)) +} + +fn sorted(mut issues: Vec) -> Vec { + issues.sort_by_key(|i| i.code); + issues +} + +/// A subpath with two anchors or more, every coordinate finite. +fn usable(sp: &SubPath) -> bool { + sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()) +} + +fn shape(sp: SubPath) -> Shape { + Shape::new(PathData::single(sp), FillRule::NonZero, 0) +} + +/// The lines across `gaps`, as one input. +fn shape_of_gaps(gaps: &[[Point; 2]]) -> Option { + (!gaps.is_empty()).then(|| Shape::new(PathData::new(gaps.iter().map(|g| SubPath::polyline(g, false)).collect()), FillRule::NonZero, 0)) +} + +/// The two ends of an open subpath; none for a closed one or one that ends where it starts. +fn ends(sp: &SubPath) -> Vec { + match (sp.anchors.first(), sp.anchors.last()) { + (Some(a), Some(b)) if !sp.closed && a.p.distance(b.p) > 1e-6 => vec![a.p, b.p], + _ => vec![], + } +} + +/// Whether `sp` encloses an area: closed, or open with its ends together. +fn is_loop(sp: &SubPath) -> bool { + ends(sp).is_empty() && sp.anchors.len() >= 2 +} + +/// Most grid cells one item is filed under by [`Cells`]; a larger one is tried for every point. +const SPAN: usize = 1024; + +/// The farthest cell from the grid's origin, on each axis, that [`Cells`] numbers a point in. +const CELL_LIMIT: f64 = 1_048_576.0; + +/// Most (cell, item) entries [`Cells`] holds in all; the items past it are tried for every point, as +/// large ones are. +const CELL_ENTRIES: usize = 1 << 21; + +/// Items (segments, faces, ends) by the cells of a square grid that their bounds cover, so that +/// finding the items near a point tests only those in its cells. +struct Cells { + origin: Point, + cell: f64, + cells: HashMap<(i64, i64), Vec>, + /// Items whose bounds cover more than [`SPAN`] cells, near every point. + wide: Vec, +} + +impl Cells { + /// `items` by their bounds, in cells `cell` wide or `1/divisions` of all the bounds where that is + /// wider. + fn new(items: Vec<(Rect, T)>, cell: f64, divisions: f64) -> Self { + let bounds = items.iter().map(|(b, _)| *b).filter(Rect::is_finite).reduce(|a, b| a.union(b)).unwrap_or_default(); + let cell = cell.max(bounds.width().max(bounds.height()) / divisions); + let cell = if cell.is_finite() && cell > 0.0 { cell } else { 1.0 }; + let mut grid = Cells { origin: bounds.origin(), cell, cells: HashMap::new(), wide: vec![] }; + let mut entries = 0usize; + for (b, item) in items { + let ((x0, y0), (x1, y1)) = (grid.cell_of(Point::new(b.x0, b.y0)), grid.cell_of(Point::new(b.x1, b.y1))); + let span = usize::try_from((x1 - x0 + 1).saturating_mul(y1 - y0 + 1)).unwrap_or(usize::MAX); + if span > SPAN || entries.saturating_add(span) > CELL_ENTRIES { + grid.wide.push(item); + continue; + } + entries += span; + for x in x0..=x1 { + for y in y0..=y1 { + grid.cells.entry((x, y)).or_default().push(item); + } + } + } + grid + } + + fn cell_of(&self, p: Point) -> (i64, i64) { + let at = |v: f64, o: f64| ((v - o) / self.cell).floor().clamp(-CELL_LIMIT, CELL_LIMIT) as i64; + (at(p.x, self.origin.x), at(p.y, self.origin.y)) + } + + /// The items whose bounds come within `r` of `p` (and some farther ones), each once. When `r` + /// spans more cells than hold items, the cells that hold items are read instead. + fn near(&self, p: Point, r: f64) -> Vec { + let mut out = self.wide.clone(); + let ((x0, y0), (x1, y1)) = (self.cell_of(Point::new(p.x - r, p.y - r)), self.cell_of(Point::new(p.x + r, p.y + r))); + let span = (x1 - x0 + 1).saturating_mul(y1 - y0 + 1); + if usize::try_from(span).map_or(true, |n| n > self.cells.len()) { + for (&(x, y), items) in &self.cells { + if (x0..=x1).contains(&x) && (y0..=y1).contains(&y) { + out.extend(items); + } + } + } else { + for x in x0..=x1 { + for y in y0..=y1 { + out.extend(self.cells.get(&(x, y)).into_iter().flatten()); + } + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The ends of `cuts` that lie more than `tolerance` from every other fold line among `cuts` and +/// `folds`, as (index into `cuts`, end). A line's own points count when they are more than +/// `tolerance` from the end along the line, so a cut line that comes back to its own end meets it. +fn loose_ends(cuts: &[&Piece], folds: &[&Piece], tolerance: f64) -> Vec<(usize, Point)> { + let segs: Vec> = cuts.iter().chain(folds).map(|p| PathData::single(p.sp.clone()).to_bezpath().segments().collect()).collect(); + let boxes = segs.iter().enumerate().flat_map(|(j, ss)| ss.iter().enumerate().map(move |(k, s)| (s.bounding_box(), (j, k)))); + // The cells are as wide as the tolerance, or 1/4096 of the lines where that is wider. + let grid = Cells::new(boxes.collect(), tolerance, 4096.0); + let mut out = vec![]; + for (i, p) in cuts.iter().enumerate() { + let own = segs.get(i).map(Vec::as_slice).unwrap_or_default(); + // How far along the line each of its segments starts, and the line's length. + let starts: Vec = own.iter().scan(0.0, |at, s| Some(std::mem::replace(at, *at + s.arclen(1e-3)))).collect(); + let total = own.last().zip(starts.last()).map_or(0.0, |(s, at)| at + s.arclen(1e-3)); + for (k, e) in ends(&p.sp).into_iter().enumerate() { + let near = grid.near(e, tolerance).into_iter().any(|(j, s)| { + let Some(seg) = segs.get(j).and_then(|ss| ss.get(s)) else { return false }; + let b = seg.bounding_box(); + if e.x < b.x0 - tolerance || e.x > b.x1 + tolerance || e.y < b.y0 - tolerance || e.y > b.y1 + tolerance { + return false; + } + let hit = seg.nearest(e, 1e-9); + if hit.distance_sq.sqrt() > tolerance { + return false; + } + if j != i { + return true; + } + let along = starts.get(s).copied().unwrap_or(0.0) + seg.subsegment(0.0..hit.t).arclen(1e-3); + (if k == 0 { along } else { total - along }) > tolerance + }); + if !near { + out.push((i, e)); + } + } + } + out +} + +/// A point inside `path`, or the middle of its bounds for one too thin to find one in. +fn point_in(path: &PathData) -> Option { + interior_point(path).or_else(|| path.bounds().map(|b| b.center())) +} + +fn contains(bp: &BezPath, p: Point) -> bool { + bp.winding(p) != 0 +} + +/// The loops that open Cut pieces and the lines across `gaps` make end to end: each chain of them +/// whose every end meets exactly one end of another piece of the chain (within 1e-6), as (index +/// into `cuts` of its first Cut piece, closed path). Pieces that lie on no cycle are left out first; +/// ends where three of the remaining pieces or more meet join nothing. +fn chains(cuts: &[&Piece], gaps: &[[Point; 2]]) -> Vec<(usize, BezPath)> { + const NEAR: f64 = 1e-6; + // Cell numbers stay far from the ends of `i64`, so a neighbor's number does not overflow. + let cell = |v: f64| (v / NEAR).round().clamp(-1e15, 1e15) as i64; + let key = |p: Point| (cell(p.x), cell(p.y)); + // The ends by node: ends within `NEAR` of a node's first end share it. + let mut nodes: HashMap<(i64, i64), usize> = HashMap::new(); + let mut firsts: Vec = vec![]; + let mut node_of = |p: Point| { + let (kx, ky) = key(p); + for dx in -1..=1 { + for dy in -1..=1 { + if let Some(&n) = nodes.get(&(kx.saturating_add(dx), ky.saturating_add(dy))) + && firsts.get(n).is_some_and(|q| q.distance(p) <= NEAR) + { + return n; + } + } + } + firsts.push(p); + nodes.insert((kx, ky), firsts.len() - 1); + firsts.len() - 1 + }; + // The open Cut pieces (with their index into `cuts`) and the gap lines, each with its segments. + let pieces = cuts + .iter() + .enumerate() + .filter(|(_, p)| ends(&p.sp).len() == 2) + .map(|(i, p)| (Some(i), PathData::single(p.sp.clone()).to_bezpath().segments().collect())); + let lines = gaps.iter().map(|g| (None, vec![PathSeg::Line(Line::new(g[0], g[1]))])); + let items: Vec<(Option, Vec)> = pieces.chain(lines).collect(); + // (index into `items`, start node, end node) of each, and the pieces at each node. + let open: Vec<(usize, usize, usize)> = + items.iter().enumerate().filter_map(|(k, (_, segs))| Some((k, node_of(segs.first()?.start()), node_of(segs.last()?.end())))).collect(); + let mut at: HashMap> = HashMap::new(); + for (k, &(_, a, b)) in open.iter().enumerate() { + at.entry(a).or_default().push(k); + at.entry(b).or_default().push(k); + } + // A piece that lies on no cycle of pieces (a slit, a line from another one's side, a cut that + // joins two loops) is no part of a loop: such pieces are dropped, so that a slit at a loop's + // corner does not stop the loop. + let live: Vec = bridges(firsts.len(), &open).into_iter().map(|b| !b).collect(); + for ks in at.values_mut() { + ks.retain(|&k| live.get(k) == Some(&true)); + } + let mut used: Vec = live.iter().map(|l| !l).collect(); + let mut out = vec![]; + for start in 0..open.len() { + if used.get(start) != Some(&false) { + continue; + } + // Walk from the start piece's first end until the chain comes back to it, or stops. + let Some(&(_, first_node, _)) = open.get(start) else { continue }; + let (mut k, mut from, mut walk) = (start, first_node, vec![]); + let closed = loop { + let Some(&(_, a, b)) = open.get(k) else { break false }; + if used.get(k) != Some(&false) { + break false; + } + if let Some(u) = used.get_mut(k) { + *u = true; + } + let forward = a == from; + walk.push((k, forward)); + let to = if forward { b } else { a }; + if to == first_node { + break true; + } + let next = at.get(&to).filter(|ks| ks.len() == 2).and_then(|ks| ks.iter().copied().find(|&j| j != k)); + match next { + Some(j) => (k, from) = (j, to), + None => break false, + } + }; + if !closed || at.get(&first_node).is_none_or(|ks| ks.len() != 2) { + continue; + } + let mut bp = BezPath::new(); + let mut first_cut = None; + for (n, &(k, forward)) in walk.iter().enumerate() { + let Some((i, segs)) = open.get(k).and_then(|&(j, _, _)| items.get(j)) else { continue }; + first_cut = first_cut.or(*i); + let segs: Vec = if forward { segs.clone() } else { segs.iter().rev().map(|s| s.reverse()).collect() }; + for (m, s) in segs.iter().enumerate() { + if n == 0 && m == 0 { + bp.move_to(s.start()); + } + match *s { + PathSeg::Line(l) => bp.line_to(l.p1), + PathSeg::Quad(q) => bp.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => bp.curve_to(c.p1, c.p2, c.p3), + } + } + } + bp.close_path(); + if let Some(i) = first_cut { + out.push((i, bp)); + } + } + out +} + +/// Which of `edges` ((id, end node, end node), nodes below `nodes`) lie on no cycle: the bridges of +/// the graph, found depth first without recursion. +fn bridges(nodes: usize, edges: &[(usize, usize, usize)]) -> Vec { + let mut adj: Vec> = vec![vec![]; nodes]; + for (k, &(_, a, b)) in edges.iter().enumerate() { + adj.get_mut(a).into_iter().for_each(|l| l.push((b, k))); + adj.get_mut(b).into_iter().for_each(|l| l.push((a, k))); + } + let mut bridge = vec![false; edges.len()]; + let (mut disc, mut low) = (vec![usize::MAX; nodes], vec![0usize; nodes]); + let mut timer = 0usize; + for s in 0..nodes { + if disc.get(s) != Some(&usize::MAX) { + continue; + } + let mut stamp = |v: usize, disc: &mut Vec, low: &mut Vec| { + disc.get_mut(v).into_iter().for_each(|d| *d = timer); + low.get_mut(v).into_iter().for_each(|l| *l = timer); + timer += 1; + }; + stamp(s, &mut disc, &mut low); + // (node, the edge it was reached by, the next of its edges to follow) + let mut stack: Vec<(usize, Option, usize)> = vec![(s, None, 0)]; + while let Some(&(v, by, i)) = stack.last() { + if let Some(&(w, e)) = adj.get(v).and_then(|l| l.get(i)) { + if let Some(top) = stack.last_mut() { + top.2 += 1; + } + if Some(e) == by { + continue; + } + match disc.get(w).copied() { + Some(usize::MAX) => { + stamp(w, &mut disc, &mut low); + stack.push((w, Some(e), 0)); + } + Some(d) => { + if let Some(l) = low.get_mut(v) { + *l = (*l).min(d); + } + } + None => {} + } + } else { + stack.pop(); + let low_v = low.get(v).copied().unwrap_or(0); + if let Some(&(u, _, _)) = stack.last() { + if let Some(l) = low.get_mut(u) { + *l = (*l).min(low_v); + } + if disc.get(u).is_some_and(|&d| low_v > d) + && let Some(b) = by.and_then(|e| bridge.get_mut(e)) + { + *b = true; + } + } + } + } + } + bridge +} + +/// The material the Cut lines leave: the faces of their planar map, which are material, which are +/// holes, and the blanks (connected pieces with material). +struct Material { + map: Adjacency, + /// For each face of `map`: a point inside it, whether it is material, whether it is a hole. + points: Vec>, + material: Vec, + hole: Vec, + /// The pieces of `map` that are blanks, in order, and each one's outline. + blanks: Vec, + bounds: Vec, + /// For each piece of `map`, the blank (index into `blanks`) it is part of: its own, or for a + /// piece that lies in a blank's material (a window), that blank. + owner: Vec>, + /// The faces of each piece of `map`, and its edges. + faces_by_piece: Vec>, + edges_by_piece: Vec>, + /// Each face's outer boundary and its whole path (with its holes), and the faces by where they + /// are. + outer: Vec, + whole: Vec, + face_cells: Cells, + /// The blanks by where their outlines are (built once every piece is classified). + bound_cells: Cells, +} + +/// A loop among the Cut lines: its path and its area. +type Loop = (BezPath, f64); + +impl Material { + /// The material of `cuts` with the lines across `gaps`, mapped as `shapes` (the cuts, then the + /// gap lines). + fn new(cuts: &[&Piece], gaps: &[[Point; 2]], shapes: Vec) -> Option { + let map = adjacency(&shapes, DEFAULT_PRECISION)?; + let points: Vec> = map.faces.iter().map(|f| point_in(&f.path)).collect(); + let pieces = map.faces.iter().map(|f| f.piece + 1).chain(map.edges.iter().map(|e| e.piece + 1)).max().unwrap_or(0); + let mut faces_by_piece = vec![vec![]; pieces]; + for (f, face) in map.faces.iter().enumerate() { + if let Some(list) = faces_by_piece.get_mut(face.piece) { + list.push(f); + } + } + // The piece each input is part of, from the edges it lies on. + let mut piece_of_input: Vec> = vec![None; shapes.len()]; + let mut edges_by_piece = vec![vec![]; pieces]; + for (e, edge) in map.edges.iter().enumerate() { + if let Some(list) = edges_by_piece.get_mut(edge.piece) { + list.push(e); + } + for &s in &edge.sources { + if let Some(slot) = piece_of_input.get_mut(s).filter(|p| p.is_none()) { + *slot = Some(edge.piece); + } + } + } + let mut loops: Vec> = vec![vec![]; pieces]; + for (i, p) in cuts.iter().enumerate().filter(|(_, p)| is_loop(&p.sp)) { + let Some(list) = piece_of_input.get(i).copied().flatten().and_then(|piece| loops.get_mut(piece)) else { continue }; + let bp = PathData::single(SubPath::of(p.sp.anchors.clone(), true)).to_bezpath(); + let area = bp.area().abs(); + list.push((bp, area)); + } + // Loops drawn as open pieces end to end, such as a slot of four lines. + for (i, bp) in chains(cuts, gaps) { + let Some(list) = piece_of_input.get(i).copied().flatten().and_then(|piece| loops.get_mut(piece)) else { continue }; + let area = bp.area().abs(); + list.push((bp, area)); + } + // Each piece's outer boundary and a point of it. + let mut outlines: Vec)>> = vec![None; pieces]; + for o in &map.outlines { + if let Some(slot) = outlines.get_mut(o.piece).filter(|s| s.is_none()) { + *slot = Some((o.path.to_bezpath(), o.path.subpaths.first().and_then(|sp| sp.anchors.first()).map(|a| a.p))); + } + } + // Outer pieces first: the face a piece lies in belongs to a piece with a larger outline. + let mut order: Vec<(usize, f64, Option)> = + outlines.iter().enumerate().map(|(p, o)| (p, o.as_ref().map_or(0.0, |o| o.0.area().abs()), o.as_ref().and_then(|o| o.1))).collect(); + order.sort_by(|a, b| b.1.total_cmp(&a.1)); + let outer: Vec = + map.faces.iter().map(|f| f.path.subpaths.first().map(|sp| PathData::single(sp.clone()).to_bezpath()).unwrap_or_default()).collect(); + let whole: Vec = map.faces.iter().map(|f| f.path.to_bezpath()).collect(); + let face_cells = Cells::new(outer.iter().enumerate().map(|(f, bp)| (bp.bounding_box(), f)).collect(), 0.0, 256.0); + let faces = map.faces.len(); + let mut m = Material { + map, + points, + material: vec![false; faces], + hole: vec![false; faces], + blanks: vec![], + bounds: vec![], + owner: vec![None; pieces], + faces_by_piece, + edges_by_piece, + outer, + whole, + face_cells, + bound_cells: Cells::new(vec![], 0.0, 256.0), + }; + for (piece, _, first) in order { + match first.and_then(|q| m.around(piece, q)) { + // A piece in a blank's material is a hole in it, a window. + Some(f) if m.material.get(f) == Some(&true) => { + let owner = m.map.faces.get(f).and_then(|x| m.owner.get(x.piece)).copied().flatten(); + for g in m.faces_by_piece.get(piece).cloned().unwrap_or_default() { + let usable = m.points.get(g).copied().flatten().is_some(); + if let Some(h) = m.hole.get_mut(g) { + *h = usable; + } + } + if let Some(o) = m.owner.get_mut(piece) { + *o = owner; + } + } + _ => { + let own = loops.get(piece).map(Vec::as_slice).unwrap_or_default(); + let fallback = outlines.get(piece).cloned().flatten().map(|o| o.0); + m.classify(piece, own, fallback); + } + } + } + m.bound_cells = Cells::new(m.bounds.iter().enumerate().map(|(b, bp)| (bp.bounding_box(), b)).collect(), 0.0, 256.0); + Some(m) + } + + /// The face of another piece than `piece` whose outer boundary holds `q`, a point of its + /// outline, the one with the smallest outer boundary when several do. The boundaries are + /// compared, not the faces' own areas, which leave out the holes in them. + fn around(&self, piece: usize, q: Point) -> Option { + let outer_area = |f: usize| self.outer.get(f).map_or(f64::INFINITY, |bp| bp.area().abs()); + self.face_cells + .near(q, 0.0) + .into_iter() + .filter(|&f| self.map.faces.get(f).is_some_and(|x| x.piece != piece)) + .filter(|&f| self.outer.get(f).is_some_and(|bp| contains(bp, q))) + .min_by(|&a, &b| outer_area(a).total_cmp(&outer_area(b))) + } + + fn area(&self, f: usize) -> f64 { + self.map.faces.get(f).map_or(f64::INFINITY, |x| x.area) + } + + /// Which faces of `piece` are material and which are holes, by its own loops `loops`; with + /// material, the piece is a blank. A loop that holds the same faces as a larger one (a loop + /// drawn twice) counts once. Its outlines are its largest loop and each smaller loop that shares + /// no face with a larger outline (two outlines joined by a cut line); its other loops cut + /// material out. When the outlines and the loops that cut out do not cover every face (an + /// outline drawn as open lines), every loop cuts out and the blank is bounded by `fallback`, its + /// outer boundary. + fn classify(&mut self, piece: usize, loops: &[Loop], fallback: Option) { + let faces = self.faces_by_piece.get(piece).cloned().unwrap_or_default(); + let mut by_area: Vec<&Loop> = loops.iter().collect(); + by_area.sort_by(|a, b| b.1.total_cmp(&a.1)); + let points = &self.points; + let unusable = |f: usize| points.get(f).copied().flatten().is_none(); + // The piece's faces by their points, so that each loop tests only the faces near it. + let at: Vec<(Rect, usize)> = + faces.iter().enumerate().filter_map(|(k, &f)| points.get(f).copied().flatten().map(|p| (Rect::from_points(p, p), k))).collect(); + let extent = at.iter().map(|(r, _)| *r).reduce(|a, b| a.union(b)); + let near = Cells::new(at, 0.0, 256.0); + // Each loop with the faces of the piece it holds (positions in `faces`, ascending); loops + // that hold none, and loops that hold the same faces as a larger one, are left out. + let mut seen: HashSet> = HashSet::new(); + let mut own: Vec<(&BezPath, Vec)> = vec![]; + for l in by_area { + let b = l.0.bounding_box().inflate(1e-6, 1e-6); + // Only the part of the loop's bounds where faces are is looked up, a few hundred cells + // across at most. + let Some(q) = extent.map(|e| b.intersect(e)).filter(|q| q.width() >= 0.0 && q.height() >= 0.0) else { continue }; + let holds: Vec = near + .near(q.center(), q.width().max(q.height()) / 2.0) + .into_iter() + .filter(|&k| faces.get(k).and_then(|&f| points.get(f).copied().flatten()).is_some_and(|p| b.contains(p) && contains(&l.0, p))) + .collect(); + if !holds.is_empty() && seen.insert(holds.clone()) { + own.push((&l.0, holds)); + } + } + // Outlines go largest first; a loop holding a face an outline holds cuts out instead. + let (mut outlines, mut others): (Vec, Vec) = (vec![], vec![]); + let mut in_an_outline = vec![false; faces.len()]; + let mut held = vec![false; faces.len()]; + for (i, (_, holds)) in own.iter().enumerate() { + holds.iter().for_each(|&k| held.get_mut(k).into_iter().for_each(|h| *h = true)); + if holds.iter().any(|&k| in_an_outline.get(k) == Some(&true)) { + others.push(i); + } else { + holds.iter().for_each(|&k| in_an_outline.get_mut(k).into_iter().for_each(|h| *h = true)); + outlines.push(i); + } + } + let covered = faces.iter().enumerate().all(|(k, &f)| held.get(k) == Some(&true) || unusable(f)); + if !covered { + outlines.clear(); + others = (0..own.len()).collect(); + } + let mut cut = vec![false; faces.len()]; + for (_, holds) in others.iter().filter_map(|&i| own.get(i)) { + holds.iter().for_each(|&k| cut.get_mut(k).into_iter().for_each(|c| *c = true)); + } + let mut any = false; + for (k, &f) in faces.iter().enumerate() { + let in_outline = outlines.is_empty() || in_an_outline.get(k) == Some(&true); + let cut_out = cut.get(k) == Some(&true); + let material = !unusable(f) && in_outline && !cut_out; + any |= material; + if let Some(m) = self.material.get_mut(f) { + *m = material; + } + if let Some(h) = self.hole.get_mut(f) { + *h = !unusable(f) && in_outline && cut_out; + } + } + if any { + let bound = if outlines.is_empty() { + fallback + } else { + let mut all = BezPath::new(); + outlines.iter().filter_map(|&o| own.get(o)).for_each(|o| all.extend(o.0.elements().iter().copied())); + Some(all) + }; + if let Some(o) = self.owner.get_mut(piece) { + *o = Some(self.blanks.len()); + } + self.blanks.push(piece); + self.bounds.push(bound.unwrap_or_default()); + } + } + + /// The face of the Cut lines' map that holds `p`, the smallest when several do. + fn face_at(&self, p: Point) -> Option { + self.face_cells + .near(p, 0.0) + .into_iter() + .filter(|&f| self.whole.get(f).is_some_and(|bp| contains(bp, p))) + .min_by(|&a, &b| self.area(a).total_cmp(&self.area(b))) + } + + /// Whether `p` lies inside the outline of a blank. + fn in_a_blank(&self, p: Point) -> bool { + self.bound_cells.near(p, 0.0).into_iter().any(|b| self.bounds.get(b).is_some_and(|bp| contains(bp, p))) + } + + /// The blank (index into `blanks`) face `f` is part of. + fn blank_of(&self, f: usize) -> Option { + let piece = self.map.faces.get(f)?.piece; + self.owner.get(piece).copied().flatten() + } +} + +/// What a face of the full map is. +#[derive(Clone, Copy, PartialEq)] +enum Place { + /// Panel `panel` of blank `blank`. + Panel { + blank: usize, + panel: usize, + }, + /// A hole of a blank. + Hole, + Outside, +} + +/// A piece of crease between two panels of one blank. +struct HingePiece { + path: PathData, + lines: Vec, +} + +struct Context<'a> { + lines: &'a [FoldLine], + pieces: &'a [Piece], + /// The fold line of each input of the Cut lines' map, in order; the gap lines come after them. + cut_lines: &'a [usize], + material: &'a Material, + full: &'a Adjacency, + tolerance: f64, +} + +impl Context<'_> { + /// The fold line that input `i` of the full map is part of; `None` for the gap lines. + fn line_of(&self, i: usize) -> Option { + self.pieces.get(i).map(|p| p.line) + } + + fn kind_of(&self, i: usize) -> LineKind { + self.line_of(i).and_then(|l| self.lines.get(l)).map_or(LineKind::Cut, |l| l.kind) + } + + fn key(&self, line: usize) -> u64 { + self.lines.get(line).map_or(0, |l| l.key) + } + + fn keys(&self, lines: impl IntoIterator) -> Vec { + lines.into_iter().map(|l| self.key(l)).collect() + } + + fn build(&self, issues: &mut Vec) -> Vec { + let mut blanks: Vec = vec![Blank::default(); self.material.blanks.len()]; + // Hole faces that share an edge are one hole (a cut line across a window splits it in two + // faces): they are grouped, and each group's faces are united. + let m = self.material; + let is_hole = |f: usize| m.hole.get(f) == Some(&true); + let mut group: Vec = (0..m.map.faces.len()).collect(); + let root = |group: &mut Vec, mut f: usize| { + while let Some(&g) = group.get(f) { + if g == f { + break; + } + let up = group.get(g).copied().unwrap_or(g); + if let Some(slot) = group.get_mut(f) { + *slot = up; + } + f = up; + } + f + }; + for e in &m.map.edges { + if let (Some(a), Some(b)) = (e.left, e.right) + && a != b + && is_hole(a) + && is_hole(b) + { + let (ra, rb) = (root(&mut group, a), root(&mut group, b)); + if let Some(slot) = group.get_mut(ra) { + *slot = rb; + } + } + } + let mut by_group: HashMap> = HashMap::new(); + for f in (0..m.map.faces.len()).filter(|&f| is_hole(f)) { + by_group.entry(root(&mut group, f)).or_default().push(f); + } + let mut groups: Vec> = by_group.into_values().collect(); + groups.sort_unstable(); + for faces in groups { + let Some(b) = faces.first().and_then(|&f| m.blank_of(f)).and_then(|b| blanks.get_mut(b)) else { continue }; + let paths: Vec<&PathData> = faces.iter().filter_map(|&f| m.map.faces.get(f).map(|x| &x.path)).collect(); + let hole = match paths.as_slice() { + [one] => (*one).clone(), + _ => unite_all(&paths.iter().map(|p| (*p, FillRule::NonZero)).collect::>()), + }; + b.holes.push(hole); + } + let places = self.places(&mut blanks); + if blanks.iter().any(|b| b.panels.len() > MAX_PANELS) { + issues.push(Issue::new(IssueCode::TooComplex, vec![], None)); + return vec![]; + } + let pieces = self.edges(&places, issues); + let hinged = self.hinges(&mut blanks, pieces, issues); + self.creases(&places, &hinged, issues); + self.slivers(issues); + self.nested(issues); + self.loose_panels(&blanks, &places, issues); + blanks + } + + /// What each face of the full map is, adding the panels to `blanks`. + fn places(&self, blanks: &mut [Blank]) -> Vec { + self.full + .faces + .iter() + .map(|face| { + let Some(c) = point_in(&face.path).and_then(|p| self.material.face_at(p)) else { return Place::Outside }; + let Some(blank) = self.material.blank_of(c) else { return Place::Outside }; + if self.material.material.get(c) == Some(&true) { + let Some(b) = blanks.get_mut(blank) else { return Place::Outside }; + b.panels.push(Panel { outline: face.path.clone(), area: face.area }); + Place::Panel { blank, panel: b.panels.len() - 1 } + } else if self.material.hole.get(c) == Some(&true) { + Place::Hole + } else { + Place::Outside + } + }) + .collect() + } + + fn place(&self, places: &[Place], f: Option) -> Place { + f.and_then(|f| places.get(f)).copied().unwrap_or(Place::Outside) + } + + /// Overlaps, dangling creases and creases in holes, from the full map's edges → the hinge + /// pieces, by (blank, panel, panel). + fn edges(&self, places: &[Place], issues: &mut Vec) -> Vec<((usize, usize, usize), HingePiece)> { + let mut pieces = vec![]; + let mut seen: HashSet<(IssueCode, Vec)> = HashSet::new(); + let mut report = |issues: &mut Vec, code: IssueCode, keys: Vec| { + let issue = Issue::new(code, keys, None); + if seen.insert((code, issue.keys.clone())) { + issues.push(issue); + } + }; + for e in &self.full.edges { + let cut = e.sources.iter().any(|&s| self.kind_of(s) == LineKind::Cut); + let creases: Vec = e.sources.iter().filter(|&&s| self.kind_of(s) != LineKind::Cut).filter_map(|&s| self.line_of(s)).collect(); + let mut by_line: Vec = e.sources.iter().filter_map(|&s| self.line_of(s)).collect(); + by_line.sort_unstable(); + by_line.dedup(); + if cut && !creases.is_empty() { + report(issues, IssueCode::CutOverCrease, self.keys(by_line.iter().copied())); + continue; + } + // Two subpaths of one kind on the same edge, from two lines or from one line's own + // subpaths (a compound path); the gap lines are left out. + let drawn: Vec = e.sources.iter().copied().filter(|&s| self.line_of(s).is_some()).collect(); + let mut duplicates: Vec = drawn + .iter() + .filter(|&&s| drawn.iter().any(|&o| o != s && self.kind_of(o) == self.kind_of(s))) + .filter_map(|&s| self.line_of(s)) + .collect(); + duplicates.sort_unstable(); + duplicates.dedup(); + if !duplicates.is_empty() { + report(issues, IssueCode::Duplicate, self.keys(duplicates)); + } + if creases.is_empty() { + continue; + } + match (self.place(places, e.left), self.place(places, e.right)) { + (Place::Panel { blank, panel: a }, Place::Panel { blank: other, panel: b }) if blank == other && a != b => { + pieces.push(((blank, a.min(b), a.max(b)), HingePiece { path: e.path.clone(), lines: creases })); + } + (Place::Panel { .. }, Place::Panel { .. }) if e.left == e.right => { + report(issues, IssueCode::DanglingCrease, self.keys(creases)); + } + (Place::Hole, _) | (_, Place::Hole) => report(issues, IssueCode::Ambiguous, self.keys(creases)), + _ => {} + } + } + pieces + } + + /// The hinges `pieces` make, added to `blanks` → the lines with a hinge. + fn hinges(&self, blanks: &mut [Blank], mut pieces: Vec<((usize, usize, usize), HingePiece)>, issues: &mut Vec) -> Vec { + pieces.sort_by_key(|p| p.0); + let mut hinged = vec![]; + let mut start = 0; + while start < pieces.len() { + let pair = pieces.get(start).map(|p| p.0); + let end = pieces.iter().skip(start).position(|p| Some(p.0) != pair).map_or(pieces.len(), |n| start + n); + let group: Vec<&HingePiece> = pieces.get(start..end).unwrap_or_default().iter().map(|p| &p.1).collect(); + start = end; + let Some((blank, a, b)) = pair else { break }; + let lines: Vec = group.iter().flat_map(|p| p.lines.iter().copied()).collect(); + match self.hinge(&group, a, b) { + Some(h) => { + if !h.straight { + issues.push(Issue::new(IssueCode::NotStraight, h.keys.clone(), None)); + } + hinged.extend(lines); + if let Some(bl) = blanks.get_mut(blank) { + bl.hinges.push(h); + } + } + None => issues.push(Issue::new(IssueCode::NoSplit, self.keys(lines.iter().copied()), None)), + } + } + hinged.sort_unstable(); + hinged.dedup(); + hinged + } + + /// The hinge between panels `a` and `b` made of `group`, along its longest piece; `None` when + /// its pieces are shorter than the tolerance in all, or span less than it. + fn hinge(&self, group: &[&HingePiece], a: usize, b: usize) -> Option { + let chord = |p: &HingePiece| { + let sp = p.path.subpaths.first()?; + Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) + }; + let longest = group.iter().filter_map(|p| Some((*p, chord(p)?))).max_by(|x, y| { + let (lx, ly) = (x.1.0.distance(x.1.1), y.1.0.distance(y.1.1)); + lx.total_cmp(&ly) + })?; + let (p0, p1) = longest.1; + let len = p0.distance(p1); + // The longest piece only sets the direction; the length check is on the whole hinge below. + if len.is_nan() || len <= 1e-9 { + return None; + } + let d = (p1 - p0) / len; + let off = |p: Point| ((p - p0).cross(d)).abs(); + let mut straight = true; + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + for p in group { + for seg in p.path.to_bezpath().segments() { + for t in [0.0, 0.25, 0.5, 0.75, 1.0] { + let q = seg.eval(t); + straight &= off(q) <= self.tolerance; + let s = (q - p0).dot(d); + lo = lo.min(s); + hi = hi.max(s); + } + } + } + // The pieces' own length, not the span from the first to the last, which takes in the gaps + // between pieces that lie apart. + let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { + return None; + } + let mut lines: Vec = group.iter().flat_map(|p| p.lines.iter().copied()).collect(); + lines.sort_unstable(); + lines.dedup(); + let angle = longest + .0 + .lines + .first() + .and_then(|&l| self.lines.get(l)) + .map(|l| l.angle.filter(|a| a.is_finite()).unwrap_or_else(|| l.kind.default_angle())) + .unwrap_or(90.0); + let mut keys = self.keys(lines); + keys.sort_unstable(); + keys.dedup(); + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, angle, keys, straight }) + } + + /// Creases with no hinge: outside every blank, or dividing no two panels. + fn creases(&self, places: &[Place], hinged: &[usize], issues: &mut Vec) { + let named: HashSet = + issues.iter().filter(|i| i.code != IssueCode::LooseEnd && i.code != IssueCode::Gap).flat_map(|i| i.keys.iter().copied()).collect(); + // Whether each line is drawn (has a usable subpath), and whether one of its edges touches a + // panel. + let mut drawn = vec![false; self.lines.len()]; + for p in self.pieces { + if let Some(d) = drawn.get_mut(p.line) { + *d = true; + } + } + let mut on_panel = vec![false; self.lines.len()]; + for e in &self.full.edges { + if [e.left, e.right].into_iter().any(|f| matches!(self.place(places, f), Place::Panel { .. })) { + for line in e.sources.iter().filter_map(|&s| self.line_of(s)) { + if let Some(on) = on_panel.get_mut(line) { + *on = true; + } + } + } + } + for (line, l) in self.lines.iter().enumerate() { + if l.kind == LineKind::Cut || hinged.binary_search(&line).is_ok() || named.contains(&l.key) || drawn.get(line) != Some(&true) { + continue; + } + let code = if on_panel.get(line) == Some(&true) { IssueCode::NoSplit } else { IssueCode::Outside }; + issues.push(Issue::new(code, vec![l.key], None)); + } + } + + /// Slivers of the full map inside a blank. + fn slivers(&self, issues: &mut Vec) { + for s in &self.full.slivers { + let Some(p) = point_in(s) else { continue }; + if self.material.in_a_blank(p) { + issues.push(Issue::new(IssueCode::Sliver, vec![], Some(p))); + } + } + } + + /// Blanks that lie inside a hole of another blank. + fn nested(&self, issues: &mut Vec) { + let m = self.material; + for (bi, &piece) in m.blanks.iter().enumerate() { + let faces = m.faces_by_piece.get(piece).map(Vec::as_slice).unwrap_or_default(); + let Some(p) = faces.iter().find(|&&f| m.material.get(f) == Some(&true)).and_then(|&f| m.points.get(f).copied().flatten()) else { + continue; + }; + let in_hole = + m.face_cells.near(p, 0.0).into_iter().any(|f| { + m.hole.get(f) == Some(&true) && m.blank_of(f).is_some_and(|b| b != bi) && m.outer.get(f).is_some_and(|bp| contains(bp, p)) + }); + if in_hole { + let edges = m.edges_by_piece.get(piece).map(Vec::as_slice).unwrap_or_default(); + let lines = edges.iter().filter_map(|&e| m.map.edges.get(e)).flat_map(|e| e.sources.iter().filter_map(|&s| self.cut_lines.get(s))); + issues.push(Issue::new(IssueCode::Ambiguous, self.keys(lines.copied()), Some(p))); + } + } + } + + /// Panels joined to their blank's base panel (the largest; on a tie, the one whose inside point is + /// highest on the page, then leftmost) by no chain of hinges. + fn loose_panels(&self, blanks: &[Blank], places: &[Place], issues: &mut Vec) { + // The edges beside each panel, by (blank, panel), gathered once. + let mut beside: HashMap<(usize, usize), Vec> = HashMap::new(); + for (i, e) in self.full.edges.iter().enumerate() { + for f in [e.left, e.right] { + if let Place::Panel { blank, panel } = self.place(places, f) { + let list = beside.entry((blank, panel)).or_default(); + if list.last() != Some(&i) { + list.push(i); + } + } + } + } + for (bi, b) in blanks.iter().enumerate() { + let Some(base) = base_panel(&b.panels) else { continue }; + let mut reached = vec![false; b.panels.len()]; + let mut queue = vec![base]; + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop() { + for h in b.hinges.iter().filter(|h| h.a == p || h.b == p) { + let other = if h.a == p { h.b } else { h.a }; + if let Some(r) = reached.get_mut(other).filter(|r| !**r) { + *r = true; + queue.push(other); + } + } + } + for (pi, panel) in b.panels.iter().enumerate().filter(|(i, _)| reached.get(*i) == Some(&false)) { + let edges = beside.get(&(bi, pi)).map(Vec::as_slice).unwrap_or_default(); + let lines = edges.iter().filter_map(|&e| self.full.edges.get(e)); + let keys = lines.flat_map(|e| e.sources.iter().filter_map(|&s| self.line_of(s))).map(|l| self.key(l)).collect(); + issues.push(Issue::new(IssueCode::LoosePanel, keys, point_in(&panel.outline))); + } + } + } +} + +/// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of +/// the larger tie, and the tie goes to the one whose inside point is highest on the page, then +/// leftmost. +pub fn base_panel(panels: &[Panel]) -> Option { + let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + if !top.is_finite() { + return None; + } + panels + .iter() + .enumerate() + .filter(|(_, p)| top - p.area <= 1e-9 * top.abs()) + .filter_map(|(i, p)| Some((i, point_in(&p.outline)?))) + .min_by(|a, b| a.1.y.total_cmp(&b.1.y).then(a.1.x.total_cmp(&b.1.x))) + .map(|(i, _)| i) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs new file mode 100644 index 0000000000..a3f2c68d37 --- /dev/null +++ b/crates/three-d/src/fold/tests.rs @@ -0,0 +1,740 @@ +use super::*; +use proptest::prelude::*; +use vectorcraft_geom::Rect; + +const TOL: f64 = 0.1; + +fn p(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn poly(points: &[(f64, f64)], closed: bool) -> PathData { + PathData::single(SubPath::polyline(&points.iter().map(|&(x, y)| p(x, y)).collect::>(), closed)) +} + +fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { + FoldLine { path: poly(points, closed), kind, angle: None, key } +} + +fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { + line(LineKind::Cut, points, true, key) +} + +fn crease(a: (f64, f64), b: (f64, f64), key: u64) -> FoldLine { + line(LineKind::Crease, &[a, b], false, key) +} + +fn codes(issues: &[Issue]) -> Vec<&'static str> { + issues.iter().map(|i| i.code.id()).collect() +} + +fn areas(b: &Blank) -> Vec { + let mut a: Vec = b.panels.iter().map(|p| (p.area * 1000.0).round() as i64).collect(); + a.sort_unstable(); + a +} + +/// A tray: a 100 × 60 base with a 30 pt wall on each side, drawn as one closed cross, and the four +/// creases round the base (keys 10 to 13). +fn tray() -> Vec { + vec![ + cut( + &[ + (30.0, 0.0), + (130.0, 0.0), + (130.0, 30.0), + (160.0, 30.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + ], + 1, + ), + crease((30.0, 30.0), (130.0, 30.0), 10), + crease((130.0, 30.0), (130.0, 90.0), 11), + crease((130.0, 90.0), (30.0, 90.0), 12), + crease((30.0, 90.0), (30.0, 30.0), 13), + ] +} + +/// The outline of a slotted box in the style of FEFCO 0201 (glue flap, four body panels 100, 60, +/// 100 and 60 wide and 80 high, 30 pt flaps top and bottom) with its 4 pt slots drawn as notches. +const NOTCHED: [(f64, f64); 30] = [ + (20.0, 0.0), + (118.0, 0.0), + (118.0, 30.0), + (122.0, 30.0), + (122.0, 0.0), + (178.0, 0.0), + (178.0, 30.0), + (182.0, 30.0), + (182.0, 0.0), + (278.0, 0.0), + (278.0, 30.0), + (282.0, 30.0), + (282.0, 0.0), + (340.0, 0.0), + (340.0, 140.0), + (282.0, 140.0), + (282.0, 110.0), + (278.0, 110.0), + (278.0, 140.0), + (182.0, 140.0), + (182.0, 110.0), + (178.0, 110.0), + (178.0, 140.0), + (122.0, 140.0), + (122.0, 110.0), + (118.0, 110.0), + (118.0, 140.0), + (20.0, 140.0), + (20.0, 110.0), + (0.0, 110.0), +]; + +/// The slotted box's creases: the glue flap's and the body panels' (vertical), and the flaps' +/// (horizontal, from slot to slot). +fn box_creases() -> Vec { + let mut out = vec![]; + for (k, x) in [20.0, 120.0, 180.0, 280.0].into_iter().enumerate() { + out.push(crease((x, 30.0), (x, 110.0), 100 + k as u64)); + } + for (k, (x0, x1)) in [(20.0, 118.0), (122.0, 178.0), (182.0, 278.0), (282.0, 340.0)].into_iter().enumerate() { + out.push(crease((x0, 30.0), (x1, 30.0), 110 + k as u64)); + out.push(crease((x0, 110.0), (x1, 110.0), 120 + k as u64)); + } + out +} + +fn notched_box() -> Vec { + let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec(); + outline.extend([(0.0, 30.0), (20.0, 30.0)]); + let mut lines = vec![cut(&outline, 1)]; + lines.extend(box_creases()); + lines +} + +fn check(lines: &[FoldLine]) -> (Vec, Vec) { + blanks(lines, TOL) +} + +#[test] +fn a_tray_has_a_base_four_walls_and_four_hinges() { + let (b, issues) = check(&tray()); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 6_000_000]); + assert_eq!(b[0].hinges.len(), 4); + for h in &b[0].hinges { + assert!(h.straight && h.angle == 90.0 && h.keys.len() == 1, "{h:?}"); + assert!((h.from.distance(h.to) - if h.keys[0] % 2 == 0 { 100.0 } else { 60.0 }).abs() < 1e-6, "{h:?}"); + } + assert_eq!(base_panel(&b[0].panels).map(|i| (b[0].panels[i].area).round()), Some(6000.0)); +} + +#[test] +fn a_slotted_box_gives_the_same_panels_however_its_slots_and_outline_are_drawn() { + let (notched, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(notched.len(), 1); + assert_eq!(notched[0].panels.len(), 13, "glue flap, four body panels, eight flaps"); + assert_eq!(notched[0].hinges.len(), 12); + assert!(notched[0].holes.is_empty()); + + // The slots as rectangles across a plain outline. + let mut across = + vec![cut(&[(20.0, 0.0), (340.0, 0.0), (340.0, 140.0), (20.0, 140.0), (20.0, 110.0), (0.0, 110.0), (0.0, 30.0), (20.0, 30.0)], 1)]; + for (k, x) in [120.0, 180.0, 280.0].into_iter().enumerate() { + across.push(cut(&[(x - 2.0, -5.0), (x + 2.0, -5.0), (x + 2.0, 30.0), (x - 2.0, 30.0)], 2 + k as u64)); + across.push(cut(&[(x - 2.0, 110.0), (x + 2.0, 110.0), (x + 2.0, 145.0), (x - 2.0, 145.0)], 5 + k as u64)); + } + across.extend(box_creases()); + let (b, issues) = check(&across); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), areas(¬ched[0])); + assert_eq!(b[0].hinges.len(), 12); + + // The notched outline as four open paths, end to end. + let mut outline: Vec<(f64, f64)> = NOTCHED.to_vec(); + outline.extend([(0.0, 30.0), (20.0, 30.0), (20.0, 0.0)]); + let mut open: Vec = + [0..9, 8..17, 16..25, 24..33].into_iter().enumerate().map(|(k, r)| line(LineKind::Cut, &outline[r], false, 1 + k as u64)).collect(); + open.extend(box_creases()); + let (b, issues) = check(&open); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(areas(&b[0]), areas(¬ched[0])); + assert_eq!(b[0].hinges.len(), 12); + + // Input order does not change the result. + let mut reversed = notched_box(); + reversed.reverse(); + let (b, _) = check(&reversed); + assert_eq!(areas(&b[0]), areas(¬ched[0])); +} + +#[test] +fn a_round_tuck_flap_folds_like_any_panel() { + let mut bp = BezPath::new(); + bp.move_to(p(0.0, 40.0)); + bp.line_to(p(0.0, 140.0)); + bp.line_to(p(100.0, 140.0)); + bp.line_to(p(100.0, 40.0)); + bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); + bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); + bp.close_path(); + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, angle: None, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].panels.len(), 2); + assert_eq!(b[0].hinges.len(), 1); +} + +#[test] +fn a_window_is_a_hole_in_its_panel() { + let mut lines = tray(); + lines.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].holes.len(), 1); + assert_eq!(areas(&b[0]), vec![1_800_000, 1_800_000, 3_000_000, 3_000_000, 4_800_000]); +} + +/// The tray's outline as one open path whose end stops `short` before its start. +fn tray_with_gap(short: f64) -> Vec { + let mut lines = tray(); + lines[0] = line( + LineKind::Cut, + &[ + (30.0 + short, 0.0), + (130.0, 0.0), + (130.0, 30.0), + (160.0, 30.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + (30.0, 0.0), + ], + false, + 1, + ); + lines +} + +#[test] +fn a_gap_within_the_tolerance_is_closed_and_one_past_it_is_a_loose_end() { + let (closed, _) = check(&tray()); + let (b, issues) = check(&tray_with_gap(0.05)); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1]); + assert_eq!(areas(&b[0]), areas(&closed[0])); + assert_eq!(b[0].hinges.len(), 4); + // The tolerance boundary. + let (_, issues) = blanks(&tray_with_gap(0.05), 0.06); + assert_eq!(codes(&issues), vec!["gap"]); + let (b, issues) = blanks(&tray_with_gap(0.05), 0.04); + assert!(codes(&issues).starts_with(&["open", "looseEnd", "looseEnd"]) || codes(&issues).starts_with(&["looseEnd"]), "{issues:?}"); + assert!(issues.iter().any(|i| i.code == IssueCode::LooseEnd && i.at.is_some_and(|a| a.distance(p(30.05, 0.0)) < 1e-9)), "{issues:?}"); + assert!(b.iter().all(|b| b.panels.len() < 5), "the outline does not close"); +} + +#[test] +fn no_cut_lines_or_no_enclosed_area_build_nothing() { + let (b, issues) = check(&[crease((0.0, 0.0), (10.0, 0.0), 1)]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["noCut"]); + let (b, issues) = check(&[]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["noCut"]); + let (b, issues) = check(&[line(LineKind::Cut, &[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0)], false, 1)]); + assert!(b.is_empty()); + assert!(codes(&issues).contains(&"open") && codes(&issues).contains(&"looseEnd"), "{issues:?}"); + // A non-finite line is left out. + let mut lines = tray(); + lines.push(line(LineKind::Crease, &[(0.0, 0.0), (f64::NAN, 1.0)], false, 9)); + let (b, issues) = check(&lines); + assert!(issues.is_empty() && b[0].panels.len() == 5, "{issues:?}"); +} + +#[test] +fn a_cut_end_inside_the_blank_is_a_loose_end() { + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 20.0)], false, 2)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}"); + assert_eq!((issues[0].keys.clone(), issues[0].at), (vec![2], Some(p(80.0, 20.0)))); + assert_eq!(b[0].panels.len(), 5, "a cut into a wall does not divide it"); + // A slit that ends on a crease is not loose: it cuts the wall in two. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 0.0), (80.0, 30.0)], false, 2)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((b[0].panels.len(), b[0].hinges.len()), (6, 5)); +} + +#[test] +fn a_cut_line_that_comes_back_through_its_own_end_meets_it() { + // From (80, 10) out to (90, 20), then back through (80, 10) to the outline at (70, 0): the + // start lies on the line's own second segment, so it is not loose. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(80.0, 10.0), (90.0, 20.0), (70.0, 0.0)], false, 2)); + let (_, issues) = check(&lines); + assert!(!codes(&issues).contains(&"looseEnd"), "{issues:?}"); + // A first segment shorter than the tolerance does not make the second one meet the end. + let mut lines = tray(); + lines.push(line(LineKind::Cut, &[(90.0, 25.0), (90.05, 25.0), (80.0, 20.0), (80.0, 0.0)], false, 2)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["looseEnd"], "{issues:?}"); + assert_eq!(issues[0].at, Some(p(90.0, 25.0))); +} + +#[test] +fn two_outlines_joined_by_a_cut_line_are_both_material() { + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(150.0, 0.0), (180.0, 0.0), (180.0, 30.0), (150.0, 30.0)], 2), + line(LineKind::Cut, &[(100.0, 10.0), (150.0, 10.0)], false, 3), + ]; + let (b, issues) = check(&lines); + assert_eq!(b.len(), 1, "one connected piece"); + assert_eq!(areas(&b[0]), vec![900_000, 10_000_000], "{issues:?}"); + assert!(b[0].holes.is_empty()); + // A slot drawn across the outline is still cut out, not made material where it sticks out. + let lines = + vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)], 2)]; + let (b, _) = check(&lines); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // The same slot drawn as four open lines end to end, one of them backwards. + let slot = [(48.0, -10.0), (52.0, -10.0), (52.0, 20.0), (48.0, 20.0)]; + let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1)]; + lines.push(line(LineKind::Cut, &[slot[0], slot[1]], false, 2)); + lines.push(line(LineKind::Cut, &[slot[2], slot[1]], false, 3)); + lines.push(line(LineKind::Cut, &[slot[2], slot[3]], false, 4)); + lines.push(line(LineKind::Cut, &[slot[3], slot[0]], false, 5)); + let (b, issues) = check(&lines); + assert_eq!(b.len(), 1, "{issues:?}"); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // And with a gap within the tolerance at one corner. + lines[4] = line(LineKind::Cut, &[slot[3], (48.0, -9.95)], false, 5); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000 - 80_000]); + // A slot right across the blank, with no corner inside the outline and no outline corner + // inside the slot, cuts it in two. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(10.0, -210.0), (20.0, -210.0), (20.0, 110.0), (10.0, 110.0)], 2), + ]; + let (b, _) = check(&lines); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![1_000_000, 8_000_000]); +} + +#[test] +fn an_outline_drawn_twice_keeps_its_material() { + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let (b, issues) = check(&[cut(&square, 1), cut(&square, 2)]); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1, 2]); + assert_eq!(b.len(), 1); + assert_eq!(areas(&b[0]), vec![10_000_000]); + // The same two squares as the subpaths of one compound path. + let mut twice = poly(&square, true); + twice.subpaths.extend(poly(&square, true).subpaths); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, angle: None, key: 1 }]); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1]); + assert_eq!(areas(&b[0]), vec![10_000_000]); +} + +#[test] +fn a_large_tolerance_still_closes_nearly_touching_ends_and_short_outlines() { + // Ends 0.0005 apart, closer than 1/10,000 of the tolerance. + let nearly = line(LineKind::Cut, &[(0.0005, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[nearly], 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(areas(&b[0]), vec![10_000_000]); + // An outline shorter than the tolerance, 0.05 pt open: a gap, and no loose end. + let short = line(LineKind::Cut, &[(0.05, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[short], 10.0); + assert_eq!(codes(&issues), vec!["gap"], "{issues:?}"); + assert_eq!(areas(&b[0]), vec![1000]); +} + +#[test] +fn a_lookup_wider_than_the_occupied_cells_reads_only_those_cells() { + // Two points 1e-9 apart make cells about 2.4e-13 wide: a lookup 1e-6 around one spans some + // 10^14 cells, and finds both points by reading the two cells that hold them. + let cells = Cells::new(vec![(Rect::from_points(p(0.0, 0.0), p(0.0, 0.0)), 1), (Rect::from_points(p(1e-9, 0.0), p(1e-9, 0.0)), 2)], 0.0, 4096.0); + assert_eq!(cells.near(p(0.0, 0.0), 1e-6), vec![1, 2]); + assert_eq!(cells.near(p(5.0, 5.0), 1e-6), Vec::::new()); + // A square open by 0.0000011 pt at a 10 pt tolerance. + let square = line(LineKind::Cut, &[(0.0000011, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)], false, 1); + let (b, issues) = blanks(&[square], 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b.len(), 1); +} + +#[test] +fn a_window_of_open_lines_with_a_slit_to_its_corner_is_still_a_hole() { + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1); + let window = [(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)]; + let slit = line(LineKind::Cut, &[(40.0, 0.0), (40.0, 40.0)], false, 2); + let (closed, issues) = check(&[outline.clone(), slit.clone(), cut(&window, 3)]); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((closed[0].holes.len(), areas(&closed[0])), (1, vec![10_000_000 - 400_000])); + let mut lines = vec![outline, slit]; + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + let (open, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((open[0].holes.len(), areas(&open[0])), (1, areas(&closed[0]))); + // The outline as four open lines too, the slit from its corner to the window's. + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let mut lines: Vec = (0..4).map(|k| line(LineKind::Cut, &[corners[k], corners[(k + 1) % 4]], false, 10 + k as u64)).collect(); + lines.push(line(LineKind::Cut, &[(0.0, 0.0), (40.0, 40.0)], false, 2)); + for k in 0..4 { + lines.push(line(LineKind::Cut, &[window[k], window[(k + 1) % 4]], false, 3 + k as u64)); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!((b[0].holes.len(), areas(&b[0])), (1, areas(&closed[0]))); +} + +#[test] +fn a_grid_of_many_touching_outlines_is_classified_without_comparing_every_pair() { + // 100 × 100 touching squares, each its own closed outline: one piece of 10,000 panels. + let mut lines = vec![]; + for i in 0..100u64 { + for j in 0..100u64 { + let (x, y) = (10.0 * i as f64, 10.0 * j as f64); + lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], 100 * i + j)); + } + } + let (b, issues) = check(&lines); + assert!(b.is_empty()); + assert!(codes(&issues).contains(&"tooComplex"), "{issues:?}"); +} + +#[test] +fn open_cut_lines_far_from_the_origin_are_checked_without_overflow() { + let lines = [ + line(LineKind::Cut, &[(1e13, 0.0), (1e13 + 4096.0, 0.0), (1e13 + 4096.0, 4096.0)], false, 1), + line(LineKind::Cut, &[(1e13 + 4096.0, 4096.0), (1e13, 4096.0), (1e13, 0.0)], false, 2), + ]; + let (b, issues) = check(&lines); + assert!(b.len() <= 1, "{issues:?}"); +} + +#[test] +fn a_blank_in_the_hole_of_a_narrow_ring_is_a_blank_of_its_own() { + // The ring's own area (1,900) is less than the hole's (8,100), but the square lies in the hole. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(5.0, 5.0), (95.0, 5.0), (95.0, 95.0), (5.0, 95.0)], 2), + cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 3), + ]; + let (b, issues) = check(&lines); + assert_eq!(b.len(), 2, "{issues:?}"); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![3]); +} + +#[test] +fn too_many_segments_are_refused_before_the_lines_are_copied() { + // Many lines that together pass the limit by one segment. + let each: Vec<(f64, f64)> = (0..=64).map(|i| (i as f64, 0.0)).collect(); + let lines: Vec = (0..=(MAX_SEGMENTS / 64) as u64).map(|k| line(LineKind::Cut, &each, false, k)).collect(); + assert!(lines.len() * 64 > MAX_SEGMENTS); + let (b, issues) = check(&lines); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); +} + +#[test] +fn many_separate_blanks_each_with_a_window_are_told_apart() { + // A 50 × 40 grid of 10 pt squares 5 pt apart, each with a 4 pt window and a crease beside it. + let mut lines = vec![]; + for i in 0..50u64 { + for j in 0..40u64 { + let (x, y) = (15.0 * i as f64, 15.0 * j as f64); + let k = 10 * (40 * i + j); + lines.push(cut(&[(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)], k)); + lines.push(cut(&[(x + 1.0, y + 1.0), (x + 5.0, y + 1.0), (x + 5.0, y + 5.0), (x + 1.0, y + 5.0)], k + 1)); + lines.push(crease((x + 7.0, y), (x + 7.0, y + 10.0), k + 2)); + } + } + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{:?}", issues.first()); + assert_eq!(blanks.len(), 2000); + assert!(blanks.iter().all(|b| b.panels.len() == 2 && b.hinges.len() == 1 && b.holes.len() == 1)); +} + +#[test] +fn many_separate_cut_lines_are_checked_by_the_cells_near_each_end() { + // 2,000 short slits from the top edge of a long blank, each ending loose inside it. + let mut lines = vec![cut(&[(0.0, 0.0), (4000.0, 0.0), (4000.0, 100.0), (0.0, 100.0)], 1)]; + for i in 0..2000u64 { + let x = 1.0 + 2.0 * i as f64; + lines.push(line(LineKind::Cut, &[(x, 0.0), (x, 50.0)], false, 10 + i)); + } + let (_, issues) = check(&lines); + let loose: Vec<&Issue> = issues.iter().filter(|i| i.code == IssueCode::LooseEnd).collect(); + assert_eq!(loose.len(), 2000); + assert!(loose.iter().all(|i| i.at.is_some_and(|at| (at.y - 50.0).abs() < 1e-9))); +} + +#[test] +fn too_many_segments_or_panels_are_too_complex() { + // One point more than segments. + let mut zigzag: Vec<(f64, f64)> = (0..=MAX_SEGMENTS + 1).map(|i| (i as f64 * 0.5, (i % 2) as f64)).collect(); + let (b, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); + zigzag.truncate(MAX_SEGMENTS + 1); + let (_, issues) = check(&[line(LineKind::Cut, &zigzag, false, 1)]); + assert!(!codes(&issues).contains(&"tooComplex"), "at the limit"); + // A grid of 16 × 16 panels is at the panel limit; 17 × 16 is past it. + let grid = |cols: usize| { + let mut lines = vec![cut(&[(0.0, 0.0), (cols as f64 * 10.0, 0.0), (cols as f64 * 10.0, 160.0), (0.0, 160.0)], 1)]; + for i in 1..cols { + lines.push(crease((i as f64 * 10.0, 0.0), (i as f64 * 10.0, 160.0), 100 + i as u64)); + } + for j in 1..16 { + lines.push(crease((0.0, j as f64 * 10.0), (cols as f64 * 10.0, j as f64 * 10.0), 200 + j as u64)); + } + lines + }; + let (b, issues) = check(&grid(16)); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].panels.len(), MAX_PANELS); + let (b, issues) = check(&grid(17)); + assert!(b.is_empty()); + assert_eq!(codes(&issues), vec!["tooComplex"]); +} + +#[test] +fn lines_on_top_of_each_other_are_reported() { + let mut lines = tray(); + lines.push(crease((40.0, 0.0), (120.0, 0.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["cutOverCrease"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![1, 20]); + + let mut lines = tray(); + lines.push(crease((130.0, 30.0), (30.0, 30.0), 20)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![10, 20]); + assert_eq!(b[0].hinges.len(), 4); + assert_eq!(b[0].hinges.iter().find(|h| h.keys.contains(&20)).map(|h| h.keys.clone()), Some(vec![10, 20])); +} + +#[test] +fn a_crease_that_ends_inside_a_panel_is_dangling() { + let mut lines = tray(); + lines.push(crease((80.0, 30.0), (80.0, 60.0), 20)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); + assert_eq!(b[0].panels.len(), 5); +} + +#[test] +fn a_hinge_shorter_than_the_tolerance_divides_nothing_and_leaves_a_loose_panel() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["noSplit", "loosePanel"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![2]); + assert!(b[0].hinges.is_empty()); + // The same with a hinge as long as the panels: no issue. + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1), crease((50.0, 0.0), (50.0, 50.0), 2)]; + let (_, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); +} + +#[test] +fn hinge_pieces_far_apart_are_measured_by_their_own_length() { + // A window leaves two 0.02 pt strips joining the halves, each crossed by a crease: 0.04 pt of + // hinge, though its pieces span 100 pt. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + cut(&[(40.0, 0.02), (60.0, 0.02), (60.0, 99.98), (40.0, 99.98)], 2), + crease((50.0, 0.0), (50.0, 0.02), 3), + crease((50.0, 99.98), (50.0, 100.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(codes(&issues).contains(&"noSplit"), "{issues:?}"); + assert!(b[0].hinges.is_empty()); +} + +#[test] +fn a_window_split_by_a_cut_line_is_one_hole() { + let mut lines = + vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), cut(&[(40.0, 40.0), (60.0, 40.0), (60.0, 60.0), (40.0, 60.0)], 2)]; + lines.push(line(LineKind::Cut, &[(40.0, 50.0), (60.0, 50.0)], false, 3)); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].holes.len(), 1); + let area = vectorcraft_pathops::area(&b[0].holes[0], FillRule::NonZero); + assert!((area - 400.0).abs() < 1e-3, "{area}"); +} + +#[test] +fn a_hinge_drawn_as_short_pieces_is_measured_whole() { + // Ten 5 pt pieces make a 50 pt hinge, longer than a 10 pt tolerance though each piece is not. + let mut lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], 1)]; + for k in 0..10u64 { + let y = 5.0 * k as f64; + lines.push(crease((50.0, y), (50.0, y + 5.0), 10 + k)); + } + let (b, issues) = blanks(&lines, 10.0); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1); + let h = &b[0].hinges[0]; + assert!((h.from.distance(h.to) - 50.0).abs() < 1e-6 && h.keys.len() == 10, "{h:?}"); +} + +#[test] +fn a_crease_outside_the_blank_is_reported() { + let mut lines = tray(); + lines.push(crease((200.0, 0.0), (250.0, 0.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["outside"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); +} + +#[test] +fn a_bent_crease_folds_along_its_longest_piece() { + let mut lines = tray(); + lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.0), (130.0, 32.0)], false, 10); + lines[0] = cut( + &[ + (30.0, 0.0), + (130.0, 0.0), + (130.0, 32.0), + (160.0, 32.0), + (160.0, 90.0), + (130.0, 90.0), + (130.0, 120.0), + (30.0, 120.0), + (30.0, 90.0), + (0.0, 90.0), + (0.0, 30.0), + (30.0, 30.0), + ], + 1, + ); + lines[2] = crease((130.0, 32.0), (130.0, 90.0), 11); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == vec![10]).unwrap(); + assert!(!h.straight); + assert!((h.from.y - 30.0).abs() < 1e-9 && (h.to.y - 30.0).abs() < 1e-9, "along the 60 pt piece: {h:?}"); + // Within the tolerance, a crease is straight. + let mut lines = tray(); + lines[1] = line(LineKind::Crease, &[(30.0, 30.0), (90.0, 30.05), (130.0, 30.0)], false, 10); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert!(b[0].hinges.iter().all(|h| h.straight)); +} + +#[test] +fn a_slot_too_narrow_to_map_is_a_sliver() { + let mut lines = tray(); + lines.push(cut(&[(60.0, 45.0), (60.004, 45.0), (60.004, 75.0), (60.0, 75.0)], 2)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["sliver"], "{issues:?}"); + assert!(issues[0].at.is_some_and(|a| Rect::new(59.9, 44.0, 60.1, 76.0).contains(a))); +} + +#[test] +fn lines_in_a_hole_are_ambiguous() { + let mut window = tray(); + window.push(cut(&[(60.0, 45.0), (100.0, 45.0), (100.0, 75.0), (60.0, 75.0)], 2)); + let mut lines = window.clone(); + lines.push(crease((70.0, 45.0), (70.0, 75.0), 20)); + let (_, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![20]); + let mut lines = window; + lines.push(cut(&[(70.0, 50.0), (90.0, 50.0), (90.0, 70.0), (70.0, 70.0)], 3)); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["ambiguous"], "{issues:?}"); + assert_eq!(issues[0].keys, vec![3]); + assert_eq!(b.len(), 2, "the square in the window is a blank of its own"); +} + +#[test] +fn partial_cuts_fold_the_other_way_and_a_line_s_own_angle_wins() { + let mut lines = tray(); + lines[1].kind = LineKind::PartialCut; + lines[2].angle = Some(45.0); + lines[3].kind = LineKind::Perforation; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let angle = |key: u64| b[0].hinges.iter().find(|h| h.keys == vec![key]).map(|h| h.angle); + assert_eq!((angle(10), angle(11), angle(12), angle(13)), (Some(-90.0), Some(45.0), Some(90.0), Some(90.0))); +} + +#[test] +fn every_code_has_an_id_and_a_severity() { + let ids: Vec<&str> = IssueCode::ALL.iter().map(|c| c.id()).collect(); + assert_eq!(ids.len(), 15); + let mut unique = ids.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), 15); + let errors: Vec<&str> = IssueCode::ALL.iter().filter(|c| c.is_error()).map(|c| c.id()).collect(); + assert_eq!(errors, vec!["noCut", "open", "looseEnd", "tooComplex", "cutOverCrease"]); + let mut sorted = IssueCode::ALL; + sorted.sort(); + assert_eq!(sorted, IssueCode::ALL, "listed in issue order"); +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(48))] + /// Random fold lines never panic, and the panels and hinges they give are consistent. + #[test] + fn random_fold_lines_give_consistent_blanks( + segs in proptest::collection::vec((0u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..10), + boxed in any::(), + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + if boxed { + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + } + let (blanks, issues) = blanks(&lines, TOL); + for b in &blanks { + prop_assert!(!b.panels.is_empty() && b.panels.len() <= MAX_PANELS); + for h in &b.hinges { + prop_assert!(h.a < h.b && h.b < b.panels.len()); + prop_assert!(h.from.is_finite() && h.to.is_finite()); + } + } + let mut sorted = issues.clone(); + sorted.sort_by_key(|i| i.code); + prop_assert_eq!(sorted, issues); + } +} diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index d01a8b9840..01b5c75d9f 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -6,6 +6,7 @@ //! intersecting profiles can have ambiguous visibility and are not solid modelling inputs. #![forbid(unsafe_code)] +pub mod fold; mod solid; mod visibility; pub use solid::{ diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 1c70bef5d0..1e827a7efc 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -2,10 +2,15 @@ //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). +//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu +//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each +//! with a Select button; the list is kept until the document changes. + +use std::sync::{Arc, Weak}; use egui::{Align, Layout, Sense, Ui, vec2}; use serde_json::{Value, json}; +use vectorcraft_engine::doc::Document; use crate::VectorcraftApp; use crate::menus::Item; @@ -18,12 +23,16 @@ pub const ID: &str = "foldLines"; pub const SET_ROLE: &str = "addon.packaging.setRole"; /// The command that picks a role's swatch. pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; +/// The command that checks the fold lines. +pub const CHECK: &str = "addon.packaging.check"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; /// Where the panel keeps the last `addon.packaging.roles` answer (panel state). const STATE: &str = "fold-lines"; +/// Where the panel keeps the last check (panel state). +const CHECKED: &str = "fold-lines-check"; /// Object › Plug-ins › Packaging Tools. pub fn menu() -> Vec { @@ -35,9 +44,141 @@ pub fn menu() -> Vec { make("Make Crease Line", "crease"), make("Make Partial Cut Line", "partialCut"), make("Make Perforation Line", "perforation"), + Item::Sep, + Item::Cmd("Check Fold Lines", CHECK, Value::Null), ] } +/// One issue of a check: whether it is an error, its message (English) and the objects it names. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Issue { + pub error: bool, + pub message: String, + pub ids: Vec, +} + +/// The document a check was made on: its id, and its content as it was then. Selecting changes +/// neither, so the issues stay listed while their Select buttons are used. The content is held +/// weakly: it is compared, never kept alive. +type DocKey = (u64, Weak); + +/// The last check of a document. +#[derive(Clone, Debug, Default)] +pub(crate) struct Checked { + pub key: Option, + pub panels: u64, + pub hinges: u64, + pub issues: Vec, +} + +impl Checked { + /// The check `r` (an `addon.packaging.check` answer) of the document `key`. + fn of(key: DocKey, r: &Value) -> Checked { + let count = |k: &str| r[k].as_u64().unwrap_or(0); + let issues: Vec = r["issues"] + .as_array() + .into_iter() + .flatten() + .map(|i| Issue { + error: i["severity"] == "error", + message: i["message"].as_str().unwrap_or_default().to_string(), + ids: i["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(), + }) + .collect(); + Checked { key: Some(key), panels: count("panels"), hinges: count("hinges"), issues } + } + + /// The summary line, in English (the status bar and the panel show it translated). + fn summary(&self) -> String { + let errors = self.issues.iter().filter(|i| i.error).count(); + crate::i18n::fmt( + "Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings}", + &[ + ("panels", &self.panels.to_string()), + ("hinges", &self.hinges.to_string()), + ("errors", &errors.to_string()), + ("warnings", &(self.issues.len() - errors).to_string()), + ], + ) + } +} + +/// The active document's [`DocKey`]. +fn doc_key(app: &VectorcraftApp) -> Option { + app.session.active().map(|st| (st.uid, Arc::downgrade(&st.doc))) +} + +/// Runs `addon.packaging.check` with `p` and shows its summary in the status bar → the check, kept +/// in `ctx` for the panel. +fn run_check(app: &mut VectorcraftApp, ctx: &egui::Context, p: Value) -> Option { + let r = app.run(CHECK, p).map_err(|e| app.status(e)).ok()?; + let checked = Checked::of(doc_key(app)?, &r); + app.status(checked.summary()); + set_pstate(ctx, CHECKED, checked.clone()); + Some(checked) +} + +/// Check Fold Lines from its menu item: checks with `p`, keeps the issues for the Fold Lines panel +/// and shows the panel. +pub(crate) fn check(app: &mut VectorcraftApp, p: Value) { + let ctx = app.ui_ctx.clone().unwrap_or_default(); + if run_check(app, &ctx, p).is_some() + && let Err(e) = crate::panel_docking::reveal_panel(app, ID) + { + app.status(e); + } +} + +/// The last check of the active document, while the document has not changed since. +fn last_check(app: &VectorcraftApp, ctx: &egui::Context) -> Option { + let checked: Checked = pstate(ctx, CHECKED); + let same = match (&checked.key, doc_key(app)) { + (Some((uid, doc)), Some((now, current))) => *uid == now && doc.ptr_eq(¤t), + _ => false, + }; + same.then_some(checked) +} + +/// The Check button, then the last check's summary and issues (errors in the error color, warnings +/// in the warning color), each with a Select button; clicking an issue selects its objects too. +fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { + widgets::divider(ui); + let width = ui.available_width(); + if widgets::flat_button(ui, tl!("Check"), width).clicked() { + run_check(app, ui.ctx(), json!({})); + } + let Some(checked) = last_check(app, ui.ctx()) else { return }; + ui.add_space(4.0); + dim_label(ui, &crate::i18n::msg(&checked.summary())); + if checked.issues.is_empty() { + dim_label(ui, tl!("No issues found.")); + } + let t = crate::theme::Tokens::get(ui.ctx()); + let mut select = None; + for (n, issue) in checked.issues.iter().enumerate() { + ui.horizontal(|ui| { + let can = !issue.ids.is_empty(); + let picked = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = ui.add_enabled_ui(can, |ui| widgets::flat_button(ui, tl!("Select"), 56.0)).inner; + let text = egui::RichText::new(crate::i18n::msg(&issue.message)).color(if issue.error { t.error } else { t.warning }); + let row = + ui.with_layout(Layout::left_to_right(Align::Center), |ui| ui.add(egui::Label::new(text).sense(Sense::click()).wrap())).inner; + button.clicked() || (row.clicked() && can) + }) + .inner; + if picked { + select = Some(n); + } + }); + } + if let Some(issue) = select.and_then(|n| checked.issues.get(n)) + && let Err(e) = app.run("select.set", json!({ "ids": issue.ids })) + { + app.status(e); + } +} + /// One role row: (role id, swatch name, the swatch's paint if the document has it, count). type Row = (String, String, Option, u64); @@ -103,6 +244,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_check(app, ui); } /// Role Swatches… (the dialog of `addon.packaging.setRoleSwatch`): when another role is picked, its diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index cfe9909dc8..808956e4d7 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,7 +1,7 @@ use serde_json::json; use vectorcraft_engine::Session; -use super::{ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; +use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show}; use crate::tests_labels::painted_text; use crate::{VectorcraftApp, menus}; @@ -125,6 +125,137 @@ fn role_swatches_shows_the_swatch_of_the_role_picked() { assert_eq!(crate::dialogs::form::params(&d), json!({"role": "crease", "swatch": "Ink"}), "the dialog sends no __role"); } +/// An app with a square blank cut on its outline, a crease across it and a cut line that stops +/// inside it, nothing selected → (app, the cut line that stops). +fn blank() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M50 50 L250 50 L250 250 L50 250 Z"); + let crease = path(&mut app, "M50 150 L250 150"); + let slit = path(&mut app, "M100 50 L100 100"); + app.run(SET_ROLE, json!({"role": "cut", "ids": [outline, slit]})).unwrap(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, slit) +} + +/// Frames of the panel in one context, the pointer clicking the middle of the element that screen +/// readers name `click` (egui finds what the pointer is over from the frame before, so the move +/// gets a frame of its own) → the text the last frame painted. +fn frames(app: &mut VectorcraftApp, ctx: &egui::Context, click: Option<&str>) -> String { + ctx.enable_accesskit(); + crate::theme::install_fonts(ctx); + // The context's clock runs on from its last frame: egui requires time to move forward. + let mut time = ctx.input(|i| i.time); + let mut frame = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 480.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + frame(app, vec![]); + let out = frame(app, vec![]); + let Some(label) = click else { return crate::tests_labels::shapes_text(&out) }; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // A button carries its text as its name, a label as its value. + let node = nodes.iter().find(|(_, n)| n.label() == Some(label) || n.value() == Some(label)); + let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + let out = frame(app, vec![button(false)]); + crate::tests_labels::shapes_text(&out) +} + +#[test] +fn check_fold_lines_lists_its_issues_in_the_panel_until_the_document_changes() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, _) = blank(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Check Fold Lines").expect("listed"); + assert_eq!(item.command.as_deref(), Some(CHECK)); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, CHECK, item.params.clone()); + assert!(crate::panel_docking::showing(&app.ui, ID), "the panel opens"); + assert_eq!(app.ui.status, "Panels: 2, creases: 1, errors: 1, warnings: 0"); + let text = frames(&mut app, &ctx, None); + assert!(text.contains("A cut line ends without meeting another cut line."), "{text}"); + assert!(text.contains("Panels: 2, creases: 1, errors: 1, warnings: 0") && text.contains("Select"), "{text}"); + // Any change to the document takes the list away. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap(); + let text = frames(&mut app, &ctx, None); + assert!(!text.contains("A cut line ends"), "{text}"); +} + +#[test] +fn the_check_button_checks_and_clicking_an_issue_selects_its_lines() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let (mut app, slit) = blank(); + let ctx = egui::Context::default(); + let text = frames(&mut app, &ctx, Some("Check")); + assert!(text.contains("A cut line ends without meeting another cut line."), "{text}"); + assert!(app.session.active().unwrap().selection.is_empty()); + frames(&mut app, &ctx, Some("A cut line ends without meeting another cut line.")); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert_eq!(selected, [slit]); + let text = frames(&mut app, &ctx, None); + assert!(text.contains("A cut line ends without meeting another cut line."), "selecting keeps the list: {text}"); + // A clean blank: no issues. + app.run("edit.clear", json!({})).unwrap(); + let text = frames(&mut app, &ctx, Some("Check")); + assert!(text.contains("No issues found.") && text.contains("Panels: 2, creases: 1, errors: 0, warnings: 0"), "{text}"); +} + +#[test] +fn issues_and_the_summary_show_in_the_interface_language() { + let (mut app, _) = blank(); + let ctx = egui::Context::default(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let text = frames(&mut app, &ctx, Some(crate::i18n::t("Check"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(!text.contains("A cut line ends") && !text.contains("Panels:"), "{text}"); + assert!(text.contains("Schnittlinie") && text.contains('2'), "{text}"); +} + +/// The messages `addon.packaging.check` gives its issues, one for each code (two for `noCut`). +const ISSUE_MESSAGES: [&str; 16] = [ + "No cut lines are in the selection.", + "No cut lines are in the document.", + "The cut lines do not enclose an area.", + "A cut line ends without meeting another cut line.", + "A gap between cut lines was closed.", + "The fold lines are too complex to check.", + "A cut line and a crease lie on top of each other.", + "Two lines of the same role lie on top of each other.", + "A crease ends inside a panel.", + "A crease does not divide two panels.", + "A crease lies outside the cut outline.", + "A crease that is not straight is folded along one straight line.", + "A gap between cut lines is too narrow to tell apart.", + "A cut-out area holds other fold lines.", + "A panel is not joined to the rest by a crease.", + "A fold line is on a non-printing layer.", +]; + +#[test] +fn every_issue_message_translates_in_every_complete_message_catalog() { + for code in [ + "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", + "ca", "nl", "da", + ] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, creases: 2, errors: 1, warnings: 0"]) { + assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); + } + } +} + #[test] fn the_panel_without_a_document_asks_for_one() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..ab9ed92de5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7084,4 +7084,23 @@ breakText Glyphs Глифи No objects are selected. Няма избрани обекти. Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване. Remove Fold Line Role Премахни вида на линията + Check Провери + Check Fold Lines Провери линиите на сгъване +@msg No cut lines are in the selection. В селекцията няма линии за рязане. +@msg No cut lines are in the document. В документа няма линии за рязане. +@msg The cut lines do not enclose an area. Линиите за рязане не ограждат площ. +@msg A cut line ends without meeting another cut line. Линия за рязане завършва, без да срещне друга линия за рязане. +@msg A gap between cut lines was closed. Процеп между линии за рязане беше затворен. +@msg The fold lines are too complex to check. Линиите на сгъване са твърде сложни за проверка. +@msg A cut line and a crease lie on top of each other. Линия за рязане и линия за биговане лежат една върху друга. +@msg Two lines of the same role lie on top of each other. Две линии от един и същи вид лежат една върху друга. +@msg A crease ends inside a panel. Линия за биговане завършва вътре в панел. +@msg A crease does not divide two panels. Линия за биговане не разделя два панела. +@msg A crease lies outside the cut outline. Линия за биговане лежи извън контура за рязане. +@msg A crease that is not straight is folded along one straight line. Линия за биговане, която не е права, се сгъва по една права линия. +@msg A gap between cut lines is too narrow to tell apart. Процеп между линии за рязане е твърде тесен, за да се различи. +@msg A cut-out area holds other fold lines. Изрязана област съдържа други линии на сгъване. +@msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. +@msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, бигове: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..d6cc94f911 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7137,4 +7137,23 @@ shape Open Otvoren No objects are selected. Nijedan objekat nije odabran. Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja. Remove Fold Line Role Ukloni vrstu linije + Check Provjeri + Check Fold Lines Provjeri linije savijanja +@msg No cut lines are in the selection. U odabiru nema linija rezanja. +@msg No cut lines are in the document. U dokumentu nema linija rezanja. +@msg The cut lines do not enclose an area. Linije rezanja ne zatvaraju nijednu površinu. +@msg A cut line ends without meeting another cut line. Linija rezanja završava a da ne susreće drugu liniju rezanja. +@msg A gap between cut lines was closed. Razmak između linija rezanja je zatvoren. +@msg The fold lines are too complex to check. Linije savijanja su previše složene za provjeru. +@msg A cut line and a crease lie on top of each other. Linija rezanja i linija bigovanja leže jedna preko druge. +@msg Two lines of the same role lie on top of each other. Dvije linije iste vrste leže jedna preko druge. +@msg A crease ends inside a panel. Linija bigovanja završava unutar panela. +@msg A crease does not divide two panels. Linija bigovanja ne razdvaja dva panela. +@msg A crease lies outside the cut outline. Linija bigovanja leži izvan konture rezanja. +@msg A crease that is not straight is folded along one straight line. Linija bigovanja koja nije ravna savija se duž jedne prave linije. +@msg A gap between cut lines is too narrow to tell apart. Razmak između linija rezanja je preuzak da bi se razlikovao. +@msg A cut-out area holds other fold lines. Izrezana površina sadrži druge linije savijanja. +@msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. +@msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, bigovi: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..0089095906 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7945,4 +7945,23 @@ breakText Glyphs Glifs No objects are selected. No hi ha cap objecte seleccionat. Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia + Check Comprova + Check Fold Lines Comprova les línies de plegat +@msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció. +@msg No cut lines are in the document. No hi ha cap línia de tall al document. +@msg The cut lines do not enclose an area. Les línies de tall no tanquen cap àrea. +@msg A cut line ends without meeting another cut line. Una línia de tall acaba sense trobar cap altra línia de tall. +@msg A gap between cut lines was closed. S’ha tancat un buit entre línies de tall. +@msg The fold lines are too complex to check. Les línies de plegat són massa complexes per comprovar-les. +@msg A cut line and a crease lie on top of each other. Una línia de tall i una d’hendit estan superposades. +@msg Two lines of the same role lie on top of each other. Dues línies del mateix tipus estan superposades. +@msg A crease ends inside a panel. Una línia d’hendit acaba dins d’un panell. +@msg A crease does not divide two panels. Una línia d’hendit no separa dos panells. +@msg A crease lies outside the cut outline. Una línia d’hendit és fora del contorn de tall. +@msg A crease that is not straight is folded along one straight line. Una línia d’hendit que no és recta es plega al llarg d’una sola línia recta. +@msg A gap between cut lines is too narrow to tell apart. Un buit entre línies de tall és massa estret per distingir-lo. +@msg A cut-out area holds other fold lines. Una àrea retallada conté altres línies de plegat. +@msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. +@msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, hendits: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..299aa6cedc 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9742,3 +9742,22 @@ breakText Glyphs Glyfy No objects are selected. Nejsou vybrány žádné objekty. Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu. Remove Fold Line Role Odstranit typ linie + Check Zkontrolovat + Check Fold Lines Zkontrolovat linie skladu +@msg No cut lines are in the selection. Ve výběru nejsou žádné linie řezu. +@msg No cut lines are in the document. V dokumentu nejsou žádné linie řezu. +@msg The cut lines do not enclose an area. Linie řezu neohraničují žádnou plochu. +@msg A cut line ends without meeting another cut line. Linie řezu končí, aniž by se setkala s jinou linií řezu. +@msg A gap between cut lines was closed. Mezera mezi liniemi řezu byla uzavřena. +@msg The fold lines are too complex to check. Linie skladu jsou příliš složité na kontrolu. +@msg A cut line and a crease lie on top of each other. Linie řezu a linie bigu leží přes sebe. +@msg Two lines of the same role lie on top of each other. Dvě linie stejného typu leží přes sebe. +@msg A crease ends inside a panel. Linie bigu končí uvnitř panelu. +@msg A crease does not divide two panels. Linie bigu nerozděluje dva panely. +@msg A crease lies outside the cut outline. Linie bigu leží mimo obrys řezu. +@msg A crease that is not straight is folded along one straight line. Linie bigu, která není rovná, se ohýbá podél jedné přímky. +@msg A gap between cut lines is too narrow to tell apart. Mezera mezi liniemi řezu je příliš úzká na rozlišení. +@msg A cut-out area holds other fold lines. Vyříznutá oblast obsahuje další linie skladu. +@msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. +@msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, bigy: {hinges}, chyby: {errors}, upozornění: {warnings} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..647596237c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9844,4 +9844,23 @@ breakText Glyphs Glyffer No objects are selected. Ingen objekter er markeret. Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer. Remove Fold Line Role Fjern linjetype + Check Kontrollér + Check Fold Lines Kontrollér foldelinjer +@msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen. +@msg No cut lines are in the document. Der er ingen skærelinjer i dokumentet. +@msg The cut lines do not enclose an area. Skærelinjerne omslutter ikke et område. +@msg A cut line ends without meeting another cut line. En skærelinje slutter uden at møde en anden skærelinje. +@msg A gap between cut lines was closed. Et mellemrum mellem skærelinjer blev lukket. +@msg The fold lines are too complex to check. Foldelinjerne er for komplekse til at kontrollere. +@msg A cut line and a crease lie on top of each other. En skærelinje og en rillelinje ligger oven på hinanden. +@msg Two lines of the same role lie on top of each other. To linjer af samme type ligger oven på hinanden. +@msg A crease ends inside a panel. En rillelinje slutter inde i et panel. +@msg A crease does not divide two panels. En rillelinje deler ikke to paneler. +@msg A crease lies outside the cut outline. En rillelinje ligger uden for skærekonturen. +@msg A crease that is not straight is folded along one straight line. En rillelinje, der ikke er lige, foldes langs én ret linje. +@msg A gap between cut lines is too narrow to tell apart. Et mellemrum mellem skærelinjer er for smalt til at skelne. +@msg A cut-out area holds other fold lines. Et udskåret område indeholder andre foldelinjer. +@msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. +@msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, riller: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..4be132dc4f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9340,3 +9340,22 @@ breakText Glyphs Glyphen No objects are selected. Es sind keine Objekte ausgewählt. Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen. Remove Fold Line Role Linienart entfernen + Check Prüfen + Check Fold Lines Faltlinien prüfen +@msg No cut lines are in the selection. Die Auswahl enthält keine Schnittlinien. +@msg No cut lines are in the document. Das Dokument enthält keine Schnittlinien. +@msg The cut lines do not enclose an area. Die Schnittlinien umschließen keine Fläche. +@msg A cut line ends without meeting another cut line. Eine Schnittlinie endet, ohne auf eine andere Schnittlinie zu treffen. +@msg A gap between cut lines was closed. Eine Lücke zwischen Schnittlinien wurde geschlossen. +@msg The fold lines are too complex to check. Die Faltlinien sind zu komplex für die Prüfung. +@msg A cut line and a crease lie on top of each other. Eine Schnittlinie und eine Rilllinie liegen übereinander. +@msg Two lines of the same role lie on top of each other. Zwei Linien derselben Linienart liegen übereinander. +@msg A crease ends inside a panel. Eine Rilllinie endet innerhalb eines Felds. +@msg A crease does not divide two panels. Eine Rilllinie trennt keine zwei Felder. +@msg A crease lies outside the cut outline. Eine Rilllinie liegt außerhalb der Schnittkontur. +@msg A crease that is not straight is folded along one straight line. Eine nicht gerade Rilllinie wird entlang einer geraden Linie gefaltet. +@msg A gap between cut lines is too narrow to tell apart. Eine Lücke zwischen Schnittlinien ist zu schmal, um sie zu unterscheiden. +@msg A cut-out area holds other fold lines. Ein ausgeschnittener Bereich enthält weitere Faltlinien. +@msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. +@msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Rilllinien: {hinges}, Fehler: {errors}, Warnungen: {warnings} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..05c6a32103 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7919,4 +7919,23 @@ breakText Glyphs Γλύφοι No objects are selected. Δεν έχουν επιλεγεί αντικείμενα. Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής + Check Έλεγχος + Check Fold Lines Έλεγχος γραμμών δίπλωσης +@msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής. +@msg No cut lines are in the document. Το έγγραφο δεν περιέχει γραμμές κοπής. +@msg The cut lines do not enclose an area. Οι γραμμές κοπής δεν περικλείουν καμία περιοχή. +@msg A cut line ends without meeting another cut line. Μια γραμμή κοπής τελειώνει χωρίς να συναντήσει άλλη γραμμή κοπής. +@msg A gap between cut lines was closed. Ένα κενό ανάμεσα σε γραμμές κοπής κλείστηκε. +@msg The fold lines are too complex to check. Οι γραμμές δίπλωσης είναι πολύ σύνθετες για έλεγχο. +@msg A cut line and a crease lie on top of each other. Μια γραμμή κοπής και μια γραμμή πτύχωσης βρίσκονται η μία πάνω στην άλλη. +@msg Two lines of the same role lie on top of each other. Δύο γραμμές του ίδιου τύπου βρίσκονται η μία πάνω στην άλλη. +@msg A crease ends inside a panel. Μια γραμμή πτύχωσης τελειώνει μέσα σε ένα πάνελ. +@msg A crease does not divide two panels. Μια γραμμή πτύχωσης δεν χωρίζει δύο πάνελ. +@msg A crease lies outside the cut outline. Μια γραμμή πτύχωσης βρίσκεται έξω από το περίγραμμα κοπής. +@msg A crease that is not straight is folded along one straight line. Μια γραμμή πτύχωσης που δεν είναι ευθεία διπλώνεται κατά μήκος μίας ευθείας. +@msg A gap between cut lines is too narrow to tell apart. Ένα κενό ανάμεσα σε γραμμές κοπής είναι πολύ στενό για να διακριθεί. +@msg A cut-out area holds other fold lines. Μια αποκομμένη περιοχή περιέχει άλλες γραμμές δίπλωσης. +@msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. +@msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, πτυχώσεις: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..12e483f369 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7906,4 +7906,23 @@ breakText Glyphs Glifos No objects are selected. No hay objetos seleccionados. Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea + Check Comprobar + Check Fold Lines Comprobar líneas de plegado +@msg No cut lines are in the selection. No hay líneas de corte en la selección. +@msg No cut lines are in the document. No hay líneas de corte en el documento. +@msg The cut lines do not enclose an area. Las líneas de corte no encierran ningún área. +@msg A cut line ends without meeting another cut line. Una línea de corte termina sin llegar a otra línea de corte. +@msg A gap between cut lines was closed. Se cerró un hueco entre líneas de corte. +@msg The fold lines are too complex to check. Las líneas de plegado son demasiado complejas para comprobarlas. +@msg A cut line and a crease lie on top of each other. Una línea de corte y una de hendido están superpuestas. +@msg Two lines of the same role lie on top of each other. Dos líneas del mismo tipo están superpuestas. +@msg A crease ends inside a panel. Una línea de hendido termina dentro de un panel. +@msg A crease does not divide two panels. Una línea de hendido no separa dos paneles. +@msg A crease lies outside the cut outline. Una línea de hendido está fuera del contorno de corte. +@msg A crease that is not straight is folded along one straight line. Una línea de hendido que no es recta se pliega a lo largo de una sola línea recta. +@msg A gap between cut lines is too narrow to tell apart. Un hueco entre líneas de corte es demasiado estrecho para distinguirlo. +@msg A cut-out area holds other fold lines. Un área recortada contiene otras líneas de plegado. +@msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. +@msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, hendidos: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..db6163e7e3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8002,4 +8002,23 @@ breakText Glyphs Merkit No objects are selected. Objekteja ei ole valittu. Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi + Check Tarkista + Check Fold Lines Tarkista taittoviivat +@msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja. +@msg No cut lines are in the document. Asiakirjassa ei ole leikkausviivoja. +@msg The cut lines do not enclose an area. Leikkausviivat eivät rajaa aluetta. +@msg A cut line ends without meeting another cut line. Leikkausviiva päättyy kohtaamatta toista leikkausviivaa. +@msg A gap between cut lines was closed. Leikkausviivojen välinen rako suljettiin. +@msg The fold lines are too complex to check. Taittoviivat ovat liian monimutkaisia tarkistettaviksi. +@msg A cut line and a crease lie on top of each other. Leikkausviiva ja nuuttausviiva ovat päällekkäin. +@msg Two lines of the same role lie on top of each other. Kaksi samantyyppistä viivaa on päällekkäin. +@msg A crease ends inside a panel. Nuuttausviiva päättyy paneelin sisään. +@msg A crease does not divide two panels. Nuuttausviiva ei jaa kahta paneelia. +@msg A crease lies outside the cut outline. Nuuttausviiva on leikkausääriviivan ulkopuolella. +@msg A crease that is not straight is folded along one straight line. Nuuttausviiva, joka ei ole suora, taitetaan yhtä suoraa viivaa pitkin. +@msg A gap between cut lines is too narrow to tell apart. Leikkausviivojen välinen rako on liian kapea erotettavaksi. +@msg A cut-out area holds other fold lines. Leikattu alue sisältää muita taittoviivoja. +@msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. +@msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, nuuttaukset: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..7ae0eab9c6 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9727,4 +9727,23 @@ breakText Glyphs Glyphes No objects are selected. Aucun objet n’est sélectionné. Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage. Remove Fold Line Role Supprimer le type de ligne + Check Vérifier + Check Fold Lines Vérifier les lignes de pliage +@msg No cut lines are in the selection. La sélection ne contient aucune ligne de découpe. +@msg No cut lines are in the document. Le document ne contient aucune ligne de découpe. +@msg The cut lines do not enclose an area. Les lignes de découpe n’entourent aucune zone. +@msg A cut line ends without meeting another cut line. Une ligne de découpe se termine sans rejoindre une autre ligne de découpe. +@msg A gap between cut lines was closed. Un écart entre des lignes de découpe a été fermé. +@msg The fold lines are too complex to check. Les lignes de pliage sont trop complexes pour être vérifiées. +@msg A cut line and a crease lie on top of each other. Une ligne de découpe et une ligne de rainage se superposent. +@msg Two lines of the same role lie on top of each other. Deux lignes du même type se superposent. +@msg A crease ends inside a panel. Une ligne de rainage se termine à l’intérieur d’un panneau. +@msg A crease does not divide two panels. Une ligne de rainage ne sépare pas deux panneaux. +@msg A crease lies outside the cut outline. Une ligne de rainage se trouve hors du contour de découpe. +@msg A crease that is not straight is folded along one straight line. Une ligne de rainage qui n’est pas droite est pliée le long d’une seule ligne droite. +@msg A gap between cut lines is too narrow to tell apart. Un écart entre des lignes de découpe est trop étroit pour être distingué. +@msg A cut-out area holds other fold lines. Une zone découpée contient d’autres lignes de pliage. +@msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. +@msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} rainage(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..d7b10bf7c0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4846,6 +4846,25 @@ swatch [Registration] [રજિસ્ટ્રેશન] No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી. Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો. Remove Fold Line Role લાઇન પ્રકાર દૂર કરો + Check ચેક કરો + Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો +@msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી. +@msg No cut lines are in the document. ડૉક્યુમેન્ટમાં કોઈ કટ લાઇન નથી. +@msg The cut lines do not enclose an area. કટ લાઇન્સ કોઈ વિસ્તાર ઘેરતી નથી. +@msg A cut line ends without meeting another cut line. એક કટ લાઇન બીજી કટ લાઇનને મળ્યા વિના પૂરી થાય છે. +@msg A gap between cut lines was closed. કટ લાઇન્સ વચ્ચેનો ગેપ બંધ કરવામાં આવ્યો. +@msg The fold lines are too complex to check. ફોલ્ડ લાઇન્સ ચેક કરવા માટે ખૂબ જટિલ છે. +@msg A cut line and a crease lie on top of each other. એક કટ લાઇન અને એક ક્રીઝ લાઇન એકબીજા પર છે. +@msg Two lines of the same role lie on top of each other. એક જ પ્રકારની બે લાઇન્સ એકબીજા પર છે. +@msg A crease ends inside a panel. એક ક્રીઝ લાઇન પેનલની અંદર પૂરી થાય છે. +@msg A crease does not divide two panels. એક ક્રીઝ લાઇન બે પેનલને અલગ કરતી નથી. +@msg A crease lies outside the cut outline. એક ક્રીઝ લાઇન કટ આઉટલાઇનની બહાર છે. +@msg A crease that is not straight is folded along one straight line. સીધી ન હોય તેવી ક્રીઝ લાઇન એક સીધી લાઇન પર ફોલ્ડ થાય છે. +@msg A gap between cut lines is too narrow to tell apart. કટ લાઇન્સ વચ્ચેનો ગેપ ઓળખવા માટે ખૂબ સાંકડો છે. +@msg A cut-out area holds other fold lines. એક કટ-આઉટ વિસ્તારમાં બીજી ફોલ્ડ લાઇન્સ છે. +@msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. +@msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, ક્રીઝ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..f632881023 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9347,3 +9347,22 @@ theme Appearance अपीयरेंस No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है। Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें। Remove Fold Line Role लाइन प्रकार हटाएँ + Check चेक करें + Check Fold Lines फ़ोल्ड लाइनें चेक करें +@msg No cut lines are in the selection. सिलेक्शन में कोई कट लाइन नहीं है। +@msg No cut lines are in the document. डॉक्यूमेंट में कोई कट लाइन नहीं है। +@msg The cut lines do not enclose an area. कट लाइनें कोई एरिया नहीं घेरतीं। +@msg A cut line ends without meeting another cut line. एक कट लाइन किसी दूसरी कट लाइन से मिले बिना खत्म हो जाती है। +@msg A gap between cut lines was closed. कट लाइनों के बीच का गैप बंद कर दिया गया। +@msg The fold lines are too complex to check. फ़ोल्ड लाइनें चेक करने के लिए बहुत जटिल हैं। +@msg A cut line and a crease lie on top of each other. एक कट लाइन और एक क्रीज़ लाइन एक-दूसरे के ऊपर हैं। +@msg Two lines of the same role lie on top of each other. एक ही प्रकार की दो लाइनें एक-दूसरे के ऊपर हैं। +@msg A crease ends inside a panel. एक क्रीज़ लाइन किसी पैनल के अंदर खत्म होती है। +@msg A crease does not divide two panels. एक क्रीज़ लाइन दो पैनलों को अलग नहीं करती। +@msg A crease lies outside the cut outline. एक क्रीज़ लाइन कट आउटलाइन के बाहर है। +@msg A crease that is not straight is folded along one straight line. जो क्रीज़ लाइन सीधी नहीं है, वह एक सीधी लाइन पर फ़ोल्ड होती है। +@msg A gap between cut lines is too narrow to tell apart. कट लाइनों के बीच का गैप पहचानने के लिए बहुत पतला है। +@msg A cut-out area holds other fold lines. एक कट-आउट एरिया में दूसरी फ़ोल्ड लाइनें हैं। +@msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। +@msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, क्रीज़: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..5ecfe58e72 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9730,3 +9730,22 @@ breakText Glyphs Glifák No objects are selected. Nincs kijelölt objektum. Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez. Remove Fold Line Role Vonaltípus eltávolítása + Check Ellenőrzés + Check Fold Lines Hajtásvonalak ellenőrzése +@msg No cut lines are in the selection. A kijelölésben nincs vágóvonal. +@msg No cut lines are in the document. A dokumentumban nincs vágóvonal. +@msg The cut lines do not enclose an area. A vágóvonalak nem zárnak közre területet. +@msg A cut line ends without meeting another cut line. Egy vágóvonal úgy ér véget, hogy nem találkozik másik vágóvonallal. +@msg A gap between cut lines was closed. A vágóvonalak közötti rés le lett zárva. +@msg The fold lines are too complex to check. A hajtásvonalak túl összetettek az ellenőrzéshez. +@msg A cut line and a crease lie on top of each other. Egy vágóvonal és egy bigvonal egymáson fekszik. +@msg Two lines of the same role lie on top of each other. Két azonos típusú vonal egymáson fekszik. +@msg A crease ends inside a panel. Egy bigvonal egy panelen belül ér véget. +@msg A crease does not divide two panels. Egy bigvonal nem választ el két panelt. +@msg A crease lies outside the cut outline. Egy bigvonal a vágási körvonalon kívül van. +@msg A crease that is not straight is folded along one straight line. Egy nem egyenes bigvonal egyetlen egyenes mentén hajlik. +@msg A gap between cut lines is too narrow to tell apart. A vágóvonalak közötti rés túl keskeny a megkülönböztetéshez. +@msg A cut-out area holds other fold lines. Egy kivágott terület további hajtásvonalakat tartalmaz. +@msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. +@msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, bigek: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..cd2ad82864 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7099,4 +7099,23 @@ breakText Glyphs Glif No objects are selected. Tidak ada objek yang dipilih. Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya. Remove Fold Line Role Hapus jenis garis + Check Periksa + Check Fold Lines Periksa garis lipat +@msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi. +@msg No cut lines are in the document. Tidak ada garis potong dalam dokumen. +@msg The cut lines do not enclose an area. Garis potong tidak melingkupi area apa pun. +@msg A cut line ends without meeting another cut line. Sebuah garis potong berakhir tanpa bertemu garis potong lain. +@msg A gap between cut lines was closed. Celah di antara garis potong telah ditutup. +@msg The fold lines are too complex to check. Garis lipat terlalu rumit untuk diperiksa. +@msg A cut line and a crease lie on top of each other. Sebuah garis potong dan sebuah garis lekuk bertumpuk. +@msg Two lines of the same role lie on top of each other. Dua garis dengan jenis yang sama bertumpuk. +@msg A crease ends inside a panel. Sebuah garis lekuk berakhir di dalam panel. +@msg A crease does not divide two panels. Sebuah garis lekuk tidak membagi dua panel. +@msg A crease lies outside the cut outline. Sebuah garis lekuk berada di luar kontur potong. +@msg A crease that is not straight is folded along one straight line. Garis lekuk yang tidak lurus dilipat di sepanjang satu garis lurus. +@msg A gap between cut lines is too narrow to tell apart. Celah di antara garis potong terlalu sempit untuk dibedakan. +@msg A cut-out area holds other fold lines. Area yang dipotong berisi garis lipat lain. +@msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. +@msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, lekuk: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..b34cf145a7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9374,3 +9374,22 @@ breakText Glyphs Glifi No objects are selected. Nessun oggetto selezionato. Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega. Remove Fold Line Role Rimuovi tipo di linea + Check Verifica + Check Fold Lines Verifica linee di piega +@msg No cut lines are in the selection. Nella selezione non ci sono linee di taglio. +@msg No cut lines are in the document. Nel documento non ci sono linee di taglio. +@msg The cut lines do not enclose an area. Le linee di taglio non racchiudono alcuna area. +@msg A cut line ends without meeting another cut line. Una linea di taglio termina senza incontrare un’altra linea di taglio. +@msg A gap between cut lines was closed. È stato chiuso uno spazio tra linee di taglio. +@msg The fold lines are too complex to check. Le linee di piega sono troppo complesse da verificare. +@msg A cut line and a crease lie on top of each other. Una linea di taglio e una di cordonatura sono sovrapposte. +@msg Two lines of the same role lie on top of each other. Due linee dello stesso tipo sono sovrapposte. +@msg A crease ends inside a panel. Una linea di cordonatura termina all’interno di un pannello. +@msg A crease does not divide two panels. Una linea di cordonatura non divide due pannelli. +@msg A crease lies outside the cut outline. Una linea di cordonatura si trova fuori dal contorno di taglio. +@msg A crease that is not straight is folded along one straight line. Una linea di cordonatura non diritta viene piegata lungo un’unica linea retta. +@msg A gap between cut lines is too narrow to tell apart. Uno spazio tra linee di taglio è troppo stretto per essere distinto. +@msg A cut-out area holds other fold lines. Un’area ritagliata contiene altre linee di piega. +@msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. +@msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cordonature: {hinges}, errori: {errors}, avvisi: {warnings} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..a224dec9f0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9441,3 +9441,22 @@ breakText Glyphs 字形 No objects are selected. オブジェクトが選択されていません。 Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。 Remove Fold Line Role 線種を解除 + Check チェック + Check Fold Lines 折り線をチェック +@msg No cut lines are in the selection. 選択範囲にカット線がありません。 +@msg No cut lines are in the document. ドキュメントにカット線がありません。 +@msg The cut lines do not enclose an area. カット線が領域を囲んでいません。 +@msg A cut line ends without meeting another cut line. カット線が他のカット線と接しないまま終わっています。 +@msg A gap between cut lines was closed. カット線間の隙間を閉じました。 +@msg The fold lines are too complex to check. 折り線が複雑すぎるためチェックできません。 +@msg A cut line and a crease lie on top of each other. カット線と筋入れ線が重なっています。 +@msg Two lines of the same role lie on top of each other. 同じ種類の線が 2 本重なっています。 +@msg A crease ends inside a panel. 筋入れ線がパネルの内側で終わっています。 +@msg A crease does not divide two panels. 筋入れ線が 2 つのパネルを分けていません。 +@msg A crease lies outside the cut outline. 筋入れ線がカットの輪郭の外側にあります。 +@msg A crease that is not straight is folded along one straight line. まっすぐでない筋入れ線は 1 本の直線に沿って折られます。 +@msg A gap between cut lines is too narrow to tell apart. カット線間の隙間が狭すぎて区別できません。 +@msg A cut-out area holds other fold lines. 切り抜かれた領域に他の折り線があります。 +@msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 +@msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、筋入れ: {hinges}、エラー: {errors}、警告: {warnings} diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..406a43c301 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10010,4 +10010,23 @@ font-script Japanese იაპონური No objects are selected. ობიექტები არ არის მონიშნული. Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მოსანიშნად. Remove Fold Line Role ხაზის ტიპის მოხსნა + Check შემოწმება + Check Fold Lines მოკეცვის ხაზების შემოწმება +@msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის. +@msg No cut lines are in the document. დოკუმენტში ჭრის ხაზები არ არის. +@msg The cut lines do not enclose an area. ჭრის ხაზები არცერთ არეს არ შემოფარგლავს. +@msg A cut line ends without meeting another cut line. ჭრის ხაზი მთავრდება ისე, რომ სხვა ჭრის ხაზს არ ხვდება. +@msg A gap between cut lines was closed. ჭრის ხაზებს შორის ღრეჩო დაიხურა. +@msg The fold lines are too complex to check. მოკეცვის ხაზები შესამოწმებლად ზედმეტად რთულია. +@msg A cut line and a crease lie on top of each other. ჭრის ხაზი და ბიგის ხაზი ერთმანეთზე დევს. +@msg Two lines of the same role lie on top of each other. ერთი ტიპის ორი ხაზი ერთმანეთზე დევს. +@msg A crease ends inside a panel. ბიგის ხაზი პანელის შიგნით მთავრდება. +@msg A crease does not divide two panels. ბიგის ხაზი ორ პანელს არ ყოფს. +@msg A crease lies outside the cut outline. ბიგის ხაზი ჭრის კონტურის გარეთაა. +@msg A crease that is not straight is folded along one straight line. ბიგის ხაზი, რომელიც სწორი არ არის, ერთი სწორი ხაზის გასწვრივ იკეცება. +@msg A gap between cut lines is too narrow to tell apart. ჭრის ხაზებს შორის ღრეჩო ზედმეტად ვიწროა გასარჩევად. +@msg A cut-out area holds other fold lines. ამოჭრილი არე სხვა მოკეცვის ხაზებს შეიცავს. +@msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. +@msg A fold line is on a non-printing layer. მოკეცვის ხაზი არასაბეჭდ შრეზეა. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ბიგები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..219bd8aa76 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9337,3 +9337,22 @@ breakText Glyphs 글리프 No objects are selected. 선택한 개체가 없습니다. Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요. Remove Fold Line Role 선 종류 제거 + Check 검사 + Check Fold Lines 접는 선 검사 +@msg No cut lines are in the selection. 선택 영역에 재단선이 없습니다. +@msg No cut lines are in the document. 문서에 재단선이 없습니다. +@msg The cut lines do not enclose an area. 재단선이 영역을 둘러싸지 않습니다. +@msg A cut line ends without meeting another cut line. 재단선이 다른 재단선과 만나지 않고 끝납니다. +@msg A gap between cut lines was closed. 재단선 사이의 틈을 닫았습니다. +@msg The fold lines are too complex to check. 접는 선이 너무 복잡해서 검사할 수 없습니다. +@msg A cut line and a crease lie on top of each other. 재단선과 오시선이 겹쳐 있습니다. +@msg Two lines of the same role lie on top of each other. 같은 종류의 선 두 개가 겹쳐 있습니다. +@msg A crease ends inside a panel. 오시선이 패널 안에서 끝납니다. +@msg A crease does not divide two panels. 오시선이 두 패널을 나누지 않습니다. +@msg A crease lies outside the cut outline. 오시선이 재단 윤곽선 밖에 있습니다. +@msg A crease that is not straight is folded along one straight line. 곧지 않은 오시선은 하나의 직선을 따라 접힙니다. +@msg A gap between cut lines is too narrow to tell apart. 재단선 사이의 틈이 너무 좁아 구별할 수 없습니다. +@msg A cut-out area holds other fold lines. 잘라 낸 영역에 다른 접는 선이 있습니다. +@msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. +@msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 오시: {hinges}, 오류: {errors}, 경고: {warnings} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..62c2566f13 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9775,3 +9775,22 @@ breakText Glyphs Glyphs No objects are selected. Er zijn geen objecten geselecteerd. Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren. Remove Fold Line Role Lijnsoort verwijderen + Check Controleren + Check Fold Lines Vouwlijnen controleren +@msg No cut lines are in the selection. De selectie bevat geen snijlijnen. +@msg No cut lines are in the document. Het document bevat geen snijlijnen. +@msg The cut lines do not enclose an area. De snijlijnen sluiten geen gebied in. +@msg A cut line ends without meeting another cut line. Een snijlijn eindigt zonder een andere snijlijn te raken. +@msg A gap between cut lines was closed. Een opening tussen snijlijnen is gesloten. +@msg The fold lines are too complex to check. De vouwlijnen zijn te complex om te controleren. +@msg A cut line and a crease lie on top of each other. Een snijlijn en een rillijn liggen over elkaar. +@msg Two lines of the same role lie on top of each other. Twee lijnen van dezelfde soort liggen over elkaar. +@msg A crease ends inside a panel. Een rillijn eindigt binnen een paneel. +@msg A crease does not divide two panels. Een rillijn verdeelt geen twee panelen. +@msg A crease lies outside the cut outline. Een rillijn ligt buiten de snijcontour. +@msg A crease that is not straight is folded along one straight line. Een rillijn die niet recht is, wordt langs één rechte lijn gevouwen. +@msg A gap between cut lines is too narrow to tell apart. Een opening tussen snijlijnen is te smal om te onderscheiden. +@msg A cut-out area holds other fold lines. Een uitgesneden gebied bevat andere vouwlijnen. +@msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. +@msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, rillijnen: {hinges}, fouten: {errors}, waarschuwingen: {warnings} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..587884f787 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9595,3 +9595,22 @@ breakText Glyphs Glify No objects are selected. Nie zaznaczono żadnych obiektów. Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia. Remove Fold Line Role Usuń rodzaj linii + Check Sprawdź + Check Fold Lines Sprawdź linie zgięcia +@msg No cut lines are in the selection. W zaznaczeniu nie ma linii cięcia. +@msg No cut lines are in the document. W dokumencie nie ma linii cięcia. +@msg The cut lines do not enclose an area. Linie cięcia nie obejmują żadnego obszaru. +@msg A cut line ends without meeting another cut line. Linia cięcia kończy się, nie stykając się z inną linią cięcia. +@msg A gap between cut lines was closed. Zamknięto przerwę między liniami cięcia. +@msg The fold lines are too complex to check. Linie zgięcia są zbyt złożone, aby je sprawdzić. +@msg A cut line and a crease lie on top of each other. Linia cięcia i linia bigowania leżą na sobie. +@msg Two lines of the same role lie on top of each other. Dwie linie tego samego rodzaju leżą na sobie. +@msg A crease ends inside a panel. Linia bigowania kończy się wewnątrz panelu. +@msg A crease does not divide two panels. Linia bigowania nie rozdziela dwóch paneli. +@msg A crease lies outside the cut outline. Linia bigowania leży poza konturem cięcia. +@msg A crease that is not straight is folded along one straight line. Linia bigowania, która nie jest prosta, jest zginana wzdłuż jednej linii prostej. +@msg A gap between cut lines is too narrow to tell apart. Przerwa między liniami cięcia jest zbyt wąska, aby ją rozróżnić. +@msg A cut-out area holds other fold lines. Wycięty obszar zawiera inne linie zgięcia. +@msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. +@msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, bigi: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..4e1f704ec8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9813,3 +9813,22 @@ swatch Yellow Green Verde-amarelado No objects are selected. Nenhum objeto selecionado. Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra. Remove Fold Line Role Remover Tipo de Linha + Check Verificar + Check Fold Lines Verificar Linhas de Dobra +@msg No cut lines are in the selection. Não há linhas de corte na seleção. +@msg No cut lines are in the document. Não há linhas de corte no documento. +@msg The cut lines do not enclose an area. As linhas de corte não delimitam nenhuma área. +@msg A cut line ends without meeting another cut line. Uma linha de corte termina sem encontrar outra linha de corte. +@msg A gap between cut lines was closed. Uma lacuna entre linhas de corte foi fechada. +@msg The fold lines are too complex to check. As linhas de dobra são complexas demais para verificar. +@msg A cut line and a crease lie on top of each other. Uma linha de corte e uma de vinco estão sobrepostas. +@msg Two lines of the same role lie on top of each other. Duas linhas do mesmo tipo estão sobrepostas. +@msg A crease ends inside a panel. Uma linha de vinco termina dentro de um painel. +@msg A crease does not divide two panels. Uma linha de vinco não divide dois painéis. +@msg A crease lies outside the cut outline. Uma linha de vinco está fora do contorno de corte. +@msg A crease that is not straight is folded along one straight line. Uma linha de vinco que não é reta é dobrada ao longo de uma única linha reta. +@msg A gap between cut lines is too narrow to tell apart. Uma lacuna entre linhas de corte é estreita demais para ser distinguida. +@msg A cut-out area holds other fold lines. Uma área recortada contém outras linhas de dobra. +@msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. +@msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, vincos: {hinges}, erros: {errors}, avisos: {warnings} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..2c6dec01d4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9834,5 +9834,24 @@ shape Open Открытый No objects are selected. Объекты не выделены. Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба. Remove Fold Line Role Убрать тип линии + Check Проверить + Check Fold Lines Проверить линии сгиба +@msg No cut lines are in the selection. В выделении нет линий реза. +@msg No cut lines are in the document. В документе нет линий реза. +@msg The cut lines do not enclose an area. Линии реза не ограничивают никакую область. +@msg A cut line ends without meeting another cut line. Линия реза заканчивается, не встречая другую линию реза. +@msg A gap between cut lines was closed. Зазор между линиями реза закрыт. +@msg The fold lines are too complex to check. Линии сгиба слишком сложны для проверки. +@msg A cut line and a crease lie on top of each other. Линия реза и линия биговки лежат друг на друге. +@msg Two lines of the same role lie on top of each other. Две линии одного типа лежат друг на друге. +@msg A crease ends inside a panel. Линия биговки заканчивается внутри панели. +@msg A crease does not divide two panels. Линия биговки не разделяет две панели. +@msg A crease lies outside the cut outline. Линия биговки лежит за пределами контура реза. +@msg A crease that is not straight is folded along one straight line. Непрямая линия биговки сгибается по одной прямой. +@msg A gap between cut lines is too narrow to tell apart. Зазор между линиями реза слишком узок, чтобы его различить. +@msg A cut-out area holds other fold lines. Вырезанная область содержит другие линии сгиба. +@msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. +@msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, биговки: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..c0ac175345 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9425,4 +9425,23 @@ digits Hindi Hindi No objects are selected. Inga objekt är markerade. Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer. Remove Fold Line Role Ta bort linjetyp + Check Kontrollera + Check Fold Lines Kontrollera falslinjer +@msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen. +@msg No cut lines are in the document. Det finns inga skärlinjer i dokumentet. +@msg The cut lines do not enclose an area. Skärlinjerna omsluter inget område. +@msg A cut line ends without meeting another cut line. En skärlinje slutar utan att möta en annan skärlinje. +@msg A gap between cut lines was closed. Ett mellanrum mellan skärlinjer stängdes. +@msg The fold lines are too complex to check. Falslinjerna är för komplexa för att kontrollera. +@msg A cut line and a crease lie on top of each other. En skärlinje och en biglinje ligger ovanpå varandra. +@msg Two lines of the same role lie on top of each other. Två linjer av samma typ ligger ovanpå varandra. +@msg A crease ends inside a panel. En biglinje slutar inuti en panel. +@msg A crease does not divide two panels. En biglinje delar inte två paneler. +@msg A crease lies outside the cut outline. En biglinje ligger utanför skärkonturen. +@msg A crease that is not straight is folded along one straight line. En biglinje som inte är rak falsas längs en rak linje. +@msg A gap between cut lines is too narrow to tell apart. Ett mellanrum mellan skärlinjer är för smalt för att skilja ut. +@msg A cut-out area holds other fold lines. Ett utskuret område innehåller andra falslinjer. +@msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. +@msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, bigningar: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..6dded8c1d7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9696,3 +9696,22 @@ breakText Glyphs Glifler No objects are selected. Hiçbir nesne seçili değil. Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın. Remove Fold Line Role Çizgi Türünü Kaldır + Check Denetle + Check Fold Lines Katlama Çizgilerini Denetle +@msg No cut lines are in the selection. Seçimde kesim çizgisi yok. +@msg No cut lines are in the document. Belgede kesim çizgisi yok. +@msg The cut lines do not enclose an area. Kesim çizgileri bir alanı çevrelemiyor. +@msg A cut line ends without meeting another cut line. Bir kesim çizgisi başka bir kesim çizgisiyle buluşmadan bitiyor. +@msg A gap between cut lines was closed. Kesim çizgileri arasındaki bir boşluk kapatıldı. +@msg The fold lines are too complex to check. Katlama çizgileri denetlenemeyecek kadar karmaşık. +@msg A cut line and a crease lie on top of each other. Bir kesim çizgisi ile bir pilyaj çizgisi üst üste. +@msg Two lines of the same role lie on top of each other. Aynı türden iki çizgi üst üste. +@msg A crease ends inside a panel. Bir pilyaj çizgisi bir panelin içinde bitiyor. +@msg A crease does not divide two panels. Bir pilyaj çizgisi iki paneli ayırmıyor. +@msg A crease lies outside the cut outline. Bir pilyaj çizgisi kesim konturunun dışında. +@msg A crease that is not straight is folded along one straight line. Düz olmayan bir pilyaj çizgisi tek bir düz çizgi boyunca katlanır. +@msg A gap between cut lines is too narrow to tell apart. Kesim çizgileri arasındaki bir boşluk ayırt edilemeyecek kadar dar. +@msg A cut-out area holds other fold lines. Kesilip çıkarılmış bir alan başka katlama çizgileri içeriyor. +@msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. +@msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, pilyajlar: {hinges}, hatalar: {errors}, uyarılar: {warnings} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..84eb22f968 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9349,3 +9349,22 @@ breakText Glyphs Гліфи No objects are selected. Об’єкти не виділено. Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину. Remove Fold Line Role Прибрати тип лінії + Check Перевірити + Check Fold Lines Перевірити лінії згину +@msg No cut lines are in the selection. У виділенні немає ліній різу. +@msg No cut lines are in the document. У документі немає ліній різу. +@msg The cut lines do not enclose an area. Лінії різу не обмежують жодної області. +@msg A cut line ends without meeting another cut line. Лінія різу закінчується, не зустрівши іншої лінії різу. +@msg A gap between cut lines was closed. Зазор між лініями різу закрито. +@msg The fold lines are too complex to check. Лінії згину надто складні для перевірки. +@msg A cut line and a crease lie on top of each other. Лінія різу та лінія біговки лежать одна на одній. +@msg Two lines of the same role lie on top of each other. Дві лінії одного типу лежать одна на одній. +@msg A crease ends inside a panel. Лінія біговки закінчується всередині панелі. +@msg A crease does not divide two panels. Лінія біговки не розділяє двох панелей. +@msg A crease lies outside the cut outline. Лінія біговки лежить поза контуром різу. +@msg A crease that is not straight is folded along one straight line. Непряма лінія біговки згинається вздовж однієї прямої. +@msg A gap between cut lines is too narrow to tell apart. Зазор між лініями різу надто вузький, щоб його розрізнити. +@msg A cut-out area holds other fold lines. Вирізана область містить інші лінії згину. +@msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. +@msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, біговки: {hinges}, помилки: {errors}, попередження: {warnings} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..00ac3f7289 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7459,6 +7459,25 @@ breakText Glyphs Glyph No objects are selected. Không có đối tượng nào được chọn. Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó. Remove Fold Line Role Bỏ loại đường + Check Kiểm tra + Check Fold Lines Kiểm tra đường gấp +@msg No cut lines are in the selection. Vùng chọn không có đường cắt nào. +@msg No cut lines are in the document. Tài liệu không có đường cắt nào. +@msg The cut lines do not enclose an area. Các đường cắt không bao quanh vùng nào. +@msg A cut line ends without meeting another cut line. Một đường cắt kết thúc mà không gặp đường cắt khác. +@msg A gap between cut lines was closed. Đã đóng một khe hở giữa các đường cắt. +@msg The fold lines are too complex to check. Các đường gấp quá phức tạp để kiểm tra. +@msg A cut line and a crease lie on top of each other. Một đường cắt và một đường cấn nằm chồng lên nhau. +@msg Two lines of the same role lie on top of each other. Hai đường cùng loại nằm chồng lên nhau. +@msg A crease ends inside a panel. Một đường cấn kết thúc bên trong một mặt. +@msg A crease does not divide two panels. Một đường cấn không chia tách hai mặt. +@msg A crease lies outside the cut outline. Một đường cấn nằm ngoài đường viền cắt. +@msg A crease that is not straight is folded along one straight line. Đường cấn không thẳng được gấp theo một đường thẳng. +@msg A gap between cut lines is too narrow to tell apart. Khe hở giữa các đường cắt quá hẹp để phân biệt. +@msg A cut-out area holds other fold lines. Một vùng bị cắt bỏ chứa các đường gấp khác. +@msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. +@msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, đường cấn: {hinges}, lỗi: {errors}, cảnh báo: {warnings} # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..40f821ffe4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9580,4 +9580,23 @@ breakText Glyphs 字形 No objects are selected. 未选择任何对象。 Open a document to mark its fold lines. 打开文档以标记其折线。 Remove Fold Line Role 移除线条类型 + Check 检查 + Check Fold Lines 检查折线 +@msg No cut lines are in the selection. 所选内容中没有切割线。 +@msg No cut lines are in the document. 文档中没有切割线。 +@msg The cut lines do not enclose an area. 切割线未围成任何区域。 +@msg A cut line ends without meeting another cut line. 一条切割线未与其他切割线相接就结束了。 +@msg A gap between cut lines was closed. 已闭合切割线之间的间隙。 +@msg The fold lines are too complex to check. 折线过于复杂,无法检查。 +@msg A cut line and a crease lie on top of each other. 一条切割线与一条压痕线重叠。 +@msg Two lines of the same role lie on top of each other. 两条同类线条重叠。 +@msg A crease ends inside a panel. 一条压痕线在面板内部结束。 +@msg A crease does not divide two panels. 一条压痕线没有分隔两个面板。 +@msg A crease lies outside the cut outline. 一条压痕线位于切割轮廓之外。 +@msg A crease that is not straight is folded along one straight line. 不直的压痕线沿一条直线折叠。 +@msg A gap between cut lines is too narrow to tell apart. 切割线之间的间隙太窄,无法区分。 +@msg A cut-out area holds other fold lines. 一个镂空区域包含其他折线。 +@msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 +@msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},压痕:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..434723a718 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9390,4 +9390,23 @@ breakText Glyphs 字符 No objects are selected. 未選取任何物件。 Open a document to mark its fold lines. 開啟文件以標記其摺線。 Remove Fold Line Role 移除線條類型 + Check 檢查 + Check Fold Lines 檢查摺線 +@msg No cut lines are in the selection. 選取範圍中沒有切割線。 +@msg No cut lines are in the document. 文件中沒有切割線。 +@msg The cut lines do not enclose an area. 切割線未圍成任何區域。 +@msg A cut line ends without meeting another cut line. 一條切割線未與其他切割線相接就結束了。 +@msg A gap between cut lines was closed. 已封閉切割線之間的間隙。 +@msg The fold lines are too complex to check. 摺線過於複雜,無法檢查。 +@msg A cut line and a crease lie on top of each other. 一條切割線與一條壓痕線重疊。 +@msg Two lines of the same role lie on top of each other. 兩條同類線條重疊。 +@msg A crease ends inside a panel. 一條壓痕線在面板內部結束。 +@msg A crease does not divide two panels. 一條壓痕線沒有分隔兩個面板。 +@msg A crease lies outside the cut outline. 一條壓痕線位於切割輪廓之外。 +@msg A crease that is not straight is folded along one straight line. 不直的壓痕線沿一條直線摺疊。 +@msg A gap between cut lines is too narrow to tell apart. 切割線之間的間隙太窄,無法區分。 +@msg A cut-out area holds other fold lines. 一個鏤空區域包含其他摺線。 +@msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 +@msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 +@msg Panels: {panels}, creases: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},壓痕:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3e48476a1a..845ea7102a 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -195,6 +195,11 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) { } return; } + // Check Fold Lines shows its summary and lists its issues in the Fold Lines panel. + if id == crate::addons::packaging::CHECK { + crate::addons::packaging::check(app, p); + return; + } // A Paste the user gives decodes a bitmap off the UI thread ([`crate::placing::adopt_for_paste`]). app.placing.for_user = id.starts_with("edit.paste"); let r = app.run(id, p); diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..e552ec49b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13033,9 +13033,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles` and `addon.packaging.setRoleSwatch`. In the desktop app, Object › -Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, and Make Cut Line, Make Crease Line, Make Partial Cut -Line and Make Perforation Line run `addon.packaging.setRole` on the selection. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the +desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, +Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs +`addon.packaging.check`. ### Fold line roles @@ -13082,6 +13083,55 @@ panel's menu opens it as Role Swatches…. {"name":"run_command","arguments":{"command":"addon.packaging.setRole","params":{"role":"crease"}}} ``` +### Check Fold Lines + +`addon.packaging.check` (`{ids?, select?: false, tolerance?: 0.1}`) finds the blanks, panels and hinges that the fold +lines make and lists what is wrong with them. It checks the fold lines among the objects (the selection by default), +through groups and clip groups, or every fold line of the document that is shown while nothing is selected and `ids` is +left out. `tolerance` is in points, from 0.01 to 10; a value outside that range, or one that is not a number or a length +such as `"2 mm"`, is an error. The command does not change the document and records no undo step. + +- Cut lines bound the material. Each connected piece of cut lines that encloses material is one blank. Its outline is its + largest closed cut line, and a closed cut line inside the outline is a hole, so a slot drawn as a rectangle across the + outline leaves the same material as a notch drawn in it. Open cut lines that meet end to end count as one closed cut + line, so an outline or a slot drawn as several open cut lines works as well. +- Crease, Partial Cut and Perforation lines divide a blank into panels. The pieces of them that lie between the same two + panels form one hinge. +- The end of a cut line that comes within `tolerance` of another cut line is joined to it with a short line, and the + check reports the gap. + +The issues come in this order. `noCut`, `open`, `looseEnd`, `tooComplex` and `cutOverCrease` are errors; the others are +warnings. + +| Code | Reported when | +|---|---| +| `noCut` | No cut line is among the objects. | +| `open` | The cut lines enclose no area. | +| `looseEnd` | An end of a cut line meets no other fold line within `tolerance`, and no gap is closed at it. `at` is the end. | +| `gap` | An end of a cut line lies within `tolerance` of another cut line without touching it; the panels are built with the gap closed. `at` is the end. | +| `tooComplex` | The lines have more than 65,536 segments, or a blank has more than 256 panels. | +| `cutOverCrease` | A cut line and a crease, partial cut or perforation lie on top of each other. | +| `duplicate` | Two lines of the same role, or two subpaths of one line, lie on top of each other. | +| `danglingCrease` | A crease ends inside a panel. | +| `noSplit` | A crease divides no two panels. | +| `outside` | A crease lies outside every blank. | +| `notStraight` | The pieces of a hinge are not on one straight line within `tolerance`; it folds along the line through its longest piece. | +| `sliver` | A gap between lines inside a blank is narrower than 0.01 pt. | +| `ambiguous` | A hole holds creases, or a blank lies inside another blank's hole. | +| `loosePanel` | A panel is joined to its blank's largest panel by no chain of hinges. | +| `nonPrinting` | A fold line is on a layer that does not print. | + +Result: `{ok, blanks, panels, hinges, holes, issues: [{severity, code, message, ids, at?}], scope}`. `ok` is true when +no issue is an error. `message` is in English, and the Fold Lines panel shows it in the interface language. `ids` names +the objects each issue is about. With `select: true`, those objects become the selection; when no issue names an +object, the selection stays as it is. The Fold Lines panel's Check button runs the same check, shows a summary line +(panels, creases, errors and warnings) and lists the issues; clicking an issue or its Select button selects its objects. +The list is shown until the document changes. + +```json +{"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, From 8c53f8ce8863fcd9ecf4df12d3644c8596fde061 Mon Sep 17 00:00:00 2001 From: Sven Lafebre Date: Mon, 16 Nov 2026 12:23:10 +0100 Subject: [PATCH 22/62] 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