diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index db6b35a63e..b9e9a959e0 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -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 { "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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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 ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 4566ef2be4..cc04612a89 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -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] diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 1987b8adba..48c90cad29 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -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(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 79250459cf..4b7ee76f4a 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -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}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 5528594c9c..7fa54caa42 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -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, } +/// 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 { + 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, +} + +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, String> { + let Some(list) = v.as_array() else { + let key = "menu.context"; + return Err(format!("`{key}` must be a list")); + }; + let mut out: Vec = 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 = 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 { + /// 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, Vec), String> { let wrong_path = || { let k = "menu.path"; let places: Vec = @@ -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::>().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..`, 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, + /// 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, /// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them. #[serde(skip)] pub(crate) declared_menu: Vec, } +/// 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(&self, s: S) -> std::result::Result { + fn params(p: &&[(String, Param)], s: S) -> std::result::Result { + 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>, + } + 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)> { + 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 = (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::>(), [("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 = + (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( diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index c8b37acbc7..2e05fca92b 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -756,7 +756,14 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b NodeKind::Blend { .. } => { let b = n.reach_bounds_with(symbols)?; let a = live_content_reach(symbols, n); - vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n)) + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n)) + } + // A radial or mirror repeat rotates or reflects each copy before applying the source's + // geometry effects. + NodeKind::Repeat(_) => { + let b = n.visual_bounds_with(symbols)?; + let a = live_content_reach(symbols, n); + vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_live_effect_bounds(symbols, n)) } _ => { let b = n.visual_bounds_with(symbols)?; @@ -841,7 +848,7 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) -> /// (Revolve builds no art from type). fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { let b = match &n.kind { - NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)), + NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_live_effect_bounds(symbols, n)), _ => n.visual_bounds_with(symbols), }?; Some(match &n.kind { @@ -850,13 +857,15 @@ fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option { }) } -/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects -/// run on the placed shapes, so their reach on the original keys need not cover what they paint. -/// Effect-free blends keep the quick rail envelope without evaluating their steps. -fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { - let NodeKind::Blend { spec, .. } = &n.kind else { return None }; - if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath { - return None; +/// A radial or mirror repeat's copies or a spine-aligned blend's steps, measured after they are +/// rotated or reflected. Geometry effects run on the placed shapes, so their reach on the source +/// need not cover what they paint. +/// Without effects, the renderer keeps the quick bounds without evaluating the copies or steps. +fn placed_live_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { + match &n.kind { + NodeKind::Blend { spec, .. } if spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath => {} + NodeKind::Repeat(r) if matches!(r.kind, vectorcraft_doc::RepeatKind::Radial { .. } | vectorcraft_doc::RepeatKind::Mirror { .. }) => {} + _ => return None, } let mut has_effects = false; n.walk(&mut |c| { diff --git a/crates/render/src/tests/changed.rs b/crates/render/src/tests/changed.rs index 3650d2208a..4440c06baf 100644 --- a/crates/render/src/tests/changed.rs +++ b/crates/render/src/tests/changed.rs @@ -171,6 +171,62 @@ fn moving_a_shadowed_object_changes_where_its_shadow_falls() { assert!(a.x1 > 86.0 && a.y1 > 70.0, "the shadow, before and after: {a:?}"); } +#[test] +fn moving_a_radial_repeat_redraws_the_effects_on_its_rotated_copies() { + for effected in [false, true] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + if effected { + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + } + let repeat = vectorcraft_doc::RepeatSpec::radial(vec![Arc::new(source)], 4, Some(12.0)); + let id = old.alloc_id(); + old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + +#[test] +fn moving_a_slanted_mirror_repeat_redraws_the_effects_on_its_reflected_copy() { + for effected in [false, true] { + let mut old = Document::new(110.0, 80.0); + let source_id = old.alloc_id(); + let mut source = Node::path( + source_id, + shapes::rectangle(Rect::new(47.0, 25.0, 49.0, 45.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + if effected { + source.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: serde_json::json!({"scaleH": 400, "scaleV": 100, "reference": 4}), + visible: true, + }); + } + let repeat = vectorcraft_doc::RepeatSpec::mirror(vec![Arc::new(source)], 45.0, 6.0); + let id = old.alloc_id(); + old.insert(Some(old.layers[0].id), 0, Node::new(id, vectorcraft_doc::NodeKind::Repeat(repeat))).unwrap(); + let mut moved = old.clone(); + moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 4.0)), false); + // A partial redraw must reproduce the whole frame, both on the move and on Undo. + area(redraw(&old, &moved)); + area(redraw(&moved, &old)); + } +} + #[test] fn adding_removing_and_restacking_change_those_objects() { let (old, [loose, _, _, _, other]) = document(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index f921b19fea..7510358fc4 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -262,6 +262,9 @@ fn distance_overlays(cx: &ToolContext, to: DistanceTo) -> Vec { /// it snaps to the original too. pub(crate) struct MoveSnap { bounds: Option, + /// The selection's geometric bounds, which Smart Guides line up with the other art's geometric + /// bounds and space evenly between them, whether Use Preview Bounds is on or off (#6436). + edges: Option, targets: Option, points: Option, /// The targets and points for a copy, gathered with the others before the previews move the @@ -300,6 +303,7 @@ impl MoveSnap { let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) }; Self { bounds: selection_bounds(cx), + edges: guides.then(|| cx.doc.bounds_of(&cx.selection.objects, false)).flatten(), targets: guides.then(|| for_move(cx, &cx.selection.objects)), points: points(&cx.selection.objects), copy_targets: guides.then(|| for_move(cx, &[])), @@ -312,7 +316,7 @@ impl MoveSnap { /// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an /// edge of the box on a gridline, and pixels put its top-left on whole pixels. pub(crate) fn grid_only(bounds: Option) -> Self { - Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } + Self { bounds, edges: None, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } } /// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View, @@ -353,7 +357,7 @@ impl MoveSnap { // The grabbed anchor landed on a path or a crossing, which a ruler guide does not pull // it off. let mut on_path = false; - if let (Some(t), Some(b)) = (targets, self.bounds) { + if let (Some(t), Some(b)) = (targets, self.edges) { // The point the selection was grabbed by, near another object's anchor or centre, // lands on it, rather than the bounds lining up a little beside it (#955). if t.has_point_near(start + d, cx.snap_tol()) { @@ -434,7 +438,7 @@ impl MoveSnap { d = q - start; guides = ov; } - if let (Some(t), Some(b)) = (targets, self.bounds) { + if let (Some(t), Some(b)) = (targets, self.edges) { if t.has_point_near(start + d, cx.snap_tol()) { let (q, ov) = t.snap_point_along(start + d, u, cx.snap_tol()); d = q - start; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index d575fda573..e74e3d9163 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1255,6 +1255,42 @@ fn an_alt_copy_snaps_to_the_original_left_behind() { assert_eq!(dx(&t.pointer(&c, &ev(PointerKind::Drag, 253.0, 150.0))), 103.0); } +/// With Use Preview Bounds on, Smart Guides line up the moved selection's geometric bounds with +/// the other art's, as they do with it off: an edge lands exactly on the other path's edge, and the +/// edge of a stroke does not pull it there (#6436). +#[test] +fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Node}; + // An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt. + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let mut add = |r: Rect| { + let id = d.alloc_id(); + let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0); + d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap(); + id + }; + let a = add(Rect::new(100.0, 100.0, 200.0, 200.0)); + add(Rect::new(300.0, 100.0, 400.0, 200.0)); + let s = Selection { objects: vec![a], ..Default::default() }; + let p = paint(); + for preview in [false, true] { + let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) }; + let dragged = |to: f64| { + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + (v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()) + }; + // The right edge, 1 pt short of the other rectangle's left edge (x = 300), lands on it. + assert_eq!(dragged(249.0), (100.0, 0.0), "preview {preview}"); + // 9 pt short, it stays where it is dragged, though the edge of its stroke is 1 pt past there. + assert_eq!(dragged(241.0), (91.0, 0.0), "preview {preview}"); + } +} + /// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it /// began goes back there, labeled "last location", a Shift move too; farther out, with the option /// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cb9ab68bd1..2efe7e984a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -395,7 +395,7 @@ fn compass(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option Option egui::Rect { + if app.ui.screen_mode >= 2 { + return rect; + } + let env = Env::of(ui); + let strip = env.tokens.size.icon.md + env.tokens.space.gap.tight; + egui::Rect::from_min_max(rect.min, egui::pos2((rect.right() - strip).max(rect.left()), rect.bottom())) +} + /// The scroll bars along the right and bottom edges (Normal and Full Screen with Menu Bar): the view /// a thumb drag or page press moved. fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 9e25bcbf93..2fff6194da 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -19,7 +19,7 @@ use serde_json::json; use vectorcraft_geom::{Affine, Point}; use super::BodyKind; -use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key}; +use super::raster::{backdrop, cache_key, frame_options, frame_ppp, frame_view, pixel_region, placed_key, plugin_key, snapped_rect}; use crate::doc_windows::Win; use crate::state::View; use crate::{CacheKey, VectorcraftApp}; @@ -141,6 +141,7 @@ impl PaneSource { pub(super) fn new(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, cv: &CanvasView) -> Option { let env = Env::of_root(ctx); let ppp = ctx.pixels_per_point(); + let device_ppp = ppp; let space = cv.rect; let v = crate::doc_windows::view(app, w).copied()?; let st = app.session.documents().get(w.0)?; @@ -165,7 +166,12 @@ impl PaneSource { Some([x0, y0, x1, y1]) => { egui::Rect::from_two_pos(cv.to_screen(Point::new(x0 as f64, y0 as f64)), cv.to_screen(Point::new(x1 as f64, y1 as f64))) } - None => space, + // The frame's own pixel size, centered on the pane and on whole device pixels, so each + // of its pixels covers one device pixel. + None => { + let size = egui::vec2(pw as f32 / ppp, ph as f32 / ppp); + snapped_rect(space.center() - size / 2.0, size, device_ppp) + } }; let frame = PaneFrame { key: PaneKey { slot: (st.uid, w.1) }, diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 9d1cdcb417..48f036012e 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -313,6 +313,18 @@ pub(super) fn frame_ppp(size: egui::Vec2, ppp: f32, max_side: usize) -> f32 { if longest.round() <= max { ppp } else { ppp * (max / longest) } } +/// Where a frame drawn `size` points across from `min` goes on a display of `device_ppp` pixels a +/// point: `min` moved to the nearest device pixel, the size unchanged. A canvas whose corner falls +/// between device pixels would otherwise draw every pixel of the frame across two device pixels, +/// and each edge in the art would show as a soft double line. +pub(super) fn snapped_rect(min: egui::Pos2, size: egui::Vec2, device_ppp: f32) -> egui::Rect { + if !(device_ppp.is_finite() && device_ppp > 0.0) { + return egui::Rect::from_min_size(min, size); + } + let snap = |c: f32| (c * device_ppp).round() / device_ppp; + egui::Rect::from_min_size(pos2(snap(min.x), snap(min.y)), size) +} + /// Pixel Preview: the whole document pixels (x0, y0, x1, y1) under the canvas, rotated view /// included. None when the view is degenerate, or when a side of the region is more than /// `max_side` pixels, the largest texture side the display supports. @@ -975,7 +987,8 @@ fn reproject_frame(app: &VectorcraftApp, painter: &egui::Painter, view: &CanvasV let old = CanvasView::new(old_rect, Point::new(k.cx, k.cy), k.zoom).rotation(rotation); let a = view.to_screen(old.to_doc(old_rect.min)); let b = view.to_screen(old.to_doc(old_rect.max)); - painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + let placed = snapped_rect(a, b - a, painter.pixels_per_point()); + painter.image(tex.id(), placed, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // The view turned after the last frame was rendered, and the worker renders the frame at // the new angle. Until it arrives, the last frame is drawn turned into this view: each diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4857c67064..3f1eddb392 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1191,6 +1191,45 @@ fn the_art_renders_within_the_largest_texture_side() { assert_eq!(pixel_region(&view, 1024), None, "more than the display's largest texture"); } +/// On a display of 2 pixels a point, a canvas whose corner falls between device pixels still draws +/// its art's frame on whole device pixels at its own size, so each frame pixel covers one device +/// pixel and a stroke's edges stay sharp instead of spreading over two device pixels. +#[test] +fn the_art_lands_on_whole_device_pixels() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":400,"height":300})).unwrap(); + app.canvas.worker_started = true; // every frame on this thread + let ctx = crate::testing::ui_context(); + ctx.set_pixels_per_point(2.0); + let mut shapes = vec![]; + // The first frame sets the pixels a point, the second draws at them. + for _ in 0..2 { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(31.3, 19.7), vec2(800.3, 600.35))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + shapes = flat_shapes(out.shapes); + } + let ppp = ctx.pixels_per_point(); + assert_eq!(ppp, 2.0); + let rect = app.canvas_view().unwrap().rect; + let off_grid = |c: f32| ((c * ppp) - (c * ppp).round()).abs() > 0.01; + assert!(off_grid(rect.min.x) || off_grid(rect.min.y), "the canvas {rect:?} starts between device pixels"); + let tex = app.canvas.texture.as_ref().expect("a rendered frame"); + let (tid, size) = (tex.id(), tex.size()); + let drawn = shapes + .iter() + .find_map(|s| match s { + Shape::Mesh(m) if m.texture_id == tid => Some(m.calc_bounds()), + _ => None, + }) + .expect("the frame is drawn"); + for (c, what) in [(drawn.min.x, "left"), (drawn.min.y, "top")] { + assert!(!off_grid(c), "the frame's {what} edge {c} is not on a device pixel"); + } + assert!((drawn.width() * ppp - size[0] as f32).abs() < 0.01, "{} device pixels across for {} frame pixels", drawn.width() * ppp, size[0]); + assert!((drawn.height() * ppp - size[1] as f32).abs() < 0.01, "{} device pixels down for {} frame pixels", drawn.height() * ppp, size[1]); +} + /// `rgb` as the display transform `t` shows it. fn convert8(t: &craft::color_ui::display::DisplayTransform, rgb: [u8; 3]) -> [u8; 3] { let mut px = [rgb[0], rgb[1], rgb[2], 255]; diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 52d92c7df6..291177c9e2 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -6,7 +6,7 @@ use std::cell::RefCell; use craft::behavior::IconId; use craft::menu::MenuBarUi; use craft::ui::buttons::{Button, IconButton, ToggleButton}; -use craft::ui::contract::{Bind, BodyCx, Props, Show, ShowContainer}; +use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer}; use craft::ui::display::Picture; use craft::ui::layout_components::Row; use craft::ui::primitives::IconSpec; @@ -114,17 +114,20 @@ fn leading(ui: &mut Ui, app: &mut VectorcraftApp) { } /// The end of the bar: each ranked control in a row of its own, which the fitted title bar gives up whole, lowest rank -/// first, before the menus narrow. +/// first, before the menus narrow. The controls are `space.gap.item` apart, the gap between neighboring controls in a +/// bar. fn trailing(ui: &mut Ui, app: &mut VectorcraftApp) { let safe = vectorcraft_plugins::safe_mode::active(); - for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) { - match t.rank() { - Some(rank) => { - Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui)); + Row::new().gap(Gap::Item).show(ui, |ui, _| { + for t in Trailing::SHOWN.into_iter().filter(|t| safe || *t != Trailing::Safe) { + match t.rank() { + Some(rank) => { + Row::new().fit_rank(rank).show(ui, |ui, _| t.show(app, ui)); + } + None => t.show(app, ui), } - None => t.show(app, ui), } - } + }); } /// The application bar, the body of the shell's title bar: brand mark, Home and menus, then Discord, diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 460a6ed51f..9848d86f1a 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -120,8 +120,15 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - if let Some(i) = - Select::new(tl!("Artboard"), Bind::given(cur), &boards).look(SelectLook::Filled).enabled(nab > 0).show(ui).events.committed().copied() + // With no document the navigator shows a dash, as the info readout does. + if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards) + .placeholder("\u{2013}") + .look(SelectLook::Filled) + .enabled(nab > 0) + .show(ui) + .events + .committed() + .copied() { go = Some(json!(i)); } @@ -264,6 +271,15 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), undo); } } + + #[test] + fn with_no_document_the_artboard_navigator_shows_a_dash() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + assert_eq!(panel.value_role("Artboard", Role::COMBO_BOX).as_deref(), Some("\u{2013}"), "the empty navigator reads as a dash"); + } } /// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 0caf6ca592..a06ee63300 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -473,6 +473,28 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { assert!(widest.zip(narrowest).is_some_and(|(w, n)| n >= w - 0.5), "the search keeps its width until it goes: {search_widths:?}"); } +/// The app bar's right-hand controls stand at least `space.gap.item` apart, the gap between neighboring controls in a +/// bar, so a hovered control's highlight does not touch the one beside it. +#[test] +fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let app = crate::VectorcraftApp::new(Session::new(), Default::default()); + let gap = Rc::new(std::cell::Cell::new(0.0_f32)); + let read = Rc::clone(&gap); + let mut bar = Shown::new(app, egui::vec2(1600.0, 600.0), move |app, ui| { + read.set(craft::ui::runtime::env::Env::of(ui).tokens.space.gap.item); + app.ui(ui); + }); + bar.frame(Vec::new()).frame(Vec::new()); + assert!(gap.get() > 0.0, "the item gap is read from the theme"); + let controls = ["Discord", "Search commands", "Choose a workspace"]; + let rects: Vec = controls.iter().map(|c| bar.starting(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect(); + for pair in rects.windows(2) { + let between = pair[1].left() - pair[0].right(); + assert!(between >= gap.get() - 0.5, "neighboring controls {pair:?} are {between} apart, under the item gap {}", gap.get()); + } +} + /// A text the status bar painted, with where it lies. #[derive(Debug)] struct StatusText { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8ec5e10ba1..caefb3bf5c 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,13 +20,13 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; -use craft::behavior::{IconId, Mixed}; +use craft::behavior::{ColumnWidth, IconId, Mixed}; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, clicked}; -use craft::ui::display::Text; +use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, clicked}; +use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Grid, Row}; use craft::ui::patterns::form_dialogs::{ CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory, }; @@ -35,6 +35,7 @@ use craft::ui::pickers::Select; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; +use craft::ui::style::TypeRole; use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use super::host::open_held; @@ -296,8 +297,8 @@ impl DocumentSettings for VcNewDocument { } }); }); - // Host viewports below the desktop main window's 800-point minimum need this row to wrap. - Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| { + // The row wraps whenever its fields do not fit the column, so Artboards is never cut off at its right edge. + Row::new().wrap(true).show(ui, |ui, _| { Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); Field::new(orientation.clone()).show(ui, |ui, _| { let entries = [ @@ -354,17 +355,24 @@ impl DocumentSettings for VcNewDocument { Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); - let more = Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui); - let mut more_open = memory.more_open != clicked(&more); - Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(&more).show(ui, |ui, _| more_settings(ui, s, lengths)); - memory.more_open = more_open; - - let manage = Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui); - let mut profiles_open = memory.profiles_open != clicked(&manage); - Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open)) - .opened_by(&manage) - .show(ui, |ui, _| manage_profiles(ui, &setup, &mut action)); - memory.profiles_open = profiles_open; + // The two buttons side by side, the item gap apart. + let (mut more, mut manage) = (None, None); + Row::new().gap(Gap::Item).wrap(true).show(ui, |ui, _| { + more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui)); + manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui)); + }); + if let Some(more) = &more { + let mut more_open = memory.more_open != clicked(more); + Popover::new(text(tl!("More Settings")), Bind::bound(&mut more_open)).opened_by(more).show(ui, |ui, _| more_settings(ui, s, lengths)); + memory.more_open = more_open; + } + if let Some(manage) = &manage { + let mut profiles_open = memory.profiles_open != clicked(manage); + Popover::new(text(tl!("Manage Profiles")), Bind::bound(&mut profiles_open)) + .opened_by(manage) + .show(ui, |ui, _| manage_profiles(ui, &setup, &mut action)); + memory.profiles_open = profiles_open; + } // Drafts stay in their controls until committed: ending the preset or choosing units cannot be undone by // restoring only a scalar value. Units and orientation only change how the page shows; other edits end the preset. @@ -475,6 +483,10 @@ fn advanced(ui: &mut egui::Ui, s: &mut DocSettings) { /// More Settings' pop-up: the artboard layout, spacing and columns. All three are off with one /// artboard, Columns also for the row and column layouts; columns stay within the artboards. fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { + crate::panels::popover_body(ui, |ui| more_settings_rows(ui, s, lengths)); +} + +fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { let several = s.artboards > 1; let grid = matches!(s.layout, ArtboardLayout::GridByRow | ArtboardLayout::GridByColumn); let (layout, spacing, columns, right_to_left) = @@ -531,22 +543,26 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) { /// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a /// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`. fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option) { - Text::new(text(tl!("NEW DOCUMENT PROFILES"))).show(ui); - for (name, customized) in &setup.profiles { - ui.push_id(name, |ui| { - Row::new().show(ui, |ui, _| { - Text::new(text(tl!(name))).show(ui); - if clicked(&Button::new(text(tl!("Edit"))).id_salt("edit").enabled(setup.has_profile_folder).show(ui)) { + crate::panels::popover_body(ui, |ui| { + Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui); + // The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up. + Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| { + for (name, customized) in &setup.profiles { + Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui); + if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) { *action = Some(format!("{EDIT_PROFILE}:{name}")); } - if clicked(&Button::new(text(tl!("Reset"))).id_salt("reset").enabled(*customized).show(ui)) { + if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) { *action = Some(format!("{RESET_PROFILE}:{name}")); } - }); + } }); - } + }); } +/// The columns of Manage Profiles' rows: the profile's name, Edit and Reset. +const PROFILE_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]; + /// The category of the settings New Document opens on: the most recent, else Print. fn first_category(app: &VectorcraftApp) -> &'static str { if app.session.prefs.recent_new_docs.is_empty() { "Print" } else { "Recent" } @@ -1009,7 +1025,8 @@ mod tests { }; let landscape = bounds("Landscape", egui::accesskit::Role::RadioButton); let artboards = bounds("Artboards", egui::accesskit::Role::SpinButton); - assert!(landscape.x1 <= artboards.x0, "Landscape {landscape:?} stays left of Artboards {artboards:?}"); + // Artboards follows Landscape on its line, or wraps below it when the column has no room for it. + assert!(landscape.x1 <= artboards.x0 || landscape.y1 <= artboards.y0, "Landscape {landscape:?} stays clear of Artboards {artboards:?}"); let group = bounds("Orientation", egui::accesskit::Role::RadioGroup); let mut drawn = Vec::new(); out.shapes.iter().for_each(|s| texts(&s.shape, &mut drawn)); diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 50f7a22216..d69545ba7c 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -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) { } } +/// 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) -> 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)> { + registry::list() + .iter() + .filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Effect)) + .filter_map(|p| { + let m = p.manifest(); + let commands: Vec = 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 { + let groups: Vec = 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 = 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, + /// 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, }, /// 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 { /// 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, + command: Option, heading: String, values: Map, ) -> 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..`), 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, + doc: u64, +} + +/// Opens the dialog of plug-in command `id` (`plugin..`), 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) { - 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) { + 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 /// 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) -> Result { - 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::(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); diff --git a/crates/ui-egui/src/dialogs/relink.rs b/crates/ui-egui/src/dialogs/relink.rs index 7220750be8..2ee70056be 100644 --- a/crates/ui-egui/src/dialogs/relink.rs +++ b/crates/ui-egui/src/dialogs/relink.rs @@ -46,7 +46,8 @@ fn scope_label(scope: &str) -> Label { /// Open the dialog on the images and placed documents `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { - let document = app.session.active().ok_or("no document open")?.uid; + let st = app.session.active().ok_or("no document open")?; + let document = (st.uid, st.reverts); let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(v) => v.as_array().cloned().ok_or_else(|| format!("`ids` must be an array of object ids, not {v}"))?, None => crate::panels::links::selected_ids(app).into_iter().map(Value::from).collect(), @@ -86,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. -fn relink(app: &mut VectorcraftApp, (document, params): &(u64, Value)) -> Result<(), String> { - if app.session.active().is_none_or(|st| st.uid != *document) { - let reason = tl!("Relink can only change links in the document where it was opened."); +/// The relink rule: one `links.relink` call with the answer's parameters, and the status it earns. OK is refused in +/// another document, and in the opening document after File > Revert has replaced its content. +fn relink(app: &mut VectorcraftApp, ((document, reverts), params): &((u64, u64), Value)) -> Result<(), String> { + let refusal = match app.session.active() { + Some(st) if st.uid == *document && st.reverts == *reverts => None, + Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")), + _ => Some(tl!("Relink can only change links in the document where it was opened.")), + }; + if let Some(reason) = refusal { app.status(reason); return Err(reason.to_owned()); } @@ -122,8 +128,8 @@ impl ItemSource for Names<'_> {} /// app (`HoldsOk`); with Each Link Separately it stays open until every link has a file. pub(crate) struct RelinkDialog { id: DialogId, - /// The document that owns the link IDs. - document: u64, + /// The document that owns the link IDs: its uid and revert count. + document: (u64, u64), ids: Vec, links: Vec, scope: String, @@ -135,7 +141,7 @@ pub(crate) struct RelinkDialog { } impl RelinkDialog { - fn new(document: u64, ids: Vec, links: Vec) -> Self { + fn new(document: (u64, u64), ids: Vec, links: Vec) -> Self { RelinkDialog { id: dialog_id(KEY), document, @@ -194,7 +200,7 @@ impl RelinkDialog { } impl HoldsOk for RelinkDialog { - type Answer = (u64, Value); + type Answer = ((u64, u64), Value); fn held_ok(self) -> Self { self @@ -451,6 +457,82 @@ mod tests { check_relink_stays_in_opening_drawing(true); } + /// Opens Relink on a saved document's linked image and chooses a replacement (in `path`, or from the file picker + /// with `native_picker`) around File > Revert, then presses OK: the restored image keeps its link, no undo step is + /// recorded and the status line reports the revert. Reopened on the restored document, Relink relinks again. + fn check_relink_refused_after_file_revert(native_picker: bool) { + use crate::tests::panel_harness::Panel; + + let (mut app, dir) = setup(if native_picker { "revert-picker" } else { "revert-path" }, &["photo.png"]); + let picker = scripted(&mut app); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + let original = dir.join("photo.png").to_string_lossy().into_owned(); + let id = place(&mut app, &dir.join("photo.png")); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let chosen = new_file(&dir, "replacement.png"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(900.0, 700.0)); + panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap(); + panel.frame(); + if native_picker { + panel.click("Relink…"); + assert_eq!(picker.requests().len(), 1); + } else { + let dialog = relink_dialog(&panel.app()).id; + answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false); + } + panel.app().run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + + panel.app().run("file.revert", json!({"confirmed": true})).unwrap(); + assert_eq!(link_path(&panel.app(), id), original, "the same id names the restored image"); + let undo = panel.app().session.active().unwrap().history.undo.len(); + if native_picker { + picker.answer(&[&chosen]); + panel.frame(); + panel.frame(); + } else { + panel.click("Relink…"); + panel.frame(); + } + { + let app = panel.app(); + assert_eq!(link_path(&app, id), original, "OK leaves the restored image's link unchanged"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue."); + let dialog = relink_dialog(&app).id; + assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + } + + let ctx = ctx(&panel.app()); + let dialogs = panel.app().dialogs().expect("a window"); + let dialog = relink_dialog(&panel.app()).id; + dialogs.with(|host| host.cancel_by_id(&ctx, dialog)); + panel.frame(); + assert!(open_dialogs(&panel.app()).is_empty()); + panel.app().run("ui.relinkDialog", json!({"ids": [id]})).unwrap(); + panel.frame(); + let dialog = relink_dialog(&panel.app()).id; + answer_dialog(&mut panel.app(), dialog, &[("path", json!(chosen))], false); + panel.click("Relink…"); + panel.frame(); + let app = panel.app(); + assert!(open_dialogs(&app).is_empty()); + assert_eq!(link_path(&app, id), chosen, "reopened, Relink relinks the restored image"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + drop(app); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn relink_is_refused_after_file_revert_for_a_path_confirmation() { + check_relink_refused_after_file_revert(false); + } + + #[test] + fn relink_is_refused_after_file_revert_when_the_file_picker_answers() { + check_relink_refused_after_file_revert(true); + } + #[test] fn replace_popup_cancel_preserves_selected_instances_and_enter_relinks_all() { use crate::tests::panel_harness::Panel; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index e56fc4abe1..4910dff672 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -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 { use vectorcraft_doc::NodeKind; let Some(st) = app.session.active() else { return vec![] }; @@ -140,6 +141,11 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { Sep, c("Export Selection…", "file.exportSelection"), ]); + // The commands plug-in manifests list here (`menu.context`), each run on the selection. + let ids: Vec = 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() } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index ec9f3a68ff..b75f523931 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -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) { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 9bb0e2efff..c9b8c1a17f 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -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)> { - 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; } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index a3f5071435..f283714902 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -65,7 +65,8 @@ use craft::theme::variant::Tone; use craft::ui::buttons::{IconButton, Link, PopupMark}; use craft::ui::choice::{Radio, RadioGroup, SwatchSpacing}; use craft::ui::contract::{ - Bind, CaptionColumn, CommandSet as _, Entry, LabelScheme, ListDrag, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, + Bind, CaptionColumn, CommandSet as _, Entry, Gap, LabelScheme, ListDrag, Pad, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, + Trigger, }; use craft::ui::display::{Divider, Shade, Text}; use craft::ui::form::{Field, FieldGroup}; @@ -1068,11 +1069,28 @@ pub(crate) fn option_link(label: impl Into