From 6857811e1f20a556098f7db96f972a787e73739f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:18:35 -0800 Subject: [PATCH 1/8] Plug-ins: generators draw generated art objects that keep their parameters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plug-in of the new kind `generator` draws art from its parameters alone. plugin.generate runs it and adds its art as a generated art object: a group that keeps the plug-in's id and name, the parameters and the transform since the art was drawn. Object › Plug-ins lists each generator, and Object › Plug-ins › Edit Generated Art… (plugin.editGenerated) runs it again with changed parameters and replaces the art as one undo step, placed, stroke-scaled and pattern-transformed as the old art was. Parameters that change nothing run nothing and make no undo step. Object › Expand makes the object an ordinary group. plugin.generatedInfo reports an object's plug-in, parameters and state. - Given parameters are checked against the manifest: an undeclared name, a number outside its range (each number of a numberList too) and text past its maxLength are errors. Parameters are capped at 64 KiB of JSON, art at 16 MiB, and the output is checked before the document changes. - The native file keeps the plug-in id, name, parameters, transforms, scales and a SHA-256 of the art's JSON. Opening a file never runs a plug-in: a missing plug-in, a plug-in of another kind, a damaged saved field or a hash mismatch keeps the art as the file has it. The open's warnings name the plug-in, except for damaged fields, which get one warning that names no plug-in. A damaged object stays damaged when saved again. - plugin.run of a generator is an error naming plugin.generate. - import_fuzz replaces each saved field with arbitrary JSON. Docs: docs/plugins.md (Generators), docs/mcp.md, docs/target-app-parity.md. --- Cargo.lock | 1 + crates/doc/Cargo.toml | 2 + crates/doc/src/generated.rs | 389 ++++++++++++++++++ crates/doc/src/lib.rs | 1 + crates/doc/src/mem.rs | 4 + crates/doc/src/node/extras.rs | 4 + crates/doc/src/node/ops.rs | 22 +- crates/doc/src/node/wire.rs | 6 + crates/doc/src/pattern.rs | 6 +- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/expand.rs | 8 +- crates/engine/src/cmd/fileio/load.rs | 2 + crates/engine/src/cmd/plugin.rs | 7 +- crates/engine/src/cmd/plugin_generated.rs | 264 ++++++++++++ crates/engine/tests/import_fuzz.rs | 85 ++++ crates/engine/tests/plugin_generate.rs | 315 ++++++++++++++ crates/plugins/src/generate.rs | 207 ++++++++++ crates/plugins/src/lib.rs | 4 +- crates/plugins/src/manifest.rs | 32 +- crates/plugins/src/permissions.rs | 6 +- crates/plugins/src/wat.rs | 5 + crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/dialogs/plugin.rs | 88 +++- .../src/dialogs/tests_plugin_generate.rs | 78 ++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 20 + crates/ui-egui/src/i18n/cs.tsv | 20 + crates/ui-egui/src/i18n/da.tsv | 20 + crates/ui-egui/src/i18n/de.tsv | 20 + crates/ui-egui/src/i18n/el.tsv | 20 + crates/ui-egui/src/i18n/es.tsv | 20 + crates/ui-egui/src/i18n/fi.tsv | 20 + crates/ui-egui/src/i18n/fr.tsv | 20 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 20 + crates/ui-egui/src/i18n/hu.tsv | 20 + crates/ui-egui/src/i18n/id.tsv | 20 + crates/ui-egui/src/i18n/it.tsv | 20 + crates/ui-egui/src/i18n/ja.tsv | 20 + crates/ui-egui/src/i18n/ka.tsv | 20 + crates/ui-egui/src/i18n/ko.tsv | 20 + crates/ui-egui/src/i18n/nl.tsv | 20 + crates/ui-egui/src/i18n/pl.tsv | 20 + crates/ui-egui/src/i18n/pt-br.tsv | 20 + crates/ui-egui/src/i18n/ru.tsv | 20 + crates/ui-egui/src/i18n/sv.tsv | 20 + crates/ui-egui/src/i18n/tests.rs | 27 ++ crates/ui-egui/src/i18n/tr.tsv | 20 + crates/ui-egui/src/i18n/uk.tsv | 20 + crates/ui-egui/src/i18n/vi.tsv | 20 + crates/ui-egui/src/i18n/zh-hans.tsv | 20 + crates/ui-egui/src/i18n/zh-hant.tsv | 20 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/state.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 8 +- docs/mcp.md | 19 +- docs/plugins.md | 59 ++- docs/target-app-parity.md | 1 + 59 files changed, 2133 insertions(+), 34 deletions(-) create mode 100644 crates/doc/src/generated.rs create mode 100644 crates/engine/src/cmd/plugin_generated.rs create mode 100644 crates/engine/tests/plugin_generate.rs create mode 100644 crates/plugins/src/generate.rs create mode 100644 crates/ui-egui/src/dialogs/tests_plugin_generate.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..b42ce353e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6866,6 +6866,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "sha2", "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..5e5094cb4a --- /dev/null +++ b/crates/doc/src/generated.rs @@ -0,0 +1,389 @@ +//! 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. + +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'-')) +} + +/// 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. +pub fn art_hash(children: &[std::sync::Arc]) -> String { + use sha2::{Digest, Sha256}; + let bytes = serde_json::to_vec(children).unwrap_or_default(); + Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// The bytes `children` take written as JSON ([`MAX_ART_BYTES`]). +pub fn art_bytes(children: &[std::sync::Arc]) -> usize { + serde_json::to_vec(children).map_or(usize::MAX, |b| b.len()) +} + +/// 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 above 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. +pub(crate) fn read(v: Value, kind: &NodeKind) -> Option> { + let NodeKind::Group { children, .. } = kind else { return None }; + 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 = 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() + } + + /// 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)); + } + + /// 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.0)), + ("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))); + // 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 5a9b27b304..705fbc9feb 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 3519986512..f9467cf0e3 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -285,6 +285,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 439d3605fd..ac4eec70ab 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -92,6 +92,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. @@ -124,6 +127,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 20dae6ec4b..acdaa82642 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -517,19 +517,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 60a3c75d79..fac3a2e1ca 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -60,6 +60,7 @@ impl Serialize for Node { is_default(&e.warp_piece), is_default(&e.clip_pieces), e.image_quad.is_none(), + e.generated.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -108,6 +109,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", &e.generated.as_deref().map(|g| crate::generated::Wire::of(g, self))); st.end() } } @@ -261,6 +263,9 @@ 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)] + generated: Option, } /// A distorted image's corners as a file holds them: a list of exactly four points, else none (the @@ -486,6 +491,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, &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 4f0d2bad63..f625a50560 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; @@ -401,6 +402,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 1818816842..255763bb97 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -624,6 +624,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 2a1b8c8b40..43e0dc82cd 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -93,7 +93,7 @@ pub fn describe(p: &Plugin) -> Value { v["format"] = json!(export::format_id(&m.id)); v["extensions"] = json!(m.extensions); } - Kind::Filter => {} + Kind::Filter | Kind::Generator => {} } if m.budget == Budget::Heavy { v["budget"] = json!("heavy"); @@ -202,6 +202,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) } @@ -1270,7 +1273,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"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), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", 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..8d0a6ebaa5 --- /dev/null +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -0,0 +1,264 @@ +//! 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![]; + doc.walk(|n| { + 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); + } + }); + 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 => { + let mut picked = st.selection.objects.iter().filter_map(|id| one(*id)); + match (picked.next(), picked.next()) { + (Some(g), None) => Some(g), + _ => 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 b655ed0eb5..5c51eaaa53 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2960,6 +2960,91 @@ 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(); + 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 { + let mut found = vec![]; + l.doc.walk(|n| { + if let Some(g) = n.extras().generated.as_deref() { + found.push((g.plugin.clone(), serde_json::to_value(&n.kind).unwrap())); + } + }); + for (plugin, kind) in &found { + prop_assert!(plugin.is_empty() || vectorcraft_doc::generated::valid_id(plugin), "{plugin:?}"); + prop_assert_eq!(kind, &art); + } + } + 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..49fbe7a908 --- /dev/null +++ b/crates/engine/tests/plugin_generate.rs @@ -0,0 +1,315 @@ +//! 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}"); +} + +/// 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"]); +} + +/// 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/plugins/src/generate.rs b/crates/plugins/src/generate.rs new file mode 100644 index 0000000000..9a0077802b --- /dev/null +++ b/crates/plugins/src/generate.rs @@ -0,0 +1,207 @@ +//! 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. +fn int_outside(v: &Value, min: i64, max: i64) -> bool { + match v.as_i64() { + Some(i) => !(min..=max).contains(&i), + None => v.is_u64() || v.as_f64().is_some_and(|f| !(min as f64..=max as f64).contains(&f.round())), + } +} + +/// 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}"); + } + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..3ea5f8b3fc 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 @@ -38,6 +39,7 @@ pub mod deferred; pub mod dialog; pub mod effect; pub mod export; +pub mod generate; pub mod host; pub mod import; pub mod manifest; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..d09fd66838 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -47,6 +47,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 { @@ -56,6 +60,7 @@ impl Kind { Kind::Effect => "effect", Kind::Exporter => "exporter", Kind::Importer => "importer", + Kind::Generator => "generator", } } } @@ -437,6 +442,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()?; @@ -525,7 +533,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 { @@ -1050,6 +1058,28 @@ 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"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an /// exporter has an export's budget, so they can't. Light, the default, isn't written back. #[test] diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..ccddcf0942 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -147,6 +147,7 @@ impl Permission { Kind::Effect => &[Permission::DocRead, Permission::EffectRender], Kind::Exporter => &[Permission::DocRead, Permission::ExportWrite], Kind::Importer => &[Permission::ImportRead], + Kind::Generator => &[Permission::DocWrite], } } @@ -163,11 +164,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 936d5d9e53..a008c63b89 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -193,6 +193,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 a24755ab12..51823252cc 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -459,6 +459,7 @@ registry! { Plugin: [plugin::KIND] => plugin::SPEC, PluginExport: [plugin::EXPORT_KIND] => plugin::EXPORT_SPEC, PluginImport: [plugin::IMPORT_KIND] => plugin::IMPORT_SPEC, + PluginGenerate: [plugin::GENERATE_KIND] => plugin::GENERATE_SPEC, PluginInstall: [plugin::INSTALL_KIND] => plugin::INSTALL_SPEC, ScriptCheck: [script_check::KIND] => script_check::SPEC, ScriptRun: [script_run::KIND] => script_run::SPEC, @@ -1118,6 +1119,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 706188f6da..9b250df5c8 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -1,7 +1,10 @@ //! 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 +//! 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 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 dialog `plugin`: one field per //! declared parameter (fields named after them; `__plugin` is the plug-in id) with a live //! Preview, and OK keeps the run as one undo step (`plugin.run`). A filter without parameters runs @@ -70,12 +73,12 @@ fn with_commands(plugin: &Plugin, own: Item) -> Item { Item::Sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) } -/// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then -/// Install Plug-in… and Reload Plug-ins. +/// Object › Plug-ins: the installed object filters (each with its commands, if it has any) and +/// generators, then Edit Generated Art…, Install Plug-in… and Reload Plug-ins. 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, Item::Cmd(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) .collect(); if items.is_empty() { @@ -83,6 +86,7 @@ pub fn object_menu() -> Vec { } items.extend([ Item::Sep, + Item::Cmd(EDIT_GENERATED, EDIT_COMMAND, Value::Null), Item::Cmd("Install Plug-in…", "ui.installPlugin", Value::Null), Item::Cmd("Reload Plug-ins", "plugin.reload", Value::Null), ]); @@ -120,14 +124,22 @@ pub fn effect_menu() -> Option { (!items.is_empty()).then_some(Item::Sub("Plug-ins", items)) } -/// `plugin.dialog {id, params?}`: run filter `id` at once when it takes no parameters or `params` -/// are given, else open its dialog prefilled 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 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").filter(|v| v.as_object().is_some_and(|o| !o.is_empty())); + if m.params.is_empty() || given.is_some() { + return app.run(GENERATE, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); + } + app.ui.dialog = Some(Dialog { kind: GENERATE_KIND.into(), fields: fields_for(m) }); + 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)), @@ -270,6 +282,68 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } } +/// The dialog kind of a generator's parameters: for new generated art, or (with `__edit`, the +/// object's id) for drawing a generated art object again. +pub const GENERATE_KIND: &str = "pluginGenerate"; + +const GENERATE: &str = "plugin.generate"; + +/// Object › Plug-ins › Edit Generated Art…, and the UI command it runs. +pub const EDIT_GENERATED: &str = "Edit Generated Art…"; +pub const EDIT_COMMAND: &str = "ui.editGeneratedArt"; + +/// Headed by the plug-in's name, as it is; OK draws the art. +pub(super) const GENERATE_SPEC: DialogSpec = + DialogSpec { heading: |d| d.str("__label"), body: export_body, confirm: generate_confirm, max_width: Some(420.0), ..DialogSpec::FORM }; + +/// `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 m = plugin.manifest(); + let mut fields = fields_for(m); + if let Some(saved) = info.get("params").and_then(Value::as_object) { + for (k, v) in saved.iter().filter(|(k, _)| m.params.iter().any(|(name, _)| name == *k)) { + fields.insert(k.clone(), v.clone()); + } + } + fields.insert("__edit".into(), id); + app.ui.dialog = Some(Dialog { kind: GENERATE_KIND.into(), fields }); + Ok(Value::Null) +} + +/// Does the selection hold exactly one generated art object, which Edit Generated Art… edits? +pub fn one_generated_selected(app: &VectorcraftApp) -> bool { + app.session + .active() + .is_some_and(|st| st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some_and(|n| n.extras().generated.is_some())).count() == 1) +} + +/// OK: draws new generated art (`plugin.generate`), or draws the object of `__edit` again +/// (`plugin.editGenerated`), as one undo step; the dialog closes once it is drawn. +fn generate_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let r = match d.fields.get("__edit").filter(|v| !v.is_null()) { + Some(id) => app.run("plugin.editGenerated", json!({"id": id, "params": form::params(d)})), + None => app.run(GENERATE, json!({"id": d.str("__plugin"), "params": form::params(d)})), + }; + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The dialog kind of an exporter's parameters, after Export As picked the file. pub const EXPORT_KIND: &str = "pluginExport"; 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..9406f3d1c3 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs @@ -0,0 +1,78 @@ +//! 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. The test installs a +//! generator of its own and removes it: plug-ins are process-wide. + +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +use super::tests_export::{frame, kind, set}; +use super::*; +use crate::Services; +use crate::menus::Item; + +/// 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]}]}]}}]}"#; + +/// 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() +} + +#[test] +fn object_plug_ins_draws_and_edits_generated_art() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + let manifest = tpl::generator("test.ui.generator", 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(); + let menu = plugin::object_menu(); + let listed = menu + .iter() + .any(|i| matches!(i, Item::Cmd(label, "plugin.dialog", p) if *label == "Test test.ui.generator…" && p["id"] == "test.ui.generator")); + assert!(listed, "{menu:?}"); + assert!(menu.iter().any(|i| matches!(i, Item::Cmd(plugin::EDIT_GENERATED, plugin::EDIT_COMMAND, _))), "{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), Some(plugin::GENERATE_KIND)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(plugin::one_generated_selected(&app)); + let st = app.session.doc().unwrap(); + let id = st.selection.objects[0].0; + let steps = st.history.undo.len(); + 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), Some(plugin::GENERATE_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.fields.get("size"), d.fields.get("__edit")), (Some(&json!(10)), Some(&json!(id)))); + frame(&mut app); + set(&mut app, "size", json!(20)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(art(&app, id), ["Big"]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(app.session.doc().unwrap().history.undo.last().map(|s| s.label.as_str()), Some("Edit Generated Art")); + + // A bad value keeps the dialog open with the error, and the art as it is. + app.run(plugin::EDIT_COMMAND, json!({})).unwrap(); + set(&mut app, "size", json!(500)); + assert!(confirm(&mut app).is_err()); + assert_eq!(art(&app, id), ["Big"]); + app.ui.dialog = None; + + // 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_eq!(kind(&app), None); + assert_eq!(art(&app, id), ["Big"]); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..8ded8dc1ef 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7767,6 +7767,10 @@ breakText Glyphs Глифи 3D Box 3D кутия 3D Box Tool Инструмент за 3D кутия +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Редактиране на генерирана графика… + Edit Generated Art Редактиране на генерирана графика + # Importer plug-ins (File › Open With, document.open) Open With Отваряне с No importer plug-ins installed Няма инсталирани плъгини за импортиране diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..296a7885af 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7822,6 +7822,10 @@ shape Open Otvoren 3D Box 3D kutija 3D Box Tool Alat za 3D kutiju +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Uredi generisanu grafiku… + Edit Generated Art Uredi generisanu grafiku + # Importer plug-ins (File › Open With, document.open) Open With Otvori pomoću No importer plug-ins installed Nisu instalirani dodaci za uvoz diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..71b5ff75e5 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8648,6 +8648,26 @@ breakText Glyphs Glifs 3D Box Caixa 3D 3D Box Tool Eina Caixa 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Edita la il·lustració generada… + Edit Generated Art Edita la il·lustració generada +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is «{name}» ({id}) no està instal·lat, així que la seva il·lustració generada no es pot tornar a dibuixar: la il·lustració es queda tal com és +@msg 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 l’identificador de complement o els paràmetres d’un objecte d’il·lustració generada estan malmesos, així que la seva il·lustració no es pot tornar a dibuixar: la il·lustració es queda tal com és +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is la il·lustració generada de «{name}» ({id}) no coincideix amb el hash del seu fitxer: la il·lustració es queda tal com és +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps la il·lustració del generador ocupa més dels {MAX_ART_BYTES} bytes que desa un objecte d’il·lustració generada +@msg select one generated art object seleccioneu un objecte d’il·lustració generada +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` és un generador: dibuixeu-ne la il·lustració amb plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` és un complement del tipus `{_2}`, no un generador +@msg `{k}` is not a parameter of `{_1}` `{k}` no és un paràmetre de `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` ha de tenir com a màxim {max_length} caràcters +@msg `{k}` must be from {min} to {max} `{k}` ha d’estar entre {min} i {max} +@msg each number of `{k}` must be from {min} to {max} cada nombre de `{k}` ha d’estar entre {min} i {max} +@msg a generator always gets the usual budget: leave `budget` out un generador sempre rep el pressupost habitual: ometeu `budget` +@msg a generator returns `objects`, not `{key}` un generador retorna `objects`, no `{key}` +@msg a generator's objects are new: leave `id` out els objectes d’un generador són nous: ometeu `id` +@msg the generator returned no objects el generador no ha retornat cap objecte +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps els paràmetres ocupen més dels {MAX_PARAMS_BYTES} bytes que desa un objecte d’il·lustració generada + # Importer plug-ins (File › Open With, document.open) Open With Obre amb No importer plug-ins installed No hi ha complements d’importació instal·lats diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..c2f1e94ba1 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8629,6 +8629,26 @@ breakText Glyphs Glyfy 3D Box 3D kvádr 3D Box Tool Nástroj 3D kvádr +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Upravit generovanou kresbu… + Edit Generated Art Upravit generovanou kresbu +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}“ ({id}) není nainstalován, takže jeho generovanou kresbu nelze znovu vykreslit: kresba zůstane, jak je +@msg 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 ID zásuvného modulu nebo parametry objektu generované kresby jsou poškozené, takže jeho kresbu nelze znovu vykreslit: kresba zůstane, jak je +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is generovaná kresba „{name}“ ({id}) neodpovídá hashi uvedenému v jejím souboru: kresba zůstane, jak je +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps kresba generátoru je větší než {MAX_ART_BYTES} bajtů, které objekt generované kresby uchová +@msg select one generated art object vyberte jeden objekt generované kresby +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` je generátor: jeho kresbu vykreslíte pomocí plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` je zásuvný modul druhu `{_2}`, ne generátor +@msg `{k}` is not a parameter of `{_1}` `{k}` není parametr `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` smí mít nejvýše {max_length} znaků +@msg `{k}` must be from {min} to {max} `{k}` musí být od {min} do {max} +@msg each number of `{k}` must be from {min} to {max} každé číslo v `{k}` musí být od {min} do {max} +@msg a generator always gets the usual budget: leave `budget` out generátor vždy dostane obvyklý rozpočet: vynechte `budget` +@msg a generator returns `objects`, not `{key}` generátor vrací `objects`, ne `{key}` +@msg a generator's objects are new: leave `id` out objekty generátoru jsou nové: vynechte `id` +@msg the generator returned no objects generátor nevrátil žádné objekty +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametry jsou větší než {MAX_PARAMS_BYTES} bajtů, které objekt generované kresby uchová + # Importer plug-ins (File › Open With, document.open) Open With Otevřít pomocí No importer plug-ins installed Nejsou nainstalovány žádné importní zásuvné moduly diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..f4afddd04c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10685,6 +10685,26 @@ breakText Glyphs Glyffer 3D Box 3D-boks 3D Box Tool 3D-boksværktøj +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Rediger genereret grafik… + Edit Generated Art Rediger genereret grafik +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is »{name}« ({id}) er ikke installeret, så dens genererede grafik kan ikke tegnes igen: grafikken forbliver, som den er +@msg 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 plug-in-id'et eller parametrene for et genereret grafikobjekt er beskadiget, så dets grafik kan ikke tegnes igen: grafikken forbliver, som den er +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is den genererede grafik fra »{name}« ({id}) passer ikke med hashen i dens fil: grafikken forbliver, som den er +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps generatorens grafik er større end de {MAX_ART_BYTES} byte, som et genereret grafikobjekt gemmer +@msg select one generated art object marker ét genereret grafikobjekt +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` er en generator: tegn dens grafik med plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` er et plug-in af typen `{_2}`, ikke en generator +@msg `{k}` is not a parameter of `{_1}` `{k}` er ikke en parameter for `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` må højst være {max_length} tegn +@msg `{k}` must be from {min} to {max} `{k}` skal være fra {min} til {max} +@msg each number of `{k}` must be from {min} to {max} hvert tal i `{k}` skal være fra {min} til {max} +@msg a generator always gets the usual budget: leave `budget` out en generator får altid det sædvanlige budget: udelad `budget` +@msg a generator returns `objects`, not `{key}` en generator returnerer `objects`, ikke `{key}` +@msg a generator's objects are new: leave `id` out en generators objekter er nye: udelad `id` +@msg the generator returned no objects generatoren returnerede ingen objekter +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametrene er større end de {MAX_PARAMS_BYTES} byte, som et genereret grafikobjekt gemmer + # Importer plug-ins (File › Open With, document.open) Open With Åbn med No importer plug-ins installed Ingen import-plug-ins installeret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..ab3cd14a2f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8254,6 +8254,26 @@ breakText Glyphs Glyphen 3D Box 3D-Quader 3D Box Tool 3D-Quader-Werkzeug +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Generierte Grafik bearbeiten… + Edit Generated Art Generierte Grafik bearbeiten +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}“ ({id}) ist nicht installiert, daher kann seine generierte Grafik nicht neu gezeichnet werden: Die Grafik bleibt, wie sie ist +@msg 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 die Plug-in-ID oder die Parameter eines generierten Grafikobjekts sind beschädigt, daher kann seine Grafik nicht neu gezeichnet werden: Die Grafik bleibt, wie sie ist +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is die generierte Grafik von „{name}“ ({id}) passt nicht zum Hash aus ihrer Datei: Die Grafik bleibt, wie sie ist +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps die Grafik des Generators ist größer als die {MAX_ART_BYTES} Byte, die ein generiertes Grafikobjekt aufnimmt +@msg select one generated art object Wählen Sie ein generiertes Grafikobjekt aus +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` ist ein Generator: Zeichnen Sie seine Grafik mit plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` ist ein Plug-in der Art `{_2}`, kein Generator +@msg `{k}` is not a parameter of `{_1}` `{k}` ist kein Parameter von `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` darf höchstens {max_length} Zeichen lang sein +@msg `{k}` must be from {min} to {max} `{k}` muss zwischen {min} und {max} liegen +@msg each number of `{k}` must be from {min} to {max} jede Zahl in `{k}` muss zwischen {min} und {max} liegen +@msg a generator always gets the usual budget: leave `budget` out ein Generator erhält immer das übliche Budget: Lassen Sie `budget` weg +@msg a generator returns `objects`, not `{key}` ein Generator gibt `objects` zurück, nicht `{key}` +@msg a generator's objects are new: leave `id` out die Objekte eines Generators sind neu: Lassen Sie `id` weg +@msg the generator returned no objects der Generator hat keine Objekte zurückgegeben +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps die Parameter sind größer als die {MAX_PARAMS_BYTES} Byte, die ein generiertes Grafikobjekt aufnimmt + # Importer plug-ins (File › Open With, document.open) Open With Öffnen mit No importer plug-ins installed Keine Import-Plug-ins installiert diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..808fb91f33 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8620,6 +8620,26 @@ breakText Glyphs Γλύφοι 3D Box Κουτί 3D 3D Box Tool Εργαλείο κουτιού 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Επεξεργασία παραγόμενου γραφικού… + Edit Generated Art Επεξεργασία παραγόμενου γραφικού +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is το «{name}» ({id}) δεν είναι εγκατεστημένο, οπότε το παραγόμενο γραφικό του δεν μπορεί να σχεδιαστεί ξανά: το γραφικό μένει όπως είναι +@msg 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 το αναγνωριστικό προσθέτου ή οι παράμετροι ενός αντικειμένου παραγόμενου γραφικού είναι κατεστραμμένα, οπότε το γραφικό του δεν μπορεί να σχεδιαστεί ξανά: το γραφικό μένει όπως είναι +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is το παραγόμενο γραφικό του «{name}» ({id}) δεν ταιριάζει με το hash του αρχείου του: το γραφικό μένει όπως είναι +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps το γραφικό της γεννήτριας είναι μεγαλύτερο από τα {MAX_ART_BYTES} byte που κρατά ένα αντικείμενο παραγόμενου γραφικού +@msg select one generated art object επιλέξτε ένα αντικείμενο παραγόμενου γραφικού +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} το `{_1}` είναι γεννήτρια: σχεδιάστε το γραφικό της με plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator το `{_1}` είναι πρόσθετο τύπου `{_2}`, όχι γεννήτρια +@msg `{k}` is not a parameter of `{_1}` το `{k}` δεν είναι παράμετρος του `{_1}` +@msg `{k}` must be at most {max_length} characters το `{k}` πρέπει να έχει το πολύ {max_length} χαρακτήρες +@msg `{k}` must be from {min} to {max} το `{k}` πρέπει να είναι από {min} έως {max} +@msg each number of `{k}` must be from {min} to {max} κάθε αριθμός του `{k}` πρέπει να είναι από {min} έως {max} +@msg a generator always gets the usual budget: leave `budget` out μια γεννήτρια παίρνει πάντα τον συνηθισμένο προϋπολογισμό: παραλείψτε το `budget` +@msg a generator returns `objects`, not `{key}` μια γεννήτρια επιστρέφει `objects`, όχι `{key}` +@msg a generator's objects are new: leave `id` out τα αντικείμενα μιας γεννήτριας είναι νέα: παραλείψτε το `id` +@msg the generator returned no objects η γεννήτρια δεν επέστρεψε κανένα αντικείμενο +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps οι παράμετροι είναι μεγαλύτερες από τα {MAX_PARAMS_BYTES} byte που κρατά ένα αντικείμενο παραγόμενου γραφικού + # Importer plug-ins (File › Open With, document.open) Open With Άνοιγμα με No importer plug-ins installed Δεν έχουν εγκατασταθεί πρόσθετα εισαγωγής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..34367eae4f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8606,6 +8606,26 @@ breakText Glyphs Glifos 3D Box Caja 3D 3D Box Tool Herramienta Caja 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Editar ilustración generada… + Edit Generated Art Editar ilustración generada +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is «{name}» ({id}) no está instalado, así que su ilustración generada no se puede volver a dibujar: la ilustración se queda como está +@msg 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 el ID de plugin o los parámetros de un objeto de ilustración generada están dañados, así que su ilustración no se puede volver a dibujar: la ilustración se queda como está +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is la ilustración generada de «{name}» ({id}) no coincide con el hash de su archivo: la ilustración se queda como está +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps la ilustración del generador ocupa más de los {MAX_ART_BYTES} bytes que guarda un objeto de ilustración generada +@msg select one generated art object seleccione un objeto de ilustración generada +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` es un generador: dibuje su ilustración con plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` es un plugin de tipo `{_2}`, no un generador +@msg `{k}` is not a parameter of `{_1}` `{k}` no es un parámetro de `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` debe tener como máximo {max_length} caracteres +@msg `{k}` must be from {min} to {max} `{k}` debe estar entre {min} y {max} +@msg each number of `{k}` must be from {min} to {max} cada número de `{k}` debe estar entre {min} y {max} +@msg a generator always gets the usual budget: leave `budget` out un generador siempre recibe el presupuesto habitual: omita `budget` +@msg a generator returns `objects`, not `{key}` un generador devuelve `objects`, no `{key}` +@msg a generator's objects are new: leave `id` out los objetos de un generador son nuevos: omita `id` +@msg the generator returned no objects el generador no devolvió ningún objeto +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps los parámetros ocupan más de los {MAX_PARAMS_BYTES} bytes que guarda un objeto de ilustración generada + # Importer plug-ins (File › Open With, document.open) Open With Abrir con No importer plug-ins installed No hay plugins de importación instalados diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..ba21749780 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8701,6 +8701,26 @@ breakText Glyphs Merkit 3D Box 3D-laatikko 3D Box Tool 3D-laatikkotyökalu +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Muokkaa luotua grafiikkaa… + Edit Generated Art Muokkaa luotua grafiikkaa +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is ”{name}” ({id}) ei ole asennettuna, joten sen luomaa grafiikkaa ei voi piirtää uudelleen: grafiikka säilyy ennallaan +@msg 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 luodun grafiikkaobjektin laajennustunnus tai parametrit ovat vahingoittuneet, joten sen grafiikkaa ei voi piirtää uudelleen: grafiikka säilyy ennallaan +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is laajennuksen ”{name}” ({id}) luoma grafiikka ei vastaa sen tiedoston tiivistettä: grafiikka säilyy ennallaan +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps generaattorin grafiikka on suurempi kuin {MAX_ART_BYTES} tavua, jotka luotu grafiikkaobjekti säilyttää +@msg select one generated art object valitse yksi luotu grafiikkaobjekti +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` on generaattori: piirrä sen grafiikka komennolla plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` on lajin `{_2}` laajennus, ei generaattori +@msg `{k}` is not a parameter of `{_1}` `{k}` ei ole laajennuksen `{_1}` parametri +@msg `{k}` must be at most {max_length} characters `{k}` saa olla enintään {max_length} merkkiä +@msg `{k}` must be from {min} to {max} `{k}` on oltava välillä {min}–{max} +@msg each number of `{k}` must be from {min} to {max} jokaisen `{k}`-luvun on oltava välillä {min}–{max} +@msg a generator always gets the usual budget: leave `budget` out generaattori saa aina tavallisen budjetin: jätä `budget` pois +@msg a generator returns `objects`, not `{key}` generaattori palauttaa `objects`, ei `{key}` +@msg a generator's objects are new: leave `id` out generaattorin objektit ovat uusia: jätä `id` pois +@msg the generator returned no objects generaattori ei palauttanut objekteja +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametrit ovat suuremmat kuin {MAX_PARAMS_BYTES} tavua, jotka luotu grafiikkaobjekti säilyttää + # Importer plug-ins (File › Open With, document.open) Open With Avaa ohjelmalla No importer plug-ins installed Tuontilaajennuksia ei ole asennettu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..749bf57125 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8625,6 +8625,26 @@ breakText Glyphs Glyphes 3D Box Boîte 3D 3D Box Tool Outil Boîte 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Modifier l’illustration générée… + Edit Generated Art Modifier l’illustration générée +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) n’est pas installé, son illustration générée ne peut donc pas être redessinée et reste telle quelle +@msg 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 l’identifiant de module externe ou les paramètres d’un objet d’illustration générée sont endommagés, son illustration ne peut donc pas être redessinée et reste telle quelle +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is l’illustration générée de “{name}” ({id}) ne correspond pas au hachage indiqué par son fichier et reste telle quelle +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps l’illustration du générateur dépasse les {MAX_ART_BYTES} octets que conserve un objet d’illustration générée +@msg select one generated art object sélectionnez un objet d’illustration générée +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` est un générateur, dessinez son illustration avec plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` est un module externe de type `{_2}`, pas un générateur +@msg `{k}` is not a parameter of `{_1}` `{k}` n’est pas un paramètre de `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` doit comporter au plus {max_length} caractères +@msg `{k}` must be from {min} to {max} `{k}` doit être compris entre {min} et {max} +@msg each number of `{k}` must be from {min} to {max} chaque nombre de `{k}` doit être compris entre {min} et {max} +@msg a generator always gets the usual budget: leave `budget` out un générateur reçoit toujours le budget habituel, omettez `budget` +@msg a generator returns `objects`, not `{key}` un générateur renvoie `objects`, pas `{key}` +@msg a generator's objects are new: leave `id` out les objets d’un générateur sont nouveaux, omettez `id` +@msg the generator returned no objects le générateur n’a renvoyé aucun objet +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps les paramètres dépassent les {MAX_PARAMS_BYTES} octets que conserve un objet d’illustration générée + # Importer plug-ins (File › Open With, document.open) Open With Ouvrir avec No importer plug-ins installed Aucun module externe d’importation installé diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..bd213c98a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1962,6 +1962,8 @@ Inspect Plug-in પ્લગઇન તપાસો Install Plug-in પ્લગઇન ઇન્સ્ટૉલ કરો Install Plug-in… પ્લગઇન ઇન્સ્ટૉલ કરો… + Edit Generated Art… જનરેટ કરેલી આર્ટ સંપાદિત કરો… + Edit Generated Art જનરેટ કરેલી આર્ટ સંપાદિત કરો Install “{name}” in place of the plug-in with the same ID? સમાન ID ધરાવતા પ્લગઇનની જગ્યાએ “{name}” ઇન્સ્ટૉલ કરીએ? Install “{name}”, which asks for a heavy budget? “{name}” ઇન્સ્ટૉલ કરીએ, જેને ભારે બજેટની જરૂર છે? Install “{name}”, which asks for these permissions? “{name}” ઇન્સ્ટૉલ કરીએ, જે આ પરવાનગીઓ માંગે છે? diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..d582a3b3a0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -10089,6 +10089,26 @@ theme Appearance अपीयरेंस Fully Enclosed पूरी तरह घिरे हुए Drag Direction खींचने की दिशा +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… जनरेट की गई आर्ट संपादित करें… + Edit Generated Art जनरेट की गई आर्ट संपादित करें +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) इंस्टॉल नहीं है, इसलिए उसकी जनरेट की गई आर्ट फिर से नहीं बनाई जा सकती: आर्ट जैसी है वैसी रहती है +@msg 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 जनरेट किए गए आर्ट ऑब्जेक्ट की प्लग-इन आईडी या पैरामीटर खराब हैं, इसलिए उसकी आर्ट फिर से नहीं बनाई जा सकती: आर्ट जैसी है वैसी रहती है +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is “{name}” ({id}) की जनरेट की गई आर्ट उसकी फ़ाइल में दिए हैश से मेल नहीं खाती: आर्ट जैसी है वैसी रहती है +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps जनरेटर की आर्ट उन {MAX_ART_BYTES} बाइट से बड़ी है जो एक जनरेट किया गया आर्ट ऑब्जेक्ट रखता है +@msg select one generated art object एक जनरेट किया गया आर्ट ऑब्जेक्ट चुनें +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` एक जनरेटर है: उसकी आर्ट plugin.generate {{"id": "{_2}"}} से बनाएँ +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` `{_2}` प्रकार का प्लग-इन है, जनरेटर नहीं +@msg `{k}` is not a parameter of `{_1}` `{k}` `{_1}` का पैरामीटर नहीं है +@msg `{k}` must be at most {max_length} characters `{k}` अधिकतम {max_length} वर्णों का होना चाहिए +@msg `{k}` must be from {min} to {max} `{k}` {min} से {max} तक होना चाहिए +@msg each number of `{k}` must be from {min} to {max} `{k}` की हर संख्या {min} से {max} तक होनी चाहिए +@msg a generator always gets the usual budget: leave `budget` out जनरेटर को हमेशा सामान्य बजट मिलता है: `budget` छोड़ दें +@msg a generator returns `objects`, not `{key}` जनरेटर `objects` लौटाता है, `{key}` नहीं +@msg a generator's objects are new: leave `id` out जनरेटर के ऑब्जेक्ट नए होते हैं: `id` छोड़ दें +@msg the generator returned no objects जनरेटर ने कोई ऑब्जेक्ट नहीं लौटाया +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps पैरामीटर उन {MAX_PARAMS_BYTES} बाइट से बड़े हैं जो एक जनरेट किया गया आर्ट ऑब्जेक्ट रखता है + # Importer plug-ins (File › Open With, document.open) Open With इसके साथ खोलें No importer plug-ins installed कोई इंपोर्टर प्लग-इन स्थापित नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..746810674a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8615,6 +8615,26 @@ breakText Glyphs Glifák 3D Box 3D doboz 3D Box Tool 3D doboz eszköz +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Generált grafika szerkesztése… + Edit Generated Art Generált grafika szerkesztése +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}” ({id}) nincs telepítve, ezért a generált grafikája nem rajzolható újra: a grafika változatlan marad +@msg 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 egy generált grafikaobjektum bővítményazonosítója vagy paraméterei sérültek, ezért a grafikája nem rajzolható újra: a grafika változatlan marad +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is „{name}” ({id}) generált grafikája nem egyezik a fájljában megadott hash-sel: a grafika változatlan marad +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps a generátor grafikája nagyobb, mint az a {MAX_ART_BYTES} bájt, amelyet egy generált grafikaobjektum megőriz +@msg select one generated art object jelöljön ki egy generált grafikaobjektumot +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` generátor: a grafikáját a plugin.generate {{"id": "{_2}"}} paranccsal rajzolhatja meg +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}`: `{_2}` fajtájú bővítmény, nem generátor +@msg `{k}` is not a parameter of `{_1}` `{k}` nem paramétere ennek: `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` legfeljebb {max_length} karakter lehet +@msg `{k}` must be from {min} to {max} `{k}` értéke {min} és {max} között kell legyen +@msg each number of `{k}` must be from {min} to {max} `{k}` minden számának {min} és {max} között kell lennie +@msg a generator always gets the usual budget: leave `budget` out a generátor mindig a szokásos keretet kapja: hagyja el a `budget` kulcsot +@msg a generator returns `objects`, not `{key}` a generátor `objects` értéket ad vissza, nem `{key}` értéket +@msg a generator's objects are new: leave `id` out a generátor objektumai újak: hagyja el az `id` kulcsot +@msg the generator returned no objects a generátor nem adott vissza objektumot +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps a paraméterek nagyobbak, mint az a {MAX_PARAMS_BYTES} bájt, amelyet egy generált grafikaobjektum megőriz + # Importer plug-ins (File › Open With, document.open) Open With Megnyitás ezzel No importer plug-ins installed Nincs telepített importáló bővítmény diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..17b311210d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8470,6 +8470,26 @@ breakText Glyphs Glif 3D Box Kotak 3D 3D Box Tool Alat Kotak 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Edit Gambar Hasil Generator… + Edit Generated Art Edit Gambar Hasil Generator +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) tidak terpasang, jadi gambar yang dihasilkannya tidak dapat digambar ulang: gambar tetap seperti apa adanya +@msg 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 ID plug-in atau parameter objek gambar hasil generator rusak, jadi gambarnya tidak dapat digambar ulang: gambar tetap seperti apa adanya +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is gambar yang dihasilkan “{name}” ({id}) tidak cocok dengan hash dari berkasnya: gambar tetap seperti apa adanya +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps gambar generator lebih besar daripada {MAX_ART_BYTES} byte yang disimpan objek gambar hasil generator +@msg select one generated art object pilih satu objek gambar hasil generator +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` adalah generator: gambar hasilnya dengan plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` adalah plug-in berjenis `{_2}`, bukan generator +@msg `{k}` is not a parameter of `{_1}` `{k}` bukan parameter `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` paling banyak {max_length} karakter +@msg `{k}` must be from {min} to {max} `{k}` harus antara {min} dan {max} +@msg each number of `{k}` must be from {min} to {max} setiap angka `{k}` harus antara {min} dan {max} +@msg a generator always gets the usual budget: leave `budget` out generator selalu mendapat anggaran biasa: hilangkan `budget` +@msg a generator returns `objects`, not `{key}` generator mengembalikan `objects`, bukan `{key}` +@msg a generator's objects are new: leave `id` out objek generator adalah objek baru: hilangkan `id` +@msg the generator returned no objects generator tidak mengembalikan objek apa pun +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parameter lebih besar daripada {MAX_PARAMS_BYTES} byte yang disimpan objek gambar hasil generator + # Importer plug-ins (File › Open With, document.open) Open With Buka Dengan No importer plug-ins installed Tidak ada plug-in impor yang terinstal diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..e8c2247453 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8292,6 +8292,26 @@ breakText Glyphs Glifi 3D Box Scatola 3D 3D Box Tool Strumento Scatola 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Modifica grafica generata… + Edit Generated Art Modifica grafica generata +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is «{name}» ({id}) non è installato, quindi la sua grafica generata non può essere ridisegnata: la grafica resta com’è +@msg 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 l’ID del plug-in o i parametri di un oggetto di grafica generata sono danneggiati, quindi la sua grafica non può essere ridisegnata: la grafica resta com’è +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is la grafica generata di «{name}» ({id}) non corrisponde all’hash indicato dal suo file: la grafica resta com’è +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps la grafica del generatore supera i {MAX_ART_BYTES} byte che un oggetto di grafica generata conserva +@msg select one generated art object selezionare un oggetto di grafica generata +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` è un generatore: disegnarne la grafica con plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` è un plug-in di tipo `{_2}`, non un generatore +@msg `{k}` is not a parameter of `{_1}` `{k}` non è un parametro di `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` deve avere al massimo {max_length} caratteri +@msg `{k}` must be from {min} to {max} `{k}` deve essere compreso tra {min} e {max} +@msg each number of `{k}` must be from {min} to {max} ogni numero di `{k}` deve essere compreso tra {min} e {max} +@msg a generator always gets the usual budget: leave `budget` out un generatore riceve sempre il budget consueto: omettere `budget` +@msg a generator returns `objects`, not `{key}` un generatore restituisce `objects`, non `{key}` +@msg a generator's objects are new: leave `id` out gli oggetti di un generatore sono nuovi: omettere `id` +@msg the generator returned no objects il generatore non ha restituito alcun oggetto +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps i parametri superano i {MAX_PARAMS_BYTES} byte che un oggetto di grafica generata conserva + # Importer plug-ins (File › Open With, document.open) Open With Apri con No importer plug-ins installed Nessun plug-in di importazione installato diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..1816fb5f8e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10181,6 +10181,26 @@ breakText Glyphs 字形 3D Box 3Dボックス 3D Box Tool 3Dボックスツール +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… 生成アートを編集… + Edit Generated Art 生成アートを編集 +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is 「{name}」({id}) がインストールされていないため、その生成アートを描き直せません。アートはそのまま残ります +@msg 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 生成アートオブジェクトのプラグイン ID またはパラメーターが壊れているため、そのアートを描き直せません。アートはそのまま残ります +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is 「{name}」({id}) の生成アートがファイルに記録されたハッシュと一致しません。アートはそのまま残ります +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps ジェネレーターのアートが、生成アートオブジェクトが保持できる {MAX_ART_BYTES} バイトを超えています +@msg select one generated art object 生成アートオブジェクトを 1 つ選択してください +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` はジェネレーターです。plugin.generate {{"id": "{_2}"}} でアートを描いてください +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` は種類 `{_2}` のプラグインで、ジェネレーターではありません +@msg `{k}` is not a parameter of `{_1}` `{k}` は `{_1}` のパラメーターではありません +@msg `{k}` must be at most {max_length} characters `{k}` は {max_length} 文字以内にしてください +@msg `{k}` must be from {min} to {max} `{k}` は {min} から {max} の範囲にしてください +@msg each number of `{k}` must be from {min} to {max} `{k}` の各数値は {min} から {max} の範囲にしてください +@msg a generator always gets the usual budget: leave `budget` out ジェネレーターには常に通常の予算が割り当てられます。`budget` は指定しないでください +@msg a generator returns `objects`, not `{key}` ジェネレーターが返すのは `objects` で、`{key}` ではありません +@msg a generator's objects are new: leave `id` out ジェネレーターのオブジェクトは新規です。`id` は指定しないでください +@msg the generator returned no objects ジェネレーターがオブジェクトを返しませんでした +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps パラメーターが、生成アートオブジェクトが保持できる {MAX_PARAMS_BYTES} バイトを超えています + # Importer plug-ins (File › Open With, document.open) Open With このアプリケーションで開く No importer plug-ins installed 読み込みプラグインはインストールされていません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..717092dfe1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10884,6 +10884,26 @@ font-script Japanese იაპონური 3D Box 3D ყუთი 3D Box Tool 3D ყუთის ხელსაწყო +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… გენერირებული გრაფიკის რედაქტირება… + Edit Generated Art გენერირებული გრაფიკის რედაქტირება +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}“ ({id}) არ არის დაინსტალირებული, ამიტომ მისი გენერირებული გრაფიკის თავიდან დახატვა შეუძლებელია: გრაფიკა რჩება ისე, როგორც არის +@msg 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 გენერირებული გრაფიკის ობიექტის პლაგინის ID ან პარამეტრები დაზიანებულია, ამიტომ მისი გრაფიკის თავიდან დახატვა შეუძლებელია: გრაფიკა რჩება ისე, როგორც არის +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is „{name}“-ის ({id}) გენერირებული გრაფიკა არ ემთხვევა მისი ფაილის ჰეშს: გრაფიკა რჩება ისე, როგორც არის +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps გენერატორის გრაფიკა აღემატება {MAX_ART_BYTES} ბაიტს, რომელსაც გენერირებული გრაფიკის ობიექტი ინახავს +@msg select one generated art object მონიშნეთ გენერირებული გრაფიკის ერთი ობიექტი +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` გენერატორია: მისი გრაფიკა დახატეთ plugin.generate {{"id": "{_2}"}}-ით +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` არის `{_2}` სახის პლაგინი და არა გენერატორი +@msg `{k}` is not a parameter of `{_1}` `{k}` არ არის `{_1}`-ის პარამეტრი +@msg `{k}` must be at most {max_length} characters `{k}` უნდა იყოს არაუმეტეს {max_length} სიმბოლო +@msg `{k}` must be from {min} to {max} `{k}` უნდა იყოს {min}-დან {max}-მდე +@msg each number of `{k}` must be from {min} to {max} `{k}`-ის ყოველი რიცხვი უნდა იყოს {min}-დან {max}-მდე +@msg a generator always gets the usual budget: leave `budget` out გენერატორი ყოველთვის ჩვეულებრივ ბიუჯეტს იღებს: გამოტოვეთ `budget` +@msg a generator returns `objects`, not `{key}` გენერატორი აბრუნებს `objects`-ს და არა `{key}`-ს +@msg a generator's objects are new: leave `id` out გენერატორის ობიექტები ახალია: გამოტოვეთ `id` +@msg the generator returned no objects გენერატორმა ობიექტები არ დააბრუნა +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps პარამეტრები აღემატება {MAX_PARAMS_BYTES} ბაიტს, რომელსაც გენერირებული გრაფიკის ობიექტი ინახავს + # Importer plug-ins (File › Open With, document.open) Open With გახსნა პროგრამით No importer plug-ins installed იმპორტის პლაგინები არ არის დაყენებული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..356de82bfa 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8264,6 +8264,26 @@ breakText Glyphs 글리프 3D Box 3D 상자 3D Box Tool 3D 상자 도구 +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… 생성된 아트 편집… + Edit Generated Art 생성된 아트 편집 +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}”({id})이(가) 설치되어 있지 않아 생성된 아트를 다시 그릴 수 없습니다. 아트는 그대로 유지됩니다 +@msg 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 생성된 아트 개체의 플러그인 ID 또는 매개변수가 손상되어 아트를 다시 그릴 수 없습니다. 아트는 그대로 유지됩니다 +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is “{name}”({id})의 생성된 아트가 파일에 기록된 해시와 일치하지 않습니다. 아트는 그대로 유지됩니다 +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps 생성기의 아트가 생성된 아트 개체가 보관하는 {MAX_ART_BYTES}바이트보다 큽니다 +@msg select one generated art object 생성된 아트 개체를 하나 선택하십시오 +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}`은(는) 생성기입니다. plugin.generate {{"id": "{_2}"}}로 아트를 그리십시오 +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}`은(는) `{_2}` 종류의 플러그인이며 생성기가 아닙니다 +@msg `{k}` is not a parameter of `{_1}` `{k}`은(는) `{_1}`의 매개변수가 아닙니다 +@msg `{k}` must be at most {max_length} characters `{k}`은(는) {max_length}자 이하여야 합니다 +@msg `{k}` must be from {min} to {max} `{k}`은(는) {min}에서 {max} 사이여야 합니다 +@msg each number of `{k}` must be from {min} to {max} `{k}`의 각 숫자는 {min}에서 {max} 사이여야 합니다 +@msg a generator always gets the usual budget: leave `budget` out 생성기는 항상 일반 예산을 받습니다. `budget`을 생략하십시오 +@msg a generator returns `objects`, not `{key}` 생성기는 `{key}`이(가) 아니라 `objects`를 반환합니다 +@msg a generator's objects are new: leave `id` out 생성기의 개체는 새 개체입니다. `id`를 생략하십시오 +@msg the generator returned no objects 생성기가 개체를 반환하지 않았습니다 +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps 매개변수가 생성된 아트 개체가 보관하는 {MAX_PARAMS_BYTES}바이트보다 큽니다 + # Importer plug-ins (File › Open With, document.open) Open With 연결 프로그램 No importer plug-ins installed 설치된 가져오기 플러그인 없음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..25aa950a68 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10523,6 +10523,26 @@ breakText Glyphs Glyphs 3D Box 3D-doos 3D Box Tool 3D-doosgereedschap +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Gegenereerde illustratie bewerken… + Edit Generated Art Gegenereerde illustratie bewerken +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}” ({id}) is niet geïnstalleerd, dus de gegenereerde illustratie ervan kan niet opnieuw worden getekend: de illustratie blijft zoals ze is +@msg 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 de plug-in-id of de parameters van een gegenereerd illustratieobject zijn beschadigd, dus de illustratie ervan kan niet opnieuw worden getekend: de illustratie blijft zoals ze is +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is de gegenereerde illustratie van „{name}” ({id}) komt niet overeen met de hash uit het bestand: de illustratie blijft zoals ze is +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps de illustratie van de generator is groter dan de {MAX_ART_BYTES} bytes die een gegenereerd illustratieobject bewaart +@msg select one generated art object selecteer één gegenereerd illustratieobject +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` is een generator: teken de illustratie ervan met plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` is een plug-in van het soort `{_2}`, geen generator +@msg `{k}` is not a parameter of `{_1}` `{k}` is geen parameter van `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` mag hoogstens {max_length} tekens bevatten +@msg `{k}` must be from {min} to {max} `{k}` moet tussen {min} en {max} liggen +@msg each number of `{k}` must be from {min} to {max} elk getal van `{k}` moet tussen {min} en {max} liggen +@msg a generator always gets the usual budget: leave `budget` out een generator krijgt altijd het gewone budget: laat `budget` weg +@msg a generator returns `objects`, not `{key}` een generator geeft `objects` terug, niet `{key}` +@msg a generator's objects are new: leave `id` out de objecten van een generator zijn nieuw: laat `id` weg +@msg the generator returned no objects de generator heeft geen objecten teruggegeven +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps de parameters zijn groter dan de {MAX_PARAMS_BYTES} bytes die een gegenereerd illustratieobject bewaart + # Importer plug-ins (File › Open With, document.open) Open With Openen met No importer plug-ins installed Geen importplug-ins geïnstalleerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..a740fdcf74 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8488,6 +8488,26 @@ breakText Glyphs Glify 3D Box Bryła 3D 3D Box Tool Narzędzie Bryła 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Edytuj wygenerowaną kompozycję… + Edit Generated Art Edytuj wygenerowaną kompozycję +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is „{name}” ({id}) nie jest zainstalowana, więc jej wygenerowanej kompozycji nie można narysować ponownie: kompozycja pozostaje bez zmian +@msg 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 identyfikator wtyczki lub parametry obiektu wygenerowanej kompozycji są uszkodzone, więc jego kompozycji nie można narysować ponownie: kompozycja pozostaje bez zmian +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is wygenerowana kompozycja „{name}” ({id}) nie zgadza się z hashem podanym w jej pliku: kompozycja pozostaje bez zmian +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps kompozycja generatora przekracza {MAX_ART_BYTES} bajtów, które przechowuje obiekt wygenerowanej kompozycji +@msg select one generated art object zaznacz jeden obiekt wygenerowanej kompozycji +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` to generator: narysuj jego kompozycję za pomocą plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` to wtyczka rodzaju `{_2}`, a nie generator +@msg `{k}` is not a parameter of `{_1}` `{k}` nie jest parametrem `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` może mieć najwyżej {max_length} znaków +@msg `{k}` must be from {min} to {max} `{k}` musi mieścić się w zakresie od {min} do {max} +@msg each number of `{k}` must be from {min} to {max} każda liczba w `{k}` musi mieścić się w zakresie od {min} do {max} +@msg a generator always gets the usual budget: leave `budget` out generator zawsze dostaje zwykły budżet: pomiń `budget` +@msg a generator returns `objects`, not `{key}` generator zwraca `objects`, a nie `{key}` +@msg a generator's objects are new: leave `id` out obiekty generatora są nowe: pomiń `id` +@msg the generator returned no objects generator nie zwrócił żadnych obiektów +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametry przekraczają {MAX_PARAMS_BYTES} bajtów, które przechowuje obiekt wygenerowanej kompozycji + # Importer plug-ins (File › Open With, document.open) Open With Otwórz za pomocą No importer plug-ins installed Brak zainstalowanych wtyczek importu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..e4d5e84a1c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8808,6 +8808,26 @@ swatch Yellow Green Verde-amarelado 3D Box Caixa 3D 3D Box Tool Ferramenta Caixa 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Editar Arte Gerada… + Edit Generated Art Editar Arte Gerada +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) não está instalado, então sua arte gerada não pode ser desenhada de novo: a arte fica como está +@msg 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 o ID do plug-in ou os parâmetros de um objeto de arte gerada estão danificados, então sua arte não pode ser desenhada de novo: a arte fica como está +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is a arte gerada de “{name}” ({id}) não corresponde ao hash indicado pelo arquivo: a arte fica como está +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps a arte do gerador ultrapassa os {MAX_ART_BYTES} bytes que um objeto de arte gerada guarda +@msg select one generated art object selecione um objeto de arte gerada +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` é um gerador: desenhe sua arte com plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` é um plug-in do tipo `{_2}`, não um gerador +@msg `{k}` is not a parameter of `{_1}` `{k}` não é um parâmetro de `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` deve ter no máximo {max_length} caracteres +@msg `{k}` must be from {min} to {max} `{k}` deve estar entre {min} e {max} +@msg each number of `{k}` must be from {min} to {max} cada número de `{k}` deve estar entre {min} e {max} +@msg a generator always gets the usual budget: leave `budget` out um gerador sempre recebe o orçamento usual: omita `budget` +@msg a generator returns `objects`, not `{key}` um gerador retorna `objects`, não `{key}` +@msg a generator's objects are new: leave `id` out os objetos de um gerador são novos: omita `id` +@msg the generator returned no objects o gerador não retornou nenhum objeto +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps os parâmetros ultrapassam os {MAX_PARAMS_BYTES} bytes que um objeto de arte gerada guarda + # Importer plug-ins (File › Open With, document.open) Open With Abrir Com No importer plug-ins installed Nenhum plug-in de importação instalado diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..168c5edf49 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8732,6 +8732,26 @@ shape Open Открытый 3D Box 3D-параллелепипед 3D Box Tool Инструмент «3D-параллелепипед» +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Изменить созданную графику… + Edit Generated Art Изменить созданную графику +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is «{name}» ({id}) не установлен, поэтому его созданную графику нельзя нарисовать заново: графика остаётся как есть +@msg 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 ID модуля или параметры объекта созданной графики повреждены, поэтому его графику нельзя нарисовать заново: графика остаётся как есть +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is созданная графика «{name}» ({id}) не совпадает с хешем из её файла: графика остаётся как есть +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps графика генератора больше {MAX_ART_BYTES} байт, которые хранит объект созданной графики +@msg select one generated art object выделите один объект созданной графики +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` является генератором: нарисуйте его графику командой plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` является модулем вида `{_2}`, а не генератором +@msg `{k}` is not a parameter of `{_1}` `{k}` не является параметром `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` должен содержать не более {max_length} символов +@msg `{k}` must be from {min} to {max} `{k}` должен быть от {min} до {max} +@msg each number of `{k}` must be from {min} to {max} каждое число в `{k}` должно быть от {min} до {max} +@msg a generator always gets the usual budget: leave `budget` out генератор всегда получает обычный бюджет: не указывайте `budget` +@msg a generator returns `objects`, not `{key}` генератор возвращает `objects`, а не `{key}` +@msg a generator's objects are new: leave `id` out объекты генератора новые: не указывайте `id` +@msg the generator returned no objects генератор не вернул ни одного объекта +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps параметры больше {MAX_PARAMS_BYTES} байт, которые хранит объект созданной графики + # Importer plug-ins (File › Open With, document.open) Open With Открыть с помощью No importer plug-ins installed Модули импорта не установлены diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..f1c7e032d7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -10545,6 +10545,26 @@ digits Hindi Hindi @msg {k} must be a string {k} måste vara en sträng @msg {k} must be true or false {k} måste vara true eller false +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Redigera genererad grafik… + Edit Generated Art Redigera genererad grafik +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is ”{name}” ({id}) är inte installerat, så dess genererade grafik kan inte ritas om: grafiken förblir som den är +@msg 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 plugin-id:t eller parametrarna för ett genererat grafikobjekt är skadade, så dess grafik kan inte ritas om: grafiken förblir som den är +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is den genererade grafiken från ”{name}” ({id}) stämmer inte med hashen i dess fil: grafiken förblir som den är +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps generatorns grafik är större än de {MAX_ART_BYTES} byte som ett genererat grafikobjekt sparar +@msg select one generated art object markera ett genererat grafikobjekt +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` är en generator: rita dess grafik med plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` är ett plugin av typen `{_2}`, inte en generator +@msg `{k}` is not a parameter of `{_1}` `{k}` är inte en parameter för `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` får vara högst {max_length} tecken +@msg `{k}` must be from {min} to {max} `{k}` måste vara från {min} till {max} +@msg each number of `{k}` must be from {min} to {max} varje tal i `{k}` måste vara från {min} till {max} +@msg a generator always gets the usual budget: leave `budget` out en generator får alltid den vanliga budgeten: utelämna `budget` +@msg a generator returns `objects`, not `{key}` en generator returnerar `objects`, inte `{key}` +@msg a generator's objects are new: leave `id` out en generators objekt är nya: utelämna `id` +@msg the generator returned no objects generatorn returnerade inga objekt +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametrarna är större än de {MAX_PARAMS_BYTES} byte som ett genererat grafikobjekt sparar + # Importer plug-ins (File › Open With, document.open) Open With Öppna med No importer plug-ins installed Inga importplugins är installerade diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..6bb89811d2 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3904,6 +3904,33 @@ fn cmx_import_notes_are_translated() { } } +/// Object › Plug-ins › Edit Generated Art… and its undo step are in every complete catalog, and the +/// notes and errors about generated art objects (as the engine fills them in) are translated in +/// every complete-message catalog. +#[test] +fn generated_art_strings_are_translated() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Edit Generated Art…", "Edit Generated Art"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let messages = [ + "“Squares” (org.example.squares) isn't installed, so its generated art can't be drawn again: the art stays as it is", + "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", + "the generated art of “Squares” (org.example.squares) doesn't match the hash its file gave: the art stays as it is", + "the generator's art is larger than the 16777216 bytes a generated art object keeps", + "select one generated art object", + "`org.example.squares` is a generator: draw its art with plugin.generate {\"id\": \"org.example.squares\"}", + "`size` must be from 1 to 100", + ]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for m in messages { + assert_ne!(message(lang, m), m, "{code}: {m}"); + } + } +} + /// The plug-in host's status and error messages (manifests, modules, runs and the output of /// importers, exporters and effects) have an `@msg` row in every complete-message catalog. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..72b58ee8fc 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10519,6 +10519,26 @@ breakText Glyphs Glifler 3D Box 3B Kutu 3D Box Tool 3B Kutu Aracı +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Oluşturulan Resmi Düzenle… + Edit Generated Art Oluşturulan Resmi Düzenle +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) yüklü değil, bu yüzden oluşturduğu resim yeniden çizilemez: resim olduğu gibi kalır +@msg 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 oluşturulan bir resim nesnesinin eklenti kimliği veya parametreleri bozuk, bu yüzden resmi yeniden çizilemez: resim olduğu gibi kalır +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is “{name}” ({id}) tarafından oluşturulan resim, dosyasındaki karma değerle eşleşmiyor: resim olduğu gibi kalır +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps oluşturucunun resmi, oluşturulan bir resim nesnesinin sakladığı {MAX_ART_BYTES} bayttan büyük +@msg select one generated art object oluşturulan bir resim nesnesi seçin +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` bir oluşturucudur: resmini plugin.generate {{"id": "{_2}"}} ile çizin +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}`, `{_2}` türünde bir eklentidir, oluşturucu değildir +@msg `{k}` is not a parameter of `{_1}` `{k}`, `{_1}` eklentisinin bir parametresi değil +@msg `{k}` must be at most {max_length} characters `{k}` en fazla {max_length} karakter olmalıdır +@msg `{k}` must be from {min} to {max} `{k}` {min} ile {max} arasında olmalıdır +@msg each number of `{k}` must be from {min} to {max} `{k}` içindeki her sayı {min} ile {max} arasında olmalıdır +@msg a generator always gets the usual budget: leave `budget` out oluşturucu her zaman olağan bütçeyi alır: `budget` anahtarını çıkarın +@msg a generator returns `objects`, not `{key}` oluşturucu `{key}` değil, `objects` döndürür +@msg a generator's objects are new: leave `id` out oluşturucunun nesneleri yenidir: `id` anahtarını çıkarın +@msg the generator returned no objects oluşturucu hiç nesne döndürmedi +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps parametreler, oluşturulan bir resim nesnesinin sakladığı {MAX_PARAMS_BYTES} bayttan büyük + # Importer plug-ins (File › Open With, document.open) Open With Birlikte Aç No importer plug-ins installed İçe aktarma eklentisi yüklü değil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..84ff856fec 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8274,6 +8274,26 @@ breakText Glyphs Гліфи 3D Box 3D-паралелепіпед 3D Box Tool Інструмент «3D-паралелепіпед» +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Змінити створену графіку… + Edit Generated Art Змінити створену графіку +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is «{name}» ({id}) не встановлено, тому його створену графіку не можна намалювати знову: графіка залишається як є +@msg 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 ID модуля або параметри об’єкта створеної графіки пошкоджено, тому його графіку не можна намалювати знову: графіка залишається як є +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is створена графіка «{name}» ({id}) не збігається з хешем з її файлу: графіка залишається як є +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps графіка генератора більша за {MAX_ART_BYTES} байтів, які зберігає об’єкт створеної графіки +@msg select one generated art object виділіть один об’єкт створеної графіки +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` є генератором: намалюйте його графіку командою plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` є модулем виду `{_2}`, а не генератором +@msg `{k}` is not a parameter of `{_1}` `{k}` не є параметром `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` має містити не більше {max_length} символів +@msg `{k}` must be from {min} to {max} `{k}` має бути від {min} до {max} +@msg each number of `{k}` must be from {min} to {max} кожне число в `{k}` має бути від {min} до {max} +@msg a generator always gets the usual budget: leave `budget` out генератор завжди отримує звичайний бюджет: не вказуйте `budget` +@msg a generator returns `objects`, not `{key}` генератор повертає `objects`, а не `{key}` +@msg a generator's objects are new: leave `id` out об’єкти генератора нові: не вказуйте `id` +@msg the generator returned no objects генератор не повернув жодного об’єкта +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps параметри більші за {MAX_PARAMS_BYTES} байтів, які зберігає об’єкт створеної графіки + # Importer plug-ins (File › Open With, document.open) Open With Відкрити за допомогою No importer plug-ins installed Модулі імпорту не встановлено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..de24f2bef2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8320,6 +8320,26 @@ breakText Glyphs Glyph 3D Box Hộp 3D 3D Box Tool Công cụ Hộp 3D +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… Sửa hình được tạo… + Edit Generated Art Sửa hình được tạo +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) chưa được cài đặt nên không thể vẽ lại hình được tạo của nó: hình được giữ nguyên +@msg 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 ID plug-in hoặc tham số của một đối tượng hình được tạo bị hỏng nên không thể vẽ lại hình của nó: hình được giữ nguyên +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is hình được tạo của “{name}” ({id}) không khớp với mã băm trong tệp của nó: hình được giữ nguyên +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps hình của trình tạo lớn hơn {MAX_ART_BYTES} byte mà một đối tượng hình được tạo lưu giữ +@msg select one generated art object hãy chọn một đối tượng hình được tạo +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` là trình tạo: hãy vẽ hình của nó bằng plugin.generate {{"id": "{_2}"}} +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` là plug-in loại `{_2}`, không phải trình tạo +@msg `{k}` is not a parameter of `{_1}` `{k}` không phải là tham số của `{_1}` +@msg `{k}` must be at most {max_length} characters `{k}` chỉ được có tối đa {max_length} ký tự +@msg `{k}` must be from {min} to {max} `{k}` phải từ {min} đến {max} +@msg each number of `{k}` must be from {min} to {max} mỗi số trong `{k}` phải từ {min} đến {max} +@msg a generator always gets the usual budget: leave `budget` out trình tạo luôn nhận ngân sách thông thường: hãy bỏ `budget` +@msg a generator returns `objects`, not `{key}` trình tạo trả về `objects`, không phải `{key}` +@msg a generator's objects are new: leave `id` out đối tượng của trình tạo là đối tượng mới: hãy bỏ `id` +@msg the generator returned no objects trình tạo không trả về đối tượng nào +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps tham số lớn hơn {MAX_PARAMS_BYTES} byte mà một đối tượng hình được tạo lưu giữ + # Importer plug-ins (File › Open With, document.open) Open With Mở bằng No importer plug-ins installed Không có plug-in nhập được cài đặt diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..8c5cb226ea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8498,6 +8498,26 @@ breakText Glyphs 字形 3D Box 3D 盒子 3D Box Tool 3D 盒子工具 +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… 编辑生成的图稿… + Edit Generated Art 编辑生成的图稿 +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is “{name}” ({id}) 未安装,因此无法重新绘制其生成的图稿:图稿保持原样 +@msg 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 某个生成图稿对象的增效工具 ID 或参数已损坏,因此无法重新绘制其图稿:图稿保持原样 +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is “{name}” ({id}) 生成的图稿与其文件中的哈希值不符:图稿保持原样 +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps 生成器的图稿超过了生成图稿对象可保存的 {MAX_ART_BYTES} 字节 +@msg select one generated art object 请选择一个生成图稿对象 +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` 是生成器:请用 plugin.generate {{"id": "{_2}"}} 绘制其图稿 +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` 是 `{_2}` 类型的增效工具,不是生成器 +@msg `{k}` is not a parameter of `{_1}` `{k}` 不是 `{_1}` 的参数 +@msg `{k}` must be at most {max_length} characters `{k}` 最多只能有 {max_length} 个字符 +@msg `{k}` must be from {min} to {max} `{k}` 必须在 {min} 到 {max} 之间 +@msg each number of `{k}` must be from {min} to {max} `{k}` 中的每个数字必须在 {min} 到 {max} 之间 +@msg a generator always gets the usual budget: leave `budget` out 生成器始终使用常规预算:请省略 `budget` +@msg a generator returns `objects`, not `{key}` 生成器返回的是 `objects`,不是 `{key}` +@msg a generator's objects are new: leave `id` out 生成器的对象是新对象:请省略 `id` +@msg the generator returned no objects 生成器未返回任何对象 +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps 参数超过了生成图稿对象可保存的 {MAX_PARAMS_BYTES} 字节 + # Importer plug-ins (File › Open With, document.open) Open With 打开方式 No importer plug-ins installed 未安装导入增效工具 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..395e13418e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8322,6 +8322,26 @@ breakText Glyphs 字符 3D Box 3D 盒子 3D Box Tool 3D 盒子工具 +# Generator plug-ins (Object › Plug-ins, plugin.generate, plugin.editGenerated) + Edit Generated Art… 編輯產生的圖稿… + Edit Generated Art 編輯產生的圖稿 +@msg “{name}” ({id}) isn't installed, so its generated art can't be drawn again: the art stays as it is 「{name}」({id}) 未安裝,因此無法重新繪製其產生的圖稿:圖稿保持原樣 +@msg 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 某個產生圖稿物件的增效模組 ID 或參數已損毀,因此無法重新繪製其圖稿:圖稿保持原樣 +@msg the generated art of “{name}” ({id}) doesn't match the hash its file gave: the art stays as it is 「{name}」({id}) 產生的圖稿與其檔案中的雜湊值不符:圖稿保持原樣 +@msg the generator's art is larger than the {MAX_ART_BYTES} bytes a generated art object keeps 產生器的圖稿超過產生圖稿物件可保存的 {MAX_ART_BYTES} 位元組 +@msg select one generated art object 請選取一個產生圖稿物件 +@msg `{_1}` is a generator: draw its art with plugin.generate {{"id": "{_2}"}} `{_1}` 是產生器:請用 plugin.generate {{"id": "{_2}"}} 繪製其圖稿 +@msg `{_1}` is a plug-in of kind `{_2}`, not a generator `{_1}` 是 `{_2}` 類型的增效模組,不是產生器 +@msg `{k}` is not a parameter of `{_1}` `{k}` 不是 `{_1}` 的參數 +@msg `{k}` must be at most {max_length} characters `{k}` 最多只能有 {max_length} 個字元 +@msg `{k}` must be from {min} to {max} `{k}` 必須介於 {min} 到 {max} 之間 +@msg each number of `{k}` must be from {min} to {max} `{k}` 中的每個數字必須介於 {min} 到 {max} 之間 +@msg a generator always gets the usual budget: leave `budget` out 產生器一律使用一般預算:請移除 `budget` +@msg a generator returns `objects`, not `{key}` 產生器傳回的是 `objects`,不是 `{key}` +@msg a generator's objects are new: leave `id` out 產生器的物件是新物件:請移除 `id` +@msg the generator returned no objects 產生器未傳回任何物件 +@msg the parameters are larger than the {MAX_PARAMS_BYTES} bytes a generated art object keeps 參數超過產生圖稿物件可保存的 {MAX_PARAMS_BYTES} 位元組 + # Importer plug-ins (File › Open With, document.open) Open With 開啟方式 No importer plug-ins installed 未安裝匯入增效模組 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index aa9451d3f9..4224c8a704 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1227,6 +1227,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), "ui.installPlugin" => io::install_plugin(app, p), "plugin.cancelRuns" => Ok(crate::plugin_runs::cancel_all(app)), "plugin.hideRuns" => Ok(crate::plugin_runs::hide_all(app)), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 5533352c18..1a481d9af4 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -376,6 +376,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), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), id if id.starts_with(crate::dialogs::perspective_presets::SLOT) => { app.session.active().is_some() && crate::dialogs::perspective_presets::slot_preset(app, id).is_some() diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..df1bcf6336 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1994,7 +1994,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, `__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)", + "{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, `__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). A generator draws new generated art at once when it takes no parameters or params are given (plugin.generate), else opens dialog `pluginGenerate` (a field per parameter, `__plugin` the id; 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 (`__plugin` its generator, `__edit` its id); 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", ), ( "ui.installPlugin", diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..baa9bb2cdc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13303,7 +13303,24 @@ 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, 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; `document.open` never runs a +plug-in, and its `warnings` name the plug-in of each object it can't draw again. `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 ab294db1ff..e7bc3ac684 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -35,6 +35,9 @@ in `crates/engine/src/cmd/plugin.rs`). | `plugin.remove` | `{"id"}` | Uninstalls, and deletes it from the `Plug-ins` folder with its [settings and cache](#settings-and-cache). | | `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` 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` files past the first 1,000, which were not tried. | +| `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. @@ -80,6 +83,47 @@ 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, and its 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, naming the plug-in. 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. +- **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 @@ -201,7 +245,7 @@ capability model proposed for PhotoCraft plug-ins | Permission | Kinds | What it allows | |---|---|---| | `doc.read` | filter, effect, exporter | Read the objects it is given. | -| `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. | @@ -213,11 +257,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` @@ -545,8 +589,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 3da663c191..1b92f1c614 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2645,6 +2645,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. - **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. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. From f373cfd546f373770f76eec4de667e2445ba3a79 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:09:53 -0800 Subject: [PATCH 2/8] Plug-ins: generated art inside generated art is saved as plain art Writing a generated art object hashed its art's JSON, and writing that JSON hashed each generated art object inside it again, so the work doubled with each level of nesting: 16 levels hashed 23 MB for a 3 KB file, and reading a crafted file did the same. A generated art object inside another one's art (its children, or their opacity masks' art) is now written without its settings, so each object's art is written and hashed once. Reading drops settings found there anyway, without hashing, and the outer object reads as changed. Docs: docs/plugins.md, docs/mcp.md. --- crates/doc/src/generated.rs | 206 ++++++++++++++++++++++++++++++++++-- crates/doc/src/node/wire.rs | 11 +- docs/mcp.md | 3 +- docs/plugins.md | 3 +- 4 files changed, 209 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/generated.rs b/crates/doc/src/generated.rs index 5e5094cb4a..be2fa6cf4d 100644 --- a/crates/doc/src/generated.rs +++ b/crates/doc/src/generated.rs @@ -10,6 +10,14 @@ //! 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}; @@ -139,19 +147,86 @@ 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. -pub fn art_hash(children: &[std::sync::Arc]) -> String { +/// 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 = serde_json::to_vec(children).unwrap_or_default(); + 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 ([`MAX_ART_BYTES`]). -pub fn art_bytes(children: &[std::sync::Arc]) -> usize { +/// 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> { @@ -216,9 +291,11 @@ fn read_scale(k: Option) -> Option { /// 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. -pub(crate) fn read(v: Value, kind: &NodeKind) -> Option> { +/// 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()) })); }; @@ -257,7 +334,7 @@ pub(crate) fn read(v: Value, kind: &NodeKind) -> Option> { }; let stroke_scale = scale("strokeScale"); let effect_scale = scale("effectScale"); - let intact = matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children)); + 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 { @@ -289,6 +366,119 @@ mod tests { 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] diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index fac3a2e1ca..2d722909f2 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, @@ -60,7 +61,7 @@ impl Serialize for Node { is_default(&e.warp_piece), is_default(&e.clip_pieces), e.image_quad.is_none(), - e.generated.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 +88,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); @@ -109,7 +112,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", &e.generated.as_deref().map(|g| crate::generated::Wire::of(g, self))); + field!("generated", &generated.map(|g| crate::generated::Wire::of(g, self))); st.end() } } @@ -456,7 +459,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,7 +494,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, &w.kind)), + generated: w.generated.and_then(|g| crate::generated::read(g, &mut w.kind)), }; Node { id: w.id, diff --git a/docs/mcp.md b/docs/mcp.md index baa9bb2cdc..a102fbcd8b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13316,7 +13316,8 @@ object whose plug-in isn't installed or is a plug-in of another kind, or whose s scales are damaged, is an error naming the plug-in, 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; `document.open` never runs a +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 it can't draw again. `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… diff --git a/docs/plugins.md b/docs/plugins.md index e7bc3ac684..68c3133b29 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -119,7 +119,8 @@ art was drawn with and the art itself, so the art can be drawn again when the pa 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, naming the plug-in. 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. + 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. From 83754912a0aac25d851b1d9de9d88ab24e2272b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:30:02 -0800 Subject: [PATCH 3/8] Plug-ins: a generated field saved as null opens as damaged generated art A file whose group holds "generated": null was read as if the field were absent, so the group opened as plain art with no damaged state and no note in the open's warnings. A present null is now read like any other value that can't be read: the object is marked damaged and keeps its art. --- crates/doc/src/generated.rs | 10 ++++++++++ crates/doc/src/node/wire.rs | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/generated.rs b/crates/doc/src/generated.rs index be2fa6cf4d..e066aec817 100644 --- a/crates/doc/src/generated.rs +++ b/crates/doc/src/generated.rs @@ -561,6 +561,16 @@ mod tests { 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(); diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 2d722909f2..4649f83483 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -267,10 +267,15 @@ pub(super) struct NodeWire { #[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)] + #[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 /// image is then placed by its transform). A point is `[x, y]` or `{"x": x, "y": y}`. A value that /// is not a list, or a list with an entry that is not a point, is none too. Values that are not From 69b4c84819711367713633da07cb9e02d6d820d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:38:24 -0800 Subject: [PATCH 4/8] Docs: generated art warnings for damaged fields name no plug-in docs/plugins.md and docs/mcp.md said that the error of plugin.editGenerated and the warnings of document.open name the plug-in in every case. For an object with damaged saved fields, both say that a generated art object's plug-in id or parameters are damaged, without a plug-in name. The docs now say so. --- docs/mcp.md | 5 +++-- docs/plugins.md | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a102fbcd8b..b9b9093ef1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13313,12 +13313,13 @@ one) again with the saved parameters changed by `params` and replaces its art, p 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, and its art stays as it is. `plugin.generatedInfo {id?}` +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 it can't draw again. `plugin.run` of a generator is an error +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 diff --git a/docs/plugins.md b/docs/plugins.md index 68c3133b29..61d1e86d00 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -109,15 +109,16 @@ art was drawn with and the art itself, so the art can be drawn again when the pa 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, and its art stays as it - is. + 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, naming the plug-in. Saving writes the hash of the art as it is then, and an object whose + 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`. From 19ba7e3d85711b6333c43b8dc63e19822be4b1e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:10:32 -0800 Subject: [PATCH 5/8] =?UTF-8?q?Plug-ins:=20Edit=20Generated=20Art=E2=80=A6?= =?UTF-8?q?=20edits=20one=20object=20of=20the=20document=20it=20opened=20i?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Edit Generated Art… is enabled only when the selection is one object, a generated art object. A generated art object selected with another object no longer enables it, and plugin.editGenerated and plugin.generatedInfo without `id` refuse that selection. - The dialog keeps the document it was opened in. When another document is active at OK, OK draws nothing, closes the dialog and reports that the document is no longer active. - A whole-number generator parameter is compared with its bounds as integers, so a value just past a maximum above 2^53 is refused instead of being clamped. - A stroke or effect scale of 0, saved after a transform that flattens the art, reads back intact instead of damaged. - The MCP UI command mirror lists ui.editGeneratedArt and the new plugin.dialog text (cargo xtask ui-commands). - The generated art fields fuzz test checks the group's art by id, also when its generated art fields are not read back. --- crates/doc/src/generated.rs | 14 +++++-- crates/engine/src/cmd/plugin_generated.rs | 11 ++---- crates/engine/tests/import_fuzz.rs | 12 ++++-- crates/engine/tests/plugin_generate.rs | 8 ++++ crates/mcp/src/ui_catalog.rs | 8 +++- crates/plugins/src/generate.rs | 27 ++++++++++++- crates/ui-egui/src/dialogs/plugin.rs | 25 +++++++++--- .../src/dialogs/tests_plugin_generate.rs | 38 +++++++++++++++++++ 8 files changed, 121 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/generated.rs b/crates/doc/src/generated.rs index e066aec817..30ef8fd250 100644 --- a/crates/doc/src/generated.rs +++ b/crates/doc/src/generated.rs @@ -280,11 +280,12 @@ fn read_affine(t: Option) -> Option { } } -/// A saved scale `k` (absent: 1): `None` when it is not a finite number above 0. +/// 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), + Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0), } } @@ -506,6 +507,13 @@ mod tests { 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 @@ -539,7 +547,7 @@ mod tests { ("strokeScale", json!(-2.0)), ("strokeScale", Value::Null), ("strokeScale", json!("big")), - ("effectScale", json!(0.0)), + ("effectScale", json!(-0.5)), ("patternTransform", json!([1, 0, 0, 1, 0])), ("patternTransform", Value::Null), ("effectScale", Value::Null), diff --git a/crates/engine/src/cmd/plugin_generated.rs b/crates/engine/src/cmd/plugin_generated.rs index 8d0a6ebaa5..2ea264b004 100644 --- a/crates/engine/src/cmd/plugin_generated.rs +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -161,13 +161,10 @@ fn target(s: &Session, c: &str, p: &Value) -> Result<(NodeId, GeneratedArt)> { let found = match super::given_objects(s, p, c)? { Some(ids) if ids.len() == 1 => one(ids[0]), Some(_) => None, - None => { - let mut picked = st.selection.objects.iter().filter_map(|id| one(*id)); - match (picked.next(), picked.next()) { - (Some(g), None) => Some(g), - _ => 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)?; diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 5c51eaaa53..e14c85e3c7 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3023,6 +3023,7 @@ proptest! { 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, @@ -3030,15 +3031,18 @@ proptest! { let bytes = serde_json::to_vec(&v).unwrap(); let loaded = vectorcraft_engine::cmd::fileio::load("x.vectorcraft", &bytes); if let Ok(l) = &loaded { - let mut found = vec![]; + // 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() { - found.push((g.plugin.clone(), serde_json::to_value(&n.kind).unwrap())); + plugins.push(g.plugin.clone()); } }); - for (plugin, kind) in &found { + for plugin in &plugins { prop_assert!(plugin.is_empty() || vectorcraft_doc::generated::valid_id(plugin), "{plugin:?}"); - prop_assert_eq!(kind, &art); } } survive("generated art fields", || loaded.ok().map(|l| l.doc))?; diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs index 49fbe7a908..cf034ce1ae 100644 --- a/crates/engine/tests/plugin_generate.rs +++ b/crates/engine/tests/plugin_generate.rs @@ -146,6 +146,14 @@ fn editing_the_parameters_draws_the_art_again_as_one_undo_step() { 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. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..1e46d7d08f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1993,7 +1993,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, `__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)", + "{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, `__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). A generator draws new generated art at once when it takes no parameters or params are given (plugin.generate), else opens dialog `pluginGenerate` (a field per parameter, `__plugin` the id; 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 (`__plugin` its generator, `__edit` its id); 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", ), ( "ui.installPlugin", diff --git a/crates/plugins/src/generate.rs b/crates/plugins/src/generate.rs index 9a0077802b..84b7379734 100644 --- a/crates/plugins/src/generate.rs +++ b/crates/plugins/src/generate.rs @@ -106,11 +106,15 @@ fn strict(m: &crate::Manifest, given: &Map) -> Result<()> { } /// 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. +/// [`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().is_some_and(|f| !(min as f64..=max as f64).contains(&f.round())), + None => v.is_u64() || v.as_f64().map(f64::round).is_some_and(|r| !(LOW..HIGH).contains(&r) || !(min..=max).contains(&(r as i64))), } } @@ -204,4 +208,23 @@ mod tests { 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/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 9b250df5c8..483f04c041 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -320,21 +320,36 @@ pub fn open_edit(app: &mut VectorcraftApp, p: &Value) -> Result { } } fields.insert("__edit".into(), id); + fields.insert(EDIT_DOC.into(), json!(app.session.active().map(|st| st.uid))); app.ui.dialog = Some(Dialog { kind: GENERATE_KIND.into(), fields }); Ok(Value::Null) } -/// Does the selection hold exactly one generated art object, which Edit Generated Art… edits? +/// The field of an Edit Generated Art… dialog that holds the [`uid`](vectorcraft_engine::DocState::uid) +/// of the document whose object it edits. +const EDIT_DOC: &str = "__editDoc"; + +/// OK's error when that document is no longer the active one. +const EDIT_DOC_GONE: &str = "the document it was prepared for is no longer active"; + +/// 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| st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some_and(|n| n.extras().generated.is_some())).count() == 1) + 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: draws new generated art (`plugin.generate`), or draws the object of `__edit` again -/// (`plugin.editGenerated`), as one undo step; the dialog closes once it is drawn. +/// (`plugin.editGenerated`), as one undo step; the dialog closes once it is drawn. When another +/// document has come to the front since Edit Generated Art… opened the dialog, OK draws nothing, +/// closes the dialog and says so. fn generate_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let r = match d.fields.get("__edit").filter(|v| !v.is_null()) { + Some(_) if d.fields.get(EDIT_DOC) != Some(&json!(app.session.active().map(|st| st.uid))) => { + app.ui.dialog = None; + return Err(EDIT_DOC_GONE.into()); + } Some(id) => app.run("plugin.editGenerated", json!({"id": id, "params": form::params(d)})), None => app.run(GENERATE, json!({"id": d.str("__plugin"), "params": form::params(d)})), }; diff --git a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs index 9406f3d1c3..fb33761352 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs @@ -76,3 +76,41 @@ fn object_plug_ins_draws_and_edits_generated_art() { assert_eq!(kind(&app), None); assert_eq!(art(&app, id), ["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 = VectorcraftApp::new(Session::new(), Services::default()); + let manifest = tpl::generator("test.ui.generator2", 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(); + 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 steps = app.session.doc().unwrap().history.undo.len(); + let e = confirm(&mut app).unwrap_err(); + assert_eq!(e, "the document it was prepared for is no longer active"); + assert!(app.ui.dialog.is_none()); + assert_eq!(art(&app, second), ["Small"]); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(art(&app, first), ["Small"]); + app.run("plugin.remove", json!({"id": "test.ui.generator2"})).unwrap(); +} From b514c4e35da66c87a4ae90fa468ca8f0aff8f1de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:07:14 -0800 Subject: [PATCH 6/8] Validate generator parameters and include mask art in opening warnings --- crates/engine/src/cmd/plugin_generated.rs | 7 +++-- crates/engine/tests/plugin_generate.rs | 15 +++++++++++ crates/ui-egui/src/dialogs/plugin.rs | 5 +++- .../src/dialogs/tests_plugin_generate.rs | 26 +++++++++++++++++++ 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/plugin_generated.rs b/crates/engine/src/cmd/plugin_generated.rs index 2ea264b004..9984bdcaf8 100644 --- a/crates/engine/src/cmd/plugin_generated.rs +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -83,7 +83,7 @@ fn changed(g: &GeneratedArt) -> String { /// 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![]; - doc.walk(|n| { + 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(), @@ -97,7 +97,10 @@ pub fn open_notes(doc: &Document) -> Vec { if !notes.contains(¬e) { notes.push(note); } - }); + }; + for layer in &doc.layers { + vectorcraft_doc::swatches::walk_with_masks(layer, &mut visit); + } notes } diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs index cf034ce1ae..dc7b7e1817 100644 --- a/crates/engine/tests/plugin_generate.rs +++ b/crates/engine/tests/plugin_generate.rs @@ -273,6 +273,21 @@ fn a_missing_plug_in_keeps_the_art_and_is_named() { 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:?}"); +} + /// 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> { diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 27ed7200e0..ba7f5d927f 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -562,7 +562,10 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { match m.kind { Kind::Filter => {} Kind::Generator => { - let given = p.get("params").filter(|v| v.as_object().is_some_and(|o| !o.is_empty())); + 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)})); } diff --git a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs index 92e79cae33..e73ce9a3f7 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs @@ -95,6 +95,32 @@ fn object_plug_ins_draws_and_edits_generated_art() { 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(); + } +} + /// 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. From 7409ec360911bfaf50a63247806ac4908b876870 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:44:32 -0800 Subject: [PATCH 7/8] Include generated art definitions in missing-plugin warnings --- crates/engine/src/cmd/plugin_generated.rs | 11 +++++++++++ crates/engine/tests/plugin_generate.rs | 13 +++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/engine/src/cmd/plugin_generated.rs b/crates/engine/src/cmd/plugin_generated.rs index 9984bdcaf8..83ef85decc 100644 --- a/crates/engine/src/cmd/plugin_generated.rs +++ b/crates/engine/src/cmd/plugin_generated.rs @@ -101,6 +101,17 @@ pub fn open_notes(doc: &Document) -> Vec { 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 } diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs index dc7b7e1817..f1f93a6227 100644 --- a/crates/engine/tests/plugin_generate.rs +++ b/crates/engine/tests/plugin_generate.rs @@ -288,6 +288,19 @@ fn a_missing_generator_in_an_opacity_mask_is_named_on_open() { 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:?}"); +} + /// 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> { From 38bffbe8b5e7dc56bf766e7831e1d84893c362dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 12:30:45 -0800 Subject: [PATCH 8/8] Fix generated art editing in containers and after parameter updates --- crates/engine/tests/plugin_generate.rs | 18 ++++++++++++++++ crates/plugins/src/objects.rs | 5 +---- crates/ui-egui/src/dialogs/plugin.rs | 7 +------ .../src/dialogs/tests_plugin_generate.rs | 21 +++++++++++++++++++ 4 files changed, 41 insertions(+), 10 deletions(-) diff --git a/crates/engine/tests/plugin_generate.rs b/crates/engine/tests/plugin_generate.rs index f1f93a6227..4e936f0d88 100644 --- a/crates/engine/tests/plugin_generate.rs +++ b/crates/engine/tests/plugin_generate.rs @@ -301,6 +301,24 @@ fn a_missing_generator_in_a_symbol_definition_is_named_on_open() { 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> { diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 4b0a528703..92608b11b8 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/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index ba7f5d927f..2d36709ece 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -680,12 +680,7 @@ const EDIT_DOC_GONE: &str = "the document it was prepared for is no longer activ 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 mut rows = m.defaults(); - for (k, v) in values { - if let Some(slot) = rows.get_mut(k) { - *slot = v.clone(); - } - } + 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(()) diff --git a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs index e73ce9a3f7..a4c8e82bc3 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_generate.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_generate.rs @@ -121,6 +121,27 @@ fn generator_dialog_validates_supplied_parameters_and_runs_an_empty_object() { } } +#[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.