diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..cef2b14775 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -44,6 +44,7 @@ //! images or symbol instances of those kinds, to read only: its output must return each of them //! unchanged ([`objects::decode_output_with`]). +use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; @@ -113,8 +114,19 @@ pub fn describe(p: &Plugin) -> Value { .iter() .map(|c| { let run = m.for_command(c); - json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), - "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}) + let mut entry = json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(), + "paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())}); + if let Some(place) = &c.place { + let mut menu = json!({"path": place.path}); + if let Some(after) = &place.after { + menu["after"] = json!(permissions::display_text(after, permissions::MAX_SHOWN_NAME)); + } + if placed_menu(p, c).is_none() { + menu["placed"] = json!(false); + } + entry["menu"] = menu; + } + entry }) .collect(); v["commands"] = json!(commands); @@ -466,15 +478,278 @@ pub fn find_spec(id: &str) -> Option<&'static CommandSpec> { command_specs().into_iter().find(|c| c.id == id) } +/// The letters and digits of `label`, lowercased. Two labels with the same key read alike in a menu +/// (`Paste (in Place)` and `Paste in Place`). +fn label_key(label: &str) -> String { + label.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect() +} + +/// The labels of engine commands whose menu item switches to the label of [`other_state`] (the +/// desktop app's dynamic labels). +pub const SWITCHING_LABELS: &[&str] = &[ + "Preview", + "Outline", + "Show Rulers", + "Change to Global Rulers", + "Show Transparency Grid", + "Lock Guides", + "Hide Slices", + "Show Print Tiling", + "Lock Grid", + "Edit Envelope", + "Edit Contents", + "Start Global Edit", +]; + +/// The label of `label`'s other state, for a menu item that switches between two labels: `Show +/// Edges` for `Hide Edges`, `Unlock Guides` for `Lock Guides`, `Stop Global Edit` for `Start Global +/// Edit`, and the reverse. +pub fn other_state(label: &str) -> Option { + const PAIRS: &[(&str, &str)] = &[ + ("Preview", "Outline"), + ("Change to Global Rulers", "Change to Artboard Rulers"), + ("Edit Envelope", "Edit Contents"), + ("Start Global Edit", "Stop Global Edit"), + ]; + let paired = |&(a, b): &(&'static str, &'static str)| { + if label == a { + Some(b) + } else if label == b { + Some(a) + } else { + None + } + }; + if let Some(other) = PAIRS.iter().find_map(paired) { + return Some(other.to_string()); + } + [("Hide ", "Show "), ("Show ", "Hide "), ("Lock ", "Unlock "), ("Unlock ", "Lock ")] + .iter() + .find_map(|(from, to)| label.strip_prefix(from).map(|rest| format!("{to}{rest}"))) +} + +/// The menu that plug-in `p`'s command `c` is listed in when its manifest's `menu` places it in +/// another menu: that menu's path, or `None` when `c` stays in its plug-in's submenu. It stays +/// there when its menu label ([`Command::menu_label`]) has the same letters and digits, ignoring +/// case, as an engine command listed in that menu (either label of one of [`SWITCHING_LABELS`]), +/// an item of [`DESKTOP_MENU_ITEMS`] there, or a command that a plug-in with a lower id, or an +/// earlier command of `p`, places in that menu. The result is the same with and without the +/// desktop app. Results for installed plug-ins are kept until the registry changes. +pub fn placed_menu(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + type Placed = HashMap>; + static PLACED: Mutex> = Mutex::new(None); + c.place.as_ref()?; + let m = p.manifest(); + // Read before the registry, so a result found while the registry changes is kept under the + // revision before the change. + let revision = registry::revision(); + // `plugin.inspect` describes a module that is not installed, or not yet in place of the + // installed one: never kept. + if !registry::get(&m.id).is_some_and(|q| std::ptr::eq(&*q, p)) { + return find_place(p, c); + } + let id = command_id(&m.id, &c.id); + if let Ok(placed) = PLACED.lock() + && let Some((at, known)) = placed.as_ref() + && *at == revision + && let Some(found) = known.get(&id) + { + return *found; + } + let found = find_place(p, c); + if let Ok(mut placed) = PLACED.lock() { + let (at, known) = placed.get_or_insert_with(|| (revision, HashMap::new())); + if *at != revision { + *at = revision; + known.clear(); + } + known.insert(id, found); + } + found +} + +/// [`placed_menu`], found again. +fn find_place(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> { + let place = c.place.as_ref()?; + let m = p.manifest(); + let key = label_key(&c.menu_label(&m.name)); + let reads_like = + |label: &str| label_key(label) == key || SWITCHING_LABELS.contains(&label) && other_state(label).is_some_and(|o| label_key(&o) == key); + if super::command_specs().iter().any(|s| s.menu == place.path && reads_like(s.label)) + || DESKTOP_MENU_ITEMS.iter().any(|(path, label)| *path == place.path && label_key(label) == key) + { + return None; + } + let taken = |name: &str, d: &Command| d.place.as_ref().is_some_and(|e| e.path == place.path) && label_key(&d.menu_label(name)) == key; + // The registry lists plug-ins in id order. `p` itself may not be installed yet (`plugin.inspect`), + // or be replacing the installed module of its id, so its own commands come from `m`. + for q in registry::list() { + let qm = q.manifest(); + if qm.id >= m.id { + break; + } + if qm.commands.iter().any(|d| taken(&qm.name, d)) { + return None; + } + } + for d in &m.commands { + if d.id == c.id { + return Some(place.path); + } + if taken(&m.name, d) { + return None; + } + } + Some(place.path) +} + +/// The labels of the desktop app's own items (not engine commands) in the menus of +/// [`vectorcraft_plugins::manifest::MENU_PLACES`], with both labels of an item that switches +/// between two. [`placed_menu`] reads them, so its result is the same with and without the desktop +/// app. +pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[ + (&["Edit"], "Spelling"), + (&["Edit"], "Edit Custom Dictionary…"), + (&["Edit"], "Edit Colors"), + (&["Edit"], "Edit Original"), + (&["Edit"], "Transparency Flattener Presets…"), + (&["Edit"], "Print Presets…"), + (&["Edit"], "PDF Presets…"), + (&["Edit"], "Tracing Presets…"), + (&["Edit"], "Perspective Grid Presets…"), + (&["Edit"], "Refresh Monitor Profile"), + (&["Edit"], "Keyboard Shortcuts…"), + (&["Edit"], "Preferences…"), + (&["Edit", "Edit Colors"], "Recolor with Preset"), + (&["Object"], "Transform"), + (&["Object"], "Arrange"), + (&["Object"], "Align"), + (&["Object"], "Distribute"), + (&["Object"], "Lock"), + (&["Object"], "Hide"), + (&["Object"], "Slice"), + (&["Object"], "Path"), + (&["Object"], "Shape"), + (&["Object"], "Pattern"), + (&["Object"], "Repeat"), + (&["Object"], "Intertwine"), + (&["Object"], "Objects on Path"), + (&["Object"], "Blend"), + (&["Object"], "Envelope Distort"), + (&["Object"], "Perspective"), + (&["Object"], "Live Paint"), + (&["Object"], "Image Trace"), + (&["Object"], "Text Wrap"), + (&["Object"], "Clipping Mask"), + (&["Object"], "Compound Path"), + (&["Object"], "Artboards"), + (&["Object"], "Graph"), + (&["Object"], "Collect for Export"), + (&["Object"], "Plug-ins"), + (&["Type"], "Font"), + (&["Type"], "Recent Fonts"), + (&["Type"], "Size"), + (&["Type"], "Bold"), + (&["Type"], "Italic"), + (&["Type"], "Glyphs"), + (&["Type"], "Insert Special Character"), + (&["Type"], "Insert Whitespace Character"), + (&["Type"], "Insert Break Character"), + (&["Type"], "Type on a Path"), + (&["Type"], "Dynamic Text Presets"), + (&["Type"], "Threaded Text"), + (&["Type"], "Find Font…"), + (&["Type"], "Change Case"), + (&["Type"], "Bullets and Numbering"), + (&["Type"], "Show Hidden Characters"), + (&["Type"], "Hide Hidden Characters"), + (&["Type"], "Type Orientation"), + (&["Select"], "Same"), + (&["Select"], "Object"), + (&["Select"], "Saved Selection"), + (&["Effect"], "Apply Last Effect"), + (&["Effect"], "Last Effect…"), + (&["Effect"], "3D and Materials"), + (&["Effect"], "Color Adjustments"), + (&["Effect"], "Color Effects"), + (&["Effect"], "Convert to Shape"), + (&["Effect"], "Crop Marks"), + (&["Effect"], "Distort & Transform"), + (&["Effect"], "Path"), + (&["Effect"], "Path Effects"), + (&["Effect"], "Pathfinder"), + (&["Effect"], "Rasterize…"), + (&["Effect"], "Stylize"), + (&["Effect"], "SVG Filters"), + (&["Effect"], "Warp"), + (&["Effect"], "Effect Gallery…"), + (&["Effect"], "Artistic"), + (&["Effect"], "Blur"), + (&["Effect"], "Brush Strokes"), + (&["Effect"], "Distort"), + (&["Effect"], "Pixelate"), + (&["Effect"], "Sharpen"), + (&["Effect"], "Sketch"), + (&["Effect"], "Texture"), + (&["Effect"], "Video"), + (&["Effect"], "Plug-ins"), + (&["View"], "Outline"), + (&["View"], "Preview"), + (&["View"], "Pixel Preview"), + (&["View"], "Trim View"), + (&["View"], "Presentation Mode"), + (&["View"], "Screen Mode"), + (&["View"], "Proof Setup"), + (&["View"], "Zoom In"), + (&["View"], "Zoom Out"), + (&["View"], "Fit Artboard in Window"), + (&["View"], "Fit All in Window"), + (&["View"], "Actual Size"), + (&["View"], "Rotate View"), + (&["View"], "Rotate View to Selection"), + (&["View"], "Reset Rotate View"), + (&["View"], "Hide Edges"), + (&["View"], "Show Edges"), + (&["View"], "Hide Artboards"), + (&["View"], "Show Artboards"), + (&["View"], "Hide Template"), + (&["View"], "Show Template"), + (&["View"], "Rulers"), + (&["View"], "Hide Bounding Box"), + (&["View"], "Show Bounding Box"), + (&["View"], "Hide Text Threads"), + (&["View"], "Show Text Threads"), + (&["View"], "Hide Gradient Annotator"), + (&["View"], "Show Gradient Annotator"), + (&["View"], "Hide Corner Widget"), + (&["View"], "Show Corner Widget"), + (&["View"], "Show Live Paint Gaps"), + (&["View"], "Hide Live Paint Gaps"), + (&["View"], "Guides"), + (&["View"], "Smart Guides"), + (&["View"], "Perspective Grid"), + (&["View"], "Show Grid"), + (&["View"], "Hide Grid"), + (&["View"], "Snap to Grid"), + (&["View"], "Snap to Pixel"), + (&["View"], "Snap to Point"), + (&["View"], "Snap to Glyph"), + (&["View"], "Saved View"), +]; + /// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and -/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live -/// effect: never a menu the manifest names) and its params description. +/// capped, and followed by the plug-in's name when it is listed in another menu), its menu +/// ([`placed_menu`], else Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a +/// live effect) and its params description. fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { let m = p.manifest(); let id = command_id(&m.id, &c.id); - let label = c.shown_label(); + let placed = placed_menu(p, c); + let label = if placed.is_some() { c.menu_label(&m.name) } else { c.shown_label() }; let top = if m.kind == Kind::Effect { "Effect" } else { "Object" }; let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME); + let submenu = [top, "Plug-ins", name.as_str()]; + let path: &[&str] = placed.unwrap_or(&submenu); let mut fields = String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)"); let doc = m.for_command(c).params_doc(); @@ -487,11 +762,14 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); - let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params; + let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == path && s.params == params; if let Some(s) = made.iter().find(same) { return s; } - let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()); + let menu: &'static [&'static str] = match placed { + Some(path) => path, + None => Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()), + }; let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec { id: registry::intern(&id), label: registry::intern(&label), @@ -1270,7 +1548,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..f2d84f00c9 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4571,6 +4571,82 @@ fn plugin_commands_are_registered_run_and_removed() { assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } +/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its +/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like +/// a built-in command of that menu, or like a command a plug-in with a lower id places there, +/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module +/// whose command has no `menu`, a command is back in its submenu. +#[test] +fn placed_plugin_commands_are_listed_in_their_menu() { + let mut s = session(); + let placing = |id: &str, name: &str, commands: &str| { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + tpl::returning(&manifest, r#"{"objects":[]}"#) + }; + let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat"); + let low = |id: &str| crate::cmd::plugin::command_id(id, "low"); + let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::>()); + let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string(); + let in_select = in_select.as_str(); + + let info = install_wat(&mut s, &placing(ant, "Tidy", in_select)); + let menu = &info["commands"][0]["menu"]; + assert_eq!(menu["path"], json!(["Select"])); + assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}"); + assert!(menu.get("placed").is_none(), "{menu}"); + let c = listed(&s, &low(ant)).expect("listed"); + assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()]))); + + // Another plug-in of the same name placing the same label at the same spot stays in its submenu. + let info = install_wat(&mut s, &placing(bee, "Tidy", in_select)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area")); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()])); + + // `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed. + let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#; + let info = install_wat(&mut s, &placing(cat, "in Place", edit)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert!(info["commands"][1]["menu"].get("placed").is_none()); + let paste = crate::cmd::plugin::command_id(cat, "paste"); + assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()])); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()])); + // `Stop Global (Edit)` reads like the other label of Select's Start Global Edit. + let dog = "test.engine.place.dog"; + let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": dog})); + // Object's Show All has one label, so `Hide (All)` is placed beside it. + let all = "test.engine.place.all"; + let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#)); + assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()])); + run(&mut s, "plugin.remove", json!({"id": all})); + // `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app. + let edges = "test.engine.place.edges"; + let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": edges})); + // Inspecting a plug-in that is not installed reports what installing it gives: of two commands + // with one label at one spot, the second stays in its submenu. + let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}"); + assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}"); + + // Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and + // Bee's takes the spot. + install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#)); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()])); + for id in [ant, bee, cat] { + run(&mut s, "plugin.remove", json!({"id": id})); + } + assert!(listed(&s, &low(bee)).is_none()); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 35f29a2a25..158a4d6798 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -707,9 +707,10 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` naming another menu, junk - /// parameters) parse to an error or to commands whose menu labels show no hidden character and - /// that sit under Plug-ins alone; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk + /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no + /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest + /// may name, with the plug-in's name; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -723,7 +724,17 @@ proptest! { 1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from), 1 => arb_junk(), ], - prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()], + prop_oneof![ + Just(Value::Null), + Just(json!("File")), + Just(json!({"path": ["Select"], "after": "Inverse"})), + Just(json!({"path": ["Object", "Path"]})), + Just(json!({"path": ["File"]})), + Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), + arb_junk().prop_map(|j| json!({"path": j})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + arb_junk(), + ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], ) .prop_map(|(id, label, menu, params)| { @@ -742,8 +753,9 @@ proptest! { ), junk in prop::option::weighted(0.1, arb_junk()), given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()], + api in 1u32..=2, ) { - let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind}); + let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind, "api": api}); if matches!(kind, "exporter" | "importer") { m["extensions"] = json!(["fz"]); } @@ -756,6 +768,12 @@ proptest! { let shown = c.shown_label(); prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let placed = c.menu_label(&man.name); + prop_assert!(!placed.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", placed); + if let Some(place) = &c.place { + prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); + prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); + } } } let mut s = rich_session(); @@ -774,7 +792,9 @@ proptest! { let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); for (id, menu) in &ran { - prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}"); + let submenu = menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"); + let place = api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&menu.as_slice()); + prop_assert!(submenu || place, "{id}: {menu:?}"); } renders(&s, "after hostile commands")?; vectorcraft_plugins::registry::remove("fuzz.commands"); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..dada995bb3 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -52,7 +52,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; +pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..b96ae96bde 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -31,6 +31,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256; /// Longest command id a manifest's `commandAllowlist` names, in bytes. pub const MAX_ALLOWED_ID: usize = 128; +/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window, +/// Help and the application menu are not among them, and neither are the submenus that list +/// files, fonts, panels or other plug-ins. +pub const MENU_PLACES: &[&[&str]] = &[ + &["Edit"], + &["Edit", "Edit Colors"], + &["Object"], + &["Object", "Transform"], + &["Object", "Arrange"], + &["Object", "Path"], + &["Object", "Compound Path"], + &["Object", "Clipping Mask"], + &["Type"], + &["Select"], + &["Select", "Same"], + &["Select", "Object"], + &["Effect"], + &["View"], +]; + +/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the +/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when +/// `after` is left out or names no built-in item there. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct MenuPlace { + pub path: &'static [&'static str], + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, +} + +impl MenuPlace { + /// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`. + fn read(v: &Value) -> std::result::Result { + let wrong_path = || { + let k = "menu.path"; + let places: Vec = + MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::>().join(", "))).collect(); + format!("`{k}` must be one of {}", places.join(", ")) + }; + let Some(o) = v.as_object() else { + let key = "menu"; + return Err(format!("`{key}` must be an object")); + }; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(format!("unknown key `{k}`; the keys here are {}", "path, after")); + } + let path: Vec<&str> = match o.get("path").and_then(Value::as_array) { + Some(path) => path.iter().map(Value::as_str).collect::>().ok_or_else(wrong_path)?, + None => return Err(wrong_path()), + }; + let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?; + let key = "menu.after"; + let after = match o.get("after") { + None => None, + Some(Value::String(s)) => { + let s = s.trim(); + if s.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { + return Err(format!("`{key}` must be 1-64 printable characters")); + } + Some(s.to_string()) + } + Some(_) => return Err(format!("`{key}` must be a string")), + }; + Ok(MenuPlace { path, after }) + } +} + /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -220,9 +288,9 @@ pub struct Param { } /// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the -/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command -/// `plugin..`, and calls the plug-in's `vc_run` with `_context.command` set to -/// `id` and the parameters it declares. +/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it +/// as the command `plugin..`, and calls the plug-in's `vc_run` with +/// `_context.command` set to `id` and the parameters it declares. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Command { /// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest. @@ -233,6 +301,13 @@ pub struct Command { /// Parameters in declaration (dialog) order, declared as the manifest's own are. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] pub params: Vec<(String, Param)>, + /// The menu it is listed in instead of the plug-in's submenu (`menu`, read at + /// [`crate::permissions::MENU_API`] and later). + #[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")] + pub place: Option, + /// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them. + #[serde(skip)] + pub(crate) declared_menu: Vec, } impl Command { @@ -241,6 +316,18 @@ impl Command { pub fn shown_label(&self) -> String { crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME) } + + /// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a + /// command placed in another menu, followed by the plug-in's name in parentheses. + pub fn menu_label(&self, plugin_name: &str) -> String { + match self.place { + None => self.shown_label(), + Some(_) => { + let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME); + format!("{} ({name})", self.shown_label()) + } + } + } } impl From for Param { @@ -360,8 +447,9 @@ impl Manifest { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } - let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; + let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; man.validate()?; + man.read_places()?; Ok(man) } @@ -397,6 +485,31 @@ impl Manifest { self.commands.iter().find(|c| c.id == id) } + /// Reads each command's `menu` into its [`Command::place`] at + /// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is + /// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given + /// twice is refused, and the error names the command. + fn read_places(&mut self) -> Result<()> { + let reads = self.api >= permissions::MENU_API; + for (i, c) in self.commands.iter_mut().enumerate() { + let menus = std::mem::take(&mut c.declared_menu); + if !reads { + continue; + } + let name = command_name(i, &c.id); + let place = match menus.as_slice() { + [] => continue, + [menu] => MenuPlace::read(menu), + _ => { + let key = "menu"; + Err(format!("duplicate field `{key}`")) + } + }; + c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?); + } + Ok(()) + } + /// Checks what the module declared: its id, name and text lengths, its extensions, a budget its /// kind may have (only a filter may be heavy), and each parameter and its dialog layout. fn validate(&self) -> Result<()> { @@ -805,7 +918,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu Err(A::Error::custom(self.wrong())) } fn visit_map>(self, mut map: A) -> std::result::Result { - let (mut id, mut label, mut params) = (None::, None::, None::); + let (mut id, mut label, mut params, mut menu) = (None::, None::, None::, Vec::::new()); let named = |id: &Option, e: &dyn std::fmt::Display| { A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default()))) }; @@ -824,6 +937,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu params = Some(map.next_value().map_err(|e| named(&id, &e))?); false } + // A repeated `menu` is refused only where the key is read ([`Manifest::parse`]). + "menu" => { + menu.push(map.next_value().map_err(|e| named(&id, &e))?); + false + } "id" | "label" | "params" => true, _ => { map.next_value::()?; @@ -840,7 +958,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu let Some(label) = label else { return Err(named(&Some(id), &"missing field `label`")); }; - Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() }) + Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu }) } } @@ -1216,7 +1334,7 @@ mod tests { } /// A filter or a live effect lists menu commands with their own parameters; a `menu` key is - /// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many + /// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many /// commands are refused, and the error names the command. #[test] fn commands_are_checked_and_errors_name_them() { @@ -1238,7 +1356,7 @@ mod tests { assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none()); let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap(); assert_eq!(effect.commands.len(), 1); - let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label(); + let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label(); assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe"); let many: Vec = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect(); @@ -1294,6 +1412,62 @@ mod tests { assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped"); } + /// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or + /// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the + /// wrong shape is refused and the error names the command. At level 1 the key is ignored. + #[test] + fn a_command_menu_names_an_allowed_place() { + let with = |api: u32, menu: &str| { + format!( + r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"# + ) + }; + let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap(); + let c = &m.commands[0]; + assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) })); + assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in"); + assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"})); + let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap(); + assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None })); + + // API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu. + for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] { + let old = Manifest::parse(with(1, menu).as_bytes()).unwrap(); + assert_eq!(old.commands[0].place, None, "{menu}"); + assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths"); + } + + let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65)); + for (menu, says) in [ + (r#"{"path":["File"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Help"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Window"]}"#, "`menu.path` must be one of"), + (r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"), + (r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"), + (r#"{"path":["select"]}"#, "`menu.path` must be one of"), + (r#"{"path":[]}"#, "`menu.path` must be one of"), + (r#"{"path":"Select"}"#, "`menu.path` must be one of"), + (r#"{"path":["Select",1]}"#, "`menu.path` must be one of"), + (r#"{"after":"Inverse"}"#, "`menu.path` must be one of"), + (r#""Select""#, "`menu` must be an object"), + (r#"["Select"]"#, "`menu` must be an object"), + (r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"), + (r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"), + (r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"), + (long.as_str(), "`menu.after` must be 1-64 printable characters"), + (r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"), + ] { + let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}"); + } + let twice = + r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#; + assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`")); + } + #[test] fn strings_and_number_lists_resolve_like_the_other_types() { let m = Manifest::parse( diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..a07b7a7a64 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -25,6 +25,10 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key +/// is ignored. +pub const MENU_API: u32 = 2; + /// Most permissions a manifest may list. pub const MAX_PERMISSIONS: usize = 16; diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..4e42b33a1a 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -11,7 +11,8 @@ //! background too, with its progress and Cancel, when it runs at once or when OK runs it without a //! kept preview ([`in_background`]). A filter or live effect with commands of //! its own is a submenu named after it, holding its item and then its commands; a command with -//! parameters opens the same dialog for them ([`open_command`]). Exporters are formats of File › Export › +//! parameters opens the same dialog for them ([`open_command`]). A command whose manifest names +//! another menu is listed in that menu instead ([`place_commands`]). Exporters are formats of File › Export › //! Export As; one with parameters opens dialog `pluginExport` once the file is picked, and its //! Export button writes the file. Importers open the files File › Open finds no built-in format //! for, and File › Open With lists them, to open a file with one of them by name; one with @@ -70,6 +71,114 @@ fn with_commands(plugin: &Plugin, own: Item) -> Item { Item::Sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) } +/// Moves each plug-in command whose manifest's `menu` names another menu +/// ([`vectorcraft_plugins::MenuPlace`]) from its plug-in's submenu into that menu of `tree`: after +/// the built-in item its `after` names (with or without an ellipsis), or at the end of the menu. +/// Its label ends with the plug-in's name ([`vectorcraft_plugins::Command::menu_label`]). +/// Commands placed at the same spot are listed in plug-in id order and then in manifest order. A +/// plug-in's submenu left with its own item alone becomes that item. A command whose menu `tree` +/// doesn't have, or that [`vectorcraft_engine::cmd::plugin::placed_menu`] leaves in its plug-in's +/// submenu, stays there. +pub fn place_commands(tree: &mut [(&'static str, Vec)]) { + let mut spots: Vec<(&'static [&'static str], Option, Vec)> = Vec::new(); + for p in registry::list() { + let m = p.manifest(); + if !matches!(m.kind, Kind::Filter | Kind::Effect) { + continue; + } + for c in &m.commands { + let Some(place) = &c.place else { continue }; + if vectorcraft_engine::cmd::plugin::placed_menu(&p, c).is_none() { + continue; + } + // An `after` that names no built-in item of the menu means the end of it, as no `after` does. + let after = place + .after + .as_deref() + .map(|a| anchor_key(a).to_string()) + .filter(|a| menu_at(tree, place.path).is_some_and(|menu| menu.iter().any(|it| is_anchor(it, a)))); + let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)); + let item = Item::Cmd(label(&c.menu_label(&m.name), !c.params.is_empty()), id, Value::Null); + match spots.iter_mut().find(|s| s.0 == place.path && s.1 == after) { + Some(s) => s.2.push(item), + None => spots.push((place.path, after, vec![item])), + } + } + } + spots.retain(|s| menu_at(tree, s.0).is_some()); + if spots.is_empty() { + return; + } + let placed: std::collections::HashSet<&str> = spots + .iter() + .flat_map(|s| s.2.iter()) + .filter_map(|it| match it { + Item::Cmd(_, id, _) => Some(*id), + _ => None, + }) + .collect(); + // Plug-in submenus are under Object › Plug-ins and Effect › Plug-ins. + for (_, items) in tree.iter_mut().filter(|(title, _)| matches!(*title, "Object" | "Effect")) { + leave_out(items, &placed); + } + for (path, after, items) in spots { + let Some(menu) = menu_at(tree, path) else { continue }; + let at = after.and_then(|a| menu.iter().position(|it| is_anchor(it, &a))).map_or(menu.len(), |i| i + 1); + menu.splice(at..at, items); + } +} + +/// A label as `after` matches it: trimmed, without a closing ellipsis. +fn anchor_key(label: &str) -> &str { + label.trim().trim_end_matches('…').trim_end() +} + +/// Is `it` the built-in item or submenu labeled `key` ([`anchor_key`])? An item of +/// [`crate::menus::DYNAMIC_LABELS`] matches by the label of either of its states +/// ([`vectorcraft_engine::cmd::plugin::other_state`]). Items that list a plug-in are never an anchor. +fn is_anchor(it: &Item, key: &str) -> bool { + match it { + Item::Cmd(l, id, p) => { + let toggles = crate::menus::DYNAMIC_LABELS.contains(l); + let other = || vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); + !crate::menus::lists_plugin(id, p) && (anchor_key(l) == key || toggles && other()) + } + Item::Sub(l, children) => !crate::menus::holds_plugin_commands(children) && anchor_key(l) == key, + _ => false, + } +} + +/// The built-in menu of `tree` at `path`: a top-level menu, then its submenus by label. +fn menu_at<'a>(tree: &'a mut [(&'static str, Vec)], path: &[&str]) -> Option<&'a mut Vec> { + let (first, rest) = path.split_first()?; + let mut menu = &mut tree.iter_mut().find(|(title, _)| title == first)?.1; + for segment in rest { + menu = menu.iter_mut().find_map(|it| match it { + Item::Sub(l, children) if l == segment && !crate::menus::holds_plugin_commands(children) => Some(children), + _ => None, + })?; + } + Some(menu) +} + +/// Takes the commands in `placed` out of the plug-in submenus under `items`; a submenu left with no +/// command becomes its plug-in's own item. +fn leave_out(items: &mut [Item], placed: &std::collections::HashSet<&str>) { + for it in items.iter_mut() { + let Item::Sub(_, children) = it else { continue }; + if !crate::menus::holds_plugin_commands(children) { + leave_out(children, placed); + continue; + } + children.retain(|c| !matches!(c, Item::Cmd(_, id, _) if placed.contains(id))); + if !children.iter().any(|c| matches!(c, Item::Cmd(_, id, _) if vectorcraft_engine::cmd::plugin::is_command_id(id))) + && let Some(own) = children.first().cloned() + { + *it = own; + } + } +} + /// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then /// Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..94332b3e72 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7691,6 +7691,7 @@ variable-list-end {0}, {1} {0} i {1} @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): una persona l’ha d’aprovar a l’aplicació d’escriptori, o passa `allowHeavy: true` en una sessió iniciada amb --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` ha de tenir 1-64 caràcters imprimibles +@msg `{key}` must be 1-64 printable characters `{key}` ha de tenir 1-64 caràcters imprimibles @msg `version`, `description` or `author` is too long `version`, `description` o `author` és massa llarg @msg `warnings` must be a list of strings `warnings` ha de ser una llista de cadenes @msg `{k}` must be one of {_1} `{k}` ha de ser un de {_1} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..27d1e9175a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7302,6 +7302,7 @@ axis Y Axis osa Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ žádá o velký výpočetní rozpočet (každé spuštění až {minutes} minut a {times}krát víc instrukcí než obvykle): musí ho schválit člověk v desktopové aplikaci, nebo předejte `allowHeavy: true` v relaci spuštěné s --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musí mít 1-64 tisknutelných znaků +@msg `{key}` must be 1-64 printable characters `{key}` musí mít 1-64 tisknutelných znaků @msg `version`, `description` or `author` is too long `version`, `description` nebo `author` je příliš dlouhé @msg `warnings` must be a list of strings `warnings` musí být seznam řetězců @msg `{k}` must be one of {_1} `{k}` musí být jedno z {_1} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..8f7631cf9a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -532,6 +532,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg an exporter always gets an export's budget: leave `budget` out en eksportør får altid et eksportbudget: udelad `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` skal være 1-64 tegn, der kan udskrives +@msg `{key}` must be 1-64 printable characters `{key}` skal være 1-64 tegn, der kan udskrives @msg `version`, `description` or `author` is too long `version`, `description` eller `author` er for lang @msg `warnings` must be a list of strings `warnings` skal være en liste med strenge @msg `{k}` must be one of {_1} `{k}` skal være en af {_1} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..4ebb7c9220 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6885,6 +6885,7 @@ axis Y Axis Y-Achse @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ verlangt ein großes Rechenbudget (jede Ausführung bis zu {minutes} Minuten und {times}-mal so viele Anweisungen wie üblich): Eine Person muss es in der Desktop-App genehmigen, oder übergeben Sie `allowHeavy: true` in einer mit --allow-plugin-grants gestarteten Sitzung # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` muss 1-64 druckbare Zeichen haben +@msg `{key}` must be 1-64 printable characters `{key}` muss 1-64 druckbare Zeichen haben @msg `version`, `description` or `author` is too long `version`, `description` oder `author` ist zu lang @msg `warnings` must be a list of strings `warnings` muss eine Liste von Zeichenketten sein @msg `{k}` must be one of {_1} `{k}` muss einer der folgenden Werte sein: {_1} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..d75cd4c4fb 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7291,6 +7291,7 @@ axis Y Axis Άξονας Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants το «{_1}» ζητά μεγάλο υπολογιστικό προϋπολογισμό (κάθε εκτέλεση έως {minutes} λεπτά και {times} φορές τις συνήθεις εντολές): πρέπει να το εγκρίνει ένα άτομο στην εφαρμογή επιφάνειας εργασίας ή περάστε `allowHeavy: true` σε μια συνεδρία που ξεκίνησε με --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters το `name` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες +@msg `{key}` must be 1-64 printable characters το `{key}` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg `version`, `description` or `author` is too long το `version`, το `description` ή το `author` είναι πολύ μεγάλο @msg `warnings` must be a list of strings το `warnings` πρέπει να είναι λίστα συμβολοσειρών @msg `{k}` must be one of {_1} το `{k}` πρέπει να είναι ένα από τα {_1} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..5a2b8f9857 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7277,6 +7277,7 @@ axis Y Axis Eje Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pide un presupuesto de cálculo grande (cada ejecución hasta {minutes} minutos y {times} veces las instrucciones habituales): una persona debe aprobarlo en la aplicación de escritorio, o pasa `allowHeavy: true` en una sesión iniciada con --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` debe tener 1-64 caracteres imprimibles +@msg `{key}` must be 1-64 printable characters `{key}` debe tener 1-64 caracteres imprimibles @msg `version`, `description` or `author` is too long `version`, `description` o `author` es demasiado largo @msg `warnings` must be a list of strings `warnings` debe ser una lista de cadenas @msg `{k}` must be one of {_1} `{k}` debe ser uno de estos: {_1} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..57f87528a4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7368,6 +7368,7 @@ axis Y Axis Y-akseli @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants ”{_1}” pyytää suurta laskentabudjettia (jokainen ajo enintään {minutes} minuuttia ja {times} kertaa tavallinen määrä käskyjä): ihmisen on hyväksyttävä se työpöytäsovelluksessa, tai anna `allowHeavy: true` istunnossa, joka on käynnistetty valitsimella --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`-kentässä on oltava 1-64 tulostettavaa merkkiä +@msg `{key}` must be 1-64 printable characters `{key}`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg `version`, `description` or `author` is too long `version`, `description` tai `author` on liian pitkä @msg `warnings` must be a list of strings `warnings` on oltava merkkijonojen luettelo @msg `{k}` must be one of {_1} `{k}` on oltava jokin seuraavista: {_1} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..56ea0bac94 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7298,6 +7298,7 @@ axis Y Axis Axe Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants « {_1} » demande un budget de calcul important (chaque exécution jusqu’à {minutes} minutes et {times} fois les instructions habituelles) : une personne doit l’approuver dans l’application de bureau, ou passez `allowHeavy: true` dans une session démarrée avec --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` doit compter 1-64 caractères imprimables +@msg `{key}` must be 1-64 printable characters `{key}` doit compter 1-64 caractères imprimables @msg `version`, `description` or `author` is too long `version`, `description` ou `author` est trop long @msg `warnings` must be a list of strings `warnings` doit être une liste de chaînes @msg `{k}` must be one of {_1} `{k}` doit valoir l’une de ces valeurs : {_1} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..54817a47c7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7114,6 +7114,7 @@ arrowhead Feather पंख @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @msg `name` must be 1-64 printable characters `name` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए +@msg `{key}` must be 1-64 printable characters `{key}` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg `names` is a list of preset names `names` प्रीसेट नामों की सूची है @msg `names` lists preset names `names` प्रीसेट नामों की सूची देता है @msg `names` must be a list of names `names` को नामों की सूची होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8b6374bd63 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7287,6 +7287,7 @@ axis Y Axis Y tengely @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants a(z) „{_1}” nagy számítási keretet kér (futásonként legfeljebb {minutes} perc és a szokásos utasításszám {times}-szorosa): egy személynek jóvá kell hagynia az asztali alkalmazásban, vagy add meg az `allowHeavy: true` értéket egy --allow-plugin-grants kapcsolóval indított munkamenetben # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters a `name` 1-64 nyomtatható karakter legyen +@msg `{key}` must be 1-64 printable characters a `{key}` 1-64 nyomtatható karakter legyen @msg `version`, `description` or `author` is too long a `version`, a `description` vagy az `author` túl hosszú @msg `warnings` must be a list of strings a `warnings` karakterláncok listája legyen @msg `{k}` must be one of {_1} `{k}`: ezek egyike kell: {_1} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..4ca1800dc3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -415,6 +415,7 @@ @msg an exporter always gets an export's budget: leave `budget` out pengekspor selalu mendapat anggaran ekspor: hilangkan `budget` @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” meminta anggaran berat (setiap proses hingga {minutes} menit dan {times} kali instruksi biasa): seseorang harus menyetujuinya di aplikasi desktop, atau berikan `allowHeavy: true` dalam sesi yang dimulai dengan --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` harus berupa 1-64 karakter yang dapat dicetak +@msg `{key}` must be 1-64 printable characters `{key}` harus berupa 1-64 karakter yang dapat dicetak @msg `version`, `description` or `author` is too long `version`, `description` atau `author` terlalu panjang @msg `warnings` must be a list of strings `warnings` harus berupa daftar string @msg `{k}` must be one of {_1} `{k}` harus salah satu dari {_1} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..3a8c3a60d1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6924,6 +6924,7 @@ axis Y Axis Asse Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” chiede un budget di calcolo elevato (ogni esecuzione fino a {minutes} minuti e {times} volte le istruzioni consuete): una persona deve approvarlo nell’app desktop, oppure passa `allowHeavy: true` in una sessione avviata con --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve avere 1-64 caratteri stampabili +@msg `{key}` must be 1-64 printable characters `{key}` deve avere 1-64 caratteri stampabili @msg `version`, `description` or `author` is too long `version`, `description` o `author` è troppo lungo @msg `warnings` must be a list of strings `warnings` deve essere un elenco di stringhe @msg `{k}` must be one of {_1} `{k}` deve essere uno dei seguenti: {_1} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..f261704aae 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6999,6 +6999,7 @@ axis Y Axis Y 軸 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」は大きな計算予算を求めています (1 回の実行につき最大 {minutes} 分、通常の {times} 倍の命令)。デスクトップ アプリで人が承認するか、--allow-plugin-grants を付けて開始したセッションで `allowHeavy: true` を指定してください # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` は印刷可能な 1-64 文字にしてください +@msg `{key}` must be 1-64 printable characters `{key}` は印刷可能な 1-64 文字にしてください @msg `version`, `description` or `author` is too long `version`、`description` または `author` が長すぎます @msg `warnings` must be a list of strings `warnings` は文字列のリストにしてください @msg `{k}` must be one of {_1} `{k}` は {_1} のいずれかにしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ef9708d8a0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9404,6 +9404,7 @@ axis Y Axis Y ღერძი @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}“ დიდ გამოთვლით ბიუჯეტს ითხოვს (თითო გაშვება {minutes} წუთამდე და ჩვეულებრივზე {times}-ჯერ მეტი ინსტრუქცია): ის დესკტოპის აპში ადამიანმა უნდა დაამტკიცოს, ან გადაეცით `allowHeavy: true` --allow-plugin-grants-ით გაშვებულ სესიაში # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან +@msg `{key}` must be 1-64 printable characters `{key}` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg `version`, `description` or `author` is too long `version`, `description` ან `author` ზედმეტად გრძელია @msg `warnings` must be a list of strings `warnings` უნდა იყოს სტრიქონების სია @msg `{k}` must be one of {_1} `{k}` უნდა იყოს ერთ-ერთი: {_1} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..c28c2e1ca0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6896,6 +6896,7 @@ axis Y Axis Y축 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”은(는) 큰 계산 예산을 요청합니다(실행당 최대 {minutes}분, 평소의 {times}배 명령어). 데스크톱 앱에서 사람이 승인하거나 --allow-plugin-grants로 시작한 세션에서 `allowHeavy: true`를 전달하세요 # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name`은(는) 인쇄 가능한 문자 1-64자여야 합니다 +@msg `{key}` must be 1-64 printable characters `{key}`은(는) 인쇄 가능한 문자 1-64자여야 합니다 @msg `version`, `description` or `author` is too long `version`, `description` 또는 `author`가 너무 깁니다 @msg `warnings` must be a list of strings `warnings`는 문자열 목록이어야 합니다 @msg `{k}` must be one of {_1} `{k}`은(는) {_1} 중 하나여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..c612a8a9fd 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -379,6 +379,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg an exporter always gets an export's budget: leave `budget` out een exportplug-in krijgt altijd het budget van een export: laat `budget` weg @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” vraagt om een groot rekenbudget (elke uitvoering tot {minutes} minuten en {times} keer het gebruikelijke aantal instructies): een persoon moet dit goedkeuren in de desktop-app, of geef `allowHeavy: true` door in een sessie die is gestart met --allow-plugin-grants @msg `name` must be 1-64 printable characters `name` moet uit 1-64 afdrukbare tekens bestaan +@msg `{key}` must be 1-64 printable characters `{key}` moet uit 1-64 afdrukbare tekens bestaan @msg `version`, `description` or `author` is too long `version`, `description` of `author` is te lang @msg `warnings` must be a list of strings `warnings` moet een lijst met strings zijn @msg `{k}` must be one of {_1} `{k}` moet een van {_1} zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..b5239d8a39 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7157,6 +7157,7 @@ axis Y Axis Oś Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants „{_1}” prosi o duży budżet obliczeń (każde uruchomienie do {minutes} minut i {times} razy więcej instrukcji niż zwykle): musi ją zatwierdzić osoba w aplikacji desktopowej albo przekaż `allowHeavy: true` w sesji uruchomionej z --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` musi mieć 1-64 drukowalnych znaków +@msg `{key}` must be 1-64 printable characters `{key}` musi mieć 1-64 drukowalnych znaków @msg `version`, `description` or `author` is too long `version`, `description` lub `author` jest za długie @msg `warnings` must be a list of strings `warnings` musi być listą ciągów znaków @msg `{k}` must be one of {_1} `{k}` musi mieć jedną z wartości: {_1} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..2bb3e74c81 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7201,6 +7201,7 @@ axis Y Axis Eixo Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” pede um orçamento de processamento grande (cada execução até {minutes} minutos e {times} vezes as instruções habituais): uma pessoa precisa aprová-lo no aplicativo de desktop, ou passe `allowHeavy: true` em uma sessão iniciada com --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` deve ter 1-64 caracteres imprimíveis +@msg `{key}` must be 1-64 printable characters `{key}` deve ter 1-64 caracteres imprimíveis @msg `version`, `description` or `author` is too long `version`, `description` ou `author` é longo demais @msg `warnings` must be a list of strings `warnings` deve ser uma lista de strings @msg `{k}` must be one of {_1} `{k}` deve ser um de {_1} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..4f1bff082f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6923,6 +6923,7 @@ axis Y Axis Ось Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запрашивает большой вычислительный бюджет (каждый запуск до {minutes} минут и в {times} раз больше инструкций, чем обычно): его должен одобрить человек в настольном приложении, либо передайте `allowHeavy: true` в сеансе, запущенном с --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` должен содержать 1-64 печатаемых символа +@msg `{key}` must be 1-64 printable characters `{key}` должен содержать 1-64 печатаемых символа @msg `version`, `description` or `author` is too long `version`, `description` или `author` слишком длинное @msg `warnings` must be a list of strings `warnings` должно быть списком строк @msg `{k}` must be one of {_1} `{k}` должно быть одним из: {_1} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..ed74b506a9 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8933,6 +8933,7 @@ digits Hindi Hindi @msg `mode` must be one of {_1} `mode` måste vara något av {_1} @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` måste vara "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" eller "lineEndHalf" @msg `name` must be 1-64 printable characters `name` måste vara 1-64 utskrivbara tecken +@msg `{key}` must be 1-64 printable characters `{key}` måste vara 1-64 utskrivbara tecken @msg `names` is a list of preset names `names` är en lista med namn på förinställningar @msg `names` lists preset names `names` listar namn på förinställningar @msg `names` must be a list of names `names` måste vara en lista med namn diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..9009698065 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5425,7 +5425,7 @@ fn script_interpreter_core_errors_are_translated() { } } -/// A manifest whose `commands` value has the wrong shape is refused with an error that every +/// A manifest whose `commands` value, or a command's `menu`, has the wrong shape is refused with an error that every /// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the /// manifest included. #[test] @@ -5442,9 +5442,35 @@ fn wrongly_shaped_plugin_commands_errors_are_translated() { r#"[{"id":"x","id":"y","label":"A"}]"#.to_string(), format!("[{}]", many.join(",")), ]; - let english = ["must", "list", "missing", "field", "duplicate", "object", "line", "column", "each", "with", "invalid", "expected"]; - for value in &commands { - let manifest = format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#); + let english = [ + "must", + "list", + "missing", + "field", + "duplicate", + "object", + "line", + "column", + "each", + "with", + "invalid", + "expected", + "unknown", + "printable", + "characters", + ]; + // A `menu` of the wrong shape (read at API level 2). + let menus = [ + r#"{"path":["File"]}"#, + r#"{"path":["Select"],"before":"Inverse"}"#, + r#"{"path":["Select"],"after":3}"#, + r#"{"path":["Select"],"after":" "}"#, + r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, + ]; + let manifests = commands.iter().map(|value| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":{value}}}"#)).chain( + menus.iter().map(|menu| format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{{"id":"x","label":"A","menu":{menu}}}]}}"#)), + ); + for manifest in manifests { let e = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); let numbers: Vec<&str> = e.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); for code in COMPLETE_MESSAGES { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..6663b1385e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7374,6 +7374,7 @@ axis Y Axis Y ekseni @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” büyük bir hesaplama bütçesi istiyor (her çalıştırma en fazla {minutes} dakika ve olağan komutların {times} katı): masaüstü uygulamasında bir kişinin onaylaması gerekir veya --allow-plugin-grants ile başlatılan bir oturumda `allowHeavy: true` geçirin # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 1-64 yazdırılabilir karakter olmalıdır +@msg `{key}` must be 1-64 printable characters `{key}` 1-64 yazdırılabilir karakter olmalıdır @msg `version`, `description` or `author` is too long `version`, `description` veya `author` çok uzun @msg `warnings` must be a list of strings `warnings` bir dize listesi olmalıdır @msg `{k}` must be one of {_1} `{k}` şunlardan biri olmalıdır: {_1} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..2bf33a0d89 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6906,6 +6906,7 @@ axis Y Axis Вісь Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» запитує великий обчислювальний бюджет (кожен запуск до {minutes} хвилин і в {times} разів більше інструкцій, ніж зазвичай): його має схвалити людина в настільному застосунку, або передайте `allowHeavy: true` у сеансі, запущеному з --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` має містити 1-64 друковані символи +@msg `{key}` must be 1-64 printable characters `{key}` має містити 1-64 друковані символи @msg `version`, `description` or `author` is too long `version`, `description` або `author` задовге @msg `warnings` must be a list of strings `warnings` має бути списком рядків @msg `{k}` must be one of {_1} `{k}` має бути одним з: {_1} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..73c4984e17 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6952,6 +6952,7 @@ axis Y Axis Trục Y @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}” yêu cầu ngân sách tính toán lớn (mỗi lần chạy tới {minutes} phút và gấp {times} lần số lệnh thông thường): cần một người phê duyệt trong ứng dụng máy tính, hoặc truyền `allowHeavy: true` trong phiên khởi động bằng --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` phải có 1-64 ký tự in được +@msg `{key}` must be 1-64 printable characters `{key}` phải có 1-64 ký tự in được @msg `version`, `description` or `author` is too long `version`, `description` hoặc `author` quá dài @msg `warnings` must be a list of strings `warnings` phải là một danh sách chuỗi @msg `{k}` must be one of {_1} `{k}` phải là một trong {_1} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..2a0fbcd5a4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7134,6 +7134,7 @@ axis Y Axis Y 轴 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants “{_1}”需要大量计算预算(每次运行最多 {minutes} 分钟,指令数为通常的 {times} 倍):需要有人在桌面应用中批准,或在以 --allow-plugin-grants 启动的会话中传入 `allowHeavy: true` # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必须是 1-64 个可打印字符 +@msg `{key}` must be 1-64 printable characters `{key}` 必须是 1-64 个可打印字符 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太长 @msg `warnings` must be a list of strings `warnings` 必须是字符串列表 @msg `{k}` must be one of {_1} `{k}` 必须是 {_1} 之一 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..5a3d90d647 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6955,6 +6955,7 @@ axis Y Axis Y 軸 @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants 「{_1}」需要大量運算預算(每次執行最多 {minutes} 分鐘,指令數為一般的 {times} 倍):需要有人在桌面應用程式中核准,或在以 --allow-plugin-grants 啟動的工作階段中傳入 `allowHeavy: true` # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` 必須是 1-64 個可列印字元 +@msg `{key}` must be 1-64 printable characters `{key}` 必須是 1-64 個可列印字元 @msg `version`, `description` or `author` is too long `version`、`description` 或 `author` 太長 @msg `warnings` must be a list of strings `warnings` 必須是字串清單 @msg `{k}` must be one of {_1} `{k}` 必須是 {_1} 其中之一 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ac5ec6825b..8b18e296ae 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -76,9 +76,9 @@ pub use invoke::{click_target, invoke, invoke_from_system_menu}; pub(crate) use keyboard::handle_input as handle_keyboard_input; // Shared numeric fields preserve their caret when a transient menu returns their focus. pub(crate) use keyboard::restoring_field_focus; -pub(crate) use labels::lists_plugin; pub(crate) use labels::shows_a_name; pub use labels::{CONTEXT_LABELS, DYNAMIC_LABELS, display_label, dynamic_label, item_shortcut, menu_strings}; +pub(crate) use labels::{holds_plugin_commands, lists_plugin}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 61a4bf5872..4a004cdbb7 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -334,9 +334,14 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Lock Grid", ]; -/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares? +/// Is `children` a plug-in's submenu: does it hold a command the plug-in declares, and only items +/// that list plug-ins? A built-in submenu that a plug-in's manifest places a command in is not. pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { children.iter().any(|c| matches!(c, Item::Cmd(_, id, _) if vectorcraft_engine::cmd::plugin::is_command_id(id))) + && children.iter().all(|c| match c { + Item::Cmd(_, id, params) => lists_plugin(id, params), + _ => true, + }) } /// Every English string the menus, the command palette, the panel registry, the toolbar and the diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..cceb9c214c 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -11,6 +11,14 @@ pub fn menu_tree() -> Vec<(&'static str, Vec)> { } pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { + let mut tree = built_in_tree(english_names); + crate::dialogs::plugin::place_commands(&mut tree); + tree +} + +/// The menus with each plug-in command in its plug-in's submenu, before +/// [`crate::dialogs::plugin::place_commands`] moves those whose manifest names another menu. +fn built_in_tree(english_names: bool) -> Vec<(&'static str, Vec)> { let panel = |label: &'static str, id: &'static str| cp(label, "window.panel", json!({ "panel": id, "toggle": true })); vec![ ( diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..7a57447356 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -619,6 +619,217 @@ fn plugin_commands_are_menu_items_and_shortcut_entries() { assert!(crate::keymap::template().bindable(&crate::keymap::command_of(grow)).is_none()); } +/// A filter at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_plugin(id: &str, name: &str, commands: &str) -> String { + placing_kind(id, name, "filter", commands) +} + +/// A plug-in of `kind` at API level 2 named `name` whose commands are `commands` (a JSON list). +fn placing_kind(id: &str, name: &str, kind: &str, commands: &str) -> String { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"{kind}","commands":{commands}}}"#); + vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()) +} + +/// A command whose manifest's `menu` names another menu is listed there, after the built-in item +/// `after` names or at the end of the menu, with its plug-in's name after its label, and not in its +/// plug-in's submenu; one with no `menu` stays there. Commands of two plug-ins at the same spot are +/// listed in plug-in id order whichever was installed first. Keyboard Shortcuts and the command +/// palette list it under its menu, and removing its plug-in takes it out of every menu. +#[test] +fn a_plugin_command_is_placed_in_the_menu_its_manifest_names() { + let mut app = app(); + let (ant, bee) = ("test.ui.place.ant", "test.ui.place.bee"); + let low = |id: &str| vectorcraft_engine::cmd::plugin::command_id(id, "low"); + // Bee is installed first; Ant's id sorts first. + let bee_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}, + {"id":"tail","label":"Tail","menu":{"path":["Select"],"after":"No Such Item"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(bee, "Bee", bee_commands)})).unwrap(); + let ant_commands = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse…"},"params":{"area":{"type":"number","min":0,"max":100,"default":4}}}, + {"id":"same","label":"Same Area","menu":{"path":["Select","Same"]}}, + {"id":"lost","label":"Lost Anchor","menu":{"path":["Select"],"after":"No Such Item"}}, + {"id":"end","label":"End","menu":{"path":["Select"]}}, + {"id":"edges","label":"Edges","menu":{"path":["View"],"after":"Show Edges"}}, + {"id":"stay","label":"Stay"}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(ant, "Ant", ant_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let at = |command: &str| select.iter().position(|e| e.command.as_deref() == Some(command)); + let inverse = at("select.inverse").expect("Inverse is listed"); + assert_eq!((at(&low(ant)), at(&low(bee))), (Some(inverse + 1), Some(inverse + 2)), "after Inverse, Ant's before Bee's"); + assert_eq!(select[inverse + 1].label, "Low Area (Ant)…", "the item names its plug-in"); + assert_eq!(select[inverse + 2].label, "Low Area (Bee)"); + // An `after` that names no item means the end of the menu, as no `after` does, and the end keeps + // plug-in id order and then manifest order too. + let command = vectorcraft_engine::cmd::plugin::command_id; + let lost = command(ant, "lost"); + let tail = [at(&lost), at(&command(ant, "end")), at(&command(bee, "tail"))]; + let n = select.len(); + assert_eq!(tail, [Some(n - 3), Some(n - 2), Some(n - 1)], "Ant's two, then Bee's, at the end"); + let same = vectorcraft_engine::cmd::plugin::command_id(ant, "same"); + assert!(entry(&entries, &["Select", "Same"], "Same Area (Ant)").is_some_and(|e| e.command.as_deref() == Some(same.as_str()))); + assert!(menus::menu_strings().contains("Same"), "Select › Same is still a built-in submenu"); + // An item that switches between two labels is matched by either of them. + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let edges = view.iter().position(|e| e.command.as_deref() == Some("view.edges")).expect("Hide Edges is listed"); + assert_eq!(view.get(edges + 1).and_then(|e| e.command.clone()), Some(command(ant, "edges")), "after the edges toggle"); + + // Each placed command is in one menu only; Stay is still in Ant's submenu. + for command in [low(ant), low(bee), same.clone(), lost.clone()] { + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(command.as_str())).count(), 1, "{command}"); + } + assert!(entry(&entries, &["Object", "Plug-ins", "Ant"], "Stay").is_some()); + let bee_item = entry(&entries, &["Object", "Plug-ins"], "Bee").expect("Bee is a plain item again: all its commands are placed"); + assert_eq!(bee_item.command.as_deref(), Some("plugin.dialog")); + + let listed = crate::shortcut_editor::entry(&low(ant)).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area (Ant)", "Select")); + assert!(crate::palette::items().iter().any(|(name, id, _)| *id == low(bee) && name.ends_with("Low Area (Bee)")), "in the command palette"); + + app.run("plugin.remove", json!({"id": ant})).unwrap(); + let entries = menus::menu_entries(&app); + assert!(entries.iter().all(|e| e.command.as_deref().is_none_or(|c| !c.starts_with("plugin.test.ui.place.ant."))), "Ant's commands are gone"); + assert!(entries.iter().any(|e| e.path == ["Select"] && e.command.as_deref() == Some(low(bee).as_str()))); + app.run("plugin.remove", json!({"id": bee})).unwrap(); + assert!(menus::menu_entries(&app).iter().all(|e| e.command.as_deref() != Some(low(bee).as_str()))); + assert!(crate::shortcut_editor::entries().iter().all(|e| e.key != low(bee))); +} + +/// A live effect whose commands are all placed elsewhere is a single item in Effect › Plug-ins. A +/// filter with the same name placing a command with the same label at the same spot keeps it in its +/// own submenu, so the menu shows that label once. Replaced by a module whose command has no +/// `menu`, the effect's command leaves the menu it was placed in and is listed once, in its +/// submenu. +#[test] +fn placed_commands_of_a_live_effect_and_a_clashing_label() { + let mut app = app(); + let (eff, twin) = ("test.ui.place.eff", "test.ui.place.twin"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let placed = r#"[{"id":"low","label":"Low Area","menu":{"path":["Select"],"after":"Inverse"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_kind(eff, "Glow", "effect", placed)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(twin, "Glow", placed)})).unwrap(); + + let entries = menus::menu_entries(&app); + let (low, twin_low) = (command(eff, "low"), command(twin, "low")); + let in_select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"] && e.label == "Low Area (Glow)").collect(); + assert_eq!(in_select.len(), 1, "the label is listed once"); + assert_eq!(in_select[0].command.as_deref(), Some(low.as_str()), "the plug-in with the lower id takes the spot"); + let own = entry(&entries, &["Effect", "Plug-ins"], "Glow").expect("the effect is a single item"); + assert!(own.command.as_deref().is_some_and(|c| !vectorcraft_engine::cmd::plugin::is_command_id(c)), "{:?}", own.command); + assert!(entries.iter().all(|e| e.path != ["Effect", "Plug-ins", "Glow"]), "no submenu is left"); + assert!(entry(&entries, &["Object", "Plug-ins", "Glow"], "Low Area").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str()))); + let listed = crate::shortcut_editor::entry(&twin_low).expect("in Keyboard Shortcuts"); + assert_eq!((listed.label.as_str(), listed.group.as_str()), ("Low Area", "Object › Plug-ins › Glow")); + + // An item whose two labels share no first word is matched by either label too. + let global = "test.ui.place.global"; + let after_stop = r#"[{"id":"next","label":"Next","menu":{"path":["Select"],"after":"Stop Global Edit"}}]"#; + app.run("plugin.install", json!({"dataBase64": placing_plugin(global, "Global", after_stop)})).unwrap(); + let entries = menus::menu_entries(&app); + let select: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["Select"]).collect(); + let toggle = select.iter().position(|e| e.command.as_deref() == Some("select.globalEdit")).expect("Start Global Edit is listed"); + assert_eq!(select.get(toggle + 1).and_then(|e| e.command.clone()), Some(command(global, "next"))); + app.run("plugin.remove", json!({"id": global})).unwrap(); + + let unplaced = placing_kind(eff, "Glow", "effect", r#"[{"id":"low","label":"Low Area"}]"#); + app.run("plugin.install", json!({"dataBase64": unplaced, "replace": true})).unwrap(); + let entries = menus::menu_entries(&app); + assert_eq!(entries.iter().filter(|e| e.command.as_deref() == Some(low.as_str())).count(), 1, "listed once"); + assert!(entry(&entries, &["Effect", "Plug-ins", "Glow"], "Low Area").is_some(), "back in its submenu"); + assert!( + entry(&entries, &["Select"], "Low Area (Glow)").is_some_and(|e| e.command.as_deref() == Some(twin_low.as_str())), + "the filter's takes the spot" + ); + for id in [eff, twin] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// Every menu a manifest's `menu` may name is a built-in menu of the menu bar, so a command placed +/// there is never left in its plug-in's submenu while Keyboard Shortcuts lists it under that menu. +#[test] +fn every_menu_a_plugin_may_name_is_in_the_menu_bar() { + fn find<'a>(items: &'a [menus::Item], label: &str) -> Option<&'a [menus::Item]> { + items.iter().find_map(|it| match it { + menus::Item::Sub(l, children) if *l == label => Some(children.as_slice()), + _ => None, + }) + } + let tree = menus::menu_tree(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut menu = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()); + for segment in rest { + menu = menu.and_then(|m| find(m, segment)); + } + assert!(menu.is_some(), "{place:?} is in the menu bar"); + } +} + +/// Every engine command whose menu item switches between two labels is in the engine's +/// `SWITCHING_LABELS`, so a placed plug-in command that reads like its other label stays in its +/// plug-in's submenu without the desktop app too. +#[test] +fn engine_commands_with_two_labels_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{SWITCHING_LABELS, other_state}; + for spec in vectorcraft_engine::cmd::command_specs() { + let switches = menus::DYNAMIC_LABELS.contains(&spec.label) + && other_state(spec.label).is_some_and(|other| menus::DYNAMIC_LABELS.contains(&other.as_str())); + assert_eq!(SWITCHING_LABELS.contains(&spec.label), switches, "{} ({})", spec.id, spec.label); + } +} + +/// Every item of a menu a plug-in command may be placed in, other than an engine command of that +/// menu, is in the engine's `DESKTOP_MENU_ITEMS` with both of its labels, so a placed plug-in +/// command that reads like it stays in its plug-in's submenu without the desktop app too. +#[test] +fn desktop_items_of_placeable_menus_are_known_to_the_engine() { + use vectorcraft_engine::cmd::plugin::{DESKTOP_MENU_ITEMS, SWITCHING_LABELS, other_state}; + let key = |l: &str| l.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect::(); + let tree = menus::menu_tree(); + let mut missing = Vec::new(); + for place in vectorcraft_plugins::manifest::MENU_PLACES { + let (first, rest) = place.split_first().unwrap(); + let mut items = tree.iter().find(|(title, _)| title == first).map(|(_, items)| items.as_slice()).unwrap(); + for segment in rest { + items = items + .iter() + .find_map(|it| match it { + menus::Item::Sub(l, children) if l == segment => Some(children.as_slice()), + _ => None, + }) + .unwrap(); + } + let engine_reads = |label: &str| { + vectorcraft_engine::cmd::command_specs().iter().any(|s| { + s.menu == *place + && (key(s.label) == key(label) + || SWITCHING_LABELS.contains(&s.label) && other_state(s.label).is_some_and(|o| key(&o) == key(label))) + }) + }; + for it in items { + let label = match it { + menus::Item::Cmd(l, id, p) if !menus::lists_plugin(id, p) => *l, + menus::Item::Sub(l, children) if !menus::holds_plugin_commands(children) => *l, + menus::Item::Todo(l, _) => *l, + _ => continue, + }; + let mut labels = vec![label.to_string()]; + if menus::DYNAMIC_LABELS.contains(&label) { + labels.extend(other_state(label)); + } + for l in labels { + let known = DESKTOP_MENU_ITEMS.iter().any(|(path, d)| path == place && key(d) == key(&l)); + if !engine_reads(&l) && !known && !missing.contains(&(place, l.clone())) { + missing.push((place, l)); + } + } + } + } + let rows: Vec = missing.iter().map(|(place, l)| format!(" (&{place:?}, {l:?}),")).collect(); + assert!(missing.is_empty(), "missing from DESKTOP_MENU_ITEMS:\n{}", rows.join("\n")); +} + /// A shortcut the user gives a plug-in command runs it. #[test] fn a_shortcut_runs_a_plugin_command() { diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..914f26f211 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13362,7 +13362,9 @@ changes nothing when a new `pluginsFolder` is missing, is not a folder or can't value or the folder the preference already holds, and the web build does not check folders. A filter or live effect may declare commands of its own ([plugins.md](plugins.md#commands)): each is the command `plugin..` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry -(`commands: [{id, command, label, params, paramsSchema}]`). Run it with `{ids?, params?}` (its parameters may also +(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path, after?, placed?}`, is the menu its +manifest places it in, with `placed: false` when the command stays in its plug-in's submenu, see +[plugins.md](plugins.md#placing-a-command-in-another-menu)). Run it with `{ids?, params?}` (its parameters may also be top-level keys): the parameters are checked before the plug-in runs, a run is one undo step named after the command, and a run that traps or runs out of its instruction budget returns an error that starts with the plug-in's name and the command's label and leaves the document and the undo history as they were. For `plugin.run` and plug-in diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..bd1a5b6073 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -88,14 +88,15 @@ replaced by a module without it. - **Menus.** A plug-in with commands is a submenu of **Object › Plug-ins** (a live effect: **Effect › Plug-ins**) named after the plug-in. The submenu holds the plug-in's own item, then its commands. A command with parameters has - an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A manifest cannot put a - command in another menu: a `menu` key in a command is ignored. -- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its submenu, and the user can give it a + an ellipsis and opens a dialog for them, with a live preview, as a filter's own item does. A command whose manifest + gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)). +- **Keyboard Shortcuts.** Edit › Keyboard Shortcuts lists each command under its menu, and the user can give it a shortcut. A manifest cannot give a command a shortcut. - **Actions and agents.** A command run is recorded in an action like any other command and plays back with its parameters. `run`, MCP and `command.batch` call it as `plugin..` with `{"ids"?: [...], "params"?: {…}}` (its parameters may also be top-level keys). MCP's `command_list` and `list_commands` list it, and `plugin.list` - lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema}]`. + lists a plug-in's commands as `commands: [{id, command, label, params, paramsSchema, menu?}]`, with `menu` for a + command whose manifest places it in another menu. - **Runs.** The parameters are checked against the command's declarations before the plug-in runs. The plug-in runs through `vc_run` on the selection (or `ids`) as a filter run does, with `_context.mode` `"command"` and `_context.command` set to the command's id ([Parameters](#parameters)), under the plug-in's @@ -105,6 +106,40 @@ replaced by a module without it. document and the undo history as they were, and the error starts with the plug-in's name and the command's label (`“Cmd Test” › Grow: …`). +#### Placing a command in another menu + +At `api` 2 a command may name the menu it is listed in with `menu`: `{"path": [menu, …], "after"?: item}`. For +example, `"menu": {"path": ["Select"], "after": "Inverse"}` lists the command in the Select menu right after +Inverse. + +- `path` is one of these menus, by their English labels: `["Edit"]`, `["Edit", "Edit Colors"]`, `["Object"]`, + `["Object", "Transform"]`, `["Object", "Arrange"]`, `["Object", "Path"]`, `["Object", "Compound Path"]`, + `["Object", "Clipping Mask"]`, `["Type"]`, `["Select"]`, `["Select", "Same"]`, `["Select", "Object"]`, `["Effect"]` + and `["View"]`. The File, Window and Help menus, the application menu, Edit › Preferences and the submenus that list + files, fonts, panels or plug-ins cannot be named. Any other `path`, a `menu` that is not an object or is given twice, + a key other than `path` and `after`, and an `after` that is not 1–64 printable characters are refused when the + module is installed, and the error names the command. +- `after` is the English label of a built-in item or submenu of that menu, with or without its closing ellipsis + (`"Inverse"`). The command is listed right after it. An item that switches between two labels is matched by either + of them (`"Show Edges"` and `"Hide Edges"`, `"Start Global Edit"` and `"Stop Global Edit"`). Without `after`, or when no + built-in item of the menu has that label, the command is listed at the end of the menu, and the module still + installs. Items of plug-ins are never matched. +- The item's label is the command's label followed by the plug-in's name in parentheses (`Low Area Closed Paths + (Tidy)`). Keyboard Shortcuts, the command palette and `command_list` list the command under that menu with that + label. +- A command stays in its plug-in's submenu, under its own label, when its label with the plug-in's name has the same + letters and digits, ignoring case, as a built-in item or submenu of that menu (`Paste (in Place)` and Edit › Paste + in Place, `Hide (Edges)` and View › Hide Edges; either label of one that switches between two), or as a command that + a plug-in with a lower id, or an earlier command of the same plug-in, places in that menu. The desktop app and + `vectorcraft-cli` give the same result. `plugin.list` then gives the command's `menu` with + `"placed": false`. +- Commands of several plug-ins placed at the same spot are listed in plug-in id order, then in manifest order. A + plug-in whose commands all name another menu is listed in Object › Plug-ins (or Effect › Plug-ins) as a single item, + without a submenu. Commands without `menu` stay in the plug-in's submenu. +- A placed command leaves the menus when its plug-in is removed or replaced by a module without the command. Turning + the plug-in off (`plugin.setEnabled`) removes it at the next launch. +- At `api` 1 a `menu` key, repeated or not, is ignored and the command stays in the plug-in's submenu. + **Preference folder.** Edit › Preferences › Plug-ins & Scratch Disks › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; the web build installs from bytes). On the desktop, Choose… beside the field picks the folder; the dialog refuses a @@ -566,10 +601,12 @@ the module's start function, in a run that isn't a filter's run on a document, o list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and `document.open` reads a file with the importer only when `importer` names it. - `commands` (filters and live effects; not heavy filters): up to 32 commands of the plug-in's own - ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}}`. An `id` is 1–32 characters from - `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with - control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` are. A malformed - entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). + ([Commands](#commands)), each `{"id": "grow", "label": "Grow", "params"?: {…}, "menu"?: {…}}`. An `id` is 1–32 + characters from `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; + menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` + are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu). + A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, + `[0]`). - `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..e352be65f6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2672,7 +2672,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) unless its manifest places it in another menu, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands of several plug-ins at one spot keep plug-in id order; a plug-in whose commands are all placed elsewhere is a single item in Object › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged. - **A drag ended by a command with Real-time Drawing off:** when Undo, Redo, a filter that calls commands or a plug-in command that calls commands ends a drag whose preview Real-time Drawing off has not applied yet, the preview is applied first and kept as an undo step of its own, as releasing the drag keeps it; a preview that fails cancels the drag. The filter or plug-in command is then given the objects where the drag left them. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`. Scores and hours unchanged.