diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index c2f4bfea52..99655b88f1 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -517,6 +517,13 @@ impl Session { } } + /// Runs `f` with the context the tools read for the active document seen through `view`, for code + /// outside the engine that draws on the tools' geometry (the canvas's selection widgets). + /// `R::default()` with no document open. + pub fn with_tool_context(&mut self, view: ViewInfo, f: impl FnOnce(&ToolContext) -> R) -> R { + self.with_tool_cx(view, |_, cx| f(cx)) + } + /// The error of a tool that panicked in the last [`Self::with_tool_cx`] call, if any. fn take_tool_panic(&mut self) -> Result<()> { self.tool_panic.take().map_or(Ok(()), Err) diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 3098ed3cb1..911c44fec4 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -204,19 +204,18 @@ pub fn hint_strings() -> Vec<&'static str> { v } -pub(super) fn hint_segments(tool: &str) -> Vec<(Cow<'static, str>, bool)> { - let search; - let segments = match hint_for(tool) { - Some(s) => s, - None => { - search = match menus::shortcut_of("help.commandPalette") { - Some(sc) => [(tl!("Press "), false), (sc, true), (tl!(" to search every command"), false)], - None => [(tl!("Use "), false), (tl!("Help › Search Commands…"), true), (tl!(" to search every command"), false)], - }; - &search - } - }; - shown_segments(segments) +pub(super) fn hint_segments(app: &VectorcraftApp, tool: &str) -> Vec<(Cow<'static, str>, bool)> { + if let Some(segments) = hint_for(tool) { + return shown_segments(segments); + } + match menus::shortcut_of(app, "help.commandPalette") { + Some(chord) => vec![ + (Cow::Borrowed(tl!("Press ")), false), + (Cow::Owned(chord.display(crate::keymap::platform())), true), + (Cow::Borrowed(tl!(" to search every command")), false), + ], + None => shown_segments(&[(tl!("Use "), false), (tl!("Help › Search Commands…"), true), (tl!(" to search every command"), false)]), + } } /// The hint bar's segments for `tool` as [`hint_segments`] shows them, the Zoom tool's for animated @@ -254,7 +253,7 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) { None => { let tool = app.session.tool_id(); let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool }; - hint_segments(hint) + hint_segments(app, hint) } }; Bar::new(tl!("Help Bar"), BarKind::Status).show(ui, |ui, _| { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 51ddb93658..abab9e481e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -223,7 +223,10 @@ fn art_of(layers: &[Arc]) -> Vec { #[test] fn hints_name_keys_as_the_menus_do() { - let text = |tool: &str| super::hint_segments(tool).into_iter().map(|(s, _)| s).collect::(); + // A drawn frame gives the window its keymap, which the Search Commands shortcut is read from. + let mut app = crate::VectorcraftApp::new(Session::new(), crate::Services::default()); + crate::tests_synthetic::key_frame(&mut app, &egui::Context::default(), vec![]); + let text = |tool: &str| super::hint_segments(&app, tool).into_iter().map(|(s, _)| s).collect::(); for tool in vectorcraft_tools::catalog::all_tools().map(|t| t.id) { let hint = text(tool); assert!(!hint.contains("Option"), "{tool}: {hint}"); diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 52d91e6cde..2a0a44595b 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -21,7 +21,6 @@ //! makes a new one, and Delete deletes it). use std::collections::BTreeSet; -use std::sync::atomic::Ordering; use craft::behavior::IconId; use craft::behavior::dock::{Action, DockEdge}; @@ -488,31 +487,14 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Vec<&'static str>); - -/// Mirror the toolbars' names for the (static) menu tree. -pub fn sync(ui: &UiState) { - let same = names_store() - .read() - .map(|v| v.len() == ui.custom_toolbars.len() && v.iter().zip(&ui.custom_toolbars).all(|(a, b)| *a == b.name)) - .unwrap_or(true); - if !same { - if let Ok(mut v) = names_store().write() { - *v = ui.custom_toolbars.iter().map(|b| crate::shortcut_editor::intern(&b.name)).collect(); - } - crate::shortcut_editor::GENERATION.fetch_add(1, Ordering::Relaxed); - } -} - /// Window › Toolbars: Advanced, Double Column and Compact Tools, the toolbars made with New -/// Toolbar (each checked while it shows), New Toolbar… and Manage Toolbars…. -pub fn menu_items() -> Vec { +/// Toolbar (`names`, each checked while it shows), New Toolbar… and Manage Toolbars…. +pub fn menu_items(names: &[String]) -> Vec { use crate::menus::{Sep, c, named}; let mut v = vec![c("Advanced", "window.toolbarAdvanced"), c("Double Column", "window.toolbarColumns"), c("Compact Tools", "window.toolbarCompact"), Sep]; - let names = names_store().read().map(|v| v.clone()).unwrap_or_default(); if !names.is_empty() { - v.extend(names.into_iter().map(|n| named(n, "window.toolbar.custom", json!({ "name": n })))); + v.extend(names.iter().map(|n| named(n.as_str(), "window.toolbar.custom", json!({ "name": n })))); v.push(Sep); } v.push(c("New Toolbar…", "window.toolbar.new")); @@ -571,8 +553,11 @@ mod tests { /// The items of Window › Toolbars: (label, command id, params). fn toolbars_menu(app: &VectorcraftApp) -> Vec<(String, String, Value)> { - sync(&app.ui); - let window = crate::menus::menu_tree().into_iter().find(|(m, _)| *m == "Window").map(|(_, items)| items).unwrap(); + let window = crate::menus::menu_tree_named(true, &crate::menus::Listed::of(app)) + .into_iter() + .find(|(m, _)| *m == "Window") + .map(|(_, items)| items) + .unwrap(); let Some(items) = window.into_iter().find_map(|n| match n { Node::Submenu { label, children, .. } if label == "Toolbars" => Some(children), _ => None, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 016d09762d..6905eee6ad 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -233,11 +233,6 @@ mod tests_hpgl; #[cfg(test)] mod tests_tiff_bmp_tga; -#[cfg(test)] -mod tests_save_for_web; -#[cfg(test)] -mod tests_save_for_web_table; - #[cfg(test)] mod tests_psd; diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index 4c8dd2e980..acb6065d7a 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -8,6 +8,8 @@ //! dialog stays open. use std::borrow::Cow; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash as _, Hasher as _}; use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::ui::buttons::Button; @@ -87,9 +89,10 @@ pub struct Row { haystack: String, } -/// The rows in `lang`, for menus that name fonts in English when `english_names` is set. -pub(crate) fn build(lang: Lang, english_names: bool) -> Vec { - menus::insertable_items(english_names) +/// The rows in `lang`, for menus that name fonts in English when `english_names` is set and list +/// the `listed` names. +pub(crate) fn build(lang: Lang, english_names: bool, listed: &menus::Listed) -> Vec { + menus::insertable_items(english_names, listed) .into_iter() .map(|item| { let english = item.path.iter().chain(std::iter::once(&item.label)).map(String::as_str).collect::>().join(" › "); @@ -105,8 +108,9 @@ pub(crate) fn build(lang: Lang, english_names: bool) -> Vec { } /// What the rows were built from: the language, the installed plug-ins, the font name setting, the -/// loaded fonts, whether the installed fonts are cataloged and the saved proof setups. -pub(crate) type RowsKey = (&'static str, u64, bool, u64, bool, u64); +/// loaded fonts, whether the installed fonts are cataloged, the saved proof setups and the names the +/// menus list ([`menus::Listed`]). +pub(crate) type RowsKey = (&'static str, u64, bool, u64, bool, u64, u64); /// The rows that every word of `find` matches, in menu order. fn matches<'a>(rows: &'a [Row], find: &str) -> impl Iterator { @@ -183,6 +187,11 @@ impl InsertMenuItemDialog { generation, cataloged, crate::dialogs::proof_setup::saved_revision(), + { + let mut h = DefaultHasher::new(); + menus::Listed::of(app).hash(&mut h); + h.finish() + }, ) } @@ -207,7 +216,7 @@ impl InsertMenuItemDialog { /// in progress. pub fn open(app: &mut VectorcraftApp, target: Option<(usize, usize)>, step: Option) { let key = InsertMenuItemDialog::rows_key(app); - let rows = build(crate::i18n::current(), app.session.prefs.font_names_in_english); + let rows = build(crate::i18n::current(), app.session.prefs.font_names_in_english, &menus::Listed::of(app)); let dialog = InsertMenuItemDialog { id: dialog_id(KEY), target: Target::new(target, step), @@ -338,7 +347,7 @@ mod tests { #[test] fn find_picks_the_one_match_and_notes_none_or_several() { - let rows = build(Lang::EN, true); + let rows = build(Lang::EN, true, &menus::Listed::default()); let mut f = fields("object group", ""); find(&rows, &mut f); assert_eq!((f.note, f.command.as_str()), (FindNote::Several, ""), "Group and Ungroup both match"); @@ -356,7 +365,7 @@ mod tests { /// Pattern's Make and Edit Pattern and the saved-selection, saved-view and recent-font items. #[test] fn the_list_holds_only_menu_items_that_can_be_steps() { - let items = menus::insertable_items(true); + let items = menus::insertable_items(true, &menus::Listed::default()); assert!(items.len() > 100, "only {} items", items.len()); for item in &items { let in_app = menus::plays_in_app(&item.command); @@ -409,8 +418,9 @@ mod tests { /// and the items that ask for values first. #[test] fn every_view_item_the_app_runs_is_listed() { - let items = menus::insertable_items(true); - let view = menus::menu_tree_named(true).into_iter().find(|(title, _)| *title == "View").map(|(_, nodes)| nodes).unwrap(); + let items = menus::insertable_items(true, &menus::Listed::default()); + let view = + menus::menu_tree_named(true, &menus::Listed::default()).into_iter().find(|(title, _)| *title == "View").map(|(_, nodes)| nodes).unwrap(); fn walk<'a>(nodes: &'a [Node], out: &mut Vec<(&'a str, &'a str)>) { for node in nodes { match node { @@ -435,7 +445,7 @@ mod tests { #[test] fn rows_show_the_translated_path_and_match_english_shown_text_and_ids() { let de = Lang::from_code("de").unwrap(); - let rows = build(de, true); + let rows = build(de, true, &menus::Listed::default()); let group = rows.iter().find(|r| r.command == "object.group").unwrap(); assert_eq!(group.shown, format!("{} › {}", crate::i18n::tr(de, "Object"), crate::i18n::tr(de, "Group"))); for words in ["object group", group.shown.as_str(), "object.group"] { diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 89e6801625..85ea23796f 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -360,7 +360,8 @@ fn push_app_data(app: &VectorcraftApp) { } let key = InsertMenuItemDialog::rows_key(app); if dialogs.with(|host| host.get::().is_some_and(|dialog| dialog.built_from() != Some(key))) { - let rows = super::action_insert_menu_item::build(crate::i18n::current(), app.session.prefs.font_names_in_english); + let rows = + super::action_insert_menu_item::build(crate::i18n::current(), app.session.prefs.font_names_in_english, &crate::menus::Listed::of(app)); dialogs.with(|host| { if let Some(dialog) = host.get_mut::() { dialog.set_rows(key, rows); diff --git a/crates/ui-egui/src/dialogs/envelope.rs b/crates/ui-egui/src/dialogs/envelope.rs index adaf624e28..da47ed612c 100644 --- a/crates/ui-egui/src/dialogs/envelope.rs +++ b/crates/ui-egui/src/dialogs/envelope.rs @@ -543,7 +543,8 @@ mod tests { assert_eq!(label(&app), "Edit Contents"); app.run("object.envelope.editContents", json!({})).unwrap(); assert_eq!(label(&app), "Edit Envelope"); - assert!(crate::menus::shortcut_of("object.envelope.editContents").is_none(), "its reference shortcut is Paste in Place's here"); + crate::tests_synthetic::key_frame(&mut app, &egui::Context::default(), vec![]); + assert!(crate::menus::shortcut_of(&app, "object.envelope.editContents").is_none(), "its reference shortcut is Paste in Place's here"); } #[test] diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 657730c404..8370288c68 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -20,6 +20,7 @@ use crate::panels::color::gamut; pub const KIND: &str = "newSwatch"; /// The open New Swatch dialog: the held dialog and the default name, which follows the colour until it is edited. +#[derive(Clone, Debug)] pub(crate) struct Open { /// The held dialog. pub(crate) id: DialogId, diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 0185d807d8..9825b4fcec 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -632,3 +632,8 @@ fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { app.status(e); } } + +#[cfg(test)] +mod tests; +#[cfg(test)] +mod tests_table; diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs similarity index 99% rename from crates/ui-egui/src/dialogs/tests_save_for_web.rs rename to crates/ui-egui/src/dialogs/save_for_web/tests.rs index 1215618635..5c2f094eb3 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -9,8 +9,8 @@ use craft::ui::shell::WindowDialogs; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use super::tests_export::{answer_saves, save_panel}; use super::*; +use crate::dialogs::tests_export::{answer_saves, save_panel}; use crate::{Services, VectorcraftApp}; pub(super) type Log = Rc>>; @@ -220,7 +220,7 @@ fn opening_uses_the_active_artboard_in_a_multiselection_and_preserves_other_sett app.run("tool.setOption", json!({"key": "selected", "value": [1, 0]})).unwrap(); assert_eq!(app.view().unwrap().artboard, 1); assert_eq!(crate::panels::artboards::picked(&app, 2), [0, 1]); - let mut expected = serde_json::to_value(super::save_for_web::options_of(&saved)).unwrap(); + let mut expected = serde_json::to_value(options_of(&saved)).unwrap(); expected["artboard"] = json!(1); app.run("file.saveForWeb", json!({})).unwrap(); for key in ["quality", "width", "metadata", "artboard"] { @@ -710,7 +710,7 @@ fn optimize_to_file_size_takes_the_settings_that_fit() { let quality = fields(&app)["quality"].as_u64().unwrap(); assert!(quality < 100, "{found}"); assert!(fields(&app).get("optimizeK").is_none(), "the rows closed"); - assert!(save_for_web::optimized_result(&app.web_export.optimized, &save_for_web::art_key(&app)).is_some()); + assert!(optimized_result(&app.web_export.optimized, &art_key(&app)).is_some()); // Save writes the size found. save(&mut app); let written = std::fs::read(dir.join("Untitled-1.jpg")).unwrap(); @@ -721,7 +721,7 @@ fn optimize_to_file_size_takes_the_settings_that_fit() { // decides the slices Save writes, and leaves the revision as it is) or a selected slice. let plant = |app: &mut VectorcraftApp| { let mut current = found.clone(); - current["art"] = json!(save_for_web::art_key(app)); + current["art"] = json!(art_key(app)); app.web_export.optimized = Some(current); frame(app); assert!(app.web_export.optimized.is_some(), "the result holds for the art it measured"); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web_table.rs b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs similarity index 98% rename from crates/ui-egui/src/dialogs/tests_save_for_web_table.rs rename to crates/ui-egui/src/dialogs/save_for_web/tests_table.rs index 731ef9fd71..76e548b537 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web_table.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests_table.rs @@ -5,8 +5,8 @@ use vectorcraft_engine::cmd::webexport; use craft::ui::patterns::form_dialogs::{ColorTableEdit, ColorTableEvent, PALETTE_COLOR_KEY, TableOrder}; -use super::save_for_web::color_table::{apply, marks, restore, shift}; -use super::tests_save_for_web::{app, frame, host, save, set}; +use super::color_table::{apply, marks, restore, shift}; +use super::tests::{app, frame, host, save, set}; const A: [u8; 3] = [0x00, 0x00, 0x00]; const B: [u8; 3] = [0x11, 0x11, 0x11]; diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 4ce89c49b1..6342673c05 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -41,6 +41,7 @@ pub const KIND: &str = "swatchOptions"; pub(super) const NO_WINDOW: &str = "no window"; /// The open Swatch Options dialog: the held dialog, the swatch it edits and the parameters its preview last ran with. +#[derive(Clone, Debug)] pub(crate) struct Open { /// The held dialog. pub(crate) id: DialogId, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 456ddb5c7f..ee75d6c045 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -78,7 +78,7 @@ pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; pub(crate) use tree::arrange_documents_items; -pub use tree::{menu_tree, menu_tree_named}; +pub use tree::{Listed, menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 721c72d9cf..6524edfd21 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -2,7 +2,7 @@ use super::context::context_items; use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label}; use super::slots::{recent_readable, recent_slot}; use super::state::{shortcut_of, shown_state}; -use super::tree::menu_tree_named; +use super::tree::{Listed, menu_tree_named}; use super::{Node, Serialize, TODO, Value, VectorcraftApp}; /// The label of the menu item that runs `id` with `p` and reads `label` in English, as the menus @@ -32,7 +32,7 @@ pub struct MenuEntry { /// Flattened menu for `ui.menu.list`. pub fn menu_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; - for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english) { + for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english, &Listed::of(app)) { flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); } out @@ -137,8 +137,9 @@ pub fn insertable(title: &str, label: &str, id: &str, p: &Value) -> bool { } /// Every menu item that can be a step of an action ([`insertable`]), in menu order. An item that -/// shows in two places is listed in both. `english_names` is as [`menu_tree_named`] takes it. -pub fn insertable_items(english_names: bool) -> Vec { +/// shows in two places is listed in both. `english_names` and `listed` are as [`menu_tree_named`] +/// takes them. +pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec { fn walk(title: &'static str, path: &mut Vec, nodes: &[Node], out: &mut Vec) { for node in nodes { match node { @@ -159,7 +160,7 @@ pub fn insertable_items(english_names: bool) -> Vec { } } let mut out = vec![]; - for (title, nodes) in menu_tree_named(english_names) { + for (title, nodes) in menu_tree_named(english_names, listed) { walk(title, &mut vec![title.to_string()], &nodes, &mut out); } out @@ -196,7 +197,7 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec String { @@ -237,19 +238,21 @@ pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter /// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. -pub fn item_shortcut(id: &str, p: &Value) -> Option<&'static str> { - match (id, p.get("panel").and_then(Value::as_str)) { - ("window.panel", Some(panel)) => crate::shortcut_editor::panel_shortcut(panel), - ("effect.dialog" | "effect.apply", _) => p.get("effect").and_then(Value::as_str).and_then(crate::shortcut_editor::effect_shortcut), - ("plugin.dialog", _) => p.get("id").and_then(Value::as_str).and_then(crate::shortcut_editor::filter_shortcut), +pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option { + let field = |name: &str| p.get(name).and_then(Value::as_str); + let key = match (id, field("panel")) { + ("window.panel", Some(panel)) => format!("panel:{panel}"), + ("effect.dialog" | "effect.apply", _) => format!("effect:{}", field("effect")?), + ("plugin.dialog", _) => format!("plugin:{}", field("id")?), // The Artboard tool's canvas menu passes the point its Paste goes to. - ("edit.paste", _) => shortcut_of(id), + ("edit.paste", _) => id.to_string(), // That menu's Cut and Copy: with the tool chosen, the keys run `edit.cut` and `edit.copy`, which do the same. - ("artboard.cut", _) => shortcut_of("edit.cut"), - ("artboard.copy", _) => shortcut_of("edit.copy"), - _ if p.is_null() => shortcut_of(id), - _ => None, - } + ("artboard.cut", _) => "edit.cut".to_string(), + ("artboard.copy", _) => "edit.copy".to_string(), + _ if p.is_null() => id.to_string(), + _ => return None, + }; + shortcut_of(app, &key) } /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 6142cd9707..8d03a6f932 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -16,7 +16,7 @@ use craft::ui::runtime::windows::WindowHost; use serde_json::{Value, json}; use super::labels::holds_plugin_commands; -use super::{TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; +use super::{Listed, TODO, display_label, menu_tree_named, plugin_revision, shown_label, shown_state, why_off}; use crate::i18n::LangExt as _; use crate::{UiState, VectorcraftApp}; @@ -155,10 +155,10 @@ fn role(title: &str) -> MenuRole { } /// The hash of what the catalog's rows depend on, which moves its generation. -fn generation(ui: &UiState) -> u64 { +fn generation(listed: &Listed) -> u64 { let mut h = DefaultHasher::new(); (crate::i18n::current().code(), plugin_revision(), crate::scripts_menu::revision(), vectorcraft_text::FontDb::global().generation()).hash(&mut h); - hash_listed_names(ui, &mut h); + listed.hash(&mut h); h.finish() } @@ -173,8 +173,9 @@ fn hash_listed_names(ui: &UiState, h: &mut DefaultHasher) { } fn rebuild(app: &mut VectorcraftApp, target: Target) { + let listed = Listed::of(app); let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new() }; - let menus: Vec = menu_tree_named(app.session.prefs.font_names_in_english) + let menus: Vec = menu_tree_named(app.session.prefs.font_names_in_english, &listed) .into_iter() .map(|(title, nodes)| { let shown = build.title(title, true); @@ -191,7 +192,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { let bar = MenuBar::new(menus); let options = LayoutOptions::new(APP_NAME).label(&translate_label); let laid = layout(&bar, target, &options).bar; - match AppCatalog::new(defs, generation(&app.ui)) { + match AppCatalog::new(defs, generation(&listed)) { Ok(catalog) => app.menus.catalog = Some(catalog), // A refused catalog is a bug in the rows; the last good one keeps the commands working. Err(e) => eprintln!("menu catalog refused: {e:?}"), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index d39e61d0f5..02ea092266 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -2,6 +2,8 @@ use super::run::{normalize_panel, toolbar_double, toolbar_panel}; use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; +use craft::keymap::Chord; +use craft::ui::runtime::commands; /// Checked state for toggle items. pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { @@ -182,9 +184,11 @@ pub fn plugin_revision() -> u64 { vectorcraft_plugins::registry::revision() } -/// Effective shortcut of a command: the user's override (Edit → Keyboard Shortcuts) or the default. -pub fn shortcut_of(id: &str) -> Option<&'static str> { - crate::shortcut_editor::command_shortcut(id) +/// The shortcut entry `key` ([`crate::keymap`]'s entry keys) shows: its first single-press binding in +/// the window's keymap, under the user's set in use (Edit → Keyboard Shortcuts). `None` before the +/// window's first frame. +pub fn shortcut_of(app: &VectorcraftApp, key: &str) -> Option { + commands::chord(app.ui_ctx.as_ref()?, &crate::keymap::command_of(key)) } /// Is a command currently enabled? diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index b55d881311..d150678ee2 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -110,8 +110,9 @@ const RASTER_MENUS: [(&str, &[&str]); 10] = [ ("Video", &["Effect", "Video"]), ]; -/// The Effect menu, built from the effects catalogue (vector effects), plus raster effects. -pub(super) fn effect_menu() -> Vec { +/// The Effect menu, built from the effects catalogue (vector effects), plus raster effects. SVG +/// Filters lists the document's own filters `svg_filters` after the defaults. +pub(super) fn effect_menu(svg_filters: &[String]) -> Vec { let cat = vectorcraft_effects::effect_catalog(); let mut out = vec![ c("Apply Last Effect", "effect.applyLast"), @@ -160,8 +161,7 @@ pub(super) fn effect_menu() -> Vec { } // Apply SVG Filter…, Import SVG Filter… and the document's filters. if sub_name == "SVG Filters" { - // PLAN: effects-w17 may give `menu_items` the document's filter names; the no-argument call is kept. - out.push(sub(sub_name, crate::dialogs::svg_filter::menu_items())); + out.push(sub(sub_name, crate::dialogs::svg_filter::menu_items(svg_filters))); continue; } let items = items_at(&["Effect", sub_name], true); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index f94c0a1df3..4ca58c027c 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -381,7 +381,7 @@ fn help_bar_toggle_is_independent_and_saved_in_workspaces() { /// then a separator; the menus list it once. #[test] fn help_starts_with_search_commands() { - let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); let tree = menu_tree(); let help = &tree.iter().find(|(title, _)| *title == "Help").expect("Help menu").1; assert!( @@ -391,7 +391,8 @@ fn help_starts_with_search_commands() { ); assert!(matches!(help[1], Node::Separator), "{:?}", help[1]); assert!(enabled(&app, "help.commandPalette")); - assert!(shortcut_of("help.commandPalette").is_some(), "the search's shortcut shows next to the item"); + crate::tests_synthetic::key_frame(&mut app, &egui::Context::default(), vec![]); + assert!(shortcut_of(&app, "help.commandPalette").is_some(), "the search's shortcut shows next to the item"); fn count(nodes: &[Node]) -> usize { nodes .iter() @@ -571,7 +572,7 @@ fn center_on_top_and_bottom_are_type_on_a_path_items() { assert_eq!(items, [("Center on Top", ids[0]), ("Center on Bottom", ids[1])]); let palette = crate::palette::items(); for (label, id) in items { - assert!(palette.iter().any(|(l, i, _)| l == &format!("Type › Type on a Path › {label}") && i == id), "{label}"); + assert!(palette.iter().any(|(l, i)| l == &format!("Type › Type on a Path › {label}") && i == id), "{label}"); } let line = app.run("path.create", json!({"d": "M60 150 L340 150"})).unwrap()["id"].clone(); let open = app.run("text.createInPath", json!({"path": line, "mode": "onPath", "text": "Along", "at": [60, 150]})).unwrap()["id"].clone(); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 5745e012ba..2e6bcbdb6f 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -10,11 +10,34 @@ use crate::i18n::LangExt as _; /// `menu_bar`); the native Mac bar is composed from the whole tree (see `native_menu`). /// `english_names` is Preferences › Type › Show Font Names in English (the Type → Font labels /// follow it; tests use the default `true`). +/// The fixed rows only: none of the [`Listed`] names. pub fn menu_tree() -> Vec<(&'static str, Vec)> { - menu_tree_named(true) + menu_tree_named(true, &Listed::default()) } -pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { +/// The names the menus list as rows of their own after their fixed rows. +#[derive(Default, Hash)] +pub struct Listed { + /// Window › Workspace: the saved workspaces. + pub workspaces: Vec, + /// Window › Toolbars: the toolbars made with New Toolbar. + pub toolbars: Vec, + /// Effect › SVG Filters: the active document's filters that are not a default's. + pub svg_filters: Vec, +} + +impl Listed { + /// The names `app` holds now. + pub fn of(app: &crate::VectorcraftApp) -> Listed { + Listed { + workspaces: app.ui.workspaces.set.saved.iter().map(|w| w.name.clone()).collect(), + toolbars: app.ui.custom_toolbars.iter().map(|b| b.name.clone()).collect(), + svg_filters: app.session.active().map(|st| crate::dialogs::svg_filter::own_names(&st.doc.svg_filters)).unwrap_or_default(), + } + } +} + +pub fn menu_tree_named(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec)> { let panel = |label: &'static str, id: &'static str| cp(label, "window.panel", json!({ "panel": id, "toggle": true })); vec![ ( @@ -557,7 +580,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { v.extend(SAVED_SELECTION_IDS.iter().map(|id| c("Saved Selection", id))); v }), - ("Effect", effect_menu()), + ("Effect", effect_menu(&listed.svg_filters)), ("View", { let mut v = vec![ c("Outline", "view.outline"), @@ -681,14 +704,14 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ]); arrange }), - sub("Workspace", crate::workspaces::menu_items()), + sub("Workspace", crate::workspaces::menu_items(&listed.workspaces)), Sep, c("Control", "window.control"), c("Help Bar", "window.helpBar"), c("Contextual Task Bar", "window.taskBar"), c("Quick Pen Toolbar", "window.quickPenToolbar"), c("Tools", "window.toolbar"), - sub("Toolbars", crate::custom_toolbars::menu_items()), + sub("Toolbars", crate::custom_toolbars::menu_items(&listed.toolbars)), Sep, ]; let lang = crate::i18n::current(); @@ -863,7 +886,7 @@ fn app_menu() -> Vec { Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings); // Only the first page carries Preferences' shortcut. if i == 0 { - item.shortcut = super::shortcut_of("edit.preferences").and_then(crate::keymap::stored::parse_vc); + item.shortcut = crate::shortcut_editor::default_command_shortcut("edit.preferences").and_then(crate::keymap::stored::parse_vc); } Node::Item(item) }) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index cb03472e96..1290747bd8 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -112,7 +112,6 @@ struct Draft { /// 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? @@ -120,16 +119,8 @@ struct Draft { } 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, - } + fn new(path: &str, label: &str, id: String) -> Draft { + Draft { path: path.to_string(), label: label.to_string(), translates: true, id, in_context: false, keyed: false } } /// The name in `lang`: the path's segments and the label translate on their own, and the id @@ -164,7 +155,7 @@ fn drafts() -> Vec { && (!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(""))); + out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string())); } // `plugin.dialog` runs nothing without an id: [`named_drafts`] lists each filter instead. A // script of the Scripts folder runs from File › Scripts, by its path. The palette's own toggle @@ -175,31 +166,31 @@ fn drafts() -> Vec { 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(""))); + out.push(Draft::new(&path, c.1, c.0.to_string())); } 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(""))); + out.push(Draft::new("", tool.label, format!("tool:{}", tool.id))); } // 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(""))); + out.push(Draft::new(PANEL_PATH, label, format!("panel:{id}"))); } // 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("")) + ..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect)) }); } out } -/// Everything the palette searches: (label, command id or `tool:`, shortcut). Labels are the -/// English names before [`distinct_names`] makes them distinct. -// PLAN: the shortcut text stays the editor's lookup: `ResolvedCommand::chord` needs a context, which `items` (no params, 7 test readers) has none of; shortcuts-w7 decides which lookup survives -pub fn items() -> Vec<(String, String, String)> { - drafts().into_iter().map(|d| (d.name(crate::i18n::Lang::EN), d.id, d.shortcut)).collect() +/// Everything the palette searches: (label, command id or `tool:`). Labels are the English +/// names before [`distinct_names`] makes them distinct; a result's shortcut is its command's in the +/// window's keymap. +pub fn items() -> Vec<(String, String)> { + drafts().into_iter().map(|d| (d.name(crate::i18n::Lang::EN), d.id)).collect() } /// The menu path a result shows when its name is another result's: its [`CONTEXTS`] path, Tools @@ -305,10 +296,11 @@ fn item_label(lang: crate::i18n::Lang, id: &str, menu_item: &str) -> String { /// translated ([`distinct_names`]). fn named_drafts(lang: Lang) -> Vec { 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("")) - })); + drafts.extend( + crate::shortcut_editor::filter_items() + .iter() + .map(|f| Draft { translates: false, ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id)) }), + ); distinct_names(&mut drafts, &[Lang::EN, lang]); drafts } @@ -885,7 +877,7 @@ mod tests { #[test] fn the_palette_lists_cancel_key_object_once() { let items = items(); - let ids: Vec<&str> = items.iter().filter(|(label, ..)| label == "Cancel Key Object").map(|(_, id, _)| id.as_str()).collect(); + let ids: Vec<&str> = items.iter().filter(|(label, ..)| label == "Cancel Key Object").map(|(_, id)| id.as_str()).collect(); assert_eq!(ids, ["select.key"]); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); let commands = crate::control::all_commands(&app); @@ -912,8 +904,8 @@ mod tests { let spec = vectorcraft_engine::command_specs().iter().find(|c| c.id == *engine).unwrap_or_else(|| panic!("{engine} is a command")); let wrapper = menus::UI_COMMANDS.iter().find(|c| c.0 == *ui).unwrap_or_else(|| panic!("{ui} is a UI command")); assert_eq!(spec.label, wrapper.1, "{engine} and {ui} share a name"); - assert!(items.iter().all(|(_, id, _)| id != engine), "{engine} is left out"); - let listed: Vec<&str> = items.iter().filter(|(_, id, _)| id == ui).map(|(label, ..)| label.as_str()).collect(); + assert!(items.iter().all(|(_, id)| id != engine), "{engine} is left out"); + let listed: Vec<&str> = items.iter().filter(|(_, id)| id == ui).map(|(label, ..)| label.as_str()).collect(); let path: String = spec.menu.iter().map(|m| format!("{m} › ")).collect(); assert_eq!(listed, [format!("{path}{}", wrapper.1)], "{ui} is listed once, with {engine}'s menu path"); } @@ -975,7 +967,7 @@ mod tests { fn a_pick_of_an_asset_export_command_opens_its_panel() { let showing = |app: &VectorcraftApp| crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID); for id in ASSET_EXPORT { - assert!(items().iter().any(|(_, item, _)| item == id), "{id} is in the palette"); + assert!(items().iter().any(|(_, item)| item == id), "{id} is in the palette"); let mut app = app_on(Session::new()); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.ui.status.clear(); @@ -1027,7 +1019,7 @@ mod tests { ("object.path.smooth", crate::dialogs::smooth_slider::showing), ]; for (id, opened) in expected { - assert!(items().iter().any(|(_, item, _)| item == id), "{id} is in the palette"); + assert!(items().iter().any(|(_, item)| item == id), "{id} is in the palette"); let mut app = app_on(Fixture::Single.session()); app.ui.status.clear(); let before = app.session.active().unwrap().history.undo.len(); @@ -1068,7 +1060,7 @@ mod tests { walk(&menu.children, &mut rows); } let mut checked: Vec<(String, CommandRef)> = vec![]; - for (_, id, _) in items() { + for (_, id) in items() { let of_id: Vec<&CommandRef> = rows.iter().map(|it| &it.command).filter(|c| c.id == id).collect(); let Some(first) = of_id.first() else { continue }; if first.params.as_object().is_none_or(serde_json::Map::is_empty) || of_id.iter().any(|c| c.params != first.params) { @@ -1129,7 +1121,7 @@ mod tests { #[test] fn a_pick_of_a_command_without_a_dialog_runs_at_once() { for id in ["object.group", "paint.swap"] { - assert!(items().iter().any(|(_, item, _)| item == id), "{id} is in the palette"); + assert!(items().iter().any(|(_, item)| item == id), "{id} is in the palette"); let mut app = app_on(Fixture::Multi.session()); let before = app.session.active().unwrap().history.undo.len(); pick(&mut app, id); @@ -1442,7 +1434,7 @@ mod tests { /// 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(); + 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"); } @@ -1543,7 +1535,7 @@ mod tests { .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 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"] { @@ -1615,7 +1607,7 @@ mod tests { /// 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 ids: Vec = items().into_iter().map(|(_, id)| id).collect(); let mut app = app_on(Fixture::Single.session()); let pick_listed = |app: &mut VectorcraftApp, id: &str| { assert!(ids.iter().any(|i| i == id), "{id} is a result"); @@ -1673,7 +1665,7 @@ mod tests { /// 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(); + 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"); } @@ -2026,7 +2018,7 @@ mod tests { #[test] fn tools_are_never_dimmed_and_panels_are_in_presentation_mode() { let mut window = Window::new(); - let tools: Vec = items().into_iter().map(|(_, id, _)| id).filter(|id| id.starts_with("tool:")).collect(); + let tools: Vec = items().into_iter().map(|(_, id)| id).filter(|id| id.starts_with("tool:")).collect(); assert!(!tools.is_empty()); assert!(tools.iter().all(|id| window.resolved(id).enabled), "{tools:?}"); assert!(window.resolved("panel:layers").enabled); @@ -2059,8 +2051,7 @@ mod tests { #[test] fn no_reason_shows_a_command_id() { let window = Window::on(Session::new()); - let reasons: Vec<(String, String)> = - items().into_iter().filter_map(|(_, id, _)| hint_of(&window.resolved(&id)).map(|why| (id, why))).collect(); + let reasons: Vec<(String, String)> = items().into_iter().filter_map(|(_, id)| hint_of(&window.resolved(&id)).map(|why| (id, why))).collect(); assert!(reasons.len() > 100, "with no document most results can't run: {}", reasons.len()); for (id, why) in &reasons { let command = crate::keymap::command_of(id).id; diff --git a/crates/ui-egui/src/panels/actions/edits.rs b/crates/ui-egui/src/panels/actions/edits.rs index 672e686b79..b2524856c8 100644 --- a/crates/ui-egui/src/panels/actions/edits.rs +++ b/crates/ui-egui/src/panels/actions/edits.rs @@ -506,7 +506,7 @@ pub fn insert_menu_item(app: &mut VectorcraftApp, p: &Value) -> Result v.clone(), Some(_) => return Err("`params` must be an object".into()), }; - let items = crate::menus::insertable_items(app.session.prefs.font_names_in_english); + let items = crate::menus::insertable_items(app.session.prefs.font_names_in_english, &crate::menus::Listed::of(app)); if !items.iter().any(|item| item.command == command && item.params == params) { return Err("no menu item that can be inserted runs this command".into()); } diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index d5514d4e00..a2f5247c91 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -902,7 +902,7 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { /// artboard to both. #[test] fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { - for item in crate::menus::insertable_items(false) { + for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { let (mut app, _) = app_with_three_moves(); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); let held = steps(&app, 0, 0)[3].1.clone(); @@ -963,7 +963,7 @@ fn an_inserted_pathfinder_effect_item_keeps_the_pathfinder_options_of_its_insert #[test] fn every_pathfinder_effect_item_step_holds_the_options_its_click_applies() { let options = json!({"precision": 0.25, "removeRedundantPoints": false, "removeUnpainted": true}); - let items: Vec<_> = crate::menus::insertable_items(false) + let items: Vec<_> = crate::menus::insertable_items(false, &crate::menus::Listed::default()) .into_iter() .filter(|item| { item.command == "effect.apply" diff --git a/crates/ui-egui/src/panels/discover.rs b/crates/ui-egui/src/panels/discover.rs index b4ba4a6124..9e7d1bf5b3 100644 --- a/crates/ui-egui/src/panels/discover.rs +++ b/crates/ui-egui/src/panels/discover.rs @@ -95,7 +95,11 @@ fn refresh(app: &mut VectorcraftApp) { hit.english_path = entry.path.clone(); hit.label = menus::shown_label(app, &hit.id, &hit.params, &hit.english_label); hit.path = entry.shown_path.clone(); - hit.shortcut = menus::item_shortcut(&hit.id, &hit.params).or_else(|| menus::shortcut_of(&hit.id)).unwrap_or_default().into(); + hit.shortcut = menus::item_shortcut(app, &hit.id, &hit.params) + .or_else(|| menus::shortcut_of(app, &hit.id)) + .map(|c| c.to_string()) + .unwrap_or_default() + .into(); } _ => {} } diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index e75c7ed80c..9e9a7a8629 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -19,7 +19,7 @@ use crate::VectorcraftApp; /// What the panel's menu sets: the scope and the category shown. Neither is saved with the /// preferences. -#[derive(Clone, Default)] +#[derive(Clone, Debug, Default)] pub struct DocInfoView { /// Only the selection's objects are counted. pub selection_only: bool, diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 7ca042c9a7..1d5c0fa510 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -61,7 +61,7 @@ const FOOTER: [(Act, &str, &str); 5] = [ ]; /// The panel's options (panel menu). -#[derive(Clone)] +#[derive(Clone, Debug)] pub(super) struct Options { pub(super) show: &'static str, pub(super) sort: Option<&'static str>, @@ -86,7 +86,7 @@ type NestedPicks = Option<((u64, Vec), Vec)>; /// What the panel keeps for the session: its options, the rows it last fetched, the request to /// show an image, the rows picked outside the layer tree, the list's selection (its lead and /// anchor) and the row whose menu is open. -#[derive(Default)] +#[derive(Clone, Debug, Default)] pub(crate) struct LinksModel { pub(super) options: Options, pub(super) cache: Arc, @@ -98,7 +98,7 @@ pub(crate) struct LinksModel { } /// `links.list` and the first selected image's `links.info`, with what they were fetched for. -#[derive(Clone, Default)] +#[derive(Clone, Debug, Default)] pub(super) struct Cache { /// (document uid, revision, show, sort, Show DCS Transparency Interactions). key: Option<(u64, u64, &'static str, Option<&'static str>, bool)>, diff --git a/crates/ui-egui/src/panels/text_styles.rs b/crates/ui-egui/src/panels/text_styles.rs index bf1f308ffe..de077c2940 100644 --- a/crates/ui-egui/src/panels/text_styles.rs +++ b/crates/ui-egui/src/panels/text_styles.rs @@ -50,7 +50,7 @@ impl Kind { } /// What the two styles panels keep between frames. -#[derive(Default)] +#[derive(Clone, Debug, Default)] pub(crate) struct StylesPanels { pub char: StylesPanel, pub para: StylesPanel, @@ -66,7 +66,7 @@ impl StylesPanels { } /// One panel's highlight. Names are the stored form: row ids are list positions, rebuilt every pass. -#[derive(Default)] +#[derive(Clone, Debug, Default)] pub(crate) struct StylesPanel { /// The uid of the document the highlight was made in. document: Option, diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index aeb3647ab3..3beaf3d5e0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2466,6 +2466,6 @@ mod tests { 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(&saved, &entry)); assert!(needs_a_value("document.setUnits")); - assert!(crate::palette::items().iter().all(|(_, id, _)| id != "document.setUnits")); + assert!(crate::palette::items().iter().all(|(_, id)| id != "document.setUnits")); } } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 9bf0312a61..f702fed53d 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -76,6 +76,11 @@ fn app_with_a_selected_rectangle() -> VectorcraftApp { app } +/// The shortcut the menu item running `id` with `params` shows, as of the last frame's keymap. +fn item_shortcut(app: &VectorcraftApp, id: &str, params: Value) -> Option { + crate::menus::item_shortcut(app, id, ¶ms).map(|c| c.to_string()) +} + /// Gives `id` the chord `shortcut`, taking it from any command that holds it. fn bind(app: &mut VectorcraftApp, id: &str, shortcut: &str) { app.run("shortcuts.set", json!({"id": id, "shortcut": shortcut, "force": true})).unwrap(); @@ -1470,9 +1475,9 @@ fn an_effect_menu_item_takes_a_shortcut_of_its_own() { let mut app = app_with_a_selected_rectangle(); assert!(!listed(&mut app, "effect:distort.transform").is_empty(), "Transform is listed"); bind(&mut app, "effect:distort.transform", "Cmd+Alt+Shift+F11"); - assert_eq!(crate::menus::item_shortcut("effect.dialog", &json!({"effect": "distort.transform"})), Some("Cmd+Alt+Shift+F11")); frame(&mut app, tap(Key::F11, cmd() | Modifiers::ALT | Modifiers::SHIFT)); assert_eq!(dialog_field(&app, "__effect"), Some(json!("distort.transform")), "{:?}", dialog_kind(&app)); + assert_eq!(item_shortcut(&app, "effect.dialog", json!({"effect": "distort.transform"})).as_deref(), Some("Cmd+Alt+Shift+F11")); } /// A live-effect plug-in installed later takes a shortcut of its own, and the key applies the effect. @@ -1494,17 +1499,17 @@ fn a_live_effect_plugin_installed_later_takes_a_shortcut_of_its_own() { install("{}"); app.run("shortcuts.set", json!({"id": key, "shortcut": chord})).unwrap(); assert_eq!(listed(&mut app, effect), vec![(key.to_string(), json!(chord))]); - assert_eq!(crate::menus::item_shortcut("effect.apply", &json!({ "effect": effect })), Some(chord)); frame(&mut app, f6()); assert_eq!(effects(&app), 1, "the key applies the effect"); + assert_eq!(item_shortcut(&app, "effect.apply", json!({ "effect": effect })).as_deref(), Some(chord)); // Removed: no row and no key; the saved shortcut is the effect's again when it comes back. vectorcraft_plugins::registry::remove(plugin); assert_eq!(listed(&mut app, effect), vec![]); install(r#"{"wiggle":{"type":"bool"}}"#); assert_eq!(listed(&mut app, effect), vec![(key.to_string(), json!(chord))]); - assert_eq!(crate::menus::item_shortcut("effect.dialog", &json!({ "effect": effect })), Some(chord)); frame(&mut app, f6()); assert_eq!(dialog_field(&app, "__effect"), Some(json!(effect)), "{:?}", dialog_kind(&app)); + assert_eq!(item_shortcut(&app, "effect.dialog", json!({ "effect": effect })).as_deref(), Some(chord)); vectorcraft_plugins::registry::remove(plugin); } @@ -1527,10 +1532,10 @@ fn each_filter_plugin_takes_a_shortcut_of_its_own() { assert_eq!(listed(&mut app, "test.ui.key_filter-"), vec![(key_one.clone(), Value::Null), (key_two.clone(), Value::Null)]); app.run("shortcuts.set", json!({"id": key_two, "shortcut": chord})).unwrap(); assert_eq!(listed(&mut app, "test.ui.key_filter-"), vec![(key_one.clone(), Value::Null), (key_two.clone(), json!(chord))]); - assert_eq!(crate::menus::item_shortcut("plugin.dialog", &json!({ "id": two })), Some(chord)); - assert_eq!(crate::menus::item_shortcut("plugin.dialog", &json!({ "id": one })), None); frame(&mut app, f7()); assert_eq!(dialog_field(&app, "__plugin"), Some(json!(two)), "the filter's dialog opens"); + assert_eq!(item_shortcut(&app, "plugin.dialog", json!({ "id": two })).as_deref(), Some(chord)); + assert_eq!(item_shortcut(&app, "plugin.dialog", json!({ "id": one })), None); close_top_dialog(&mut app, false); // Removed: no row and no key; back under another name and without parameters it runs at once. vectorcraft_plugins::registry::remove(two); @@ -1562,16 +1567,17 @@ fn a_filter_plugin_keeps_its_shortcut_when_replaced_or_reloaded() { vectorcraft_plugins::registry::install_bytes(&wasm("Original", "{}")).unwrap(); app.run("shortcuts.set", json!({"id": key, "shortcut": chord})).unwrap(); vectorcraft_plugins::registry::install_bytes(&wasm("Replaced", with_params)).unwrap(); - assert_eq!(crate::menus::item_shortcut("plugin.dialog", &json!({ "id": id })), Some(chord)); frame(&mut app, f6()); assert_eq!(dialog_field(&app, "__plugin"), Some(json!(id)), "the replaced filter has parameters"); + assert_eq!(item_shortcut(&app, "plugin.dialog", json!({ "id": id })).as_deref(), Some(chord)); close_top_dialog(&mut app, false); let folder = std::env::temp_dir().join(format!("vectorcraft-ui-filter-shortcut-{}", std::process::id())); std::fs::create_dir_all(&folder).unwrap(); std::fs::write(folder.join("filter.wasm"), wasm("Reloaded", with_params)).unwrap(); app.run("plugin.reload", json!({ "path": folder.display().to_string() })).unwrap(); std::fs::remove_dir_all(&folder).ok(); - assert_eq!(crate::menus::item_shortcut("plugin.dialog", &json!({ "id": id })), Some(chord)); + frame(&mut app, vec![]); + assert_eq!(item_shortcut(&app, "plugin.dialog", json!({ "id": id })).as_deref(), Some(chord)); let mut empty = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); empty.run("shortcuts.set", json!({"id": key, "shortcut": chord})).unwrap(); frame(&mut empty, f6()); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 810b1c19b0..ad10a9bac5 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -38,7 +38,6 @@ mod ruler_origin; mod save; mod saveext; mod screenmode; -mod screenshots; mod script_check; mod script_dialogs; mod script_run; diff --git a/crates/ui-egui/src/tests/fonts.rs b/crates/ui-egui/src/tests/fonts.rs index 83ca797d6c..b09d896f0d 100644 --- a/crates/ui-egui/src/tests/fonts.rs +++ b/crates/ui-egui/src/tests/fonts.rs @@ -38,4 +38,3 @@ fn type_font_menu_lists_every_available_family() { } panic!("the fonts kept changing"); } - diff --git a/crates/ui-egui/src/tests/removeanchors.rs b/crates/ui-egui/src/tests/removeanchors.rs index 804e2691a0..0288a15d51 100644 --- a/crates/ui-egui/src/tests/removeanchors.rs +++ b/crates/ui-egui/src/tests/removeanchors.rs @@ -110,7 +110,7 @@ fn the_path_menu_and_bars_run_it_for_direct_selected_anchors() { assert_eq!(entries[0].path, ["Object", "Path"]); assert!(!entries[0].enabled, "an object selection is not enough"); assert!(!labels(&menus::context_items(&app)).iter().any(|l| l == LABEL)); - assert!(crate::palette::items().iter().any(|(_, cmd, _)| cmd == "path.removeAnchors")); + assert!(crate::palette::items().iter().any(|(_, cmd)| cmd == "path.removeAnchors")); app.select_tool("directSelection"); app.run("select.anchors", json!({"id": id.0, "anchors": [[0, 1]]})).unwrap(); diff --git a/crates/ui-egui/src/tests/rotateview.rs b/crates/ui-egui/src/tests/rotateview.rs index d92d323f1f..aa712cf646 100644 --- a/crates/ui-egui/src/tests/rotateview.rs +++ b/crates/ui-egui/src/tests/rotateview.rs @@ -240,7 +240,7 @@ fn the_view_menu_lists_the_status_bar_angles_and_checks_the_current_one() { /// filled in, and OK turns the view to the angle entered. #[test] fn rotate_view_without_an_angle_asks_for_one() { - assert!(crate::palette::items().iter().any(|(label, id, _)| (label.as_str(), id.as_str()) == ("Rotate View", "view.rotate"))); + assert!(crate::palette::items().iter().any(|(label, id)| (label.as_str(), id.as_str()) == ("Rotate View", "view.rotate"))); let mut app = with_document(); app.run("view.rotate", json!({"angle": 30})).unwrap(); menus::invoke(&mut app, "view.rotate", json!({})); diff --git a/crates/ui-egui/src/tests/scripts_menu.rs b/crates/ui-egui/src/tests/scripts_menu.rs index 8a641757bc..e422253344 100644 --- a/crates/ui-egui/src/tests/scripts_menu.rs +++ b/crates/ui-egui/src/tests/scripts_menu.rs @@ -221,7 +221,7 @@ fn script_and_folder_names_are_shown_as_they_are_in_every_language() { write(&dir, "Zed/All Artboards.js", ""); read(&app); assert!(!menus::menu_strings().contains("All Artboards") && !menus::menu_strings().contains("Zed")); - assert!(!crate::palette::items().iter().any(|(_, id, _)| id == scripts_menu::COMMAND), "a script runs from its menu item"); + assert!(!crate::palette::items().iter().any(|(_, id)| id == scripts_menu::COMMAND), "a script runs from its menu item"); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/tests/slices.rs b/crates/ui-egui/src/tests/slices.rs index b8d8510251..dc2bf8f232 100644 --- a/crates/ui-egui/src/tests/slices.rs +++ b/crates/ui-egui/src/tests/slices.rs @@ -74,7 +74,6 @@ fn slice_menu_items_follow_the_state() { assert_eq!(crate::menus::checked(&app, "view.slices.lock", &json!({})), Some(true)); } - #[test] fn the_slice_tools_are_real_tools() { let mut app = app(); diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 841afd4928..38f903134f 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -12,7 +12,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -use std::sync::atomic::Ordering; use craft::behavior::dock::{NamedWorkspace, Workspace as DockWorkspace, WorkspaceChrome, WorkspaceError, WorkspaceKeeps, WorkspaceSet}; use craft::keymap::CommandRef; @@ -504,30 +503,16 @@ pub fn rename(ui: &mut UiState, from: &str, to: &str) -> Result<(), String> { Ok(()) } -// ---------- menu support (menu_tree has no app access) ---------- +// ---------- the menu ---------- -crate::shortcut_editor::ui_mirror!(fn names_store() -> Vec<&'static str>); - -/// Mirror the user workspace names for the (static) menu tree. -pub fn sync(ui: &UiState) { - let saved = &ui.workspaces.set.saved; - let same = names_store().read().map(|v| v.len() == saved.len() && v.iter().zip(saved).all(|(a, b)| *a == b.name)).unwrap_or(true); - if !same { - if let Ok(mut v) = names_store().write() { - *v = saved.iter().map(|w| crate::shortcut_editor::intern(&w.name)).collect(); - } - crate::shortcut_editor::GENERATION.fetch_add(1, Ordering::Relaxed); - } -} - -/// Window → Workspace submenu items. -pub fn menu_items() -> Vec { +/// Window → Workspace submenu items: the built-in workspaces, the saved ones (`saved`) and the +/// workspace commands. +pub fn menu_items(saved: &[String]) -> Vec { use crate::menus::{Node, Sep, c, named}; let mut v: Vec = builtins().into_iter().map(|b| named(b.name, "window.workspace", json!({"name": b.name}))).collect(); - let custom = names_store().read().map(|v| v.clone()).unwrap_or_default(); - if !custom.is_empty() { + if !saved.is_empty() { v.push(Sep); - v.extend(custom.into_iter().map(|n| named(n, "window.workspace", json!({"name": n})))); + v.extend(saved.iter().map(|n| named(n.as_str(), "window.workspace", json!({"name": n})))); } v.push(Sep); v.push(c("Reset Essentials", "window.workspace.reset"));