diff --git a/Cargo.lock b/Cargo.lock index b5d10171b8..7492a7ccb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8659,6 +8659,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "vectorcraft-color", diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index 6d1f33dd5c..10adb09199 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -28,6 +28,8 @@ tiff = { workspace = true } craft-stream-codecs = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +# The hash of a generated art object's art, which its file holds (`generated`). +sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } chrono = { workspace = true } diff --git a/crates/doc/src/generated.rs b/crates/doc/src/generated.rs new file mode 100644 index 0000000000..30ef8fd250 --- /dev/null +++ b/crates/doc/src/generated.rs @@ -0,0 +1,597 @@ +//! Generated art objects: a group whose children a generator plug-in drew from its parameters +//! (`plugin.generate`). The group keeps the plug-in's id and name, the parameters it was drawn with +//! and the transform its art has had since, so `plugin.editGenerated` can run the plug-in again and +//! replace the art. Its children are ordinary objects for every renderer and exporter, so the art +//! draws, prints and exports whether or not the plug-in is installed. +//! +//! A file holds the fields beside a SHA-256 of the art as it was written ([`art_hash`]). Reading +//! never runs a plug-in. A field that can't be read (an id that is not a plug-in id, parameters +//! that are not an object or are past [`MAX_PARAMS_BYTES`], a transform that is not one) marks the +//! object [`State::Damaged`], and art that doesn't match the hash marks it [`State::Changed`]: the +//! art stays as it was read either way. A damaged object is saved with `damaged: true`, so it stays +//! damaged when the file is opened again. +//! +//! A generated art object inside another one's art (anywhere in its children or their opacity +//! masks) is written and read as plain art: its settings are left out of the file, and a file that +//! has them there anyway loses them when it is read, its outer object marked [`State::Changed`] +//! without hashing. So each object's art is written and hashed once, whatever the nesting. + +use std::cell::Cell; +use std::sync::Arc; + +use serde::Serialize; +use serde_json::{Map, Value}; +use vectorcraft_geom::Affine; + +use crate::Effect; +use crate::node::{Node, NodeKind, Scaling}; + +/// Most bytes a generated art object's parameters take, written as JSON. +pub const MAX_PARAMS_BYTES: usize = 64 << 10; + +/// Most bytes the art of a generated art object takes when a generator draws it, written as JSON. +pub const MAX_ART_BYTES: usize = 16 << 20; + +/// Longest plug-in id, in bytes, as plug-in manifests limit it. +pub const MAX_ID: usize = 64; + +/// Longest plug-in name kept, in characters, as plug-in manifests limit it. +pub const MAX_NAME: usize = 64; + +/// How the fields of a generated art object were read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum State { + /// Made in this session, or read with every field and the art's hash intact. + #[default] + Intact, + /// A field could not be read: the plug-in id is not one, or the parameters or the transform + /// are not usable. The art can't be drawn again. + Damaged, + /// The fields were read, but the art doesn't match the hash the file gave for it. + Changed, +} + +/// The settings of a generated art object ([`crate::NodeExtras::generated`]). +#[derive(Clone, Debug, PartialEq)] +pub struct GeneratedArt { + /// The id of the plug-in that drew it. + pub plugin: String, + /// The plug-in's name when it drew it, to name the plug-in while it is not installed. + pub name: String, + /// The plug-in's parameters it was drawn with, each one given. + pub params: Map, + /// The transform its art has had since it was drawn (moves, scales, rotations, reflections + /// and shears). + pub transform: Affine, + /// What its art's stroke weights and dashes have been scaled by since it was drawn (the + /// transforms made with Scale Strokes & Effects on). + pub stroke_scale: f64, + /// What its art's effect distances have been scaled by since it was drawn. + pub effect_scale: f64, + /// The transform its art's pattern tiles have had since it was drawn (the transforms made with + /// Transform Patterns on). + pub pattern_transform: Affine, + /// How it was read; not written to files. + pub state: State, +} + +impl GeneratedArt { + /// The settings of art drawn by plug-in `plugin` (named `name`) with `params`, not transformed + /// since. + pub fn new(plugin: &str, name: &str, params: Map) -> Self { + Self { + plugin: plugin.into(), + name: name.chars().take(MAX_NAME).collect(), + params, + transform: Affine::IDENTITY, + stroke_scale: 1.0, + effect_scale: 1.0, + pattern_transform: Affine::IDENTITY, + state: State::Intact, + } + } + + /// Its art transformed by `a`, with what `sc` says scales besides its geometry. + pub fn transform(&mut self, a: Affine, sc: &Scaling) { + self.transform = a * self.transform; + if let Some(k) = Scaling::factor(a) + && sc.strokes + { + self.stroke_scale *= k; + if sc.effects.is_some() { + self.effect_scale *= k; + } + } + if sc.patterns { + self.pattern_transform = a * self.pattern_transform; + } + } + + /// Places `art`, drawn by the generator as it is drawn untransformed, as the object's art has + /// been transformed since it was drawn: its geometry, stroke weights, effect distances and + /// pattern tiles. `scale` scales an effect's distance parameters (the effects catalogue's). + pub fn place(&self, art: &mut Node, scale: fn(&mut Effect, f64)) { + if self.transform != Affine::IDENTITY { + art.transform(self.transform, false); + } + self.restyle(art, scale); + } + + /// Scales the strokes and effects of `n` and its descendants, and transforms their pattern + /// tiles, as [`Self::place`] says. + fn restyle(&self, n: &mut Node, scale: fn(&mut Effect, f64)) { + if self.stroke_scale != 1.0 { + n.appearance.scale_strokes(self.stroke_scale); + } + if self.effect_scale != 1.0 { + n.appearance.scale_effects(self.effect_scale, scale); + } + if self.pattern_transform != Affine::IDENTITY { + crate::pattern::transform_pattern_paints(n, self.pattern_transform); + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + self.restyle(std::sync::Arc::make_mut(c), scale); + } + } + } + + /// Can its art be drawn again: are its fields intact or only its art changed? + pub fn redrawable(&self) -> bool { + self.state != State::Damaged + } +} + +/// Is `id` shaped as a plug-in id: 1 to [`MAX_ID`] characters from `A-Z a-z 0-9 . _ -`? +pub fn valid_id(id: &str) -> bool { + (1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +std::thread_local! { + /// Is a generated art object's art being written on this thread ([`Inside`])? + static INSIDE: Cell = const { Cell::new(false) }; +} + +#[cfg(test)] +std::thread_local! { + /// The bytes [`art_hash`] has hashed on this thread. + static HASHED: Cell = const { Cell::new(0) }; +} + +/// While it lives, objects written on this thread are part of a generated art object's art, and +/// the generated art objects among them are written as plain art ([`written`]). +pub(crate) struct Inside(bool); + +impl Inside { + pub(crate) fn enter() -> Self { + Self(INSIDE.with(|i| i.replace(true))) + } +} + +impl Drop for Inside { + fn drop(&mut self) { + INSIDE.with(|i| i.set(self.0)); + } +} + +/// The settings `g` an object writes: none while a generated art object's art is being written. +pub(crate) fn written(g: Option<&GeneratedArt>) -> Option<&GeneratedArt> { + g.filter(|_| !INSIDE.with(Cell::get)) +} + +/// The SHA-256 of `children` written as JSON, in lower-case hexadecimal: what a file holds as the +/// hash of a generated art object's art. Generated art objects among them are written as plain +/// art. +pub fn art_hash(children: &[Arc]) -> String { + use sha2::{Digest, Sha256}; + let bytes = { + let _inside = Inside::enter(); + serde_json::to_vec(children).unwrap_or_default() + }; + #[cfg(test)] + HASHED.with(|h| h.set(h.get() + bytes.len())); + Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The bytes `children` take written as JSON, generated art objects among them as plain art +/// ([`MAX_ART_BYTES`]). +pub fn art_bytes(children: &[Arc]) -> usize { + let _inside = Inside::enter(); + serde_json::to_vec(children).map_or(usize::MAX, |b| b.len()) +} + +/// Drops the settings of the generated art objects in `nodes`, among their descendants and in +/// their opacity masks' art, which become plain art; returns whether there were any. It doesn't +/// look among the children of such an object, which reading it already made plain art, only at +/// its opacity mask's art. +fn plain_art(nodes: &mut [Arc]) -> bool { + let mut found = false; + for a in nodes { + let generated = a.extras().generated.is_some(); + if !generated && a.children().is_none_or(Vec::is_empty) && a.extras().mask.is_none() { + continue; + } + let n = Arc::make_mut(a); + if generated { + n.extras_mut().generated = None; + found = true; + } else if let Some(ch) = n.children_mut() { + found |= plain_art(ch); + } + if n.extras().mask.is_some() + && let Some(m) = n.extras_mut().mask.as_mut() + { + found |= plain_art(std::slice::from_mut(&mut m.art)); + } + } + found +} + +/// How a file holds a generated art object's settings, borrowed from the node. +#[derive(Serialize)] +pub(crate) struct Wire<'a> { + plugin: &'a str, + name: &'a str, + params: &'a Map, + #[serde(skip_serializing_if = "is_identity")] + transform: &'a Affine, + #[serde(rename = "strokeScale", skip_serializing_if = "is_one")] + stroke_scale: f64, + #[serde(rename = "effectScale", skip_serializing_if = "is_one")] + effect_scale: f64, + #[serde(rename = "patternTransform", skip_serializing_if = "is_identity")] + pattern_transform: &'a Affine, + hash: String, + #[serde(skip_serializing_if = "std::ops::Not::not")] + damaged: bool, +} + +fn is_identity(a: &&Affine) -> bool { + **a == Affine::IDENTITY +} + +fn is_one(k: &f64) -> bool { + *k == 1.0 +} + +impl<'a> Wire<'a> { + /// The settings `g` of node `n`, with the hash of its art. + pub(crate) fn of(g: &'a GeneratedArt, n: &Node) -> Self { + let hash = art_hash(n.children().map_or(&[][..], Vec::as_slice)); + Wire { + plugin: &g.plugin, + name: &g.name, + params: &g.params, + transform: &g.transform, + stroke_scale: g.stroke_scale, + effect_scale: g.effect_scale, + pattern_transform: &g.pattern_transform, + hash, + damaged: g.state == State::Damaged, + } + } +} + +/// A saved transform `t` (absent: none): `None` when it is not six finite numbers. +fn read_affine(t: Option) -> Option { + match t { + None => Some(Affine::IDENTITY), + Some(t) => serde_json::from_value::(t).ok().filter(|a| a.as_coeffs().iter().all(|c| c.is_finite())), + } +} + +/// A saved scale `k` (absent: 1): `None` when it is not a finite number of 0 or more. A transform +/// that flattens the art to a line or a point scales its strokes and effects by 0. +fn read_scale(k: Option) -> Option { + match k { + None => Some(1.0), + Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0), + } +} + +/// The settings a file gives (`v`, its `generated` field) for a node of `kind`: `None` for anything +/// but a group, else what could be read, marked [`State::Damaged`] or [`State::Changed`] when a +/// field or the art's hash doesn't hold up. A field that can't be read is kept empty: an id is +/// kept only when it is a plug-in id, a name at most [`MAX_NAME`] characters long. Generated art +/// objects in the group's art become plain art ([`plain_art`]), and the art is then not hashed. +pub(crate) fn read(v: Value, kind: &mut NodeKind) -> Option> { + let NodeKind::Group { children, .. } = kind else { return None }; + let nested = plain_art(children); + let Value::Object(mut o) = v else { + return Some(Box::new(GeneratedArt { state: State::Damaged, ..GeneratedArt::new("", "", Map::new()) })); + }; + let mut damaged = !matches!(o.remove("damaged"), None | Some(Value::Bool(false))); + let plugin = match o.remove("plugin") { + Some(Value::String(id)) if valid_id(&id) => id, + _ => { + damaged = true; + String::new() + } + }; + let name: String = match o.remove("name") { + Some(Value::String(n)) => n.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(), + _ => String::new(), + }; + let params = match o.remove("params") { + Some(Value::Object(p)) if serde_json::to_vec(&p).is_ok_and(|b| b.len() <= MAX_PARAMS_BYTES) => p, + _ => { + damaged = true; + Map::new() + } + }; + let mut affine = |key: &str| { + read_affine(o.remove(key)).unwrap_or_else(|| { + damaged = true; + Affine::IDENTITY + }) + }; + let transform = affine("transform"); + let pattern_transform = affine("patternTransform"); + let mut scale = |key: &str| { + read_scale(o.remove(key)).unwrap_or_else(|| { + damaged = true; + 1.0 + }) + }; + let stroke_scale = scale("strokeScale"); + let effect_scale = scale("effectScale"); + let intact = !nested && matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children)); + let state = if damaged { + State::Damaged + } else if intact { + State::Intact + } else { + State::Changed + }; + Some(Box::new(GeneratedArt { plugin, name, params, transform, stroke_scale, effect_scale, pattern_transform, state })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::node::NodeId; + use serde_json::json; + use std::sync::Arc; + use vectorcraft_geom::{Rect, shapes}; + + fn art() -> Node { + let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default()); + let mut g = Node::group(NodeId(1), vec![Arc::new(square)]); + let mut params = Map::new(); + params.insert("size".into(), json!(10)); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params))); + g + } + + fn reread(v: &Value) -> Node { + serde_json::from_value(v.clone()).unwrap() + } + + /// `depth` generated art objects, each the only child of the one around it, the innermost + /// [`art`]. + fn nested(depth: usize) -> Node { + let mut n = art(); + for i in 1..depth { + let mut g = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new()))); + n = g; + } + n + } + + /// The bytes [`art_hash`] hashes while `f` runs. + fn hashed(f: impl FnOnce() -> T) -> (T, usize) { + HASHED.with(|h| h.set(0)); + let out = f(); + (out, HASHED.with(Cell::get)) + } + + /// The generated art objects in `n` and below it, outermost first, as (depth, state). + fn generated_in(n: &Node) -> Vec<(usize, State)> { + let mut out = vec![]; + let mut at = Some((n, 0)); + while let Some((n, d)) = at { + if let Some(g) = &n.extras().generated { + out.push((d, g.state)); + } + at = n.children().and_then(|c| c.first()).map(|c| (&**c, d + 1)); + } + out + } + + /// Generated art objects nested in one another are written with the outermost one's settings + /// alone, so writing and reading them hash each object's art once, however deep they nest; a + /// file that has settings on the inner ones anyway loses them, without hashing. + #[test] + fn nested_generated_art_is_written_and_read_with_its_art_hashed_once() { + crate::depth::with_deep_stack(|| { + for depth in [16, 200] { + let n = nested(depth); + let (bytes, writing) = hashed(|| serde_json::to_vec(&n).unwrap()); + assert!(writing <= bytes.len(), "{depth} deep: {writing} bytes hashed to write {}", bytes.len()); + assert_eq!(String::from_utf8_lossy(&bytes).matches("\"generated\"").count(), 1, "{depth} deep"); + let v = serde_json::to_value(&n).unwrap(); + let (back, reading) = hashed(|| reread(&v)); + assert!(reading <= bytes.len(), "{depth} deep: {reading} bytes hashed to read {}", bytes.len()); + assert_eq!(generated_in(&back), vec![(0, State::Intact)], "{depth} deep"); + // Settings on every level, each with a hash: none is hashed, the inner ones are + // dropped, and the outermost reads as changed. + let mut crafted = v.clone(); + let settings = v["generated"].clone(); + let mut at = crafted.pointer_mut("/kind/children/0"); + while let Some(c) = at { + if c.pointer("/kind/children/0").is_some() { + c["generated"] = settings.clone(); + } + at = c.pointer_mut("/kind/children/0"); + } + let (crafted_back, reading) = hashed(|| reread(&crafted)); + assert!(reading <= bytes.len(), "{depth} deep, crafted: {reading} bytes hashed to read {}", bytes.len()); + assert_eq!(generated_in(&crafted_back), vec![(0, State::Changed)], "{depth} deep, crafted"); + assert_eq!(crafted_back.children(), back.children(), "{depth} deep, crafted"); + } + }); + } + + /// A generated art object inside another one's art, whose opacity mask's art is a generated art + /// object too, reads as plain art with plain mask art. + #[test] + fn a_nested_generated_art_objects_mask_art_reads_as_plain_art() { + let mut inner = art(); + inner.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(art(), true))); + let mut outer = Node::group(NodeId(20), vec![Arc::new(inner)]); + outer.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new()))); + let v = serde_json::to_value(&outer).unwrap(); + assert!(v.pointer("/kind/children/0/generated").is_none() && v.pointer("/kind/children/0/mask/art/generated").is_none()); + let mut crafted = v.clone(); + let settings = v["generated"].clone(); + crafted["kind"]["children"][0]["generated"] = settings.clone(); + crafted["kind"]["children"][0]["mask"]["art"]["generated"] = settings; + let back = reread(&crafted); + assert_eq!(back.extras().generated.as_ref().map(|g| g.state), Some(State::Changed)); + let inner = &back.children().unwrap()[0]; + assert!(inner.extras().generated.is_none()); + assert!(inner.extras().mask.as_ref().is_some_and(|m| m.art.extras().generated.is_none())); + assert_eq!(back.children(), reread(&v).children()); + } + + /// A generated art object inside plain groups is still checked against its hash: intact as + /// written, changed when its art is tampered with. + #[test] + fn a_generated_art_object_deep_in_plain_groups_keeps_its_hash_check() { + crate::depth::with_deep_stack(|| { + let mut n = art(); + for i in 1..200 { + n = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]); + } + let v = serde_json::to_value(&n).unwrap(); + let state = |v: &Value| generated_in(&reread(v)).into_iter().map(|(_, s)| s).collect::>(); + assert_eq!(state(&v), vec![State::Intact]); + let mut tampered = v.clone(); + let mut at = tampered.pointer_mut("/kind/children/0"); + while let Some(c) = at { + if c.get("generated").is_some() { + c["kind"]["children"][0]["name"] = json!("tampered"); + break; + } + at = c.pointer_mut("/kind/children/0"); + } + assert_eq!(state(&tampered), vec![State::Changed]); + }); + } + + /// A generated art object writes its plug-in, name, parameters and the hash of its art, and + /// reads back the same, intact. + #[test] + fn a_generated_art_object_round_trips_with_the_hash_of_its_art() { + let g = art(); + let v = serde_json::to_value(&g).unwrap(); + let saved = &v["generated"]; + assert_eq!((&saved["plugin"], &saved["name"], &saved["params"]), (&json!("org.example.gen"), &json!("Squares"), &json!({"size": 10}))); + assert_eq!(saved["hash"], json!(art_hash(g.children().unwrap()))); + assert!(saved.get("transform").is_none()); + let back = reread(&v); + assert_eq!(back, g); + assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Intact)); + // A moved object keeps its transform. + let mut moved = g.clone(); + moved.transform(Affine::translate((5.0, 0.0)), false); + let back = reread(&serde_json::to_value(&moved).unwrap()); + assert_eq!(back.extras().generated.as_ref().map(|a| (a.transform, a.state)), Some((Affine::translate((5.0, 0.0)), State::Intact))); + // A scale with Scale Strokes & Effects and Transform Patterns keeps what it scaled. + let mut scaled = g.clone(); + let sc = Scaling { strokes: true, patterns: true, ..Scaling::default() }; + scaled.transform(Affine::scale(2.0), sc); + scaled.transform(Affine::scale(3.0), false); + let back = reread(&serde_json::to_value(&scaled).unwrap()); + let a = back.extras().generated.as_deref().unwrap(); + assert_eq!((a.stroke_scale, a.effect_scale, a.pattern_transform, a.state), (2.0, 1.0, Affine::scale(2.0), State::Intact)); + assert_eq!(a.transform, Affine::scale(6.0)); + // A transform that flattens it to a point, with Scale Strokes & Effects on, scales its + // strokes and effects by 0, and it reads back intact with those scales. + let mut flat = g.clone(); + flat.transform(Affine::new([0.0; 6]), Scaling { strokes: true, effects: Some(|_, _| {}), ..Scaling::default() }); + let back = reread(&serde_json::to_value(&flat).unwrap()); + let a = back.extras().generated.as_deref().unwrap(); + assert_eq!((a.stroke_scale, a.effect_scale, a.state), (0.0, 0.0, State::Intact)); + } + + /// Art that doesn't match the file's hash, and fields that can't be read, keep the art and say + /// how the object was read; a garbled id is never kept. + #[test] + fn damaged_fields_and_changed_art_keep_the_art() { + let g = art(); + let v = serde_json::to_value(&g).unwrap(); + let state = |v: &Value| reread(v).extras().generated.as_ref().map(|a| (a.plugin.clone(), a.state)); + // The art edited, with the hash of the art before. + let mut edited = g.clone(); + if let Some(c) = edited.children_mut().and_then(|c| c.first_mut()) { + Arc::make_mut(c).transform(Affine::translate((1.0, 0.0)), false); + } + let mut changed = serde_json::to_value(&edited).unwrap(); + changed["generated"]["hash"] = v["generated"]["hash"].clone(); + assert_eq!(state(&changed), Some(("org.example.gen".into(), State::Changed))); + let mut no_hash = v.clone(); + no_hash["generated"].as_object_mut().unwrap().remove("hash"); + assert_eq!(state(&no_hash), Some(("org.example.gen".into(), State::Changed))); + for (field, bad) in [ + ("plugin", json!("../evil")), + ("plugin", json!("x".repeat(65))), + ("plugin", json!("")), + ("plugin", json!("a\u{0}b")), + ("plugin", json!(7)), + ("params", json!([1, 2])), + ("params", json!({"blob": "x".repeat(MAX_PARAMS_BYTES)})), + ("transform", json!("sideways")), + ("transform", Value::Null), + ("strokeScale", json!(-2.0)), + ("strokeScale", Value::Null), + ("strokeScale", json!("big")), + ("effectScale", json!(-0.5)), + ("patternTransform", json!([1, 0, 0, 1, 0])), + ("patternTransform", Value::Null), + ("effectScale", Value::Null), + ("damaged", json!(true)), + ("damaged", json!("no")), + ] { + let mut w = v.clone(); + w["generated"][field] = bad; + let back = reread(&w); + let a = back.extras().generated.as_ref().unwrap(); + assert_eq!(a.state, State::Damaged, "{field}"); + assert!(a.plugin.is_empty() || a.plugin == "org.example.gen", "{field}: {}", a.plugin); + assert_eq!(back.children(), g.children(), "{field}"); + // Saved again and read back, it stays damaged. + let again = reread(&serde_json::to_value(&back).unwrap()); + assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged), "{field} saved again"); + } + // Not an object at all. + let mut w = v.clone(); + w["generated"] = json!("art"); + assert_eq!(state(&w), Some((String::new(), State::Damaged))); + // A null field is read as a field that can't be read, not as an absent one, from a value + // and from a file's text; the art stays, and saved again the object stays damaged. + let mut w = v.clone(); + w["generated"] = Value::Null; + assert_eq!(state(&w), Some((String::new(), State::Damaged))); + let back: Node = serde_json::from_str(&w.to_string()).unwrap(); + assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged)); + assert_eq!(back.children(), g.children()); + let again = reread(&serde_json::to_value(&back).unwrap()); + assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged)); + // On a path the field is dropped, and the path stays as it was. + let path = g.children().unwrap()[0].clone(); + let mut p = serde_json::to_value(&*path).unwrap(); + p["generated"] = v["generated"].clone(); + let back = reread(&p); + assert!(back.extras().generated.is_none()); + assert_eq!(back, *path); + // A name is cut to its limit and loses control characters. + let mut w = v.clone(); + w["generated"]["name"] = json!(format!("A\u{202e}\n{}", "n".repeat(100))); + let back = reread(&w); + let name = &back.extras().generated.as_ref().unwrap().name; + assert_eq!(name.chars().count(), MAX_NAME); + assert!(!name.chars().any(char::is_control)); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index dfe6e22e73..de8bfc2875 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -18,6 +18,7 @@ pub mod decode; pub mod depth; pub mod dimension; pub mod flare; +pub mod generated; pub mod graph; mod halftone_radii; pub mod hit; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a1bfaefe7d..685d4dcec5 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -286,6 +286,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u .map_or(0, |m| ALLOC + size_of::() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::() + json_bytes(&f.params)); + b += e + .generated + .as_ref() + .map_or(0, |g| ALLOC + size_of::() + g.plugin.capacity() + g.name.capacity() + map_bytes(&g.params)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); if e.intertwine_tiers.capacity() > 0 { b += ALLOC + e.intertwine_tiers.capacity() * size_of::() + e.intertwine_tiers.iter().map(path_bytes).sum::(); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 0eed9c7829..9dbb409706 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -96,6 +96,9 @@ pub struct NodeExtras { /// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they /// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]). pub image_quad: Option>, + /// Generated art object: the generator plug-in and parameters its group's children were drawn + /// with (`plugin.generate`); its ordinary group children hold its art ([`crate::generated`]). + pub generated: Option>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -129,6 +132,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { warp_piece: false, clip_pieces: false, image_quad: None, + generated: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index ebb462ba35..39b39fc294 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -611,19 +611,23 @@ impl Node { self.children()?.iter().find(|c| c.id == r.path)?.path_data() } - fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { - // A dimension's measurement moves with it. - if let Some(e) = self.extras_if_any() - && let Some(dimension) = &mut e.dimension - { + /// Moves what `a` moves in the node's extras: a dimension's measurement, a flare's center and + /// end point, and the place a generator's art is drawn again at, with what `sc` scales. + fn transform_extras(&mut self, a: Affine, sc: &Scaling) { + let Some(e) = self.extras_if_any() else { return }; + if let Some(dimension) = &mut e.dimension { dimension.transform(a); } - // So does a flare's center and end point. - if let Some(e) = self.extras_if_any() - && let Some(flare) = &mut e.flare - { + if let Some(flare) = &mut e.flare { flare.transform(a); } + if let Some(generated) = &mut e.generated { + generated.transform(a, sc); + } + } + + fn transform_scaled(&mut self, a: Affine, sc: &Scaling) { + self.transform_extras(a, sc); // The path the objects are attached to, before it is transformed. let on_path_before = self.on_path_data().cloned(); // A distorted image's placement nearest its corners, before they are transformed (`None` diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index d9642e7866..d543c9d9e1 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -18,6 +18,7 @@ impl Serialize for Node { use crate::skip::{is_default, is_one, is_true}; use serde::ser::SerializeStruct; let e = self.extras(); + let generated = crate::generated::written(e.generated.as_deref()); // As the derive did: the fields written, then each field written or skipped in order. let skips = [ false, @@ -61,6 +62,7 @@ impl Serialize for Node { is_default(&e.warp_piece), is_default(&e.clip_pieces), e.image_quad.is_none(), + generated.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -87,6 +89,8 @@ impl Serialize for Node { field!("type_outlines", &e.type_outlines); field!("pixelated", &e.pixelated); field!("shaper", &e.shaper); + // A generated art object's art, written while this lives, holds plain art only. + let _inside = generated.map(|_| crate::generated::Inside::enter()); field!("kind", &self.kind); field!("graphic_style", &e.graphic_style); field!("attrs", &e.attrs); @@ -110,6 +114,7 @@ impl Serialize for Node { field!("warp_piece", &e.warp_piece); field!("clip_pieces", &e.clip_pieces); field!("image_quad", &e.image_quad); + field!("generated", &generated.map(|g| crate::generated::Wire::of(g, self))); st.end() } } @@ -265,6 +270,14 @@ pub(super) struct NodeWire { clip_pieces: bool, #[serde(default, deserialize_with = "image_corners")] image_quad: Option>, + /// Read as it is and checked against the node's kind and art ([`crate::generated`]). + #[serde(default, deserialize_with = "present_value")] + generated: Option, +} + +/// A field's value as a file holds it, a null included: only an absent field is none. +fn present_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + serde_json::Value::deserialize(d).map(Some) } /// A distorted image's corners as a file holds them: a list of exactly four points, else none (the @@ -455,7 +468,7 @@ fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result for Node { - fn from(w: NodeWire) -> Self { + fn from(mut w: NodeWire) -> Self { // Corners an image cannot take are dropped, so a later transform cannot make them its own. let image_quad = match &w.kind { NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()), @@ -491,6 +504,7 @@ impl From for Node { warp_piece: w.warp_piece, clip_pieces: w.clip_pieces, image_quad, + generated: w.generated.and_then(|g| crate::generated::read(g, &mut w.kind)), }; Node { id: w.id, diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index b2c00d8ab3..f4c0bfb614 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -425,9 +425,13 @@ pub fn uses_pattern(n: &Node, name: Option<&str>) -> bool { } /// Transform Patterns without Transform Objects: `m` moves the pattern tiles of `n` and of -/// everything inside it, and the art stays where it is. +/// everything inside it, and the art stays where it is. A generated art object keeps the move, so +/// its art drawn again has its tiles moved too. pub fn transform_patterns_only(n: &mut Node, m: Affine) { transform_pattern_paints(n, m); + if let Some(g) = n.extras_if_any().and_then(|e| e.generated.as_deref_mut()) { + g.pattern_transform = m * g.pattern_transform; + } for c in n.children_mut().into_iter().flatten() { transform_patterns_only(Arc::make_mut(c), m); } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a3897a293c..054395d796 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -77,6 +77,7 @@ pub mod perspgrid; pub mod place; pub mod plugin; pub(crate) mod plugin_call; +pub mod plugin_generated; mod preflight; pub mod prefscmds; pub mod print; @@ -405,6 +406,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(printpresets::specs()); v.extend(printtiling::specs()); v.extend(plugin::specs()); + v.extend(plugin_generated::specs()); v.extend(scripts::specs()); v.extend(cut::specs()); v.extend(halftone::specs()); diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index d63489fb2e..b5ab256440 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -182,7 +182,7 @@ impl Expandable { n.walk(&mut |c| { let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); e.text |= matches!(c.kind, NodeKind::Text(_)); - e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some(); + e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some() || c.extras().generated.is_some(); e.effects |= !c.appearance.effects.is_empty(); e.envelope |= matches!(c.kind, NodeKind::Envelope { .. }); e.blends |= matches!(c.kind, NodeKind::Blend { .. }); @@ -503,7 +503,8 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec) -> Result<() Ok(()) } -/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts. +/// Makes the live shapes in `n` plain paths, and the flares and generated art objects plain groups +/// of their parts. fn drop_live(n: &mut Node) { if let NodeKind::Path { live, .. } = &mut n.kind { *live = None; @@ -511,6 +512,9 @@ fn drop_live(n: &mut Node) { if n.extras().flare.is_some() { n.extras_mut().flare = None; } + if n.extras().generated.is_some() { + n.extras_mut().generated = None; + } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { drop_live(Arc::make_mut(c)); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 3c1a8f1d3c..409354719b 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -655,6 +655,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result doc.title = title; } warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes))); + // Generated art that can't be drawn again keeps its art; opening runs no plug-in. + warnings.extend(crate::cmd::plugin_generated::open_notes(&doc)); Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data, native_pdf_compatible }) } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 1c67f8b656..db6b35a63e 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -111,7 +111,7 @@ pub fn describe(p: &Plugin) -> Value { v["place"] = json!(true); } } - Kind::Filter => {} + Kind::Filter | Kind::Generator => {} } if m.budget == Budget::Heavy { v["budget"] = json!("heavy"); @@ -274,6 +274,9 @@ impl FilterRun { format!("`{}` is an importer: open a file with document.open {{\"importer\": \"{}\"}}", m.id, export::format_id(&m.id)), )); } + Kind::Generator => { + return Err(bad(C, format!("`{}` is a generator: draw its art with plugin.generate {{\"id\": \"{}\"}}", m.id, m.id))); + } } Self::prepare_with(s, plugin, None, C, p) } @@ -2402,7 +2405,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), 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)} (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/cmd/plugin_generated.rs b/crates/engine/src/cmd/plugin_generated.rs new file mode 100644 index 0000000000..83ef85decc --- /dev/null +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -0,0 +1,275 @@ +//! Generated art objects: art a generator plug-in draws from its parameters alone +//! ([`vectorcraft_plugins::generate`]), kept in a group with the parameters it was drawn with +//! ([`vectorcraft_doc::generated`]). +//! +//! `plugin.generate` runs a generator and adds its art as a new generated art object, one undo +//! step. `plugin.editGenerated` runs the object's generator again with changed parameters and +//! replaces the art, one undo step (none when nothing changes), placed as the object has been +//! moved, scaled, rotated, reflected or sheared since it was drawn. Object › Expand makes it an +//! ordinary group of its art. `plugin.generatedInfo` describes one. +//! +//! The plug-in runs only when one of these commands asks it to, with its own permissions and budget: +//! opening, placing, pasting, drawing and exporting a document never run it. A generated art object +//! whose plug-in isn't installed, whose saved fields are damaged, or whose art doesn't match the hash +//! its file gave keeps its art as it is, and opening the file says so ([`open_notes`]). + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::generated::{GeneratedArt, MAX_ART_BYTES, State, art_bytes}; +use vectorcraft_doc::{Document, Node, NodeId}; +use vectorcraft_plugins::objects::{self, OutObject}; +use vectorcraft_plugins::permissions::{self, display_text}; +use vectorcraft_plugins::{Plugin, generate, registry}; + +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_doc, str_param}; + +const GENERATE: &str = "plugin.generate"; +const EDIT: &str = "plugin.editGenerated"; +const INFO: &str = "plugin.generatedInfo"; + +/// The undo step of `plugin.editGenerated`. +pub const EDIT_LABEL: &str = "Edit Generated Art"; + +/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing. +fn err(e: vectorcraft_plugins::Error) -> EngineError { + match e { + vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled, + e => EngineError::Other(e.to_string()), + } +} + +/// The error of a plug-in's bad parameters for command `c`, others as [`err`] gives them. +fn params_err(c: &str) -> impl Fn(vectorcraft_plugins::Error) -> EngineError + '_ { + move |e| match e { + vectorcraft_plugins::Error::Params(why) => bad(c, why), + e => err(e), + } +} + +/// The limits a generator runs under: its own, with the Plug-in Instruction Budget in force. +fn limits(s: &Session, plugin: &Plugin) -> vectorcraft_plugins::Limits { + match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + } +} + +/// The plug-in of generated art `g` as a message shows it: its name (its id when it has none) and +/// its id, each as a prompt shows a manifest string. +fn shown(g: &GeneratedArt) -> (String, String) { + let id = display_text(&g.plugin, permissions::MAX_SHOWN_FIELD); + let name = if g.name.trim().is_empty() { id.clone() } else { display_text(g.name.trim(), permissions::MAX_SHOWN_NAME) }; + (name, id) +} + +/// Generated art whose plug-in, by its saved id, isn't installed. +fn not_installed(g: &GeneratedArt) -> String { + let (name, id) = shown(g); + format!("“{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is") +} + +/// Generated art whose saved fields can't be read. +const DAMAGED: &str = "a generated art object's plug-in id or parameters are damaged, so its art can't be drawn again: the art stays as it is"; + +/// Generated art that doesn't match the hash its file gave. +fn changed(g: &GeneratedArt) -> String { + let (name, id) = shown(g); + format!("the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is") +} + +/// What opening `doc` says about its generated art objects, each note once: those whose plug-in +/// isn't installed or is installed as a plug-in of another kind, those whose saved fields are +/// damaged, and those whose art doesn't match its file's hash. Opening runs no plug-in. +pub fn open_notes(doc: &Document) -> Vec { + let mut notes: Vec = vec![]; + let mut visit = |n: &Node| { + let Some(g) = n.extras().generated.as_deref() else { return }; + let note = match g.state { + State::Damaged => DAMAGED.to_string(), + state => match generate::named(&g.plugin) { + Err(vectorcraft_plugins::Error::NotFound(_)) => not_installed(g), + Err(e) => e.to_string(), + Ok(_) if state == State::Changed => changed(g), + Ok(_) => return, + }, + }; + if !notes.contains(¬e) { + notes.push(note); + } + }; + for layer in &doc.layers { + vectorcraft_doc::swatches::walk_with_masks(layer, &mut visit); + } + for symbol in &doc.symbols { + vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut visit); + } + for pattern in &doc.patterns { + for art in &pattern.art { + vectorcraft_doc::swatches::walk_with_masks(art, &mut visit); + } + } + for design in &doc.graph_designs { + vectorcraft_doc::swatches::walk_with_masks(&design.art, &mut visit); + } + notes +} + +/// Draws the art `out` in generated art object `gid`, in place of the art it holds, placed as +/// `settings` says its art has been transformed ([`GeneratedArt::place`]). The objects go through a +/// filter's checks; art past [`MAX_ART_BYTES`] is refused. +fn draw(d: &mut Document, gid: NodeId, out: Vec, settings: &GeneratedArt) -> Result<()> { + if let Some(ch) = d.node_mut(gid).and_then(Node::children_mut) { + ch.clear(); + } + let admit = |fx: &[vectorcraft_doc::Effect], n: &Node| super::plugin::admit_effects_for(GENERATE, fx, n); + let ids = objects::apply_output(d, &[], out, Some(gid), &admit).map_err(err)?; + let g = d.node_mut(gid).ok_or(EngineError::NoNode(gid))?; + if let Some(ch) = g.children_mut() { + for c in ch.iter_mut() { + settings.place(Arc::make_mut(c), vectorcraft_render::effects::scale_effect); + } + } + if art_bytes(g.children().map_or(&[][..], Vec::as_slice)) > MAX_ART_BYTES { + return Err(err(vectorcraft_plugins::Error::Output(format!( + "the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps" + )))); + } + if !super::super::sanity::objects_in_range(d, &ids) { + return Err(EngineError::Other("result would exceed the canvas (coordinates out of range)".into())); + } + Ok(()) +} + +/// `plugin.generate {id, params?}`: runs generator `id` with its parameters (checked first: missing +/// ones take their defaults) and adds its art as a new generated art object in the current layer, +/// selected, as one undo step named after the plug-in → `{id, plugin}`. +fn generate_art(s: &mut Session, p: &Value) -> Result { + let id = str_param(p, "id").ok_or_else(|| bad(GENERATE, "missing `id` (see plugin.list)"))?; + let plugin = generate::named(id).map_err(params_err(GENERATE))?; + let given = p.get("params").cloned().unwrap_or(Value::Null); + let params = generate::resolve(&plugin, &given).map_err(params_err(GENERATE))?; + let parent = s.doc()?.target_parent()?; + let out = generate::run(&plugin, ¶ms, &limits(s, &plugin)).map_err(err)?; + let m = plugin.manifest(); + let label = m.name.trim_end_matches('…').to_string(); + let gid = s.edit(&label, |d, sel| { + let gid = d.alloc_id(); + let mut g = Node::group(gid, vec![]); + g.name = Some(m.name.trim_end_matches('…').to_string()); + let settings = GeneratedArt::new(&m.id, &m.name, params); + g.extras_mut().generated = Some(Box::new(settings.clone())); + d.insert(parent, usize::MAX, g)?; + draw(d, gid, out, &settings)?; + sel.set([gid]); + Ok(gid) + })?; + Ok(json!({"id": gid.0, "plugin": m.id})) +} + +/// The generated art object `p` names (`id`), else the one selected → its id and settings. A +/// locked or hidden one, and a selection that holds none or more than one, are errors. +fn target(s: &Session, c: &str, p: &Value) -> Result<(NodeId, GeneratedArt)> { + let st = s.doc()?; + let one = |id: NodeId| st.doc.node(id).and_then(|n| n.extras().generated.as_deref().cloned()).map(|g| (id, g)); + let found = match super::given_objects(s, p, c)? { + Some(ids) if ids.len() == 1 => one(ids[0]), + Some(_) => None, + None => match st.selection.objects.as_slice() { + [id] => one(*id), + _ => None, + }, + }; + let select = || bad(c, "select one generated art object"); + let (id, g) = found.ok_or_else(select)?; + if !st.doc.is_editable(id) { + return Err(select()); + } + Ok((id, g)) +} + +/// The installed generator of generated art `g`, which must be able to draw it again. +fn generator_of(c: &str, g: &GeneratedArt) -> Result> { + if g.state == State::Damaged { + return Err(bad(c, DAMAGED)); + } + match registry::get(&g.plugin) { + None => Err(bad(c, not_installed(g))), + Some(_) => generate::named(&g.plugin).map_err(params_err(c)), + } +} + +/// `plugin.editGenerated {id?, params}`: runs the generator of generated art object `id` (else the +/// selected one) again with its saved parameters changed by `params` (checked against the plug-in's +/// manifest; saved ones it no longer declares are left out) and replaces its art, placed as the +/// object has been transformed since it was drawn, as one undo step. Parameters that change nothing +/// run nothing and make no undo step → `{id, plugin, changed}`. +fn edit_generated(s: &mut Session, p: &Value) -> Result { + let (id, g) = target(s, EDIT, p)?; + let plugin = generator_of(EDIT, &g)?; + let m = plugin.manifest(); + let given = match p.get("params") { + None | Some(Value::Null) => Value::Object(Map::new()), + Some(v @ Value::Object(_)) => v.clone(), + Some(_) => return Err(bad(EDIT, "`params` must be an object")), + }; + let params = generate::resolve_over(&plugin, &g.params, &given).map_err(params_err(EDIT))?; + if params == g.params { + return Ok(json!({"id": id.0, "plugin": g.plugin, "changed": false})); + } + let out = generate::run(&plugin, ¶ms, &limits(s, &plugin)).map_err(err)?; + let settings = GeneratedArt { params, state: State::Intact, name: m.name.chars().take(vectorcraft_doc::generated::MAX_NAME).collect(), ..g }; + s.edit(EDIT_LABEL, |d, _| { + draw(d, id, out, &settings)?; + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + n.extras_mut().generated = Some(Box::new(settings)); + Ok(()) + })?; + Ok(json!({"id": id.0, "plugin": m.id, "changed": true})) +} + +/// `plugin.generatedInfo {id?}`: generated art object `id` (else the selected one) → `{id, plugin, +/// name, params, state, installed}`. +fn info(s: &mut Session, p: &Value) -> Result { + let (id, g) = target(s, INFO, p)?; + let state = match g.state { + State::Intact => "intact", + State::Damaged => "damaged", + State::Changed => "changed", + }; + let installed = g.state != State::Damaged && generate::named(&g.plugin).is_ok(); + Ok(json!({"id": id.0, "plugin": g.plugin, "name": g.name, "params": g.params, "state": state, "installed": installed})) +} + +/// This module's commands: `plugin.generate`, `plugin.editGenerated` and `plugin.generatedInfo`. +pub fn specs() -> Vec { + vec![ + cmd!( + "plugin.generate", + "Generate Art", + [], + None, + "{id: a generator plug-in (plugin.list kind \"generator\"), params?: {…} (its parameters; missing ones take their defaults, see plugin.info; a bad one is an error)} run the generator and add its art to the current layer as a new generated art object (a group that keeps the plug-in's id and name and the parameters, at most 64 KiB of JSON), selected, as one undo step named after the plug-in; its objects go through a filter's checks and the art may take at most 16 MiB of JSON. Edit it with plugin.editGenerated; Object › Expand makes it an ordinary group → {id, plugin}", + has_doc, + generate_art + ), + cmd!( + "plugin.editGenerated", + "Edit Generated Art", + [], + None, + "{id?: a generated art object (default: the one selected), params: {…} (the parameters to change; the others keep their saved values)} run the object's generator again and replace its art, placed as the object has been moved, scaled, rotated, reflected or sheared since it was drawn, as one undo step; parameters that change nothing run nothing and make no undo step. An object whose plug-in isn't installed, or whose saved plug-in id, parameters, transforms or scales are damaged, is an error, and its art stays as it is (Object › Expand keeps it as ordinary art) → {id, plugin, changed}", + has_doc, + edit_generated + ), + cmd!( + query "plugin.generatedInfo", + "Generated Art Info", + [], + None, + "{id?: a generated art object (default: the one selected)} → {id, plugin (its generator's id), name (the generator's name when it drew the art), params, state: \"intact\" | \"damaged\" (its saved plug-in id, parameters, transforms or scales can't be read: it can't be drawn again) | \"changed\" (its art doesn't match the hash its file gave), installed (its generator is installed)}", + has_doc, + info + ), + ] +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 7a1f808509..749dc57646 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3058,6 +3058,95 @@ proptest! { } } +// ---------- generated art objects' saved fields ---------- + +/// A native document holding one generated art object (a square drawn by plug-in +/// `org.example.gen`), as pretty JSON text. +fn generated_sample() -> Value { + use std::sync::Arc; + use vectorcraft_doc::generated::GeneratedArt; + use vectorcraft_doc::{Node, NodeId}; + let mut d = Document::new(200.0, 200.0); + let layer = d.layers.first().map(|l| l.id); + let square = + Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(10.0, 10.0, 60.0, 60.0)), Default::default()); + let mut g = Node::group(NodeId(0), vec![Arc::new(square)]); + g.id = d.alloc_id(); + let mut params = serde_json::Map::new(); + params.insert("size".into(), json!(50)); + g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params))); + d.insert(layer, usize::MAX, g).unwrap(); + serde_json::from_slice(&vectorcraft_format::save(&d, true)).unwrap() +} + +/// The object of `v` (a native file's JSON) that holds a `generated` field. +fn generated_node(v: &mut Value) -> Option<&mut Value> { + match v { + Value::Object(o) if o.contains_key("generated") => Some(v), + Value::Object(o) => o.values_mut().find_map(generated_node), + Value::Array(a) => a.iter_mut().find_map(generated_node), + _ => None, + } +} + +/// Any JSON a damaged or hand-made file may hold in a saved field: strings (empty, long, with NUL, +/// control, bidi and path characters), numbers, booleans, null, lists and objects. +fn arb_saved_value() -> impl Strategy { + let leaf = prop_oneof![ + Just(Value::Null), + any::().prop_map(Value::from), + any::().prop_map(Value::from), + any::().prop_map(|f| serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number)), + ".{0,80}".prop_map(Value::from), + prop::sample::select(vec!["org.example.gen", "org.example.gen ", "../x", "a\u{0}b", "\u{202e}gen", "", "x.y-z_1"]).prop_map(Value::from), + (0usize..200_000).prop_map(|n| Value::from("p".repeat(n))), + ]; + leaf.prop_recursive(3, 24, 6, |inner| { + prop_oneof![ + prop::collection::vec(inner.clone(), 0..6).prop_map(Value::from), + prop::collection::btree_map("[a-z_]{0,8}", inner, 0..6).prop_map(|m| Value::Object(m.into_iter().collect())), + ] + }) +} + +proptest! { + #![proptest_config(config())] + + /// A generated art object's saved plug-in id, name, parameters, transforms, scales and hash + /// replaced by anything, and the whole field too: the file opens without running a plug-in and + /// keeps the art, or is refused; an id is kept only when it is a plug-in id. It then renders, + /// exports and saves. + #[test] + fn generated_art_saved_fields_never_panic_and_keep_the_art(field in 0usize..9, value in arb_saved_value()) { + let mut v = generated_sample(); + let node = generated_node(&mut v).unwrap(); + let art = node["kind"].clone(); + let id = vectorcraft_doc::NodeId(node["id"].as_u64().unwrap()); + match ["plugin", "name", "params", "transform", "strokeScale", "effectScale", "patternTransform", "hash"].get(field) { + Some(key) => node["generated"][*key] = value, + None => node["generated"] = value, + } + let bytes = serde_json::to_vec(&v).unwrap(); + let loaded = vectorcraft_engine::cmd::fileio::load("x.vectorcraft", &bytes); + if let Ok(l) = &loaded { + // The group keeps its art whatever was read of its generated art fields. + let group = l.doc.node(id); + prop_assert!(group.is_some(), "the group is gone"); + prop_assert_eq!(group.map(|n| serde_json::to_value(&n.kind).unwrap()), Some(art)); + let mut plugins = vec![]; + l.doc.walk(|n| { + if let Some(g) = n.extras().generated.as_deref() { + plugins.push(g.plugin.clone()); + } + }); + for plugin in &plugins { + prop_assert!(plugin.is_empty() || vectorcraft_doc::generated::valid_id(plugin), "{plugin:?}"); + } + } + survive("generated art fields", || loaded.ok().map(|l| l.doc))?; + } +} + /// A native file whose area type has 2^60 rows, 2^60 columns, or 2^32 of each (their product /// overflows) opens with 100 in place of each count over 100, and renders and exports. #[test] diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs new file mode 100644 index 0000000000..4e936f0d88 --- /dev/null +++ b/crates/engine/tests/plugin_generate.rs @@ -0,0 +1,369 @@ +//! Generator plug-ins (`"kind": "generator"`, docs/plugins.md › Generators) through the engine: the +//! generated art objects `plugin.generate` makes, `plugin.editGenerated` drawing them again, Expand, +//! and what a saved file keeps and says when the plug-in is missing, its fields are damaged or its +//! art no longer matches. Opening a file never runs a plug-in. +//! +//! A test binary of its own: installed plug-ins are process-wide. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::Node; +use vectorcraft_doc::generated::State; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// A generator's art: a 10 pt square at (0, 0). +const SMALL: &str = r#"{"objects":[{"type":"path","name":"Small","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[10,0]},{"p":[10,10]},{"p":[0,10]}]}]}}]}"#; + +/// A generator's art: a 20 pt square at (0, 0) and a line. +const BIG: &str = r#"{"objects":[{"type":"path","name":"Big","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[20,0]},{"p":[20,20]},{"p":[0,20]}]}]}},{"type":"path","name":"Line","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,30]},{"p":[20,30]}]}]}}]}"#; + +/// The parameters of the test generators. +const PARAMS: &str = r#"{"size":{"type":"int","min":1,"max":100,"default":10},"label":{"type":"string","default":"a"}}"#; + +/// Installs the plug-in written in WAT `src` (`replace`: in place of the one with its id). +fn install(s: &mut Session, src: &str, replace: bool) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": replace})).unwrap() +} + +/// A generator `id` that draws [`BIG`] when its `size` is 20 and [`SMALL`] otherwise. +fn sizes(s: &mut Session, id: &str) { + install(s, &tpl::when_given_else(&tpl::generator(id, PARAMS), Given::Params, r#""size":20"#, BIG, SMALL), false); +} + +/// A new document with generated art from generator `id` → the object's id. +fn generated(s: &mut Session, id: &str) -> u64 { + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let r = s.execute("plugin.generate", &json!({"id": id})).unwrap(); + assert_eq!(r["plugin"], json!(id)); + r["id"].as_u64().unwrap() +} + +/// The node `id` of the active document. +fn node(s: &Session, id: u64) -> Node { + s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap() +} + +/// The names of `id`'s children. +fn art(s: &Session, id: u64) -> Vec { + node(s, id).children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect() +} + +/// The undo steps of the active document. +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The active document saved as native text and opened again → the open's warnings. +fn reopen(s: &mut Session) -> Vec { + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + reopen_bytes(s, &bytes) +} + +fn reopen_bytes(s: &mut Session, bytes: &[u8]) -> Vec { + let r = s.execute("document.open", &json!({"name": "Gen.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap(); + r["warnings"].as_array().map(|w| w.iter().map(|w| w.as_str().unwrap_or_default().to_string()).collect()).unwrap_or_default() +} + +/// The only generated art object of the active document → its id. +fn the_generated(s: &Session) -> u64 { + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if n.extras().generated.is_some() { + ids.push(n.id.0); + } + }); + assert_eq!(ids.len(), 1, "{ids:?}"); + ids[0] +} + +#[test] +fn a_generator_draws_a_generated_art_object_as_one_undo_step() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.create"); + let entry = s.execute("plugin.info", &json!({"id": "test.gen.create"})).unwrap(); + assert_eq!((&entry["kind"], &entry["permissions"]), (&json!("generator"), &json!(["doc.write"]))); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let before = steps(&s); + let id = s.execute("plugin.generate", &json!({"id": "test.gen.create"})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(steps(&s), before + 1); + assert_eq!(art(&s, id), ["Small"]); + let n = node(&s, id); + let g = n.extras().generated.as_deref().unwrap(); + assert_eq!((g.plugin.as_str(), g.name.as_str(), g.state), ("test.gen.create", "Test test.gen.create", State::Intact)); + assert_eq!(serde_json::to_value(&g.params).unwrap(), json!({"size": 10, "label": "a"})); + assert_eq!(s.doc().unwrap().selection.objects, [vectorcraft_doc::NodeId(id)]); + // Given parameters are checked: a bad one is an error and nothing is added. + for bad in [json!({"size": 500}), json!({"size": "big"}), json!({"color": 1})] { + assert!(s.execute("plugin.generate", &json!({"id": "test.gen.create", "params": bad})).is_err(), "{bad}"); + } + assert_eq!(steps(&s), before + 1); + // Another kind of plug-in is not a generator, and plugin.run doesn't run a generator. + install(&mut s, &tpl::module(&tpl::manifest("test.gen.filter", "filter", "{}"), tpl::ECHO, "", 1), false); + let e = s.execute("plugin.generate", &json!({"id": "test.gen.filter"})).unwrap_err().to_string(); + assert!(e.contains("not a generator"), "{e}"); + let e = s.execute("plugin.run", &json!({"id": "test.gen.create"})).unwrap_err().to_string(); + assert!(e.contains("plugin.generate"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).is_none()); +} + +#[test] +fn editing_the_parameters_draws_the_art_again_as_one_undo_step() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.edit"); + let id = generated(&mut s, "test.gen.edit"); + // Moved since it was drawn: the new art is drawn where the object is. + s.execute("object.move", &json!({"dx": 100, "dy": 50})).unwrap(); + let before = steps(&s); + let r = s.execute("plugin.editGenerated", &json!({"params": {"size": 20}})).unwrap(); + assert_eq!((&r["id"], &r["changed"]), (&json!(id), &json!(true))); + assert_eq!(steps(&s), before + 1); + assert_eq!(art(&s, id), ["Big", "Line"]); + let b = s.doc().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (100.0, 50.0, 120.0, 80.0)); + let n = node(&s, id); + let g = n.extras().generated.as_deref().unwrap(); + assert_eq!(serde_json::to_value(&g.params).unwrap(), json!({"size": 20, "label": "a"})); + // The same parameters again change nothing and make no undo step. + let r = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(steps(&s), before + 1); + // A bad parameter is an error, and the art stays. + for bad in [json!({"size": 0}), json!({"size": true}), json!({"other": 1})] { + assert!(s.execute("plugin.editGenerated", &json!({"id": id, "params": bad})).is_err(), "{bad}"); + } + assert!(s.execute("plugin.editGenerated", &json!({"id": id, "params": [1]})).is_err()); + assert_eq!((steps(&s), art(&s, id)), (before + 1, vec!["Big".to_string(), "Line".to_string()])); + // One undo step brings back the art and the parameters it had. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(art(&s, id), ["Small"]); + let n = node(&s, id); + assert_eq!(serde_json::to_value(&n.extras().generated.as_deref().unwrap().params).unwrap(), json!({"size": 10, "label": "a"})); + // Nothing selected that is generated art. + s.execute("select.none", &json!({})).unwrap(); + let e = s.execute("plugin.editGenerated", &json!({"params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{e}"); + // The generated art object selected with another object: neither command picks it out. + let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 10, "height": 10})).unwrap(); + s.execute("select.set", &json!({"ids": [id, square["id"]]})).unwrap(); + for (c, p) in [("plugin.editGenerated", json!({"params": {"size": 20}})), ("plugin.generatedInfo", json!({}))] { + let e = s.execute(c, &p).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{c}: {e}"); + } + assert_eq!(art(&s, id), ["Small"]); +} + +/// A generator's art: a line with a 2 pt stroke. +const STROKED: &str = r#"{"objects":[{"type":"path","name":"Stroked","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[10,0]}]}]},"strokes":[{"paint":{"type":"solid","color":{"model":"rgb","r":0,"g":0,"b":0}},"width":2}]}]}"#; + +/// The stroke weights of the art of generated art object `id`. +fn stroke_widths(s: &Session, id: u64) -> Vec { + let n = node(s, id); + let mut widths = vec![]; + for c in n.children().unwrap() { + for it in &c.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(st) = it { + widths.push(st.width); + } + } + } + widths +} + +#[test] +fn drawing_again_keeps_the_stroke_weights_a_scale_gave_the_art() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::generator("test.gen.strokes", PARAMS), STROKED), false); + let id = generated(&mut s, "test.gen.strokes"); + assert_eq!(stroke_widths(&s, id), [2.0]); + // Scaled to 200% with Scale Strokes & Effects: the stroke doubles, and stays doubled when the + // art is drawn again. + s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + s.execute("plugin.editGenerated", &json!({"params": {"label": "b"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + // Scaled to 50% without it: the stroke keeps its weight, drawn again too. + s.execute("object.scale", &json!({"sx": 50, "strokes": false})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + s.execute("plugin.editGenerated", &json!({"params": {"label": "c"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); + // A saved file keeps what the strokes were scaled by. + reopen(&mut s); + let id = the_generated(&s); + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"label": "d"}})).unwrap(); + assert_eq!(stroke_widths(&s, id), [4.0]); +} + +#[test] +fn a_plug_in_of_another_kind_in_place_of_the_generator_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.kind"); + generated(&mut s, "test.gen.kind"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + install(&mut s, &tpl::module(&tpl::manifest("test.gen.kind", "filter", "{}"), tpl::ECHO, "", 1), true); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("`test.gen.kind` is a plug-in of kind `filter`, not a generator"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"]); + assert_eq!(s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()["installed"], json!(false)); +} + +#[test] +fn expand_makes_generated_art_an_ordinary_group() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.expand"); + let id = generated(&mut s, "test.gen.expand"); + s.execute("object.expand", &json!({"object": true})).unwrap(); + let n = node(&s, id); + assert!(n.extras().generated.is_none()); + assert_eq!(art(&s, id), ["Small"]); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("select one generated art object"), "{e}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, id).extras().generated.is_some()); +} + +#[test] +fn a_saved_file_keeps_the_parameters_and_the_art_and_opening_runs_no_plug_in() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.save"); + generated(&mut s, "test.gen.save"); + s.execute("plugin.editGenerated", &json!({"params": {"size": 20, "label": "b"}})).unwrap(); + // The installed generator now always draws the small square: opening must not run it. + install(&mut s, &tpl::returning(&tpl::generator("test.gen.save", PARAMS), SMALL), true); + let warnings = reopen(&mut s); + assert!(warnings.is_empty(), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Big", "Line"]); + let info = s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap(); + assert_eq!((&info["plugin"], &info["state"], &info["installed"]), (&json!("test.gen.save"), &json!("intact"), &json!(true))); + assert_eq!(info["params"], json!({"size": 20, "label": "b"})); + // An explicit edit runs it. + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"label": "c"}})).unwrap(); + assert_eq!(art(&s, id), ["Small"]); +} + +#[test] +fn a_missing_plug_in_keeps_the_art_and_is_named() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.gone"); + generated(&mut s, "test.gen.gone"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("“Test test.gen.gone” (test.gen.gone) isn't installed"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"]); + let info = s.execute("plugin.generatedInfo", &json!({})).unwrap_or_else(|_| s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()); + assert_eq!((&info["state"], &info["installed"]), (&json!("intact"), &json!(false))); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("isn't installed"), "{e}"); + assert_eq!(art(&s, id), ["Small"]); + // Saved again without the plug-in, it keeps its fields. + let again = vectorcraft_format::save(&s.doc().unwrap().doc, true); + sizes(&mut s, "test.gen.gone"); + assert!(reopen_bytes(&mut s, &again).is_empty()); + let id = the_generated(&s); + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, id), ["Big", "Line"]); +} + +#[test] +fn a_missing_generator_in_an_opacity_mask_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.mask.gone"); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let target = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone(); + let mask = s.execute("plugin.generate", &json!({"id": "test.gen.mask.gone"})).unwrap()["id"].clone(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [target, mask]})).unwrap(); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.mask.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("test.gen.mask.gone") && warnings[0].contains("isn't installed"), "{warnings:?}"); +} + +#[test] +fn a_missing_generator_in_a_symbol_definition_is_named_on_open() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.symbol.gone"); + generated(&mut s, "test.gen.symbol.gone"); + s.execute("symbol.new", &json!({"name": "Generated"})).unwrap(); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + s.execute("plugin.remove", &json!({"id": "test.gen.symbol.gone"})).unwrap(); + let warnings = reopen_bytes(&mut s, &bytes); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("test.gen.symbol.gone") && warnings[0].contains("isn't installed"), "{warnings:?}"); +} + +#[test] +fn generated_art_inside_live_containers_can_be_drawn_again() { + for (index, command) in ["object.blend.make", "object.repeat.grid", "object.envelope.makeWithWarp"].into_iter().enumerate() { + let mut s = Session::new(); + let plugin = format!("test.gen.container.{index}"); + sizes(&mut s, &plugin); + let generated = generated(&mut s, &plugin); + let other = s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()["id"].clone(); + s.execute(command, &json!({"ids": [generated, other]})).unwrap(); + let before = steps(&s); + s.execute("plugin.editGenerated", &json!({"id": generated, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, generated), ["Big", "Line"], "{command}"); + assert_eq!(steps(&s), before + 1, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(art(&s, generated), ["Small"], "{command}"); + } +} + +/// The saved native text `bytes` with the generated art object's JSON changed by `f`. +fn tampered(bytes: &[u8], f: impl FnOnce(&mut Value)) -> Vec { + fn find(v: &mut Value) -> Option<&mut Value> { + match v { + Value::Object(o) if o.contains_key("generated") => Some(v), + Value::Object(o) => o.values_mut().find_map(find), + Value::Array(a) => a.iter_mut().find_map(find), + _ => None, + } + } + let mut v: Value = serde_json::from_slice(bytes).unwrap(); + f(find(&mut v).unwrap()); + serde_json::to_vec(&v).unwrap() +} + +#[test] +fn a_garbled_id_or_changed_art_keeps_the_art() { + let mut s = Session::new(); + sizes(&mut s, "test.gen.garbled"); + generated(&mut s, "test.gen.garbled"); + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, true); + for bad in [json!("test.gen.garbled/../x"), json!(""), json!(42), json!("t\u{0}x")] { + let file = tampered(&bytes, |n| n["generated"]["plugin"] = bad.clone()); + let warnings = reopen_bytes(&mut s, &file); + assert!(warnings.iter().any(|w| w.contains("plug-in id or parameters are damaged")), "{bad}: {warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Small"], "{bad}"); + let info = s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap(); + assert_eq!((&info["state"], &info["installed"]), (&json!("damaged"), &json!(false)), "{bad}"); + let e = s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap_err().to_string(); + assert!(e.contains("damaged"), "{bad}: {e}"); + } + // Art edited outside the app no longer matches the hash: it is kept as it is. + let file = tampered(&bytes, |n| { + let child = &mut n["kind"]["children"][0]; + assert!(child.get("name").is_some(), "{child}"); + child["name"] = json!("Edited"); + }); + let warnings = reopen_bytes(&mut s, &file); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("doesn't match the hash its file gave"), "{warnings:?}"); + let id = the_generated(&s); + assert_eq!(art(&s, id), ["Edited"]); + assert_eq!(s.execute("plugin.generatedInfo", &json!({"id": id})).unwrap()["state"], json!("changed")); + // An explicit edit may still draw it again with its plug-in. + s.execute("plugin.editGenerated", &json!({"id": id, "params": {"size": 20}})).unwrap(); + assert_eq!(art(&s, id), ["Big", "Line"]); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 40e43e861c..df482dc13b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2004,7 +2004,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns). On the web the dialog has no live preview, and every filter it runs, at once or on OK, runs in a Web Worker → {background: true, status}", + "{id: an object filter or generator plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns). On the web the filter's dialog has no live preview, and every filter it runs, at once or on OK, runs in a Web Worker → {background: true, status}. A generator draws new generated art at once when it takes no parameters or params are given (plugin.generate), else opens dialog `pluginGenerate` (a row per parameter; OK runs plugin.generate)", + ), + ( + "ui.editGeneratedArt", + "Edit Generated Art…", + "", + "{id?: a generated art object (default: the one selected)} Object › Plug-ins › Edit Generated Art…: open dialog `pluginGenerate` with the parameters the object was drawn with; OK runs plugin.editGenerated, which draws its art again as one undo step (none when nothing changed). An object whose generator isn't installed, or whose saved plug-in id, parameters, transforms or scales are damaged, is an error naming it, and its art stays as it is", ), ( "plugin.applyLastFilter", diff --git a/crates/plugins/src/generate.rs b/crates/plugins/src/generate.rs new file mode 100644 index 0000000000..84b7379734 --- /dev/null +++ b/crates/plugins/src/generate.rs @@ -0,0 +1,230 @@ +//! Generator plug-ins: a plug-in of kind `generator` draws art from its parameters alone. The host +//! keeps the art in a generated art object with the parameters it was drawn with +//! ([`vectorcraft_doc::generated`]), so the art can be drawn again when the parameters change. +//! +//! A run is given no objects (`{"objects": []}`) and its checked parameters with +//! `_context.mode` `"generate"`, and returns the art's objects in the form filters return new +//! objects ([`crate::objects`]): `{"objects": [...]}`, or `{"error": "…"}` to decline. Each object +//! is new (no `id`) and goes through a filter's checks. The parameters a generated art object keeps +//! are at most [`MAX_PARAMS_BYTES`] of JSON. A run takes the plug-in's own budget, and Cancel stops +//! it between two slices of it ([`Error::Cancelled`]). + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; + +use crate::objects::{OutObject, declined, printable}; +use crate::{Error, Kind, Limits, Plugin, Result, registry}; + +pub use vectorcraft_doc::generated::MAX_PARAMS_BYTES; + +/// The keys a generator's output may have. +const OUTPUT_KEYS: &[&str] = &["objects", "error"]; + +/// What a generator is given in place of objects. +const INPUT: &[u8] = br#"{"objects":[]}"#; + +/// The installed generators, by plug-in id. +pub fn installed() -> Vec> { + registry::list().into_iter().filter(|p| p.manifest().kind == Kind::Generator).collect() +} + +/// The installed generator with plug-in id `id`. A plug-in of another kind, and one that isn't +/// installed, are errors that say so. +pub fn named(id: &str) -> Result> { + let plugin = registry::get(id).ok_or_else(|| Error::NotFound(id.into()))?; + match plugin.manifest().kind { + Kind::Generator => Ok(plugin), + _ => Err(not_generator(plugin.manifest())), + } +} + +/// The error of plug-in `m`, which is not a generator, asked to draw generated art. +fn not_generator(m: &crate::Manifest) -> Error { + Error::Params(format!("`{}` is a plug-in of kind `{}`, not a generator", m.id, m.kind.name())) +} + +/// The parameters `params` checked against generator `plugin`'s manifest (missing ones take their +/// defaults, others are errors), at most [`MAX_PARAMS_BYTES`] of JSON: what a generated art object +/// keeps. +pub fn resolve(plugin: &Plugin, params: &Value) -> Result> { + resolve_over(plugin, &Map::new(), params) +} + +/// [`resolve`] for parameters `params` that change the `saved` ones of a generated art object: +/// `params` is checked as [`resolve`] checks it, and the saved values the manifest still declares +/// fill in the rest, brought into its ranges as a filter's are. +pub fn resolve_over(plugin: &Plugin, saved: &Map, params: &Value) -> Result> { + let m = plugin.manifest(); + if m.kind != Kind::Generator { + return Err(not_generator(m)); + } + let given = match params { + Value::Null => &Map::new(), + Value::Object(given) => given, + _ => return Err(Error::Params("plug-in parameters must be a JSON object".into())), + }; + strict(m, given)?; + let mut merged: Map = + saved.iter().filter(|(k, _)| m.params.iter().any(|(name, _)| name == *k)).map(|(k, v)| (k.clone(), v.clone())).collect(); + merged.extend(given.iter().map(|(k, v)| (k.clone(), v.clone()))); + let resolved = m.resolve_params(&Value::Object(merged))?; + if serde_json::to_vec(&resolved).map_or(usize::MAX, |b| b.len()) > MAX_PARAMS_BYTES { + return Err(Error::Params(format!("the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps"))); + } + Ok(resolved) +} + +/// Refuses what [`crate::Manifest::resolve_params`] would bring into range: a parameter `m` does not +/// declare, a number (or a number of a list) outside its range and text longer than its limit are +/// errors, so the parameters a generated art object keeps are the ones it was given. +fn strict(m: &crate::Manifest, given: &Map) -> Result<()> { + use crate::manifest::ParamSpec; + for (k, v) in given { + let Some((_, p)) = m.params.iter().find(|(name, _)| name == k) else { + return Err(Error::Params(format!("`{k}` is not a parameter of `{}`", m.id))); + }; + if v.is_null() { + continue; + } + let range = |min: &dyn std::fmt::Display, max: &dyn std::fmt::Display| Error::Params(format!("`{k}` must be from {min} to {max}")); + match &p.spec { + ParamSpec::Number { min, max, .. } if v.as_f64().is_some_and(|f| !(*min..=*max).contains(&f)) => return Err(range(min, max)), + ParamSpec::Int { min, max, .. } if int_outside(v, *min, *max) => return Err(range(min, max)), + ParamSpec::NumberList { min, max, .. } + if v.as_array().is_some_and(|items| items.iter().any(|x| x.as_f64().is_some_and(|f| !(*min..=*max).contains(&f)))) => + { + return Err(Error::Params(format!("each number of `{k}` must be from {min} to {max}"))); + } + ParamSpec::Text { max_length, .. } if v.as_str().is_some_and(|s| s.chars().count() > *max_length) => { + return Err(Error::Params(format!("`{k}` must be at most {max_length} characters"))); + } + _ => {} + } + } + Ok(()) +} + +/// Is `v`, a number given for a whole-number parameter, outside `min..=max` (rounded, as +/// [`crate::Manifest::resolve_params`] rounds it)? A value that is not a number is not. The rounded +/// value is compared with the bounds as integers: an `i64` bound past 2^53 has no exact `f64`. +fn int_outside(v: &Value, min: i64, max: i64) -> bool { + // -2^63 and 2^63, exact as f64: a whole number in between converts to i64 exactly. + const LOW: f64 = -9_223_372_036_854_775_808.0; + const HIGH: f64 = 9_223_372_036_854_775_808.0; + match v.as_i64() { + Some(i) => !(min..=max).contains(&i), + None => v.is_u64() || v.as_f64().map(f64::round).is_some_and(|r| !(LOW..HIGH).contains(&r) || !(min..=max).contains(&(r as i64))), + } +} + +/// Runs generator `plugin` with `params` ([`resolve`]d) under `limits` → the objects of its art, in +/// paint order (bottom first), checked as a filter's new objects are. +pub fn run(plugin: &Plugin, params: &Map, limits: &Limits) -> Result> { + let m = plugin.manifest(); + if m.kind != Kind::Generator { + return Err(not_generator(m)); + } + let mut params = Value::Object(params.clone()); + params["_context"] = json!({"mode": "generate"}); + let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; + decode(&plugin.run_limited(INPUT, ¶ms, limits)?) +} + +/// A generator's output: `{"objects": [...]}` of new objects (no `id`), or `{"error": "…"}` to +/// decline with a message for the user. An output without objects, with an object that has an +/// `id`, or with keys of its own, is refused. +pub fn decode(bytes: &[u8]) -> Result> { + let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; + if let Some(e) = declined(&v) { + return Err(e); + } + if let Some(key) = v.as_object().and_then(|o| o.keys().find(|k| !OUTPUT_KEYS.contains(&k.as_str()))) { + let key = printable(&json!(key), 64); + return Err(Error::Output(format!("a generator returns `objects`, not `{key}`"))); + } + let objects = crate::objects::decode(bytes)?; + if objects.is_empty() { + return Err(Error::Output("the generator returned no objects".into())); + } + if let Some(i) = objects.iter().position(|o| o.id.is_some()) { + return Err(crate::objects::out_err(&format!("objects[{i}]"), "a generator's objects are new: leave `id` out")); + } + Ok(objects) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SQUARE: &str = r#"{"type":"path","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[10,0]},{"p":[10,10]}]}]}}"#; + + #[test] + fn output_is_new_objects_or_a_decline() { + let out = decode(format!(r#"{{"objects":[{SQUARE},{SQUARE}]}}"#).as_bytes()).unwrap(); + assert_eq!(out.len(), 2); + assert!(out.iter().all(|o| o.id.is_none() && o.path.is_some())); + assert_eq!(decode(br#"{"error": "No\nstars."}"#), Err(Error::Failed("Nostars.".into()))); + } + + /// Nothing a generator returns reaches a document unchecked: malformed JSON, no objects, keys + /// the host doesn't read, objects with ids and bad objects are all errors. + #[test] + fn bad_output_is_refused() { + let far = r#"{"objects":[{"path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[1e9,0]}]}]}}]}"#; + let with_id = format!(r#"{{"objects":[{}]}}"#, SQUARE.replacen('{', r#"{"id":4,"#, 1)); + for (bad, says) in [ + (&b"[]"[..], "objects"), + (b"{}", "objects"), + (b"not json", "not JSON"), + (br#"{"objects":[]}"#, "no objects"), + (br#"{"objects":[1]}"#, "JSON object"), + (far.as_bytes(), "out of range"), + (br#"{"objects":[],"documentData":{}}"#, "not `documentData`"), + (with_id.as_bytes(), "leave `id` out"), + ] { + let e = decode(bad).unwrap_err().to_string(); + assert!(e.contains(says), "{}: {e}", String::from_utf8_lossy(bad)); + } + } + + /// A number of a list outside the list's range is an error, not brought into range. + #[test] + fn a_number_list_entry_out_of_range_is_refused() { + let m: crate::Manifest = serde_json::from_value(json!({ + "id": "t.gen", "name": "T", "kind": "generator", + "params": {"stops": {"type": "numberList", "min": 0, "max": 10, "default": [1]}} + })) + .unwrap(); + let given = |v: Value| json!({"stops": v}).as_object().cloned().unwrap(); + assert!(strict(&m, &given(json!([0, 5, 10]))).is_ok()); + // A declared name may be null (its default); an undeclared one is an error even when null. + assert!(strict(&m, &given(Value::Null)).is_ok()); + let typo = json!({"stosp": null}).as_object().cloned().unwrap(); + let e = strict(&m, &typo).unwrap_err().to_string(); + assert!(e.contains("`stosp` is not a parameter of `t.gen`"), "{e}"); + for bad in [json!([100]), json!([1, -0.5])] { + let e = strict(&m, &given(bad.clone())).unwrap_err().to_string(); + assert!(e.contains("each number of `stops` must be from 0 to 10"), "{bad}: {e}"); + } + } + + /// A whole-number parameter's bounds are compared exactly, also past 2^53, where `max as f64` + /// rounds up to the next value an f64 holds; a fraction is still rounded first. + #[test] + fn a_whole_number_just_past_a_large_maximum_is_refused() { + let m: crate::Manifest = serde_json::from_value(json!({ + "id": "t.gen", "name": "T", "kind": "generator", + "params": {"n": {"type": "int", "min": -9007199254740995_i64, "max": 9007199254740995_i64}} + })) + .unwrap(); + let given = |v: Value| json!({"n": v}).as_object().cloned().unwrap(); + for ok in [json!(9007199254740995_i64), json!(3.6), json!(-9007199254740995_i64), json!(9007199254740994.0)] { + assert!(strict(&m, &given(ok.clone())).is_ok(), "{ok}"); + } + for bad in [json!(9007199254740996.0), json!(-9007199254740996.0), json!(1e300), json!(-1e300), json!(u64::MAX)] { + let e = strict(&m, &given(bad.clone())).unwrap_err().to_string(); + assert!(e.contains("`n` must be from -9007199254740995 to 9007199254740995"), "{bad}: {e}"); + } + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index e776a4a414..79250459cf 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -26,7 +26,8 @@ //! time it is drawn, from an appearance stack, and at `api` 2 may paint what it returns //! ([`painted`]); an **exporter** ([`export`]) writes the whole //! document in a file format of its own; an **importer** ([`import`]) reads a file in a format of -//! its own into a new document. The process-wide [`registry`] holds the installed +//! its own into a new document; a **generator** ([`generate`]) draws art from its parameters alone, +//! which the document keeps with them so the art can be drawn again. The process-wide [`registry`] holds the installed //! plug-ins; in [`safe_mode`] none of them loads or runs. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A @@ -43,6 +44,7 @@ pub mod deferred; pub mod dialog; pub mod effect; pub mod export; +pub mod generate; pub mod host; pub mod import; pub mod js; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 9e68d6b70c..5528594c9c 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -118,6 +118,10 @@ pub enum Kind { /// An importer: reads a file in a format of its own, whose extensions the manifest lists, into /// a new document (File › Open, `document.open`; see [`crate::import`]). Importer, + /// A generator: draws art from its parameters alone into a generated art object, which keeps + /// them so the art can be drawn again with changed ones (Object › Plug-ins, `plugin.generate`; + /// see [`crate::generate`]). + Generator, } impl Kind { @@ -127,6 +131,7 @@ impl Kind { Kind::Effect => "effect", Kind::Exporter => "exporter", Kind::Importer => "importer", + Kind::Generator => "generator", } } } @@ -668,6 +673,9 @@ impl Manifest { (Budget::Heavy, Kind::Importer) => { return Err(Error::Manifest("an importer always gets an import's budget: leave `budget` out".into())); } + (Budget::Heavy, Kind::Generator) => { + return Err(Error::Manifest("a generator always gets the usual budget: leave `budget` out".into())); + } } self.validate_params()?; self.validate_commands()?; @@ -837,7 +845,7 @@ impl Manifest { if self.commands.is_empty() { return Ok(()); } - if matches!(self.kind, Kind::Exporter | Kind::Importer) { + if matches!(self.kind, Kind::Exporter | Kind::Importer | Kind::Generator) { return Err(Error::Manifest("only a filter or a live effect declares `commands`".into())); } if self.budget == Budget::Heavy { @@ -1394,6 +1402,29 @@ mod tests { } } + /// A generator gets the usual budget and needs `doc.write`, which its manifest implies; it + /// declares no extensions, commands, inputs or other permissions. + #[test] + fn a_generator_writes_art_with_the_usual_budget() { + let m = Manifest::parse(br#"{"id":"org.example.stars","name":"Stars","kind":"generator"}"#).unwrap(); + assert_eq!((m.kind, m.budget), (Kind::Generator, Budget::Light)); + assert_eq!(serde_json::to_value(&m).unwrap()["kind"], json!("generator")); + assert_eq!(m.permissions(), [Permission::DocWrite]); + let listed = Manifest::parse(br#"{"id":"a","name":"x","kind":"generator","permissions":["doc.write"]}"#).unwrap(); + assert_eq!(listed.permissions(), [Permission::DocWrite]); + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"generator","budget":"heavy"}"#, "the usual budget"), + (r#"{"id":"a","name":"x","kind":"generator","extensions":["plt"]}"#, "only an exporter or an importer"), + (r#"{"id":"a","name":"x","kind":"generator","permissions":[]}"#, "needs the permission `doc.write`"), + (r#"{"id":"a","name":"x","kind":"generator","permissions":["doc.write","doc.read"]}"#, "doesn't apply"), + (r#"{"id":"a","name":"x","kind":"generator","commands":[{"id":"again","label":"Again"}]}"#, "only a filter or a live effect"), + (r#"{"id":"a","name":"x","kind":"generator","place":true}"#, "`place` is only for an importer"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// Only an importer sets `place`, to a boolean, and it asks for no permission beyond /// `import.read`; false, the default, isn't written back. #[test] diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 1b8396ddb5..4331faf49a 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -1325,10 +1325,7 @@ impl Plan { } else if let Some(r) = self.replace.remove(&c.id) { emitted.push(Arc::new(r)); changed = true; - } else if let Some(ch) = match &c.kind { - NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => self.list(Some(c.id), children), - _ => None, - } { + } else if let Some(ch) = c.children().and_then(|children| self.list(Some(c.id), children)) { let mut m = (**c).clone(); if let Some(slot) = m.children_mut() { *slot = ch; diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 538a454f52..f1af2b17ef 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -164,6 +164,7 @@ impl Permission { Kind::Effect => &[Permission::DocRead, Permission::EffectRender], Kind::Exporter => &[Permission::DocRead, Permission::ExportWrite], Kind::Importer => &[Permission::ImportRead], + Kind::Generator => &[Permission::DocWrite], } } @@ -180,11 +181,12 @@ impl Permission { /// The permissions a plug-in of `kind` can't work without, which its list must hold: a live /// effect and an exporter are always handed objects, and only draw or write; an importer is - /// always handed the file being opened. A filter may leave any of its permissions out. + /// always handed the file being opened; a generator always adds its art to the document. A + /// filter may leave any of its permissions out. fn required(kind: Kind) -> &'static [Permission] { match kind { Kind::Filter => &[], - Kind::Effect | Kind::Exporter | Kind::Importer => Permission::implied(kind), + Kind::Effect | Kind::Exporter | Kind::Importer | Kind::Generator => Permission::implied(kind), } } } diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index 19199c466a..a00821c720 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -241,6 +241,11 @@ pub fn importer(id: &str, extensions: &str, params: &str) -> String { format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","extensions":{extensions},"params":{params}}}"#) } +/// The manifest of a test generator `id` with `params` (a JSON object of specs). +pub fn generator(id: &str, params: &str) -> String { + manifest(id, "generator", params) +} + /// What [`echo_exporter`] writes as its file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Echo { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 65b70a9a80..0e5e2100ba 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -211,6 +211,8 @@ mod tests_plugin_export; #[cfg(test)] mod tests_plugin_fields; #[cfg(test)] +mod tests_plugin_generate; +#[cfg(test)] mod tests_plugin_import; #[cfg(test)] mod tests_raster_formats; diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 18c7d4c327..50f7a22216 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -1,8 +1,11 @@ //! WebAssembly plug-ins in the menus and their generated dialogs. //! -//! Object › Plug-ins lists the installed object filters (`plugin.dialog {id}`), then Install -//! Plug-in… and Reload Plug-ins; Effect › Plug-ins lists the live-effect plug-ins, which open the -//! effect dialog (`effect.dialog`). A filter with parameters opens a hosted dialog `plugin`: one row +//! Object › Plug-ins lists the installed object filters and generators (`plugin.dialog {id}`), +//! then Edit Generated Art…, Install Plug-in… and Reload Plug-ins. A generator with parameters +//! opens a hosted dialog `pluginGenerate`, whose OK draws new generated art (`plugin.generate`); +//! Edit Generated Art… opens it with a selected generated art object's parameters, and its OK draws +//! the object again (`plugin.editGenerated`). Effect › Plug-ins lists the live-effect plug-ins, +//! which open the effect dialog (`effect.dialog`). A filter with parameters opens a hosted dialog `plugin`: one row //! per declared parameter, shown while its `visibleWhen` holds, with a live Preview, and OK keeps the //! run as one undo step (`plugin.run`). A filter without parameters runs at once. A heavy filter (its //! manifest's `budget`) has no Preview, since a run may take minutes: it runs in the background @@ -22,8 +25,9 @@ //! files File › Open finds no built-in format for, and File › Open With lists them; one with //! parameters opens dialog `pluginImport` once the file is picked, and its Open button opens it. //! -//! The one open filter, export or import dialog is [`PluginDialog`]: what the hosted dialog cannot -//! hold (the plug-in, the live preview, the export's or open's own parameters) lives there, and +//! The one open filter, generator, export or import dialog is [`PluginDialog`]: what the hosted +//! dialog cannot hold (the plug-in, the live preview, the edited object, the export's or open's own +//! parameters) lives there, and //! [`pump`] reads the dialog's values each frame and acts on its answer. //! //! [`InstallPrompt`] asks a person to approve a plug-in's permissions or heavy budget. What it @@ -195,12 +199,13 @@ fn leave_out(items: &mut [Node], placed: &std::collections::HashSet) { } } -/// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then -/// Install Plug-in…, Reload Plug-ins and Plug-ins That Didn't Load… ([`super::failed_plugins`]). +/// 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`]). pub fn object_menu() -> Vec { let mut items: Vec = registry::list() .iter() - .filter(|p| p.manifest().kind == Kind::Filter) + .filter(|p| matches!(p.manifest().kind, Kind::Filter | Kind::Generator)) .map(|p| with_commands(p, cp(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) .collect(); if items.is_empty() { @@ -208,6 +213,7 @@ pub fn object_menu() -> Vec { } items.extend([ Sep, + c(EDIT_GENERATED, EDIT_COMMAND), c("Install Plug-in…", "ui.installPlugin"), c("Reload Plug-ins", "plugin.reload"), c("Plug-ins That Didn't Load…", super::failed_plugins::COMMAND), @@ -270,6 +276,9 @@ pub(crate) enum Opened { refused: bool, params: Arc<[Param]>, }, + /// A generator's parameters: for new generated art (`edit` is `None`), or for drawing the + /// generated art object `edit` names again. + Generate { plugin: String, edit: Option, params: Arc<[Param]> }, /// An exporter's parameters, with Export As's own parameters (`format`, `path`, …) kept for Export. Export { plugin: String, @@ -294,13 +303,13 @@ impl PluginDialog { impl Opened { fn plugin(&self) -> &str { match self { - Opened::Filter { plugin, .. } | Opened::Export { plugin, .. } | Opened::Import { plugin, .. } => plugin, + Opened::Filter { plugin, .. } | Opened::Generate { plugin, .. } | Opened::Export { plugin, .. } | Opened::Import { plugin, .. } => plugin, } } fn params(&self) -> &Arc<[Param]> { match self { - Opened::Filter { params, .. } | Opened::Export { params, .. } | Opened::Import { params, .. } => params, + Opened::Filter { params, .. } | Opened::Generate { params, .. } | Opened::Export { params, .. } | Opened::Import { params, .. } => params, } } @@ -563,15 +572,26 @@ pub fn open_last(app: &mut VectorcraftApp) -> Result { Ok(Value::Null) } -/// `plugin.dialog {id, params?}`: run filter `id` at once when it takes no parameters or `params` -/// are given, else open its dialog prefilled with the parameters it last ran with in this session -/// ([`remembered`]), or with its defaults. +/// `plugin.dialog {id, params?}`: run filter or generator `id` at once when it takes no parameters +/// or `params` are given, else open its dialog prefilled with the parameters a filter last ran with +/// in this session ([`remembered`]), or with its defaults. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_str).ok_or("missing `id` (see plugin.list)")?; let plugin = registry::get(id).ok_or_else(|| format!("no plug-in {id:?} is installed"))?; let m = plugin.manifest(); match m.kind { Kind::Filter => {} + Kind::Generator => { + let given = p.get("params"); + if given.is_some_and(|value| !value.is_object()) { + return Err(vectorcraft_plugins::Error::Params("plug-in parameters must be a JSON object".into()).to_string()); + } + if m.params.is_empty() || given.is_some() { + return app.run(GENERATE, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); + } + open_generate(app, &plugin, None, &Map::new())?; + return Ok(Value::Null); + } Kind::Effect => return Err(format!("{} is a live effect (Effect › Plug-ins)", m.name)), Kind::Exporter => return Err(format!("{} is an exporter (File › Export › Export As…)", m.name)), Kind::Importer => return Err(format!("{} is an importer (File › Open With)", m.name)), @@ -658,6 +678,78 @@ fn run(app: &mut VectorcraftApp, plugin: &Plugin, p: Value) -> Result, +} + +/// OK's error when the document of an Edit Generated Art… dialog is no longer the active one. +const EDIT_DOC_GONE: &str = "the document it was prepared for is no longer active"; + +/// Opens the dialog of generator `plugin`: its rows at the parameters `values` holds, else at their +/// defaults, for new generated art, or for drawing the object of `edit` again. +fn open_generate(app: &mut VectorcraftApp, plugin: &Plugin, edit: Option, values: &Map) -> Result<(), String> { + let m = plugin.manifest(); + let look = Look { title: m.name.trim_end_matches('…').to_string(), description: m.description.clone(), previews: false, note: false, ok: None }; + let rows = vectorcraft_plugins::generate::resolve_over(plugin, values, &Value::Null).map_err(|error| error.to_string())?; + let (id, params) = open_hosted(app, GENERATE_KIND, plugin.id(), m.clone(), rows, look)?; + app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Generate { plugin: plugin.id().to_string(), edit, params } }); + Ok(()) +} + +/// `ui.editGeneratedArt {id?}`: opens the dialog of generated art object `id` (else the one +/// selected) with the parameters it was drawn with, for the parameters its plug-in still declares. +/// An object whose plug-in isn't installed, or whose saved fields are damaged, is an error that says +/// so, and its art stays as it is. +pub fn open_edit(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut q = json!({}); + if let Some(id) = p.get("id").filter(|v| !v.is_null()) { + q["id"] = id.clone(); + } + let info = app.run("plugin.generatedInfo", q)?; + let id = info.get("id").cloned().unwrap_or(Value::Null); + let installed = info.get("installed") == Some(&Value::Bool(true)); + let Some(plugin) = info.get("plugin").and_then(Value::as_str).and_then(registry::get).filter(|_| installed) else { + // The engine's error says which plug-in is missing or that the saved fields are damaged. + return app.run("plugin.editGenerated", json!({"id": id, "params": {}})); + }; + let saved = info.get("params").and_then(Value::as_object).cloned().unwrap_or_default(); + let edit = EditTarget { object: id, doc: app.session.active().map(|st| st.uid) }; + open_generate(app, &plugin, Some(edit), &saved)?; + Ok(Value::Null) +} + +/// Is the selection one object, a generated art object, which Edit Generated Art… edits? +pub fn one_generated_selected(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| match st.selection.objects.as_slice() { + [id] => st.doc.node(*id).is_some_and(|n| n.extras().generated.is_some()), + _ => false, + }) +} + +/// OK of a generator dialog: draws new generated art (`plugin.generate`), or draws the object of +/// `edit` again (`plugin.editGenerated`), as one undo step. When another document has come to the +/// front since Edit Generated Art… opened the dialog, it draws nothing and says so. +fn generate_with(app: &mut VectorcraftApp, plugin: String, edit: Option, values: Map) -> Result { + match edit { + Some(e) if e.doc != app.session.active().map(|st| st.uid) => Err(EDIT_DOC_GONE.into()), + Some(e) => app.run("plugin.editGenerated", json!({"id": e.object, "params": values})), + None => app.run(GENERATE, json!({"id": plugin, "params": values})), + } +} + /// The key of an exporter's parameters dialog, after Export As picked the file. pub const EXPORT_KIND: &str = "pluginExport"; @@ -817,6 +909,7 @@ fn pump_dialog(app: &mut VectorcraftApp, ctx: &egui::Context) { // The dialog is already closed, so a failure goes to the status line. let done = match open.kind { Opened::Filter { .. } => confirm_filter(app, open.kind, values), + Opened::Generate { plugin, edit, .. } => generate_with(app, plugin, edit, values), Opened::Export { export, document, .. } => export_with(app, export, document, values), Opened::Import { open, .. } => import_with(app, open, values), }; diff --git a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs new file mode 100644 index 0000000000..a4c8e82bc3 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs @@ -0,0 +1,179 @@ +//! Generator plug-ins in Object › Plug-ins: listed with the filters, a generator with parameters +//! opens dialog `pluginGenerate`, whose OK draws new generated art, and Edit Generated Art… opens +//! it with a selected object's parameters and draws the object again. Each test installs a +//! generator of its own and removes it: plug-ins are process-wide. + +use craft::menu::Node; +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +use super::tests_export::{cancel, fields, frame, kind, set, try_confirm, try_set}; +use super::*; +use crate::Services; +use crate::VectorcraftApp; + +/// The generator's art: a 10 pt square, and a 20 pt one when its `size` is 20. +const SMALL: &str = r#"{"objects":[{"type":"path","name":"Small","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[10,0]},{"p":[10,10]},{"p":[0,10]}]}]}}]}"#; +const BIG: &str = r#"{"objects":[{"type":"path","name":"Big","path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[20,0]},{"p":[20,20]},{"p":[0,20]}]}]}}]}"#; + +/// An app with a window, where the dialogs open, and generator `id` installed. +fn app(id: &str) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + let manifest = tpl::generator(id, r#"{"size":{"type":"int","min":1,"max":100,"default":10}}"#); + let wasm = wat::parse_str(tpl::when_given_else(&manifest, Given::Params, r#""size":20"#, BIG, SMALL)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + app +} + +/// The names of the art of generated art object `id`. +fn art(app: &VectorcraftApp, id: u64) -> Vec { + let st = app.session.doc().unwrap(); + let n = st.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + n.children().unwrap().iter().map(|c| c.name.clone().unwrap_or_default()).collect() +} + +/// The undo steps of the active document. +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn object_plug_ins_draws_and_edits_generated_art() { + let mut app = app("test.ui.generator"); + let menu = plugin::object_menu(); + let listed = menu.iter().any(|n| { + matches!(n, Node::Item(item) if item.command.id == "plugin.dialog" + && item.label == "Test test.ui.generator…" + && item.command.params["id"] == "test.ui.generator") + }); + assert!(listed, "{menu:?}"); + let edit_listed = + menu.iter().any(|n| matches!(n, Node::Item(item) if item.command.id == plugin::EDIT_COMMAND && item.label == plugin::EDIT_GENERATED)); + assert!(edit_listed, "{menu:?}"); + + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + assert!(!plugin::one_generated_selected(&app)); + app.run("plugin.dialog", json!({"id": "test.ui.generator"})).unwrap(); + assert_eq!(kind(&app).as_deref(), Some(plugin::GENERATE_KIND)); + assert_eq!(fields(&app)["size"].as_f64(), Some(10.0)); + frame(&mut app); + try_confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); + assert!(plugin::one_generated_selected(&app)); + let id = app.session.doc().unwrap().selection.objects[0].0; + let before = steps(&app); + assert_eq!(art(&app, id), ["Small"]); + + // Edit Generated Art… shows the saved parameters; OK draws the art again as one undo step. + app.run(plugin::EDIT_COMMAND, json!({})).unwrap(); + assert_eq!(kind(&app).as_deref(), Some(plugin::GENERATE_KIND)); + assert_eq!(fields(&app)["size"].as_f64(), Some(10.0)); + frame(&mut app); + set(&mut app, "size", json!(20)); + try_confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); + assert_eq!(art(&app, id), ["Big"]); + assert_eq!(steps(&app), before + 1); + assert_eq!(app.session.doc().unwrap().history.undo.last().map(|s| s.label.as_str()), Some("Edit Generated Art")); + + // A value out of the parameter's range is refused, and Cancel leaves the art as it is. + app.run(plugin::EDIT_COMMAND, json!({})).unwrap(); + frame(&mut app); + assert_eq!(fields(&app)["size"].as_f64(), Some(20.0)); + assert!(try_set(&mut app, "size", json!(500)).is_err()); + cancel(&mut app); + assert!(kind(&app).is_none()); + assert_eq!(art(&app, id), ["Big"]); + assert_eq!(steps(&app), before + 1); + + // Without its plug-in, the object can't be drawn again: the error names it. + app.run("plugin.remove", json!({"id": "test.ui.generator"})).unwrap(); + let e = app.run(plugin::EDIT_COMMAND, json!({})).unwrap_err(); + assert!(e.contains("“Test test.ui.generator” (test.ui.generator) isn't installed"), "{e}"); + assert!(kind(&app).is_none()); + assert_eq!(art(&app, id), ["Big"]); +} + +#[test] +fn generator_dialog_validates_supplied_parameters_and_runs_an_empty_object() { + for (id, with_parameters) in [("test.ui.generator.params", true), ("test.ui.generator.no_params", false)] { + let mut app = app(id); + if !with_parameters { + let wasm = wat::parse_str(tpl::returning(&tpl::generator(id, "{}"), SMALL)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": true})).unwrap(); + } + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + let undo = steps(&app); + for params in [json!([]), json!("bad"), json!(false), json!(7), serde_json::Value::Null] { + assert!(app.run("plugin.dialog", json!({"id": id, "params": params})).is_err(), "{params}"); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(steps(&app), undo); + assert!(kind(&app).is_none()); + } + app.run("plugin.dialog", json!({"id": id, "params": {}})).unwrap(); + assert!(kind(&app).is_none()); + assert_eq!(steps(&app), undo + 1); + let selected = app.session.doc().unwrap().selection.objects[0].0; + assert_eq!(art(&app, selected), ["Small"]); + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +#[test] +fn editing_generated_art_resolves_saved_parameters_after_an_update() { + let id = "test.ui.generator.narrower"; + let mut app = app(id); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let generated = app.run("plugin.generate", json!({"id": id, "params": {"size": 80}})).unwrap()["id"].clone(); + let manifest = tpl::generator( + id, + r#"{"show":{"type":"bool","default":false},"size":{"type":"int","min":1,"max":20,"default":10,"visibleWhen":{"show":[true]}}}"#, + ); + let module = wat::parse_str(tpl::returning(&manifest, BIG)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module), "replace": true})).unwrap(); + app.run(plugin::EDIT_COMMAND, json!({"id": generated})).unwrap(); + assert_eq!(fields(&app)["size"].as_f64(), Some(20.0)); + frame(&mut app); + let before = steps(&app); + try_confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before + 1); + assert_eq!(art(&app, generated.as_u64().unwrap()), ["Big"]); +} + +/// Edit Generated Art… is for one selected object: a generated art object selected with another +/// object is not. OK in its dialog draws the object of the document it was opened in: after another +/// document comes to the front, OK draws nothing there, closes the dialog and says why. +#[test] +fn edit_generated_art_is_for_one_object_of_the_document_it_opened_in() { + let mut app = app("test.ui.generator2"); + let generate = |app: &mut VectorcraftApp| { + app.run("plugin.generate", json!({"id": "test.ui.generator2", "params": {}})).unwrap(); + app.session.doc().unwrap().selection.objects[0].0 + }; + + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let first = generate(&mut app); + let square = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [first, square["id"]]})).unwrap(); + assert!(!plugin::one_generated_selected(&app), "a generated art object and a rectangle"); + app.run("select.set", json!({"ids": [first]})).unwrap(); + assert!(plugin::one_generated_selected(&app)); + + app.run(plugin::EDIT_COMMAND, json!({})).unwrap(); + frame(&mut app); + set(&mut app, "size", json!(20)); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + let second = generate(&mut app); + let before = steps(&app); + app.ui.status.clear(); + try_confirm(&mut app).unwrap(); + assert!(kind(&app).is_none()); + assert!(app.ui.status.contains("the document it was prepared for is no longer active"), "{}", app.ui.status); + assert_eq!(art(&app, second), ["Small"]); + assert_eq!(steps(&app), before); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(art(&app, first), ["Small"]); + app.run("plugin.remove", json!({"id": "test.ui.generator2"})).unwrap(); +} diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b429cb6878..d0020042ba 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1212,6 +1212,7 @@ fn run_ui_part13(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::print::open_preset(app, p), "plugin.dialog" => crate::dialogs::plugin::open(app, p), + crate::dialogs::plugin::EDIT_COMMAND => crate::dialogs::plugin::open_edit(app, p), crate::dialogs::plugin::APPLY_LAST => crate::dialogs::plugin::apply_last(app), crate::dialogs::plugin::LAST => crate::dialogs::plugin::open_last(app), "ui.installPlugin" => io::install_plugin(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b187c20846..9bb0e2efff 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -403,6 +403,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "view.guides" | "view.grid" => !app.ui.view.trim_view, "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), + crate::dialogs::plugin::EDIT_COMMAND => crate::dialogs::plugin::one_generated_selected(app), // A filter may take no objects and add new ones, so no selection is needed. crate::dialogs::plugin::APPLY_LAST | crate::dialogs::plugin::LAST => { app.session.active().is_some() && crate::dialogs::plugin::last_filter(app).is_some() diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 9e7a4bf122..5e866c34bd 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2005,7 +2005,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns). On the web the dialog has no live preview, and every filter it runs, at once or on OK, runs in a Web Worker → {background: true, status}", + "{id: an object filter or generator plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns). On the web the filter's dialog has no live preview, and every filter it runs, at once or on OK, runs in a Web Worker → {background: true, status}. A generator draws new generated art at once when it takes no parameters or params are given (plugin.generate), else opens dialog `pluginGenerate` (a row per parameter; OK runs plugin.generate)", + ), + ( + "ui.editGeneratedArt", + "Edit Generated Art…", + "", + "{id?: a generated art object (default: the one selected)} Object › Plug-ins › Edit Generated Art…: open dialog `pluginGenerate` with the parameters the object was drawn with; OK runs plugin.editGenerated, which draws its art again as one undo step (none when nothing changed). An object whose generator isn't installed, or whose saved plug-in id, parameters, transforms or scales are damaged, is an error naming it, and its art stays as it is", ), ( "plugin.applyLastFilter", diff --git a/docs/mcp.md b/docs/mcp.md index e2eeaf98bd..d869b488b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14753,7 +14753,26 @@ the web it opens File › Open's picker) and adds it to Open Recent. With `path` on the desktop a picked file is read off the UI thread and the reply is `{background: true, status}`, and `file.cancelOpen` stops the importer. An importer with parameters, given no `params`, first asks for them in the `pluginImport` dialog. `params` holds the importer's parameters (their defaults when -omitted). A failing plug-in returns an error and leaves the document as it was (an export writes +omitted). A generator ([plug-ins](plugins.md#generators)) draws art from its parameters alone: +`plugin.generate {id, params?}` runs it and adds its art to the current layer as a new generated art object (a group +that keeps the plug-in's id and name, the parameters and the art), selected, as one undo step named after the plug-in, +and returns `{id, plugin}`. A parameter the manifest doesn't declare, a value of the wrong type, a number outside its +range and text past its `maxLength` are errors; the parameters kept are at most 64 KiB of JSON, and the art at most +16 MiB. `plugin.editGenerated {id?, params}` runs the generator of generated art object `id` (default: the selected +one) again with the saved parameters changed by `params` and replaces its art, placed as the object has been +transformed since it was drawn (stroke weights, effect distances and pattern tiles included), as one undo step named +Edit Generated Art; parameters that change nothing run nothing, make no undo step and return `changed: false`. An +object whose plug-in isn't installed or is a plug-in of another kind, or whose saved plug-in id, parameters, transforms or +scales are damaged, is an error (naming the plug-in when it is missing or of another kind), and its art stays as it is. `plugin.generatedInfo {id?}` +returns `{id, plugin, name, params, state, installed}`, with `state` `"intact"`, `"damaged"` or `"changed"` (its art +doesn't match the hash its file gave). `object.expand` makes a generated art object an ordinary group. The native file +keeps each object's plug-in id, name, parameters, transforms and scales and a SHA-256 of its art (a generated art object +inside another one's art is saved as plain art); `document.open` never runs a +plug-in, and its `warnings` name the plug-in of each object whose plug-in is missing or of another kind or whose art +changed, and say so once for objects with damaged fields. `plugin.run` of a generator is an error +that names `plugin.generate`. In the app, Object › Plug-ins lists the generators with the filters (`plugin.dialog {id}` +opens the `pluginGenerate` dialog for one with parameters), and Object › Plug-ins › Edit Generated Art… +(`ui.editGeneratedArt {id?}`) opens that dialog with a selected object's parameters. A failing plug-in returns an error and leaves the document as it was (an export writes no file, and an import opens no document). A filter whose manifest asks for a heavy budget (minutes rather than a minute, `budget: "heavy"` in its `plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` from a request. `plugin.run` diff --git a/docs/plugins.md b/docs/plugins.md index 9a2275ff08..ae8e4a5480 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -40,6 +40,9 @@ in `crates/engine/src/cmd/plugin.rs`). | `plugin.clearCache` | `{"id"?}` | Deletes every entry in the [cache](#settings-and-cache) of plug-in `id`, or of every installed plug-in; settings stay. Returns `{"cleared": [id], "bytesFreed"}`. | | `plugin.reload` | `{"path"?: "folder"}` (default: the preference folder) | Installs every `*.wasm` and `*.vcplugin` in a folder, the first 1,000 by file name; a bad module is reported and skipped, and so are an entry that is not a regular file, a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). Returns `{"folder", "loaded", "failed": [{file, error}], "leftOut"}`; `leftOut` counts the `*.wasm` and `*.vcplugin` files past the first 1,000, which were not tried. | | `plugin.retry` | `{"file"?}` (a file `plugin.list`'s `failed` names; default: every one) | Loads a plug-in file that [didn't load](#plug-ins-that-didnt-load) again, with the same checks as the load it failed in. Returns `{"retried": [{file, loaded, id?, error?}]}`. | +| `plugin.generate` | `{"id", "params"?: {…}}` | Runs a [generator](#generators) and adds its art to the current layer as a new generated art object, selected. One undo step named after the plug-in. Returns `{"id", "plugin"}`. | +| `plugin.editGenerated` | `{"id"?: object, "params": {…}}` (default: the selected generated art object) | Runs the object's generator again with the saved parameters changed by `params` and replaces its art, one undo step; parameters that change nothing run nothing and make no undo step. Returns `{"id", "plugin", "changed"}`. | +| `plugin.generatedInfo` | `{"id"?: object}` (default: the selected one) | `{"id", "plugin", "name", "params", "state", "installed"}`: `state` is `"intact"`, `"damaged"` (its saved plug-in id, parameters, transforms or scales can't be read) or `"changed"` (its art doesn't match the hash its file gave). | Live effects are applied like any effect: `effect.apply {"effect": "plugin.", "params": {…}}`, edited with `effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance. @@ -145,6 +148,49 @@ too (on the web this is how plug-ins get in). A heavy filter asks before it is i ([below](#heavy-filters)). A plug-in that lists permissions asks for them before it is installed ([below](#permissions)). +### Generators + +A plug-in of kind `generator` draws art from its parameters alone. Its art goes into a **generated art object**: a group that keeps the plug-in's id and name, the parameters the +art was drawn with and the art itself, so the art can be drawn again when the parameters change. + +- **Menus.** Installed generators are listed under **Object › Plug-ins** with the filters. One without parameters + draws its art at once; one with parameters opens a dialog generated from its schema, and OK draws the art. + **Object › Plug-ins › Edit Generated Art…** (`ui.editGeneratedArt`), enabled while one generated art object is + selected, opens the same dialog with the parameters the object was drawn with, and OK draws it again. +- **Runs.** The generator is given `{"objects": []}` and its parameters with `_context.mode` `"generate"` + ([Parameters](#parameters)), and returns new objects as a filter does (`{"objects": [...]}`, each without `id`), or + `{"error": "…"}` to decline. It runs under its own instruction budget and the Plug-in Instruction Budget preference, + and Cancel stops it as it stops a filter. Its output is checked before the document changes: an output with no + objects, a key other than `objects` and `error`, an object with an `id`, an object the filter checks refuse, art + outside the canvas and art past 16 MiB of JSON are errors, and the document is left as it was. +- **Parameters.** Given parameters are checked against the manifest: a name it doesn't declare, a value of the wrong + type, a number outside its range (each number of a `numberList` too) and text longer than its `maxLength` are + errors, and parameters left out take their defaults. The parameters a generated art object keeps are at most 64 KiB + of JSON. `plugin.editGenerated` + checks the parameters it is given the same way and takes the others from the object; saved parameters the plug-in + no longer declares are dropped, and saved values outside a narrower range are brought into it. +- **Editing.** Drawing the art again replaces the group's art as one undo step named **Edit Generated Art**, placed + as the object has been moved, scaled, rotated, reflected or sheared since it was drawn. The new art's stroke weights, + dashes and effect distances are scaled as Scale Strokes & Effects scaled the old art's, and its pattern tiles are + moved as Transform Patterns moved them. Object › Expand makes a generated art object an ordinary group of its art. A + generated art object can't be drawn again while its plug-in isn't installed or is installed as a plug-in of another + kind, or while its saved fields are damaged. The error names the plug-in when it is missing or of another kind, and + the object's art stays as it is. +- **Files.** The native file keeps each generated art object's plug-in id, its name (at most 64 characters), the + parameters, the transform since it was drawn, what its strokes and effects were scaled by and its pattern tiles + transformed by (`strokeScale`, `effectScale`, `patternTransform`), and a SHA-256 of its art's JSON (`generated`). + Opening a file never runs a plug-in: each object is drawn from the art the file holds. When its plug-in isn't + installed or is a plug-in of another kind, when its saved plug-in id is not a plug-in id or its parameters, + transforms or scales can't be read, or when its art doesn't match the hash, the art stays as the file has it and the + open's warnings say so. The warnings name the plug-in, except for damaged fields, where they say that a generated + art object's plug-in id or parameters are damaged. Saving writes the hash of the art as it is then, and an object whose + saved fields were damaged is saved with `damaged: true`, so it still can't be drawn again after the file is opened + again. A generated art object inside another one's art is saved as plain art, without its own settings. A file that + has settings on such an object anyway opens with them left out, and the outer object reads as `changed`. +- **Permissions.** A generator implies `doc.write`, and a list of `permissions` must hold it. + +These rules are VectorCraft's own. + ### Commands A filter or a live effect may declare commands of its own in its manifest (`commands`, [below](#manifest)). Each @@ -352,7 +398,7 @@ capability model proposed for PhotoCraft plug-ins | Permission | Kinds | What it allows | |---|---|---| | `doc.read` | filter, effect, exporter | Read the objects it is given, and the [document information](#document-information) its `context` lists. | -| `doc.write` | filter, effect with `commands` | Change, add and delete objects in the document. | +| `doc.write` | filter, effect with `commands`, generator | Change, add and delete objects in the document. | | `state` | filter, effect with `commands` | Keep data of its own with the document (`documentData`). | | `effect.render` | effect | Change how the objects its effect is applied to are drawn. | | `export.write` | exporter | Write the document as a file in its own format. | @@ -364,11 +410,11 @@ capability model proposed for PhotoCraft plug-ins - A manifest without `permissions` gets the ones its kind implies, as plug-ins did before the key existed: a filter `doc.read`, `doc.write` and `state`; an effect `doc.read` and `effect.render`, and also `doc.write` and `state` - when it declares [commands](#commands); an exporter `doc.read` and `export.write`; an importer `import.read`. Such a - plug-in installs without a prompt. This rule is VectorCraft's own. A filter whose list is empty may do none of + when it declares [commands](#commands); an exporter `doc.read` and `export.write`; an importer `import.read`; a generator `doc.write`. + Such a plug-in installs without a prompt. This rule is VectorCraft's own. A filter whose list is empty may do none of these, and also installs without a prompt. -- An effect, an exporter or an importer that lists permissions lists all of its implied ones (`doc.read` and - `effect.render`; `doc.read` and `export.write`; `import.read`). An effect with commands may add `doc.write` and +- An effect, an exporter, an importer or a generator that lists permissions lists all of its implied ones (`doc.read` + and `effect.render`; `doc.read` and `export.write`; `import.read`; `doc.write`). An effect with commands may add `doc.write` and `state`, which only its commands use. A filter may list any of its three, and `commands` with a `commandAllowlist`. Any kind may add `progress`, `settings` and `cache`, which no kind implies. An unknown name, a name listed twice, a name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` @@ -788,8 +834,9 @@ the module's start function, in a run that isn't a filter's run on a document, o - `id`: 1–64 characters from `A-Z a-z 0-9 . _ -` (reverse-DNS recommended). Installing a module with the same id replaces the old one. A live effect's effect id is `plugin.`. - `name`: the menu label, or an exporter's or importer's format name in Export As, Open and Open With (1–64 printable - characters). `kind`: `"filter"` (object filter), `"effect"` (live effect), `"exporter"` or `"importer"`. Exporters - and importers came after the first ABI v1 hosts, which refuse the kind when the plug-in is installed. + characters). `kind`: `"filter"` (object filter), `"effect"` (live effect), `"exporter"`, `"importer"` or + `"generator"` ([generators](#generators)). Exporters, importers and generators came after the first ABI v1 hosts, + which refuse the kind when the plug-in is installed. - `budget` (filters only): `"light"` (the default) or `"heavy"`, for work that takes minutes ([heavy filters](#heavy-filters)). Hosts from before it ignore the key, so there the filter gets a light run's budget. - `api`: the plug-in API level, `1` when left out. `permissions`: what the plug-in may do, a list of names diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e2727928a..760036593e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2796,6 +2796,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. +- **Generator plug-ins (G17):** a WebAssembly plug-in of kind `generator` draws art from its parameters into a generated art object, a group that keeps the plug-in's id, the parameters and the art, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_plugin_group_suite) describes for plug-in groups whose art the plug-in draws and redraws. Object › Plug-ins lists generators with the filters; Edit Generated Art… and `plugin.editGenerated` draw the art again from changed parameters as one undo step (none when nothing changes), placed as the object has been transformed since, and Object › Expand makes it an ordinary group. Parameters are checked against the manifest (unknown names, wrong types, out-of-range numbers and long text are errors) and kept up to 64 KiB, and the art up to 16 MiB. The native file keeps the plug-in id, parameters, transform and a SHA-256 of the art; opening never runs a plug-in, and an object whose plug-in is missing, whose saved fields are damaged or whose art doesn't match its hash keeps its art and is named in the open's warnings. The limits and the file fields are VectorCraft's own. Regressions: `crates/engine/tests/plugin_generate.rs`, `crates/engine/tests/import_fuzz.rs` (`generated_art_saved_fields_never_panic_and_keep_the_art`), `crates/doc/src/generated.rs`, `crates/ui-egui/src/dialogs/tests_plugin_generate.rs`. Scores and hours unchanged. - **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged.