mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #9130 from dotCooCoo/feat/plugin-api-context-menus
Plug-ins: a command's manifest can list it in the canvas and Layers panel context menus
This commit is contained in:
17 files changed
+797
-66
No files matched your search
@@ -156,6 +156,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
}
|
||||
entry["menu"] = menu;
|
||||
}
|
||||
if !c.context.is_empty() {
|
||||
entry["menu"]["context"] = json!(c.context);
|
||||
}
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
@@ -2405,7 +2408,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), 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), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), 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, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, 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), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), 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\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), 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), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), 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, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, 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), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (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), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), 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
|
||||
),
|
||||
|
||||
@@ -7269,6 +7269,27 @@ fn placed_plugin_commands_are_listed_in_their_menu() {
|
||||
assert!(listed(&s, &low(bee)).is_none());
|
||||
}
|
||||
|
||||
/// `plugin.info`'s `manifest` gives each command's context menus in its `menu`, for a command
|
||||
/// placed in another menu and for one listed only in context menus.
|
||||
#[test]
|
||||
fn plugin_info_gives_a_command_s_context_menus() {
|
||||
let mut s = session();
|
||||
let id = "test.engine.place.context";
|
||||
let commands = json!([
|
||||
{"id": "low", "label": "Low", "menu": {"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}},
|
||||
{"id": "tidy", "label": "Tidy", "menu": {"context": [{"menu": "layers", "when": "layerRow"}]}},
|
||||
{"id": "keep", "label": "Keep"}
|
||||
]);
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#);
|
||||
install_wat(&mut s, &tpl::returning(&manifest, r#"{"objects":[]}"#));
|
||||
let info = run(&mut s, "plugin.info", json!({"id": id}));
|
||||
let shown = &info["manifest"]["commands"];
|
||||
assert_eq!(shown[0]["menu"], json!({"path": ["Select"], "context": [{"menu": "canvas", "when": "selection"}]}), "{info}");
|
||||
assert_eq!(shown[1]["menu"], json!({"context": [{"menu": "layers", "when": "layerRow"}]}), "{info}");
|
||||
assert!(shown[2].get("menu").is_none(), "{info}");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A command run is journaled like any other, so an action records it with its parameters and
|
||||
/// plays it back.
|
||||
#[test]
|
||||
|
||||
@@ -793,10 +793,11 @@ proptest! {
|
||||
}
|
||||
|
||||
/// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with
|
||||
/// 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
|
||||
/// control and bidirectional override characters, a `menu` of any shape naming any menu or
|
||||
/// context 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, and in at most the capped number of
|
||||
/// context menu items; 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(
|
||||
@@ -819,6 +820,11 @@ proptest! {
|
||||
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})),
|
||||
Just(json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers", "when": "layerRow"}]})),
|
||||
Just(json!({"context": [{"menu": "canvas", "when": "layerRow"}]})),
|
||||
arb_junk().prop_map(|j| json!({"context": j})),
|
||||
arb_junk().prop_map(|j| json!({"context": [{"menu": "layers", "when": j}]})),
|
||||
arb_junk().prop_map(|j| json!({"path": ["Select"], "context": [j]})),
|
||||
arb_junk(),
|
||||
],
|
||||
prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()],
|
||||
@@ -860,6 +866,11 @@ proptest! {
|
||||
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);
|
||||
}
|
||||
prop_assert!(api >= 2 || c.context.is_empty(), "level 1 lists no context menu: {:?}", c.context);
|
||||
prop_assert!(c.context.iter().all(|p| p.menu == vectorcraft_plugins::ContextMenu::Layers || p.when != Some(vectorcraft_plugins::ContextWhen::LayerRow)));
|
||||
}
|
||||
for menu in [vectorcraft_plugins::ContextMenu::Canvas, vectorcraft_plugins::ContextMenu::Layers] {
|
||||
prop_assert!(man.context_commands(menu).count() <= vectorcraft_plugins::manifest::MAX_CONTEXT_COMMANDS);
|
||||
}
|
||||
}
|
||||
let mut s = rich_session();
|
||||
|
||||
@@ -64,7 +64,9 @@ pub mod worker;
|
||||
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime};
|
||||
pub use manifest::{
|
||||
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime,
|
||||
};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, RunJob, Step, heavy_terms, keep_modules};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
+253
-11
@@ -54,6 +54,9 @@ pub const MENU_PLACES: &[&[&str]] = &[
|
||||
&["View"],
|
||||
];
|
||||
|
||||
/// Most commands of one plug-in that one context menu lists (`menu.context`).
|
||||
pub const MAX_CONTEXT_COMMANDS: usize = 8;
|
||||
|
||||
/// 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.
|
||||
@@ -64,9 +67,119 @@ pub struct MenuPlace {
|
||||
pub after: Option<String>,
|
||||
}
|
||||
|
||||
/// A context menu a command's `menu.context` lists it in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ContextMenu {
|
||||
/// The canvas context menu, while objects are selected.
|
||||
Canvas,
|
||||
/// The menu of a layer, group or object row of the Layers panel.
|
||||
Layers,
|
||||
}
|
||||
|
||||
impl ContextMenu {
|
||||
/// Its name in a manifest.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
ContextMenu::Canvas => "canvas",
|
||||
ContextMenu::Layers => "layers",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When a context menu item can be chosen (`when`); without one it always can.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ContextWhen {
|
||||
/// One or more objects are selected (in the Layers panel: one or more rows are clicked).
|
||||
Selection,
|
||||
/// Exactly one object, which is not a layer, is selected or clicked.
|
||||
OneObject,
|
||||
/// One of the objects selected or clicked is a type object.
|
||||
TypeObject,
|
||||
/// Every row clicked in the Layers panel is a layer or sublayer (Layers panel only).
|
||||
LayerRow,
|
||||
}
|
||||
|
||||
impl ContextWhen {
|
||||
const ALL: [(&'static str, ContextWhen); 4] = [
|
||||
("selection", ContextWhen::Selection),
|
||||
("oneObject", ContextWhen::OneObject),
|
||||
("typeObject", ContextWhen::TypeObject),
|
||||
("layerRow", ContextWhen::LayerRow),
|
||||
];
|
||||
|
||||
/// The conditions context menu `menu` takes: every one in the Layers panel, all but
|
||||
/// `layerRow` on the canvas.
|
||||
fn allowed(menu: ContextMenu) -> impl Iterator<Item = (&'static str, ContextWhen)> {
|
||||
Self::ALL.into_iter().filter(move |(_, w)| menu == ContextMenu::Layers || *w != ContextWhen::LayerRow)
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a command's `menu.context`: the context menu that lists it and when its item can
|
||||
/// be chosen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct ContextPlace {
|
||||
pub menu: ContextMenu,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub when: Option<ContextWhen>,
|
||||
}
|
||||
|
||||
impl ContextPlace {
|
||||
/// Reads `menu.context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`, each
|
||||
/// menu at most once.
|
||||
fn read_list(v: &Value) -> std::result::Result<Vec<ContextPlace>, String> {
|
||||
let Some(list) = v.as_array() else {
|
||||
let key = "menu.context";
|
||||
return Err(format!("`{key}` must be a list"));
|
||||
};
|
||||
let mut out: Vec<ContextPlace> = Vec::with_capacity(list.len().min(2));
|
||||
for (i, entry) in list.iter().enumerate() {
|
||||
let Some(o) = entry.as_object() else {
|
||||
let key = format!("menu.context[{i}]");
|
||||
return Err(format!("`{key}` must be an object"));
|
||||
};
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "menu" | "when")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "menu, when"));
|
||||
}
|
||||
let menu = match o.get("menu").and_then(Value::as_str) {
|
||||
Some("canvas") => ContextMenu::Canvas,
|
||||
Some("layers") => ContextMenu::Layers,
|
||||
_ => {
|
||||
let k = format!("menu.context[{i}].menu");
|
||||
return Err(format!("`{k}` must be one of {}", "\"canvas\", \"layers\""));
|
||||
}
|
||||
};
|
||||
let when = match o.get("when") {
|
||||
None => None,
|
||||
Some(w) => {
|
||||
let found = w.as_str().and_then(|w| ContextWhen::allowed(menu).find(|(name, _)| *name == w));
|
||||
match found {
|
||||
Some((_, when)) => Some(when),
|
||||
None => {
|
||||
let k = format!("menu.context[{i}].when");
|
||||
let names: Vec<String> = ContextWhen::allowed(menu).map(|(name, _)| format!("{name:?}")).collect();
|
||||
return Err(format!("`{k}` must be one of {}", names.join(", ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if out.iter().any(|p| p.menu == menu) {
|
||||
let (key, name) = ("menu.context", menu.name());
|
||||
return Err(format!("`{key}` names \"{name}\" twice"));
|
||||
}
|
||||
out.push(ContextPlace { menu, when });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl MenuPlace {
|
||||
/// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`.
|
||||
fn read(v: &Value) -> std::result::Result<MenuPlace, String> {
|
||||
/// Reads a command's `menu` value: `{"path"?: [label, …], "after"?: label, "context"?: [...]}`
|
||||
/// ([`ContextPlace::read_list`]). `path` may be left out only when `context` is given, and
|
||||
/// `after` only goes with `path`.
|
||||
fn read(v: &Value) -> std::result::Result<(Option<MenuPlace>, Vec<ContextPlace>), String> {
|
||||
let wrong_path = || {
|
||||
let k = "menu.path";
|
||||
let places: Vec<String> =
|
||||
@@ -77,9 +190,16 @@ impl MenuPlace {
|
||||
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")) {
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after" | "context")) {
|
||||
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after"));
|
||||
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after, context"));
|
||||
}
|
||||
let context = match o.get("context") {
|
||||
Some(c) => ContextPlace::read_list(c)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
if o.get("context").is_some() && !o.contains_key("path") && !o.contains_key("after") {
|
||||
return Ok((None, context));
|
||||
}
|
||||
let path: Vec<&str> = match o.get("path").and_then(Value::as_array) {
|
||||
Some(path) => path.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(wrong_path)?,
|
||||
@@ -98,7 +218,7 @@ impl MenuPlace {
|
||||
}
|
||||
Some(_) => return Err(format!("`{key}` must be a string")),
|
||||
};
|
||||
Ok(MenuPlace { path, after })
|
||||
Ok((Some(MenuPlace { path, after }), context))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,7 +484,7 @@ pub struct Param {
|
||||
/// 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.<plug-in id>.<id>`, 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)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
pub struct Command {
|
||||
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
|
||||
pub id: String,
|
||||
@@ -376,13 +496,45 @@ pub struct Command {
|
||||
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")]
|
||||
#[serde(skip)]
|
||||
pub place: Option<MenuPlace>,
|
||||
/// The context menus that also list it (`menu.context`, read at
|
||||
/// [`crate::permissions::MENU_API`] and later), at most one entry per menu.
|
||||
#[serde(skip)]
|
||||
pub context: Vec<ContextPlace>,
|
||||
/// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them.
|
||||
#[serde(skip)]
|
||||
pub(crate) declared_menu: Vec<Value>,
|
||||
}
|
||||
|
||||
/// A command as its manifest gives it: `id`, `label`, `params` and, when it has a place or context
|
||||
/// menus, `menu` with its `path`, `after` and `context`.
|
||||
impl Serialize for Command {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
fn params<S: serde::Serializer>(p: &&[(String, Param)], s: S) -> std::result::Result<S::Ok, S::Error> {
|
||||
params_as_object(p, s)
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Menu<'a> {
|
||||
#[serde(flatten)]
|
||||
place: Option<&'a MenuPlace>,
|
||||
#[serde(skip_serializing_if = "<[_]>::is_empty")]
|
||||
context: &'a [ContextPlace],
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
struct Shown<'a> {
|
||||
id: &'a str,
|
||||
label: &'a str,
|
||||
#[serde(serialize_with = "params")]
|
||||
params: &'a [(String, Param)],
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
menu: Option<Menu<'a>>,
|
||||
}
|
||||
let menu = (self.place.is_some() || !self.context.is_empty()).then_some(Menu { place: self.place.as_ref(), context: &self.context });
|
||||
Shown { id: &self.id, label: &self.label, params: &self.params, menu }.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl Command {
|
||||
/// The label as menus and errors show it: control and bidirectional characters escaped, at
|
||||
/// most [`crate::permissions::MAX_SHOWN_NAME`] characters.
|
||||
@@ -612,7 +764,7 @@ impl Manifest {
|
||||
continue;
|
||||
}
|
||||
let name = command_name(i, &c.id);
|
||||
let place = match menus.as_slice() {
|
||||
let read = match menus.as_slice() {
|
||||
[] => continue,
|
||||
[menu] => MenuPlace::read(menu),
|
||||
_ => {
|
||||
@@ -620,11 +772,27 @@ impl Manifest {
|
||||
Err(format!("duplicate field `{key}`"))
|
||||
}
|
||||
};
|
||||
c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?);
|
||||
(c.place, c.context) = read.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?;
|
||||
}
|
||||
// Each context menu lists at most MAX_CONTEXT_COMMANDS of the plug-in's commands; the
|
||||
// error names the first command past that.
|
||||
for menu in [ContextMenu::Canvas, ContextMenu::Layers] {
|
||||
let mut listed = self.commands.iter().enumerate().filter(|(_, c)| c.context.iter().any(|p| p.menu == menu));
|
||||
if let Some((i, c)) = listed.nth(MAX_CONTEXT_COMMANDS) {
|
||||
let (name, key) = (command_name(i, &c.id), "menu.context");
|
||||
let e = format!("`{key}`: a plug-in may put at most {MAX_CONTEXT_COMMANDS} commands in each context menu");
|
||||
return Err(Error::Manifest(format!("command {name}: {e}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The commands context menu `menu` lists (`menu.context`), in manifest order, each with when
|
||||
/// its item can be chosen.
|
||||
pub fn context_commands(&self, menu: ContextMenu) -> impl Iterator<Item = (&Command, Option<ContextWhen>)> {
|
||||
self.commands.iter().filter_map(move |c| c.context.iter().find(|p| p.menu == menu).map(|p| (c, p.when)))
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -1192,7 +1360,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(), place: None, declared_menu: menu })
|
||||
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, context: Vec::new(), declared_menu: menu })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1772,7 +1940,9 @@ 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(), place: None, declared_menu: Vec::new() }.shown_label();
|
||||
let label = |l: &str| {
|
||||
Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, context: Vec::new(), declared_menu: Vec::new() }.shown_label()
|
||||
};
|
||||
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
|
||||
|
||||
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
|
||||
@@ -1887,6 +2057,78 @@ mod tests {
|
||||
assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`"));
|
||||
}
|
||||
|
||||
/// At API level 2 a command's `menu.context` lists it in the canvas and Layers panel context
|
||||
/// menus, each with an optional `when` from a fixed list, with or without a `path`. A context
|
||||
/// entry of the wrong shape, an unknown menu or condition, `layerRow` on the canvas, a menu
|
||||
/// named twice and more than [`MAX_CONTEXT_COMMANDS`] commands in one menu are refused, and the
|
||||
/// error names the command and the key. At level 1 the key is ignored.
|
||||
#[test]
|
||||
fn a_command_menu_context_lists_it_in_context_menus() {
|
||||
let with = |api: u32, menu: &str| {
|
||||
format!(r#"{{"id":"org.example.t","name":"Tidy","api":{api},"kind":"filter","commands":[{{"id":"tidy","label":"Tidy","menu":{menu}}}]}}"#)
|
||||
};
|
||||
let m = Manifest::parse(with(2, r#"{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers"}]}"#).as_bytes()).unwrap();
|
||||
let c = &m.commands[0];
|
||||
assert_eq!(c.place, None, "no other menu: it stays in its plug-in's submenu");
|
||||
assert_eq!(
|
||||
c.context,
|
||||
vec![
|
||||
ContextPlace { menu: ContextMenu::Canvas, when: Some(ContextWhen::TypeObject) },
|
||||
ContextPlace { menu: ContextMenu::Layers, when: None }
|
||||
]
|
||||
);
|
||||
assert_eq!(c.menu_label(&m.name), "Tidy", "a context item is not renamed");
|
||||
assert_eq!(m.context_commands(ContextMenu::Layers).map(|(c, w)| (c.id.as_str(), w)).collect::<Vec<_>>(), [("tidy", None)]);
|
||||
let both = Manifest::parse(with(2, r#"{"path":["Select"],"context":[{"menu":"layers","when":"layerRow"}]}"#).as_bytes()).unwrap();
|
||||
assert_eq!(both.commands[0].place, Some(MenuPlace { path: &["Select"], after: None }));
|
||||
assert_eq!(both.commands[0].context, vec![ContextPlace { menu: ContextMenu::Layers, when: Some(ContextWhen::LayerRow) }]);
|
||||
// The manifest a plug-in's info gives carries the context menus, with or without a place.
|
||||
assert_eq!(
|
||||
serde_json::to_value(&both.commands[0]).unwrap()["menu"],
|
||||
json!({"path": ["Select"], "context": [{"menu": "layers", "when": "layerRow"}]})
|
||||
);
|
||||
assert_eq!(serde_json::to_value(c).unwrap()["menu"], json!({"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers"}]}));
|
||||
let plain = Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap();
|
||||
assert!(serde_json::to_value(&plain.commands[0]).unwrap().get("menu").is_none(), "no place and no context menu: no `menu`");
|
||||
assert!(Manifest::parse(with(2, r#"{"context":[]}"#).as_bytes()).unwrap().commands[0].context.is_empty());
|
||||
assert!(Manifest::parse(with(1, r#"{"context":[{"menu":"sky"}]}"#).as_bytes()).unwrap().commands[0].context.is_empty(), "ignored at level 1");
|
||||
|
||||
for (menu, says) in [
|
||||
(r#"{"context":"canvas"}"#, "`menu.context` must be a list"),
|
||||
(r#"{"context":["canvas"]}"#, "`menu.context[0]` must be an object"),
|
||||
(r#"{"context":[{"menu":"canvas","if":"selection"}]}"#, "unknown key `if`"),
|
||||
(r#"{"context":[{"menu":"Canvas"}]}"#, "`menu.context[0].menu` must be one of \"canvas\", \"layers\""),
|
||||
(r#"{"context":[{}]}"#, "`menu.context[0].menu` must be one of"),
|
||||
(r#"{"context":[{"menu":"layers"},{"menu":"canvas","when":"always"}]}"#, "`menu.context[1].when` must be one of"),
|
||||
(
|
||||
r#"{"context":[{"menu":"canvas","when":"layerRow"}]}"#,
|
||||
"`menu.context[0].when` must be one of \"selection\", \"oneObject\", \"typeObject\"",
|
||||
),
|
||||
(r#"{"context":[{"menu":"canvas","when":1}]}"#, "`menu.context[0].when` must be one of"),
|
||||
(r#"{"context":[{"menu":"canvas"},{"menu":"canvas"}]}"#, "`menu.context` names \"canvas\" twice"),
|
||||
(r#"{"after":"Inverse","context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"),
|
||||
(r#"{"path":["File"],"context":[{"menu":"canvas"}]}"#, "`menu.path` must be one of"),
|
||||
] {
|
||||
let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains("command `tidy`") && e.contains(says), "{menu}: {e}");
|
||||
}
|
||||
|
||||
let listed = |n: usize, menu: &str| {
|
||||
let commands: Vec<String> =
|
||||
(0..n).map(|i| format!(r#"{{"id":"c{i}","label":"C{i}","menu":{{"context":[{{"menu":"{menu}"}}]}}}}"#)).collect();
|
||||
format!(r#"{{"id":"a","name":"x","api":2,"kind":"filter","commands":[{}]}}"#, commands.join(","))
|
||||
};
|
||||
for menu in ["canvas", "layers"] {
|
||||
assert_eq!(
|
||||
Manifest::parse(listed(MAX_CONTEXT_COMMANDS, menu).as_bytes()).unwrap().context_commands(ContextMenu::Canvas).count(),
|
||||
if menu == "canvas" { MAX_CONTEXT_COMMANDS } else { 0 }
|
||||
);
|
||||
let e = Manifest::parse(listed(MAX_CONTEXT_COMMANDS + 1, menu).as_bytes()).unwrap_err().to_string();
|
||||
let past = format!("command `c{MAX_CONTEXT_COMMANDS}`");
|
||||
assert!(e.contains(&past) && e.contains("`menu.context`: a plug-in may put at most 8 commands in each context menu"), "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_and_number_lists_resolve_like_the_other_types() {
|
||||
let m = Manifest::parse(
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
//! ([`crate::plugin_runs`]). 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`]).
|
||||
//! instead ([`place_commands`]), and one whose manifest lists context menus is also listed there
|
||||
//! ([`context_commands`]).
|
||||
//! Object › Plug-ins starts with Apply Last Filter and Last Filter…, which run the filter that last
|
||||
//! ran again with the same parameters or open its dialog with them, and a filter's dialog opens with
|
||||
//! the parameters it last ran with in the session ([`LastFilters`]).
|
||||
@@ -50,7 +51,7 @@ use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use egui::Ui;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_engine::cmd::plugin::InstallApproval;
|
||||
use vectorcraft_plugins::{Budget, Kind, Manifest, Plugin, permissions, registry};
|
||||
use vectorcraft_plugins::{Budget, ContextMenu, ContextWhen, Kind, Manifest, Plugin, permissions, registry};
|
||||
|
||||
use super::form;
|
||||
use super::preview::LivePreview;
|
||||
@@ -199,6 +200,79 @@ fn leave_out(items: &mut [Node], placed: &std::collections::HashSet<String>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does condition `when` of a context menu item hold for objects `ids` of `doc` (the selection on
|
||||
/// the canvas, the clicked rows in the Layers panel)? `selection`: one or more; `oneObject`: one,
|
||||
/// which is not a layer; `typeObject`: one of them is a type object; `layerRow`: each is a layer or
|
||||
/// sublayer. Without a condition the item can always be chosen.
|
||||
pub fn context_holds(doc: &vectorcraft_doc::Document, ids: &[u64], when: Option<ContextWhen>) -> bool {
|
||||
let nodes = || ids.iter().filter_map(|id| doc.node(vectorcraft_doc::NodeId(*id)));
|
||||
match when {
|
||||
None => true,
|
||||
Some(ContextWhen::Selection) => !ids.is_empty(),
|
||||
Some(ContextWhen::OneObject) => ids.len() == 1 && nodes().count() == 1 && nodes().all(|n| !n.is_layer()),
|
||||
Some(ContextWhen::TypeObject) => nodes().any(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Text(_))),
|
||||
Some(ContextWhen::LayerRow) => !ids.is_empty() && nodes().count() == ids.len() && nodes().all(|n| n.is_layer()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One plug-in command of a context menu: its label (with an ellipsis when it has parameters), its
|
||||
/// command id and whether its condition holds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ContextCommand {
|
||||
pub label: &'static str,
|
||||
pub command: &'static str,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// The plug-in commands context menu `menu` lists for objects `ids` of `doc`
|
||||
/// ([`vectorcraft_plugins::Command::context`]): for each filter or live effect, in plug-in id
|
||||
/// order, its name as it is and its commands in manifest order, each enabled only while its `when`
|
||||
/// holds ([`context_holds`]).
|
||||
pub fn context_commands(menu: ContextMenu, doc: &vectorcraft_doc::Document, ids: &[u64]) -> Vec<(&'static str, Vec<ContextCommand>)> {
|
||||
registry::list()
|
||||
.iter()
|
||||
.filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Effect))
|
||||
.filter_map(|p| {
|
||||
let m = p.manifest();
|
||||
let commands: Vec<ContextCommand> = m
|
||||
.context_commands(menu)
|
||||
.map(|(c, when)| ContextCommand {
|
||||
label: label(&c.shown_label(), !c.params.is_empty()),
|
||||
command: registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)),
|
||||
enabled: context_holds(doc, ids, when),
|
||||
})
|
||||
.collect();
|
||||
let name = registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME));
|
||||
(!commands.is_empty()).then_some((name, commands))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The canvas context menu's Plug-ins submenu for the selection `ids`: a submenu per plug-in that
|
||||
/// lists commands there, named after it, each item running its command on `ids`. `None` when no
|
||||
/// installed plug-in lists a command there.
|
||||
pub fn canvas_submenu(doc: &vectorcraft_doc::Document, ids: &[u64]) -> Option<Node> {
|
||||
let groups: Vec<Node> = context_commands(ContextMenu::Canvas, doc, ids)
|
||||
.into_iter()
|
||||
.map(|(name, commands)| {
|
||||
let items =
|
||||
commands.into_iter().map(|command| cp(command.label, command.command, json!({ "ids": ids })).enabled(command.enabled)).collect();
|
||||
sub(name, items)
|
||||
})
|
||||
.collect();
|
||||
(!groups.is_empty()).then_some(sub("Plug-ins", groups))
|
||||
}
|
||||
|
||||
/// Can the canvas context menu's item for plug-in command `id` with `p` be chosen? Only an item
|
||||
/// that carries `ids` ([`canvas_submenu`]) has a condition; every other item can.
|
||||
pub fn canvas_item_enabled(app: &VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
let Some(ids) = p.get("ids").and_then(Value::as_array) else { return true };
|
||||
let Some((_, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return true };
|
||||
let Some(place) = c.context.iter().find(|p| p.menu == ContextMenu::Canvas) else { return true };
|
||||
let ids: Vec<u64> = ids.iter().filter_map(Value::as_u64).collect();
|
||||
app.session.active().is_some_and(|st| context_holds(&st.doc, &ids, place.when))
|
||||
}
|
||||
|
||||
/// Object › Plug-ins: the installed object filters (each with its commands, if it has any) and
|
||||
/// generators, then Edit Generated Art…, Install Plug-in…, Reload Plug-ins and Plug-ins That Didn't
|
||||
/// Load… ([`super::failed_plugins`]).
|
||||
@@ -275,6 +349,11 @@ pub(crate) enum Opened {
|
||||
/// Whether the last preview failed.
|
||||
refused: bool,
|
||||
params: Arc<[Param]>,
|
||||
/// The objects a context menu opened a command's dialog for, which its runs are given.
|
||||
ids: Option<Value>,
|
||||
/// The uid of the document a command's dialog opened on, the only one it runs on; `None`
|
||||
/// for a filter's own dialog, which runs on the active document.
|
||||
doc: Option<u64>,
|
||||
},
|
||||
/// A generator's parameters: for new generated art (`edit` is `None`), or for drawing the
|
||||
/// generated art object `edit` names again.
|
||||
@@ -298,6 +377,16 @@ impl PluginDialog {
|
||||
pub(crate) fn opens_picked(&self) -> bool {
|
||||
matches!(&self.kind, Opened::Import { open, .. } if open["picked"] == true)
|
||||
}
|
||||
|
||||
/// The plug-in command a command's dialog runs and the objects it runs on, if a context menu
|
||||
/// gave them; `None` for any other dialog.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn runs_command(&self) -> Option<(&str, Option<&Value>)> {
|
||||
match &self.kind {
|
||||
Opened::Filter { command: Some(c), ids, .. } => Some((c.as_str(), ids.as_ref())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Opened {
|
||||
@@ -320,6 +409,25 @@ impl Opened {
|
||||
other => registry::get(other.plugin()).is_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the dialog is a command's opened on a document that is not the active one.
|
||||
fn elsewhere(&self, app: &VectorcraftApp) -> bool {
|
||||
match self {
|
||||
Opened::Filter { doc: Some(uid), .. } => app.session.active().is_none_or(|st| st.uid != *uid),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolls back the filter dialog's shown preview, unless another document is the active one,
|
||||
/// whose edit in progress it leaves alone.
|
||||
fn roll_back(self, app: &mut VectorcraftApp) {
|
||||
let elsewhere = self.elsewhere(app);
|
||||
if let Opened::Filter { preview, .. } = self
|
||||
&& !elsewhere
|
||||
{
|
||||
preview.cancel(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a hosted plug-in dialog looks.
|
||||
@@ -385,9 +493,7 @@ fn close_open(app: &mut VectorcraftApp) {
|
||||
if let (Some(ctx), Some(dialogs)) = (app.ui_ctx.clone(), app.dialogs()) {
|
||||
dialogs.with(|host| host.cancel_by_id(&ctx, old.id));
|
||||
}
|
||||
if let Opened::Filter { preview, .. } = old.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
old.kind.roll_back(app);
|
||||
}
|
||||
|
||||
/// Object › Plug-ins' first items: Apply Last Filter, which runs the filter that last ran again with
|
||||
@@ -608,15 +714,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
/// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs
|
||||
/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. Where
|
||||
/// filters run in workers (the web build) the dialog has no Preview: a preview would run the plug-in
|
||||
/// on the page.
|
||||
/// on the page. A command's dialog runs on its objects when given, and only on its document
|
||||
/// ([`CommandRun`]).
|
||||
fn open_filter(
|
||||
app: &mut VectorcraftApp,
|
||||
plugin: &Plugin,
|
||||
m: Manifest,
|
||||
command: Option<String>,
|
||||
command: Option<CommandRun>,
|
||||
heading: String,
|
||||
values: Map<String, Value>,
|
||||
) -> Result<(), String> {
|
||||
let (command, ids, doc) = match command {
|
||||
Some(c) => (Some(c.id), c.ids, Some(c.doc)),
|
||||
None => (None, None, None),
|
||||
};
|
||||
let own = plugin.manifest();
|
||||
let heavy = own.budget == Budget::Heavy;
|
||||
let light = !heavy && !crate::plugin_runs::in_workers(app);
|
||||
@@ -632,33 +743,50 @@ fn open_filter(
|
||||
previewing: light,
|
||||
refused: false,
|
||||
params,
|
||||
ids,
|
||||
doc,
|
||||
};
|
||||
app.plugin_dialog = Some(PluginDialog { id, kind });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens the dialog of plug-in command `id` (`plugin.<plug-in id>.<command id>`), given no params,
|
||||
/// when it has parameters and a document is open: its rows at their defaults with a live Preview, and
|
||||
/// OK keeps the run as one undo step. False for any other command, which then runs as it was given.
|
||||
pub fn open_command(app: &mut VectorcraftApp, id: &str) -> bool {
|
||||
let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false };
|
||||
if c.params.is_empty() || app.session.active().is_none() {
|
||||
/// The plug-in command a filter dialog runs: its id, the objects a context menu gave it, and the
|
||||
/// uid of the document the dialog opened on, the only one it runs on.
|
||||
struct CommandRun {
|
||||
id: String,
|
||||
ids: Option<Value>,
|
||||
doc: u64,
|
||||
}
|
||||
|
||||
/// Opens the dialog of plug-in command `id` (`plugin.<plug-in id>.<command id>`), given no params
|
||||
/// or only `ids` (a context menu's objects), when it has parameters and a document is open: its
|
||||
/// rows at their defaults with a live Preview, and OK keeps the run on those objects as one undo
|
||||
/// step. The dialog runs only on the document that was active when it opened. False for any other
|
||||
/// command or params, which then run as they were given.
|
||||
pub fn open_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
let only_ids = (p.is_null() || p.as_object().is_some_and(|o| o.keys().all(|k| k == "ids"))) && p.get("ids").is_none_or(Value::is_array);
|
||||
if !only_ids {
|
||||
return false;
|
||||
}
|
||||
let Some((plugin, c)) = vectorcraft_engine::cmd::plugin::command_of(id) else { return false };
|
||||
let Some(doc) = app.session.active().map(|st| st.uid).filter(|_| !c.params.is_empty()) else { return false };
|
||||
let ids = p.get("ids").cloned();
|
||||
let m = plugin.manifest().for_command(&c);
|
||||
let defaults = m.defaults();
|
||||
if let Err(e) = open_filter(app, &plugin, m, Some(id.to_string()), c.shown_label().to_string(), defaults) {
|
||||
let run = CommandRun { id: id.to_string(), ids, doc };
|
||||
if let Err(e) = open_filter(app, &plugin, m, Some(run), c.shown_label().to_string(), defaults) {
|
||||
app.status(e);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The command a filter dialog runs and its params: `plugin.run` for the filter's own dialog, else
|
||||
/// its plug-in command.
|
||||
fn command(plugin: &str, command: Option<&str>, values: Map<String, Value>) -> (String, Value) {
|
||||
match command {
|
||||
None => (CMD.to_string(), json!({"id": plugin, "params": values})),
|
||||
Some(c) => (c.to_string(), json!({"params": values})),
|
||||
/// its plug-in command, given objects `ids` when a context menu opened it.
|
||||
fn command(plugin: &str, command: Option<&str>, ids: Option<&Value>, values: Map<String, Value>) -> (String, Value) {
|
||||
match (command, ids) {
|
||||
(None, _) => (CMD.to_string(), json!({"id": plugin, "params": values})),
|
||||
(Some(c), Some(ids)) => (c.to_string(), json!({"ids": ids, "params": values})),
|
||||
(Some(c), None) => (c.to_string(), json!({"params": values})),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -824,10 +952,14 @@ fn import_with(app: &mut VectorcraftApp, open: Value, values: Map<String, Value>
|
||||
/// no preview, and a light one that runs in the background ([`in_background`]) with Preview off or a
|
||||
/// failed preview, start in the background ([`run`]). On the web the filter or its command always
|
||||
/// starts in a worker. A preview still shown when Preview was just turned off, or one that failed, is
|
||||
/// rolled back first.
|
||||
/// rolled back first. A command's dialog answered while another document is the active one changes
|
||||
/// no document.
|
||||
fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map<String, Value>) -> Result<Value, String> {
|
||||
let Opened::Filter { plugin, command: own, preview, light, previewing, refused, .. } = kind else { return Ok(Value::Null) };
|
||||
let (cmd, p) = command(&plugin, own.as_deref(), values);
|
||||
if kind.elsewhere(app) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let Opened::Filter { plugin, command: own, preview, light, previewing, refused, ids, .. } = kind else { return Ok(Value::Null) };
|
||||
let (cmd, p) = command(&plugin, own.as_deref(), ids.as_ref(), values);
|
||||
let kept = light && previewing && app.session.in_interaction() && !refused;
|
||||
match registry::get(&plugin) {
|
||||
// On the web, with no Preview, the filter or its command always runs in a worker; a command
|
||||
@@ -878,17 +1010,17 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if let Some(link) = help {
|
||||
form::open_help(app, &link);
|
||||
}
|
||||
if open.kind.gone() {
|
||||
// A command's dialog closes once its command is gone, or once another document is the
|
||||
// active one, whose edit in progress it leaves alone.
|
||||
if open.kind.gone() || open.kind.elsewhere(app) {
|
||||
dialogs.with(|host| host.cancel_by_id(ctx, id));
|
||||
if let Opened::Filter { preview, .. } = open.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
open.kind.roll_back(app);
|
||||
return;
|
||||
}
|
||||
if let Opened::Filter { plugin, command: own, label, preview, previewing, refused, light, .. } = &mut open.kind {
|
||||
if let Opened::Filter { plugin, command: own, label, preview, previewing, refused, light, ids, .. } = &mut open.kind {
|
||||
*previewing = on;
|
||||
if *light {
|
||||
let (cmd, p) = command(plugin, own.as_deref(), values);
|
||||
let (cmd, p) = command(plugin, own.as_deref(), ids.as_ref(), values);
|
||||
if let Some(answer) = preview.run(app, on, label, &cmd, &p) {
|
||||
*refused = answer.is_err();
|
||||
}
|
||||
@@ -900,9 +1032,7 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// The dialog is closed: answered, or cancelled from outside.
|
||||
let answer = dialogs.with(|host| host.take_by_id::<HostedParamDialog>(id));
|
||||
let Some(DialogResult::Ok(result)) = answer else {
|
||||
if let Opened::Filter { preview, .. } = open.kind {
|
||||
preview.cancel(app);
|
||||
}
|
||||
open.kind.roll_back(app);
|
||||
return;
|
||||
};
|
||||
let values = form::json_of(¶ms, &result.fields);
|
||||
|
||||
@@ -4,7 +4,8 @@ use super::{Sep, Value, VectorcraftApp, c, cp, heading, json, sub};
|
||||
use craft::menu::{Node, tidy};
|
||||
|
||||
/// The canvas context menu (right-click): what applies to the selection, or to the view when
|
||||
/// nothing is selected. Commands that can't run now are left out rather than greyed out.
|
||||
/// nothing is selected. Commands that can't run now are left out rather than greyed out; a plug-in
|
||||
/// command whose `when` fails for the selection is greyed out in the Plug-ins submenu.
|
||||
pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
@@ -140,6 +141,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec<Node> {
|
||||
Sep,
|
||||
c("Export Selection…", "file.exportSelection"),
|
||||
]);
|
||||
// The commands plug-in manifests list here (`menu.context`), each run on the selection.
|
||||
let ids: Vec<u64> = st.selection.objects.iter().map(|id| id.0).collect();
|
||||
if let Some(plugins) = crate::dialogs::plugin::canvas_submenu(&st.doc, &ids) {
|
||||
v.extend([Sep, plugins]);
|
||||
}
|
||||
}
|
||||
[spelling, prune(app, v)].concat()
|
||||
}
|
||||
|
||||
@@ -4,10 +4,11 @@ use super::{Value, VectorcraftApp, json};
|
||||
/// What a menu click runs: items whose label ends with "…" and that carry default params open a
|
||||
/// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the
|
||||
/// Scripts folder runs, whatever its name ends with, and so does a proof setup saved in the Proof
|
||||
/// Setups folder.
|
||||
/// Setups folder. A plug-in command's item runs its command, which opens the plug-in's own dialog.
|
||||
pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) {
|
||||
let dialog = label.ends_with('…')
|
||||
&& p.as_object().is_some_and(|o| !o.is_empty())
|
||||
&& !vectorcraft_engine::cmd::plugin::is_command_id(id)
|
||||
&& !matches!(
|
||||
id,
|
||||
"effect.dialog"
|
||||
@@ -115,8 +116,9 @@ pub fn invoke(app: &mut VectorcraftApp, id: &str, p: Value) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A plug-in command with parameters asks for them, from its menu item or its shortcut.
|
||||
if p.as_object().is_none_or(|o| o.is_empty()) && crate::dialogs::plugin::open_command(app, id) {
|
||||
// A plug-in command with parameters asks for them, from its menu item, its shortcut or a
|
||||
// context menu (which gives only `ids`).
|
||||
if crate::dialogs::plugin::open_command(app, id, &p) {
|
||||
return;
|
||||
}
|
||||
if open_view_dialog(app, id, &p) || open_object_dialog(app, id, &p) {
|
||||
|
||||
@@ -173,7 +173,9 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
|
||||
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
|
||||
/// ([`east_asian_hidden`]).
|
||||
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
|
||||
let en = enabled(app, id) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p));
|
||||
let en = enabled(app, id)
|
||||
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
|
||||
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
|
||||
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -277,7 +277,7 @@ fn object_menu(tree: &DocLayers, id: NodeId, ids: &[u64]) -> Vec<MenuRow<String>
|
||||
let lock_label = if lock == "layer.lockOthers" { "Lock Others" } else { "Unlock All Layers" };
|
||||
let hide_label = if hide == "layer.hideOthers" { "Hide Others" } else { "Show All Layers" };
|
||||
let export = |multiple: bool| json!({ "ids": ids, "multiple": multiple });
|
||||
vec![
|
||||
let mut rows = vec![
|
||||
entry("ui.layerOptions", json!({ "ids": ids }), options, true),
|
||||
entry("layer.duplicate", json!({ "ids": ids }), duplicate, duplicate_ok),
|
||||
entry("layer.delete", json!({ "ids": ids }), delete, delete_ok),
|
||||
@@ -291,7 +291,21 @@ fn object_menu(tree: &DocLayers, id: NodeId, ids: &[u64]) -> Vec<MenuRow<String>
|
||||
tl!("Collect for Export").to_string().into(),
|
||||
vec![entry("assets.add", export(false), "As Single Asset", true), entry("assets.add", export(true), "As Multiple Assets", true)],
|
||||
),
|
||||
]
|
||||
];
|
||||
// The commands plug-in manifests list in this menu (`menu.context`): a submenu per plug-in,
|
||||
// each entry running its command on these rows' objects.
|
||||
let plugins = crate::dialogs::plugin::context_commands(vectorcraft_plugins::ContextMenu::Layers, doc, ids);
|
||||
if !plugins.is_empty() {
|
||||
let groups = plugins
|
||||
.into_iter()
|
||||
.map(|(name, commands)| {
|
||||
let entries = commands.into_iter().map(|c| entry(c.command, json!({ "ids": ids }), c.label, c.enabled)).collect();
|
||||
MenuRow::Submenu(name.to_string().into(), entries)
|
||||
})
|
||||
.collect();
|
||||
rows.extend([separator(), MenuRow::Submenu(tl!("Plug-ins").to_string().into(), groups)]);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Locate Object, or Locate Layer with Show Layers Only on, for row `id`.
|
||||
|
||||
@@ -253,11 +253,16 @@ pub(super) fn apply(app: &mut VectorcraftApp, events: Vec<LayersEvent<RowId>>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the commands of one event other than a toggle sweep or an open.
|
||||
/// Runs the commands of one event other than a toggle sweep or an open. A plug-in command from a
|
||||
/// row's menu asks for its parameters first, as its menu item does.
|
||||
fn run_commands(app: &mut VectorcraftApp, event: LayersEvent<RowId>) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
for (c, p) in commands(app, st, event) {
|
||||
app.run(&c, p).ok();
|
||||
if vectorcraft_engine::cmd::plugin::is_command_id(&c) {
|
||||
crate::menus::invoke(app, &c, p);
|
||||
} else {
|
||||
app.run(&c, p).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -931,6 +931,62 @@ fn full_layers_are_the_layers_with_all_their_art_selected() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A row's menu ends with a Plug-ins submenu while a plug-in lists commands in the Layers panel's
|
||||
/// context menu (`menu.context`): a submenu named after the plug-in holding those commands, each
|
||||
/// enabled while its `when` holds for the rows the menu acts on. A pick runs the command on that
|
||||
/// row's object, whatever the selection, as one undo step.
|
||||
#[test]
|
||||
fn row_menus_list_plugin_commands() {
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::layers::ui::panel::MenuTarget;
|
||||
use craft::ui::menu::MenuRow;
|
||||
use vectorcraft_plugins::wat::{Given, when_given};
|
||||
let (mut app, layer, [a, b]) = two_rects();
|
||||
let id = "test.layers.context";
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Row Tools","api":2,"version":"1","kind":"filter","commands":[
|
||||
{{"id":"one","label":"One","menu":{{"context":[{{"menu":"layers","when":"oneObject"}}]}}}},
|
||||
{{"id":"canvas","label":"Canvas","menu":{{"context":[{{"menu":"canvas"}}]}}}}]}}"#
|
||||
);
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
let module = wat::parse_str(when_given(&manifest, Given::Input, r#""name":"Target""#, triangle)).unwrap();
|
||||
app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap();
|
||||
app.run("layer.setProps", json!({"ids": [a.0], "name": "Target"})).unwrap();
|
||||
app.run("select.set", json!({"ids": [b.0]})).unwrap();
|
||||
// The Plug-ins submenu of the menu on `row`: (plug-in, [(label, command, params, enabled)]).
|
||||
type Entries = Vec<(String, String, serde_json::Value, bool)>;
|
||||
let plugins = |app: &VectorcraftApp, row: NodeId| -> Vec<(String, Entries)> {
|
||||
let tree = DocLayers::new(app, app.session.active().unwrap());
|
||||
let menu = controls::row_menu(&tree, &MenuTarget::new(Some(layer_key(row))));
|
||||
let groups = menu.iter().find_map(|r| match r {
|
||||
MenuRow::Submenu(label, groups) if label.as_str() == tl!("Plug-ins") => Some(groups.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let entry = |r: &MenuRow<String>| {
|
||||
let MenuRow::Entry(e) = r else { panic!("a plug-in's submenu holds entries only") };
|
||||
let c = CommandRef::parse_key(e.value().expect("an entry runs a command")).expect("a command key");
|
||||
(e.label().as_str().to_string(), c.id.to_string(), c.params.clone(), e.is_enabled())
|
||||
};
|
||||
let group = |r: &MenuRow<String>| {
|
||||
let MenuRow::Submenu(name, entries) = r else { panic!("a plug-in's group is a submenu") };
|
||||
(name.as_str().to_string(), entries.iter().map(entry).collect())
|
||||
};
|
||||
groups.unwrap_or_default().iter().map(group).collect()
|
||||
};
|
||||
let one = vectorcraft_engine::cmd::plugin::command_id(id, "one");
|
||||
assert_eq!(plugins(&app, a), vec![("Row Tools".to_string(), vec![("One".to_string(), one.clone(), json!({"ids": [a.0]}), true)])]);
|
||||
assert!(!plugins(&app, layer)[0].1[0].3, "a layer row is not one object");
|
||||
|
||||
let undo = undo_len(&app);
|
||||
feed(&mut app, vec![LayersEvent::menu(MenuTarget::new(Some(layer_key(a))), CommandRef::with_params(&one, json!({"ids": [a.0]})).key())]);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!((undo_len(&app), st.history.undo.last().map(|s| s.label.as_str())), (undo + 1, Some("One")));
|
||||
assert!(st.doc.node(a).is_none() && st.doc.node(b).is_some(), "the plug-in was given the row's object, not the selection");
|
||||
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert!(plugins(&app, b).is_empty(), "removed: no Plug-ins submenu");
|
||||
}
|
||||
|
||||
/// A target circle's appearance held across File › Revert and dropped on another row's circle
|
||||
/// leaves the restored objects with the same IDs as they were; a drag started after the revert
|
||||
/// still moves the appearance.
|
||||
|
||||
@@ -681,7 +681,7 @@ fn on_the_web_a_command_dialog_runs_its_command_in_a_worker() {
|
||||
);
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, TRIANGLE)).unwrap());
|
||||
app.run("plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"]})).unwrap();
|
||||
assert!(dialogs::plugin::open_command(&mut app, &format!("plugin.{id}.same")));
|
||||
assert!(dialogs::plugin::open_command(&mut app, &format!("plugin.{id}.same"), &serde_json::Value::Null));
|
||||
pump(&mut app);
|
||||
assert!(!app.session.in_interaction(), "nothing previewed");
|
||||
app.session.begin_interaction("Move").unwrap();
|
||||
@@ -711,7 +711,7 @@ fn on_the_web_a_command_dialog_automation_confirms_runs_on_the_page() {
|
||||
);
|
||||
let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::returning(&manifest, TRIANGLE)).unwrap());
|
||||
app.run("plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"]})).unwrap();
|
||||
assert!(dialogs::plugin::open_command(&mut app, &format!("plugin.{id}.same")));
|
||||
assert!(dialogs::plugin::open_command(&mut app, &format!("plugin.{id}.same"), &serde_json::Value::Null));
|
||||
pump(&mut app);
|
||||
app.ui.answering_control = true;
|
||||
answer_open(&mut app, true);
|
||||
|
||||
@@ -699,6 +699,210 @@ fn desktop_items_of_placeable_menus_are_known_to_the_engine() {
|
||||
assert!(missing.is_empty(), "missing from DESKTOP_MENU_ITEMS:\n{}", rows.join("\n"));
|
||||
}
|
||||
|
||||
/// A filter at API level 2 named Ctx whose commands are `commands` (a JSON list): each adds a
|
||||
/// triangle when it is given an object named Target, and leaves its input as it is otherwise.
|
||||
fn context_plugin(id: &str, commands: &str) -> String {
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Ctx","api":2,"version":"1","kind":"filter","commands":{commands}}}"#);
|
||||
let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[5,0]},{"p":[5,5]}]}]}}]}"#;
|
||||
vectorcraft_format::base64_encode(&wat::parse_str(tpl::when_given(&manifest, tpl::Given::Input, r#""name":"Target""#, triangle)).unwrap())
|
||||
}
|
||||
|
||||
/// The items of the canvas context menu's Plug-ins submenu: (plug-in, label, command, params).
|
||||
fn canvas_plugin_items(app: &VectorcraftApp) -> Vec<(String, String, String, Value)> {
|
||||
let items = menus::context_items(app);
|
||||
let plugins = items.iter().find_map(|it| match it {
|
||||
menus::Node::Submenu { label, children, .. } if label.as_str() == "Plug-ins" => Some(children),
|
||||
_ => None,
|
||||
});
|
||||
let mut out = Vec::new();
|
||||
for p in plugins.into_iter().flatten() {
|
||||
let menus::Node::Submenu { label: name, children, .. } = p else { panic!("a plug-in's group is a submenu: {p:?}") };
|
||||
for c in children {
|
||||
let menus::Node::Item(i) = c else { panic!("a plug-in group holds commands only: {c:?}") };
|
||||
out.push((name.as_str().to_string(), i.label.as_str().to_string(), i.command.id.to_string(), i.command.params.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The plug-in command the open plug-in dialog runs, and the objects it runs on.
|
||||
fn dialog_runs(app: &VectorcraftApp) -> Option<(String, Option<Value>)> {
|
||||
app.plugin_dialog.as_ref()?.runs_command().map(|(c, ids)| (c.to_string(), ids.cloned()))
|
||||
}
|
||||
|
||||
/// A command whose manifest's `menu.context` names the canvas or the Layers panel is listed in that
|
||||
/// context menu, in a Plug-ins submenu holding a submenu named after the plug-in; a command without
|
||||
/// it is not. An item whose `when` fails is greyed out. Chosen, it runs its command on the
|
||||
/// selection (canvas) or on the clicked rows (Layers panel, whatever the selection) as one undo
|
||||
/// step named after the command; one with parameters opens its dialog first, and OK runs it on
|
||||
/// those objects. Nothing is listed while nothing is selected, and nothing once the plug-in is
|
||||
/// removed.
|
||||
#[test]
|
||||
fn plugin_commands_are_listed_in_the_canvas_and_layers_context_menus() {
|
||||
use dialogs::plugin::{ContextCommand, context_commands};
|
||||
use vectorcraft_plugins::ContextMenu;
|
||||
let mut h = window(app());
|
||||
let id = "test.ui.context";
|
||||
let command = |c: &str| vectorcraft_engine::cmd::plugin::command_id(id, c);
|
||||
let commands = r#"[{"id":"tidy","label":"Tidy","menu":{"context":[{"menu":"canvas"},{"menu":"layers","when":"oneObject"}]}},
|
||||
{"id":"text","label":"Text Only","menu":{"context":[{"menu":"canvas","when":"typeObject"},{"menu":"layers","when":"layerRow"}]}},
|
||||
{"id":"size","label":"Size","menu":{"context":[{"menu":"canvas"},{"menu":"layers"}]},"params":{"by":{"type":"number","min":0,"max":10,"default":2}}},
|
||||
{"id":"plain","label":"Plain"}]"#;
|
||||
let app = h.state_mut();
|
||||
app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap();
|
||||
let target = red_rect(app);
|
||||
app.run("layer.setProps", json!({"ids": [target.0], "name": "Target"})).unwrap();
|
||||
let other = red_rect(app);
|
||||
let layer = app.session.doc().unwrap().doc.layers[0].id;
|
||||
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(canvas_plugin_items(app).is_empty(), "nothing selected: no Plug-ins submenu");
|
||||
|
||||
app.run("select.set", json!({"ids": [target.0]})).unwrap();
|
||||
let ids = json!({"ids": [target.0]});
|
||||
let listed = canvas_plugin_items(app);
|
||||
let expected = [("Ctx", "Tidy", command("tidy")), ("Ctx", "Text Only", command("text")), ("Ctx", "Size…", command("size"))];
|
||||
assert_eq!(listed.iter().map(|(p, l, c, _)| (p.as_str(), l.as_str(), c.clone())).collect::<Vec<_>>(), expected);
|
||||
assert!(listed.iter().all(|(.., p)| *p == ids), "{listed:?}");
|
||||
let shown = |app: &VectorcraftApp, c: &str| menus::shown_state(app, c, &ids).map(|(enabled, _)| enabled);
|
||||
assert_eq!((shown(app, &command("tidy")), shown(app, &command("text"))), (Some(true), Some(false)), "no type object is selected");
|
||||
fn rendered_enabled(nodes: &[menus::Node], command: &str) -> Option<bool> {
|
||||
nodes.iter().find_map(|node| match node {
|
||||
menus::Node::Item(item) if item.command.id == command => Some(item.enabled),
|
||||
menus::Node::Submenu { children, .. } => rendered_enabled(children, command),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
let rendered = menus::context_items(app);
|
||||
assert_eq!(rendered_enabled(&rendered, &command("tidy")), Some(true));
|
||||
assert_eq!(rendered_enabled(&rendered, &command("text")), Some(false));
|
||||
|
||||
let doc = app.session.doc().unwrap().doc.clone();
|
||||
let rows = |ids: &[u64]| context_commands(ContextMenu::Layers, &doc, ids);
|
||||
let item = |label: &'static str, c: &str, enabled| ContextCommand { label, command: vectorcraft_plugins::registry::intern(&command(c)), enabled };
|
||||
assert_eq!(rows(&[target.0]), vec![("Ctx", vec![item("Tidy", "tidy", true), item("Text Only", "text", false), item("Size…", "size", true)])]);
|
||||
assert_eq!(rows(&[layer.0])[0].1[..2], [item("Tidy", "tidy", false), item("Text Only", "text", true)], "a layer row");
|
||||
assert_eq!(rows(&[target.0, other.0])[0].1[0], item("Tidy", "tidy", false), "two rows are not one object");
|
||||
|
||||
// The canvas item runs on the selection as one undo step.
|
||||
// The plug-in's output, a triangle in place of what it was given, replaces Target only when
|
||||
// Target is what it was given.
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
menus::invoke(app, &command("tidy"), ids.clone());
|
||||
let st = app.session.doc().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Tidy"));
|
||||
assert!(st.doc.node(target).is_none() && st.doc.node(other).is_some(), "the plug-in was given Target alone");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
|
||||
// Clicking the canvas item of a command with parameters opens the plug-in's own dialog for the
|
||||
// selection, not the generic parameter dialog.
|
||||
let (_, label, c, p) = listed.iter().find(|(_, l, ..)| l == "Size…").unwrap();
|
||||
let (cmd, p) = menus::click_target(label, c, p);
|
||||
assert_eq!(cmd, command("size"), "not the generic parameter dialog");
|
||||
menus::invoke(app, &cmd, p);
|
||||
step(&mut h);
|
||||
assert_eq!(dialog_runs(h.state()), Some((command("size"), Some(json!([target.0])))), "Size opens its dialog from the canvas");
|
||||
answer(&mut h, false);
|
||||
|
||||
// A row's item runs on that row's object, not on the selection; one with parameters asks first.
|
||||
h.state_mut().run("select.set", json!({"ids": [other.0]})).unwrap();
|
||||
let undo = h.state().session.doc().unwrap().history.undo.len();
|
||||
menus::invoke(h.state_mut(), &command("size"), ids.clone());
|
||||
step(&mut h);
|
||||
assert_eq!(dialog_runs(h.state()), Some((command("size"), Some(json!([target.0])))), "Size opens its dialog");
|
||||
answer(&mut h, true);
|
||||
let st = h.state().session.doc().unwrap();
|
||||
assert_eq!((st.history.undo.len(), st.history.undo.last().unwrap().label.as_str()), (undo + 1, "Size"));
|
||||
assert!(st.doc.node(target).is_none() && st.doc.node(other).is_some(), "the plug-in was given the row's object, not the selection");
|
||||
|
||||
let app = h.state_mut();
|
||||
let list = app.run("plugin.list", json!({})).unwrap();
|
||||
let entry = list["plugins"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone();
|
||||
assert_eq!(entry["commands"][0]["menu"], json!({"context": [{"menu": "canvas"}, {"menu": "layers", "when": "oneObject"}]}));
|
||||
assert!(entry["commands"][3].get("menu").is_none(), "Plain lists no menu");
|
||||
|
||||
app.run("plugin.remove", json!({"id": id})).unwrap();
|
||||
assert!(canvas_plugin_items(app).is_empty(), "removed: nothing listed");
|
||||
assert!(rows(&[other.0]).is_empty());
|
||||
}
|
||||
|
||||
/// A command dialog opened for objects of one document changes no document once another document
|
||||
/// is the active one, even one holding an object with the same id: drawn, the dialog closes and
|
||||
/// leaves that document's edit in progress, and OK closes it. On its own document, OK runs the
|
||||
/// command on those objects.
|
||||
#[test]
|
||||
fn a_plugin_command_dialog_stays_with_its_document() {
|
||||
let mut h = window(app());
|
||||
let id = "test.ui.context.doc";
|
||||
let size = vectorcraft_engine::cmd::plugin::command_id(id, "size");
|
||||
let commands = r#"[{"id":"size","label":"Size","params":{"by":{"type":"number","min":0,"max":10,"default":2}}}]"#;
|
||||
let app = h.state_mut();
|
||||
app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap();
|
||||
let target = red_rect(app);
|
||||
app.run("layer.setProps", json!({"ids": [target.0], "name": "Target"})).unwrap();
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let twin = red_rect(app);
|
||||
app.run("layer.setProps", json!({"ids": [twin.0], "name": "Target"})).unwrap();
|
||||
assert_eq!(twin, target, "the second document's object has the first one's id");
|
||||
let ids = json!({"ids": [target.0]});
|
||||
let undos = |app: &VectorcraftApp| app.session.documents().iter().map(|st| st.history.undo.len()).collect::<Vec<_>>();
|
||||
let kept = |app: &VectorcraftApp| app.session.documents().iter().map(|st| st.doc.node(target).is_some()).collect::<Vec<_>>();
|
||||
let before = undos(app);
|
||||
let opened = Some((size.clone(), Some(json!([target.0]))));
|
||||
|
||||
// Drawn while the other document is active, the dialog closes.
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
menus::invoke(app, &size, ids.clone());
|
||||
step(&mut h);
|
||||
assert_eq!(dialog_runs(h.state()), opened);
|
||||
h.state_mut().run("document.activate", json!({"index": 1})).unwrap();
|
||||
h.state_mut().begin_interaction("Edit").unwrap();
|
||||
step(&mut h);
|
||||
assert!(h.state().plugin_dialog.is_none() && top(h.state()).is_none(), "the dialog closes on another document");
|
||||
assert!(h.state().session.in_interaction(), "closing it leaves the other document's edit in progress");
|
||||
h.state_mut().session.cancel_interaction().unwrap();
|
||||
assert_eq!((undos(h.state()), kept(h.state())), (before.clone(), vec![true, true]));
|
||||
|
||||
// OK while the other document is active closes the dialog and changes neither document.
|
||||
h.state_mut().run("document.activate", json!({"index": 0})).unwrap();
|
||||
menus::invoke(h.state_mut(), &size, ids.clone());
|
||||
step(&mut h);
|
||||
assert_eq!(dialog_runs(h.state()), opened);
|
||||
h.state_mut().run("document.activate", json!({"index": 1})).unwrap();
|
||||
answer(&mut h, true);
|
||||
assert!(h.state().plugin_dialog.is_none());
|
||||
assert_eq!((undos(h.state()), kept(h.state())), (before.clone(), vec![true, true]));
|
||||
|
||||
// On its own document, OK runs the command on the objects it opened for.
|
||||
h.state_mut().run("document.activate", json!({"index": 0})).unwrap();
|
||||
menus::invoke(h.state_mut(), &size, ids);
|
||||
step(&mut h);
|
||||
answer(&mut h, true);
|
||||
assert_eq!((undos(h.state()), kept(h.state())), (vec![before[0] + 1, before[1]], vec![false, true]));
|
||||
h.state_mut().run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// A command with parameters given params that are neither nothing nor an object of `ids` alone
|
||||
/// opens no dialog: they go to the command as they were given, and it changes nothing.
|
||||
#[test]
|
||||
fn a_plugin_command_given_other_params_opens_no_dialog() {
|
||||
let mut h = window(app());
|
||||
let id = "test.ui.context.params";
|
||||
let size = vectorcraft_engine::cmd::plugin::command_id(id, "size");
|
||||
let commands = r#"[{"id":"size","label":"Size","params":{"by":{"type":"number","min":0,"max":10,"default":2}}}]"#;
|
||||
let app = h.state_mut();
|
||||
app.run("plugin.install", json!({"dataBase64": context_plugin(id, commands)})).unwrap();
|
||||
let target = red_rect(app);
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
for p in [json!(5), json!("by"), json!([target.0]), json!({"ids": target.0})] {
|
||||
menus::invoke(h.state_mut(), &size, p.clone());
|
||||
step(&mut h);
|
||||
assert!(h.state().plugin_dialog.is_none(), "{p} opens no dialog");
|
||||
assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "{p} changes nothing");
|
||||
}
|
||||
h.state_mut().run("plugin.remove", json!({"id": id})).unwrap();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
+4
-3
@@ -14897,9 +14897,10 @@ 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.<id>.<command>` while the plug-in is installed, listed by `command_list` and in its `plugin.list` entry
|
||||
(`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
|
||||
(`commands: [{id, command, label, params, paramsSchema, menu?}]`; `menu`, `{path?, after?, placed?, context?}`, 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), and `context`, `[{menu, when?}]`, lists the context menus
|
||||
that also list it, see [plugins.md](plugins.md#context-menus)). Run it with `{ids?, params?}` (its parameters may also
|
||||
be top-level keys) → `{plugin, command, ids, notice?, pluginName?}`, with `notice` and `pluginName` as `plugin.run`
|
||||
returns them: 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
|
||||
|
||||
+35
-4
@@ -200,7 +200,8 @@ 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 command whose manifest
|
||||
gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)).
|
||||
gives a `menu` is listed in that menu instead ([below](#placing-a-command-in-another-menu)), and one whose `menu`
|
||||
gives a `context` is also listed in the canvas or Layers panel context menu ([Context menus](#context-menus)).
|
||||
- **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
|
||||
@@ -229,8 +230,9 @@ Inverse.
|
||||
`["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.
|
||||
a key other than `path`, `after` and `context`, and an `after` that is not 1–64 printable characters are refused when
|
||||
the module is installed, and the error names the command. `path` may be left out only when `context` is given
|
||||
([Context menus](#context-menus)), and `after` needs `path`.
|
||||
- `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
|
||||
@@ -252,6 +254,34 @@ Inverse.
|
||||
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.
|
||||
|
||||
#### Context menus
|
||||
|
||||
At `api` 2 a command's `menu` may also list it in the canvas context menu and in the menu of a Layers panel row, with
|
||||
`context`: a list of `{"menu": "canvas" | "layers", "when"?: condition}`. For example,
|
||||
`"menu": {"context": [{"menu": "canvas", "when": "typeObject"}, {"menu": "layers"}]}`. The command stays where `path`
|
||||
puts it (or in its plug-in's submenu) as well.
|
||||
|
||||
- The canvas context menu lists the command while objects are selected, after Export Selection…, in a **Plug-ins**
|
||||
submenu that holds a submenu named after each plug-in, in plug-in id order. Its items are the commands in manifest
|
||||
order, under their own labels, with an ellipsis for a command with parameters. A row's menu in the Layers panel lists
|
||||
the same way after Collect for Export. Guide rows and blend spine rows list no plug-in commands. With no command
|
||||
listed there, the menu has no Plug-ins submenu.
|
||||
- `when` is one of `"selection"` (one or more objects are selected, or rows clicked), `"oneObject"` (exactly one
|
||||
object that is not a layer), `"typeObject"` (one of them is a type object) and `"layerRow"` (every clicked row is a
|
||||
layer or sublayer; Layers panel only). Without `when` the item can always be chosen. While its condition fails, the
|
||||
item is shown dimmed.
|
||||
- Choosing the item runs `plugin.<id>.<command>` as its other menu items do, with the same permissions, and one run is
|
||||
one undo step. On the canvas it runs on the selection. In the Layers panel it runs on the clicked row, or on every
|
||||
highlighted row when the clicked row is one of them, whatever is selected on the canvas; a layer or group row gives
|
||||
the run the objects in it. Both pass the objects as `ids`, so an action records them. A command with parameters
|
||||
opens its dialog first, and its preview and OK run on those objects. Nothing runs until an item is chosen.
|
||||
- Each menu may be listed once in a command's `context`. A `context` that is not a list, an entry that is not an
|
||||
object or has a key other than `menu` and `when`, an unknown `menu` or `when`, `"layerRow"` for the canvas and a
|
||||
menu named twice are refused when the module is installed. A plug-in may list at most 8 commands in each context
|
||||
menu; the module is refused otherwise. Each error names the command and the key.
|
||||
- `plugin.list` gives the command's `menu` with its `context`, and so does the `manifest` that `plugin.info` gives.
|
||||
- At `api` 1 the key is ignored, as the rest of `menu` is.
|
||||
|
||||
**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
|
||||
@@ -882,7 +912,8 @@ the module's start function, in a run that isn't a filter's run on a document, o
|
||||
([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).
|
||||
are. `menu` (`api` 2 and later; ignored at `api` 1) places the command in [another menu](#placing-a-command-in-another-menu)
|
||||
and lists it in [context menus](#context-menus).
|
||||
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
|
||||
|
||||
@@ -2835,6 +2835,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a write or removal that failed after the generation was raised) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file, and `plugin.remove` of a stored plug-in that didn't load deletes its module and reports it removed. When the key store can't be reached, an approval lasts for the session only, the file is left as it is, and `plugin.remove` fails and leaves the plug-in installed. A key store that can't be reached is tried again the next time it is needed. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/store/grant_keys.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.<id>.<command>` 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.
|
||||
- **Plug-in commands in context menus (G17):** at plug-in API level 2 a command's `menu.context` (`[{menu: "canvas" | "layers", when?}]`) also lists it in the canvas context menu while objects are selected and in the menu of a Layers panel layer, group or object row, in a Plug-ins submenu holding a submenu named after each plug-in. `when` is `selection`, `oneObject`, `typeObject` or `layerRow` (Layers panel only), and the item is dimmed while it fails. The item runs the command as one undo step on the selection, or on the clicked or highlighted rows whatever the selection, passing them as `ids`; a command with parameters opens its dialog for those objects first. A plug-in may list at most 8 commands in each context menu; any other `context` is refused by command and key when the module is installed. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`, `crates/ui-egui/src/i18n/tests.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.
|
||||
|
||||
Reference in new issue
Block a user