diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 44caf0515d..ab77ba5a02 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); @@ -497,15 +509,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(); @@ -518,11 +793,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), @@ -1301,7 +1579,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 1c0539a2f9..0e183e0a6e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4798,6 +4798,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 081b6b49dd..18e0cb1f84 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -711,9 +711,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( @@ -727,7 +728,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)| { @@ -746,8 +757,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"]); } @@ -760,6 +772,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(); @@ -778,7 +796,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 899cdb9152..b9e36cfd24 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -34,6 +34,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 trimmed = s.trim(); + if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) { + return Err(format!("`{key}` must be 1-64 printable characters")); + } + Some(trimmed.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")] @@ -223,9 +291,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. @@ -236,6 +304,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 { @@ -244,6 +319,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 { @@ -364,8 +451,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) } @@ -401,6 +489,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<()> { @@ -809,7 +922,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()))) }; @@ -828,6 +941,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::()?; @@ -844,7 +962,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 }) } } @@ -1220,7 +1338,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() { @@ -1242,7 +1360,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(); @@ -1298,6 +1416,65 @@ 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)); + let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64)); + 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"), + (r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"), + (long.as_str(), "`menu.after` must be 1-64 printable characters"), + (padded.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 6b6952a6ca..94f8ed84df 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -11,6 +11,7 @@ //! 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`]). +//! 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; one with @@ -78,6 +79,117 @@ fn with_commands(plugin: &Plugin, own: Node) -> Node { 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 command in &m.commands { + let Some(place) = &command.place else { continue }; + if vectorcraft_engine::cmd::plugin::placed_menu(&p, command).is_none() { + continue; + } + // An `after` that names no built-in item of the menu means the end of it, as no `after` does. + // The spot is the item's own label, so both labels of an item that switches are one spot. + let after = place.after.as_deref().and_then(|a| { + let menu = menu_at(tree, place.path)?; + menu.iter().find(|it| is_anchor(it, anchor_key(a))).and_then(own_key).map(str::to_string) + }); + let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &command.id)); + let item = c(label(&command.menu_label(&m.name), !command.params.is_empty()), id); + 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 = spots + .iter() + .flat_map(|s| s.2.iter()) + .filter_map(|it| match it { + Node::Item(i) => Some(i.command.id.clone()), + _ => 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| own_key(it) == Some(a.as_str()))).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: &Node, key: &str) -> bool { + let other = |l: &str| crate::menus::DYNAMIC_LABELS.contains(&l) && vectorcraft_engine::cmd::plugin::other_state(l).is_some_and(|o| o == key); + own_key(it).is_some_and(|own| own == key || matches!(it, Node::Item(i) if other(&i.label))) +} + +/// The label of `it` as [`anchor_key`] reads it, when `it` is a built-in item or submenu that can be +/// an anchor; `None` for an item that lists a plug-in. +fn own_key(it: &Node) -> Option<&str> { + match it { + Node::Item(i) if !crate::menus::lists_plugin(&i.command.id, &i.command.params) => Some(anchor_key(&i.label)), + Node::Submenu { label, children, .. } if !crate::menus::holds_plugin_commands(children) => Some(anchor_key(label)), + _ => None, + } +} + +/// 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 { + Node::Submenu { label, children, .. } if label.as_str() == *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 [Node], placed: &std::collections::HashSet) { + for it in items.iter_mut() { + let Node::Submenu { children, .. } = it else { continue }; + if !crate::menus::holds_plugin_commands(children) { + leave_out(children, placed); + continue; + } + children.retain(|c| !matches!(c, Node::Item(i) if placed.contains(&i.command.id))); + if !children.iter().any(|c| matches!(c, Node::Item(i) if vectorcraft_engine::cmd::plugin::is_command_id(&i.command.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/menus.rs b/crates/ui-egui/src/menus.rs index 7d003be560..499ee94817 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -66,9 +66,9 @@ use entries::flatten; pub use entries::{InsertableItem, MenuEntry, context_entries, insertable, insertable_items, menu_entries, plays_in_app, shown_label}; pub(crate) use invoke::graph_dialog; pub use invoke::{click_target, invoke}; -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(crate) use model::{MAC_LABELS, home_key, home_showing}; pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 030eb40b98..d26e0d1806 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -344,9 +344,14 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Advanced", ]; -/// 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: &[Node]) -> bool { children.iter().any(|c| matches!(c, Node::Item(i) if vectorcraft_engine::cmd::plugin::is_command_id(&i.command.id))) + && children.iter().all(|c| match c { + Node::Item(i) => lists_plugin(&i.command.id, &i.command.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 13b33dde44..53b5d973f7 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -45,6 +45,14 @@ impl Listed { } pub fn menu_tree_named(english_names: bool, listed: &Listed) -> Vec<(&'static str, Vec)> { + let mut tree = built_in_tree(english_names, listed); + 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, listed: &Listed) -> 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 7bb145686a..24ec586447 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -467,6 +467,241 @@ fn plugin_commands_are_menu_items_and_shortcut_entries() { assert!(row(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))); +} + +/// Commands placed after an item that switches between two labels are one spot whichever label +/// their `after` names: they keep manifest order within a plug-in and plug-in id order across +/// plug-ins. +#[test] +fn both_labels_of_a_switching_item_are_one_spot() { + let mut app = app(); + let (ape, bat) = ("test.ui.place.ape", "test.ui.place.bat"); + let command = vectorcraft_engine::cmd::plugin::command_id; + let ape_commands = r#"[{"id":"first","label":"First","menu":{"path":["View"],"after":"Hide Bounding Box"}}, + {"id":"second","label":"Second","menu":{"path":["View"],"after":"Show Bounding Box"}}]"#; + let bat_commands = r#"[{"id":"third","label":"Third","menu":{"path":["View"],"after":"Hide Bounding Box"}}]"#; + // Bat is installed first; Ape's id sorts first. + app.run("plugin.install", json!({"dataBase64": placing_plugin(bat, "Bat", bat_commands)})).unwrap(); + app.run("plugin.install", json!({"dataBase64": placing_plugin(ape, "Ape", ape_commands)})).unwrap(); + + let entries = menus::menu_entries(&app); + let view: Vec<&menus::MenuEntry> = entries.iter().filter(|e| e.path == ["View"]).collect(); + let toggle = view.iter().position(|e| e.command.as_deref() == Some("view.boundingBox")).expect("Hide Bounding Box is listed"); + let after: Vec> = (1..=3).map(|i| view.get(toggle + i).and_then(|e| e.command.clone())).collect(); + assert_eq!(after, [Some(command(ape, "first")), Some(command(ape, "second")), Some(command(bat, "third"))]); + for id in [ape, bat] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// 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::Node], label: &str) -> Option<&'a [menus::Node]> { + items.iter().find_map(|it| match it { + menus::Node::Submenu { label: 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::Node::Submenu { label, children, .. } if label.as_str() == *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::Node::Item(i) if !menus::lists_plugin(&i.command.id, &i.command.params) => i.label.as_str(), + menus::Node::Submenu { label, children, .. } if !menus::holds_plugin_commands(children) => label.as_str(), + _ => 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")); +} + /// The `grant` and `allowHeavy` that `ui.installPlugin` is given approve nothing: it asks all the /// same, and what OK would approve comes from the manifest. A module with nothing to approve /// installs without either. diff --git a/docs/mcp.md b/docs/mcp.md index c18aca7992..eeeb59e934 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13521,7 +13521,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 242afb543c..b0f72bfb63 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -89,14 +89,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 @@ -106,6 +107,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 @@ -587,10 +622,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 6f71c6e139..06171aaeec 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2690,7 +2690,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 at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › 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.